-
Notifications
You must be signed in to change notification settings - Fork 148
feat(api): add scoped persistent access token infrastructure #790
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
DavidMStraub
merged 8 commits into
gramps-project:master
from
elig-45:anniversary-ics-api
Jun 28, 2026
Merged
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
260c818
feat(api): add scoped persistent access token infrastructure
elig-45 48a708e
test(api): add persistent access token endpoint tests
elig-45 9641d94
fix(api): call permission check inside access token handlers
elig-45 c24029b
Update __init__.py
elig-45 77658aa
Update 6d8f3cb50b71_add_persistent_access_tokens_table.py
elig-45 f1d3eba
fix(api): hash persistent access tokens and hide token on GET
elig-45 ea521e0
fix(alembic): rebase access-token migration onto latest head
elig-45 4b686e6
single named unique index for token_hash instead of redundant column-…
elig-45 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
64 changes: 64 additions & 0 deletions
64
alembic_users/versions/6d8f3cb50b71_add_persistent_access_tokens_table.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| """add persistent access tokens table | ||
|
|
||
| Revision ID: 6d8f3cb50b71 | ||
| Revises: c1d2e3f4a5b6 | ||
| Create Date: 2026-03-31 00:25:00.000000 | ||
|
|
||
| """ | ||
|
|
||
| from alembic import op | ||
| import sqlalchemy as sa | ||
| from sqlalchemy.engine.reflection import Inspector | ||
|
|
||
| from gramps_webapi.auth.sql_guid import GUID | ||
|
|
||
|
|
||
| # revision identifiers, used by Alembic. | ||
| revision = "6d8f3cb50b71" | ||
| down_revision = "c1d2e3f4a5b6" | ||
| branch_labels = None | ||
| depends_on = None | ||
|
|
||
|
|
||
| def upgrade(): | ||
| conn = op.get_bind() | ||
| inspector = Inspector.from_engine(conn) | ||
| tables = inspector.get_table_names() | ||
| if "access_tokens" in tables: | ||
| # If table already exists, do nothing | ||
| return None | ||
|
|
||
| op.create_table( | ||
| "access_tokens", | ||
| sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True), | ||
| sa.Column("user_id", GUID(), nullable=False), | ||
| sa.Column("scope", sa.String(length=64), nullable=False), | ||
| sa.Column("token_hash", sa.String(length=64), nullable=True), | ||
| sa.Column( | ||
| "created_at", | ||
| sa.DateTime(), | ||
| nullable=False, | ||
| server_default=sa.func.now(), | ||
| ), | ||
| sa.Column( | ||
| "updated_at", | ||
| sa.DateTime(), | ||
| nullable=False, | ||
| server_default=sa.func.now(), | ||
| ), | ||
| sa.Column("revoked_at", sa.DateTime(), nullable=True), | ||
| sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"), | ||
| sa.UniqueConstraint("user_id", "scope", name="uq_access_tokens_user_scope"), | ||
| ) | ||
| op.create_index("ix_access_tokens_user_id", "access_tokens", ["user_id"], unique=False) | ||
| op.create_index("ix_access_tokens_scope", "access_tokens", ["scope"], unique=False) | ||
| op.create_index( | ||
| "ix_access_tokens_token_hash", "access_tokens", ["token_hash"], unique=True | ||
| ) | ||
|
|
||
|
|
||
| def downgrade(): | ||
| op.drop_index("ix_access_tokens_token_hash", table_name="access_tokens") | ||
| op.drop_index("ix_access_tokens_scope", table_name="access_tokens") | ||
| op.drop_index("ix_access_tokens_user_id", table_name="access_tokens") | ||
| op.drop_table("access_tokens") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| # | ||
| # Gramps Web API - A RESTful API for the Gramps genealogy program | ||
| # | ||
| # Copyright (C) 2026 Gramps Web contributors | ||
| # | ||
| # This program is free software; you can redistribute it and/or modify | ||
| # it under the terms of the GNU Affero General Public License as published by | ||
| # the Free Software Foundation; either version 3 of the License, or | ||
| # (at your option) any later version. | ||
| # | ||
|
|
||
| """Persistent access token resources.""" | ||
|
|
||
| from flask_jwt_extended import get_jwt_identity | ||
| from marshmallow import Schema | ||
| from webargs import fields | ||
|
|
||
| from ...auth import ( | ||
| get_name, | ||
| has_user_access_token, | ||
| normalize_access_token_scope, | ||
| revoke_user_access_token, | ||
| rotate_user_access_token, | ||
| ) | ||
| from ...auth.const import PERM_EDIT_OWN_USER | ||
| from ..auth import require_permissions | ||
| from ..blueprint import api_blueprint | ||
| from ..util import abort_with_message | ||
| from . import ProtectedResource | ||
|
|
||
|
|
||
| class AccessTokenStatusSchema(Schema): | ||
| """Response schema for persistent access token status.""" | ||
|
|
||
| active = fields.Boolean( | ||
| required=True, | ||
| metadata={"description": "Whether a token is currently active."}, | ||
| ) | ||
|
|
||
|
|
||
| class AccessTokenCreateSchema(Schema): | ||
| """Response schema for newly created or rotated persistent token.""" | ||
|
|
||
| active = fields.Boolean( | ||
| required=True, | ||
| metadata={"description": "Whether a token is currently active."}, | ||
| ) | ||
| token = fields.Str( | ||
| required=True, | ||
| metadata={"description": "Newly created persistent token value."}, | ||
| ) | ||
|
|
||
|
|
||
| class UserAccessTokenResource(ProtectedResource): | ||
| """Resource for managing current user's persistent tokens by scope.""" | ||
|
|
||
| def _get_user_name(self) -> str: | ||
| user_id = get_jwt_identity() | ||
| try: | ||
| return get_name(user_id) | ||
| except ValueError: | ||
| abort_with_message(401, "User not found for token ID") | ||
| raise # unreachable | ||
|
|
||
| def _validate_scope(self, scope: str) -> str: | ||
| try: | ||
| return normalize_access_token_scope(scope) | ||
| except ValueError as exc: | ||
| abort_with_message(422, str(exc)) | ||
| raise # unreachable | ||
|
|
||
| @api_blueprint.response(200, AccessTokenStatusSchema()) | ||
| def get(self, scope: str): | ||
| """Get persistent token status for current user and scope.""" | ||
| require_permissions([PERM_EDIT_OWN_USER]) | ||
| scope = self._validate_scope(scope) | ||
| user_name = self._get_user_name() | ||
| active = has_user_access_token(user_name, scope) | ||
| return {"active": active}, 200 | ||
|
|
||
| @api_blueprint.response(200, AccessTokenCreateSchema()) | ||
| def post(self, scope: str): | ||
| """Create or rotate persistent token for current user and scope.""" | ||
| require_permissions([PERM_EDIT_OWN_USER]) | ||
| scope = self._validate_scope(scope) | ||
| user_name = self._get_user_name() | ||
| token = rotate_user_access_token(user_name, scope) | ||
| return {"active": True, "token": token}, 200 | ||
|
|
||
| @api_blueprint.response(200, AccessTokenStatusSchema()) | ||
| def delete(self, scope: str): | ||
| """Revoke persistent token for current user and scope.""" | ||
| require_permissions([PERM_EDIT_OWN_USER]) | ||
| scope = self._validate_scope(scope) | ||
| user_name = self._get_user_name() | ||
| revoke_user_access_token(user_name, scope) | ||
| return {"active": False}, 200 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.