~edwargix/git.sr.ht

e401e41dea5cbd6245e042a7ca975e308284e42d — Drew DeVault 7 years ago 3ed6fe9
Remove old API, obsolete webhooks table
5 files changed, 35 insertions(+), 181 deletions(-)

A gitsrht/alembic/versions/27ad57b7c4a5_remove_obsolete_webhook_table.py
M gitsrht/app.py
D gitsrht/blueprints/api.py
M gitsrht/types/__init__.py
D gitsrht/types/webhook.py
A gitsrht/alembic/versions/27ad57b7c4a5_remove_obsolete_webhook_table.py => gitsrht/alembic/versions/27ad57b7c4a5_remove_obsolete_webhook_table.py +35 -0
@@ 0,0 1,35 @@
"""Remove obsolete webhook table

Revision ID: 27ad57b7c4a5
Revises: 447ac6ff8f40
Create Date: 2018-12-31 13:31:13.665300

"""

# revision identifiers, used by Alembic.
revision = '27ad57b7c4a5'
down_revision = '447ac6ff8f40'

from alembic import op
import sqlalchemy as sa


def upgrade():
    op.drop_table("webhook")


def downgrade():
    op.create_table('webhook',
        sa.Column('id', sa.INTEGER(), nullable=False),
        sa.Column('created', postgresql.TIMESTAMP(), autoincrement=False, nullable=False),
        sa.Column('updated', postgresql.TIMESTAMP(), autoincrement=False, nullable=False),
        sa.Column('description', sa.VARCHAR(length=1024), autoincrement=False, nullable=True),
        sa.Column('oauth_token_id', sa.INTEGER(), autoincrement=False, nullable=True),
        sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=False),
        sa.Column('repo_id', sa.INTEGER(), autoincrement=False, nullable=True),
        sa.Column('url', sa.VARCHAR(length=2048), autoincrement=False, nullable=False),
        sa.Column('validate_ssl', sa.BOOLEAN(), autoincrement=False, nullable=False),
        sa.ForeignKeyConstraint(['oauth_token_id'], ['oauthtoken.id'], name='webhook_oauth_token_id_fkey'),
        sa.ForeignKeyConstraint(['repo_id'], ['repository.id'], name='webhook_repo_id_fkey'),
        sa.ForeignKeyConstraint(['user_id'], ['user.id'], name='webhook_user_id_fkey'),
        sa.PrimaryKeyConstraint('id', name='webhook_pkey'))

M gitsrht/app.py => gitsrht/app.py +0 -2
@@ 36,13 36,11 @@ class GitApp(SrhtFlask):

        self.url_map.strict_slashes = False

        from gitsrht.blueprints.api import api
        from gitsrht.blueprints.public import public
        from gitsrht.blueprints.repo import repo
        from gitsrht.blueprints.stats import stats
        from gitsrht.blueprints.manage import manage

        self.register_blueprint(api)
        self.register_blueprint(public)
        self.register_blueprint(repo)
        self.register_blueprint(stats)

D gitsrht/blueprints/api.py => gitsrht/blueprints/api.py +0 -152
@@ 1,152 0,0 @@
from flask import Blueprint, request, redirect, abort, url_for
from gitsrht.types import Repository, RepoVisibility, User, Webhook, Redirect
from gitsrht.access import UserAccess, has_access, get_repo, check_repo
from gitsrht.repos import create_repo
from srht.validation import Validation, valid_url
from srht.oauth import oauth
from srht.database import db

api = Blueprint("api", __name__)

repo_json = lambda r: {
    "id": r.id,
    "name": r.name,
    "description": r.description,
    "created": r.created,
    "updated": r.updated,
    "visibility": r.visibility.value
}

wh_json = lambda wh: {
    "id": wh.id,
    "created": wh.created,
    "description": wh.description,
    "url": wh.url,
    "validate_ssl": wh.validate_ssl,
    "repo": "~{}/{}".format(wh.repository.owner.username,
        wh.repository.name) if wh.repository else None
}

@api.route("/api/repos")
@oauth("repos")
def repos_GET(oauth_token):
    start = request.args.get('start') or -1
    repos = Repository.query.filter(Repository.owner_id == oauth_token.user_id)
    if start != -1:
        repos = repos.filter(Repository.id <= start)
    repos = repos.order_by(Repository.id.desc()).limit(11).all()
    if len(repos) != 11:
        next_id = -1
    else:
        next_id = repos[-1].id
        repos = repos[:10]
    return {
        "next": next_id,
        "results": [repo_json(r) for r in repos]
    }

@api.route("/api/repos", methods=["POST"])
@oauth("repos:write")
def repos_POST(oauth_token):
    valid = Validation(request)
    repo = create_repo(valid, oauth_token.user)
    if not valid.ok:
        return valid.response
    return repo_json(repo)

