Skip to content

Commit

Permalink
Authorized Custom Feed (user-specific results) (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarshalX authored Jan 12, 2024
1 parent 2977b0f commit e71d71e
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
atproto==0.0.35
atproto==0.0.37
peewee~=3.16.2
Flask~=2.3.2
python-dotenv~=1.0.0
9 changes: 9 additions & 0 deletions server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ def get_feed_skeleton():
if not algo:
return 'Unsupported algorithm', 400

# Example of how to check auth if giving user-specific results:
"""
from server.auth import AuthorizationError, validate_auth
try:
requester_did = validate_auth(request)
except AuthorizationError:
return 'Unauthorized', 401
"""

try:
cursor = request.args.get('cursor', default=None, type=str)
limit = request.args.get('limit', default=20, type=int)
Expand Down
41 changes: 41 additions & 0 deletions server/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from atproto import DidInMemoryCache, IdResolver, verify_jwt
from atproto.exceptions import TokenInvalidSignatureError
from flask import Request


_CACHE = DidInMemoryCache()
_ID_RESOLVER = IdResolver(cache=_CACHE)

_AUTHORIZATION_HEADER_NAME = 'Authorization'
_AUTHORIZATION_HEADER_VALUE_PREFIX = 'Bearer '


class AuthorizationError(Exception):
...


def validate_auth(request: 'Request') -> str:
"""Validate authorization header.
Args:
request: The request to validate.
Returns:
:obj:`str`: Requester DID.
Raises:
:obj:`AuthorizationError`: If the authorization header is invalid.
"""
auth_header = request.headers.get(_AUTHORIZATION_HEADER_NAME)
if not auth_header:
raise AuthorizationError('Authorization header is missing')

if not auth_header.startswith(_AUTHORIZATION_HEADER_VALUE_PREFIX):
raise AuthorizationError('Invalid authorization header')

jwt = auth_header[len(_AUTHORIZATION_HEADER_VALUE_PREFIX) :].strip()

try:
return verify_jwt(jwt, _ID_RESOLVER.did.resolve_atproto_key).iss
except TokenInvalidSignatureError as e:
raise AuthorizationError('Invalid signature') from e

0 comments on commit e71d71e

Please sign in to comment.