core/auth/authenticate.py

81 lines
2.8 KiB
Python
Raw Normal View History

2022-09-14 04:42:31 +00:00
from functools import wraps
from typing import Optional, Tuple
from graphql.type import GraphQLResolveInfo
2022-09-14 04:42:31 +00:00
from starlette.authentication import AuthenticationBackend
from starlette.requests import HTTPConnection
2022-09-14 04:42:31 +00:00
from auth.credentials import AuthCredentials, AuthUser
from services.auth.users import UserStorage
2022-11-22 03:11:26 +00:00
from settings import SESSION_TOKEN_HEADER
2022-11-24 14:31:52 +00:00
from auth.tokenstorage import SessionToken
from base.exceptions import InvalidToken
2022-09-14 04:42:31 +00:00
class JWTAuthenticate(AuthenticationBackend):
async def authenticate(
self, request: HTTPConnection
) -> Optional[Tuple[AuthCredentials, AuthUser]]:
2022-11-22 03:11:26 +00:00
if SESSION_TOKEN_HEADER not in request.headers:
2022-09-14 04:42:31 +00:00
return AuthCredentials(scopes=[]), AuthUser(user_id=None)
2022-11-24 14:31:52 +00:00
token = request.headers.get(SESSION_TOKEN_HEADER)
if not token:
print("[auth.authenticate] no token in header %s" % SESSION_TOKEN_HEADER)
return AuthCredentials(scopes=[], error_message=str("no token")), AuthUser(
user_id=None
)
2022-11-22 03:11:26 +00:00
2022-09-14 04:42:31 +00:00
try:
2022-11-24 14:31:52 +00:00
if len(token.split('.')) > 1:
payload = await SessionToken.verify(token)
else:
InvalidToken("please try again")
2022-09-14 04:42:31 +00:00
except Exception as exc:
2022-11-23 09:57:58 +00:00
print("[auth.authenticate] session token verify error")
print(exc)
2022-09-14 04:42:31 +00:00
return AuthCredentials(scopes=[], error_message=str(exc)), AuthUser(
user_id=None
)
if payload is None:
return AuthCredentials(scopes=[]), AuthUser(user_id=None)
user = await UserStorage.get_user(payload.user_id)
if not user:
return AuthCredentials(scopes=[]), AuthUser(user_id=None)
scopes = await user.get_permission()
return (
AuthCredentials(user_id=payload.user_id, scopes=scopes, logged_in=True),
user,
)
def login_required(func):
@wraps(func)
async def wrap(parent, info: GraphQLResolveInfo, *args, **kwargs):
2022-10-23 09:33:28 +00:00
# print('[auth.authenticate] login required for %r with info %r' % (func, info)) # debug only
2022-09-14 04:42:31 +00:00
auth: AuthCredentials = info.context["request"].auth
if not auth.logged_in:
return {"error": auth.error_message or "Please login"}
return await func(parent, info, *args, **kwargs)
return wrap
2022-11-24 08:27:01 +00:00
def permission_required(resource, operation, func):
@wraps(func)
async def wrap(parent, info: GraphQLResolveInfo, *args, **kwargs):
2022-11-24 15:19:58 +00:00
print('[auth.authenticate] permission_required for %r with info %r' % (func, info)) # debug only
2022-11-24 08:27:01 +00:00
auth: AuthCredentials = info.context["request"].auth
if not auth.logged_in:
return {"error": auth.error_message or "Please login"}
# TODO: add check permission logix
return await func(parent, info, *args, **kwargs)
return wrap