@api.route("/api/repos/~<owner>")
def repos_username_GET(owner):
    user = User.query.filter(User.username == owner).first()
    if not user:
        abort(404)
    start = request.args.get('start') or -1
    repos = (Repository.query
        .filter(Repository.owner_id == user.id)
        .filter(Repository.visibility == RepoVisibility.public)
    )
    if start != -1:
        repos = repos.filter(Repository.id <= start)
    repos = repos.order_by(Repository.id.desc()).limit(11).all()
    if len(repos) != 11:
        next_id = -1
    else:
        next_id = repos[-1].id
        repos = repos[:10]
    return {
        "next": next_id,
        "results": [repo_json(r) for r in repos]
    }

@api.route("/api/repos/~<owner>/<name>")
def repos_by_name_GET(owner, name):
    user, repo = check_repo(owner, name)
    if isinstance(repo, Redirect):
        return redirect(url_for(".repos_by_name_GET",
            owner=owner, name=repo.new_repo.name))
    return repo_json(repo)

def prop(valid, resource, prop, **kwargs):
    value = valid.optional(prop, **kwargs)
    if value:
        setattr(resource, prop, value)

@api.route("/api/repos/~<owner>/<name>", methods=["PUT"])
@oauth("repos:write")
def repos_by_name_PUT(oauth_token, owner, name):
    user, repo = check_repo(owner, name, authorized=oauth_token.user)
    if isinstance(repo, Redirect):
        abort(404)
    valid = Validation(request)
    prop(valid, repo, "visibility", cls=RepoVisibility)
    prop(valid, repo, "description", cls=str)
    db.session.commit()
    return repo_json(repo)

@api.route("/api/webhooks")
@oauth("webhooks")
def webhooks_GET(oauth_token):
    start = request.args.get('start') or -1
    webhooks = (Webhook.query
        .filter(Webhook.user_id == oauth_token.user_id)
        .filter(Webhook.repo_id == None)
    )
    if start != -1:
        webhooks = webhooks.filter(Webhook.id <= start)
    webhooks = webhooks.order_by(Webhook.id.desc()).limit(11).all()
    if len(webhooks) != 11:
        next_id = -1
    else:
        next_id = webhooks[-1].id
        webhooks = webhooks[:10]
    return {
        "next": next_id,
        "results": [wh_json(wh) for wh in webhooks]
    }

@api.route("/api/webhooks", methods=["POST"])
@oauth("webhooks:write")
def webhooks_POST(oauth_token):
    valid = Validation(request)
    desc = valid.optional("description", cls=str)
    url = valid.require("url")
    valid.expect(not url or valid_url(url), "This URL is invalid", field="url")
    validate_ssl = valid.optional("validate_ssl", cls=bool, default=True)
    repo = valid.optional("repo", cls=str)
    if repo:
        [owner, name] = repo.split("/")
        if owner.starswith("~"):
            owner = owner[1:]
        # TODO: don't abort here
        _, repo = check_repo(owner, name, authorized=oauth_token.user)
    if not valid.ok:
        return valid.response
    wh = Webhook()
    wh.description = desc
    wh.url = url
    wh.validate_ssl = validate_ssl
    wh.user_id = oauth_token.user_id
    wh.repo_id = repo.id if repo else None
    wh.oauth_token_id = oauth_token.id
    db.session.add(wh)
    db.session.commit()
    return wh_json(wh)

M gitsrht/types/__init__.py => gitsrht/types/__init__.py +0 -1
@@ 8,6 8,5 @@ class OAuthToken(Base, ExternalOAuthTokenMixin):
    pass

from .repository import Repository, RepoVisibility
from .webhook import Webhook
from .redirect import Redirect
from .access import Access, AccessMode

D gitsrht/types/webhook.py => gitsrht/types/webhook.py +0 -26
@@ 1,26 0,0 @@
import sqlalchemy as sa
import sqlalchemy_utils as sau
from srht.database import Base

class Webhook(Base):
    __tablename__ = "webhook"
    id = sa.Column(sa.Integer, primary_key=True)
    created = sa.Column(sa.DateTime, nullable=False)
    updated = sa.Column(sa.DateTime, nullable=False)
    description = sa.Column(sa.Unicode(1024))

    oauth_token_id = sa.Column(sa.Integer,
            sa.ForeignKey("oauthtoken.id", ondelete="CASCADE"))
    oauth_token = sa.orm.relationship("OAuthToken",
            backref=sa.orm.backref("webhooks", cascade="all, delete"))

    user_id = sa.Column(sa.Integer, sa.ForeignKey("user.id"), nullable=False)
    user = sa.orm.relationship("User", backref=sa.orm.backref("webhooks"))

    repo_id = sa.Column(sa.Integer,
            sa.ForeignKey("repository.id", ondelete="CASCADE"))
    repository = sa.orm.relationship("Repository",
            backref=sa.orm.backref("webhooks", cascade="all, delete"))

    url = sa.Column(sa.Unicode(2048), nullable=False)
    validate_ssl = sa.Column(sa.Boolean, nullable=False, default=True)