feat: billing guest access

This commit is contained in:
2024-08-08 07:49:53 +03:00
parent a7c4fabed0
commit 97f835ffde
30 changed files with 682 additions and 140 deletions

View File

@@ -19,8 +19,10 @@ oauth2_schema = HTTPBearer()
algorithm = 'HS256'
async def get_current_user(session: Annotated[AsyncSession, Depends(get_session)],
token: Annotated[HTTPAuthorizationCredentials, Depends(oauth2_schema)]) -> User | None:
async def get_current_user(
session: Annotated[AsyncSession, Depends(get_session)],
token: Annotated[HTTPAuthorizationCredentials, Depends(oauth2_schema)]
) -> Union[User, None, dict]:
if not token.credentials:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Invalid token')
try:
@@ -28,6 +30,8 @@ async def get_current_user(session: Annotated[AsyncSession, Depends(get_session)
user_id = payload.get('sub')
if not user_id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Invalid credentials')
if user_id == 'guest':
return payload
user_id = int(user_id)
user = await session.get(User, user_id)
@@ -35,16 +39,26 @@ async def get_current_user(session: Annotated[AsyncSession, Depends(get_session)
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Invalid credentials')
return user
except JWTError as e:
print(e)
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Invalid token')
async def authorized_user(
user: Annotated[User, Depends(get_current_user)]
):
if type(user) is User:
return user
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Invalid token')
async def guest_user(user: Annotated[User, Depends(get_current_user)]):
if (type(user) is User) or (type(user) is dict):
return user
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Invalid token')
class AuthService(BaseService):
@staticmethod
def _generate_jwt_token(user: User) -> str:
payload = {
'sub': str(user.id)
}
def _generate_jwt_token(payload: dict) -> str:
return jwt.encode(payload, backend.config.SECRET_KEY, algorithm=algorithm)
async def authenticate(self, request: AuthLoginRequest):
@@ -60,5 +74,16 @@ class AuthService(BaseService):
)
self.session.add(user)
await self.session.commit()
access_token = self._generate_jwt_token(user)
payload = {
'sub': str(user.id)
}
access_token = self._generate_jwt_token(payload)
return AuthLoginResponse(access_token=access_token)
def create_deal_guest_token(self, deal_id: int):
payload = {
'sub': 'guest',
'deal_id': deal_id
}
return self._generate_jwt_token(payload)