Skip to content

Commit

Permalink
added cookie to response on tg login success
Browse files Browse the repository at this point in the history
  • Loading branch information
ychebyshev committed Mar 1, 2024
1 parent b5046ef commit 34a2f8b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 11 deletions.
19 changes: 8 additions & 11 deletions shvatka/api/routes/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
from starlette.responses import HTMLResponse, Response

from shvatka.api.config.models.auth import AuthConfig
from shvatka.api.models.auth import UserTgAuth, Token
from shvatka.api.models.auth import UserTgAuth
from shvatka.api.utils.cookie_auth import set_auth_response
from shvatka.core.services.user import upsert_user
from shvatka.infrastructure.db.dao.holder import HolderDao
from shvatka.api.dependencies.auth import AuthProperties, check_tg_hash
Expand Down Expand Up @@ -41,27 +42,23 @@ async def login(
):
user = await auth_properties.authenticate_user(form_data.username, form_data.password, dao)
token = auth_properties.create_user_token(user)
response.set_cookie(
"Authorization",
value=f"{token.token_type} {token.access_token}",
samesite=config.samesite,
domain=config.domain,
httponly=config.httponly,
secure=config.secure,
)
set_auth_response(config, response, token)
return {"ok": True}


@inject
async def tg_login_result(
response: Response,
user: Annotated[UserTgAuth, fDepends()],
dao: Annotated[HolderDao, Depends()],
auth_properties: Annotated[AuthProperties, Depends()],
config: Annotated[AuthConfig, Depends()],
) -> Token:
):
check_tg_hash(user, config.bot_token)
await upsert_user(user.to_dto(), dao.user)
return auth_properties.create_user_token(user.to_dto())
token = auth_properties.create_user_token(user.to_dto())
set_auth_response(config, response, token)
return {"ok": True}


@inject
Expand Down
13 changes: 13 additions & 0 deletions shvatka/api/utils/cookie_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel, OAuthFlowPassword
from fastapi.security import OAuth2
from fastapi.security.utils import get_authorization_scheme_param
from starlette.responses import Response

from shvatka.api.config.models.auth import AuthConfig
from shvatka.api.models.auth import Token


Expand Down Expand Up @@ -37,3 +39,14 @@ def get_token(self, request: Request) -> Optional[Token]:
)
return None
return Token(access_token=param, token_type="bearer")


def set_auth_response(config: AuthConfig, response: Response, token: Token) -> None:
response.set_cookie(
"Authorization",
value=f"{token.token_type} {token.access_token}",
samesite=config.samesite,
domain=config.domain,
httponly=config.httponly,
secure=config.secure,
)

0 comments on commit 34a2f8b

Please sign in to comment.