Skip to content

Commit

Permalink
added basic auth support
Browse files Browse the repository at this point in the history
  • Loading branch information
ychebyshev committed Apr 11, 2024
1 parent 75c02ff commit 7267227
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions shvatka/api/dependencies/auth.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import base64
import hashlib
import hmac
import logging
Expand Down Expand Up @@ -99,6 +100,16 @@ async def get_current_user(
raise credentials_exception from e
return user

async def get_user_basic(self, request: Request, dao: HolderDao) -> dto.User | None:
if (header := request.headers.get("Authorization")) is None:
return None
schema, token = header.split(" ", maxsplit=1)
if schema.lower() != "basic":
return None
decoded = base64.urlsafe_b64decode(token).decode("utf-8")
username, password = decoded.split(":", maxsplit=1)
return await self.authenticate_user(username, password, dao)


class AuthProvider(Provider):
scope = Scope.APP
Expand All @@ -112,20 +123,22 @@ def get_auth_properties(self, config: AuthConfig) -> AuthProperties:
def get_cookie_auth(self) -> OAuth2PasswordBearerWithCookie:
return OAuth2PasswordBearerWithCookie(token_url="auth/token")

@provide(scope=Scope.REQUEST)
async def get_token(
self, request: Request, cookie_auth: OAuth2PasswordBearerWithCookie
) -> Token:
return cookie_auth.get_token(request)

@provide(scope=Scope.REQUEST)
async def get_current_user(
self,
token: Token,
request: Request,
cookie_auth: OAuth2PasswordBearerWithCookie,
auth_properties: AuthProperties,
dao: HolderDao,
) -> dto.User:
return await auth_properties.get_current_user(token, dao)
try:
token = cookie_auth.get_token(request)
return await auth_properties.get_current_user(token, dao)
except (JWTError, HTTPException):
user = await auth_properties.get_user_basic(request, dao)
if user is None:
raise
return user


def check_tg_hash(user: UserTgAuth, bot_token: str):
Expand Down

0 comments on commit 7267227

Please sign in to comment.