Add ability to limit APITokens to a package

This commit is contained in:
rubenwardy 2020-01-24 19:26:00 +00:00
parent 2fa2c3afec
commit 6f1472addb
4 changed files with 41 additions and 1 deletions

@ -29,6 +29,8 @@ from wtforms.ext.sqlalchemy.fields import QuerySelectField
class CreateAPIToken(FlaskForm):
name = StringField("Name", [InputRequired(), Length(1, 30)])
package = QuerySelectField("Limit to package", allow_blank=True, \
get_pk=lambda a: a.id, get_label=lambda a: a.title)
submit = SubmitField("Save")
@ -70,6 +72,8 @@ def create_edit_token(username, id=None):
access_token = session.pop("token_" + str(id), None)
form = CreateAPIToken(formdata=request.form, obj=token)
form.package.query_factory = lambda: Package.query.filter_by(author=user).all()
if request.method == "POST" and form.validate():
if is_new:
token = APIToken()

@ -864,12 +864,21 @@ class PackageScreenshot(db.Model):
class APIToken(db.Model):
id = db.Column(db.Integer, primary_key=True)
access_token = db.Column(db.String(34), unique=True)
name = db.Column(db.String(100), nullable=False)
owner_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
# owner is created using backref
created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow)
package_id = db.Column(db.Integer, db.ForeignKey("package.id"), nullable=True)
package = db.relationship("Package", foreign_keys=[package_id])
def canOperateOnPackage(self, package):
return packages.count() == 0 or package in packages
if self.package and self.package != None:
return False
return package.owner == self.owner
class EditRequest(db.Model):

@ -47,6 +47,7 @@
{{ form.hidden_tag() }}
{{ render_field(form.name, placeholder="Human readable") }}
{{ render_field(form.package) }}
{{ render_submit_field(form.submit) }}
</form>

@ -0,0 +1,26 @@
"""empty message
Revision ID: df66c78e6791
Revises: a0f6c8743362
Create Date: 2020-01-24 18:39:58.363417
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = 'df66c78e6791'
down_revision = 'a0f6c8743362'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('api_token', sa.Column('package_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'api_token', 'package', ['package_id'], ['id'])
def downgrade():
op.drop_constraint(None, 'api_token', type_='foreignkey')
op.drop_column('api_token', 'package_id')