Coverage for apps/kwai-api/src/kwai_api/v1/auth/endpoints/validation.py: 78%

18 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2024-01-01 00:00 +0000

1"""Module that defines some endpoints to validate a login.""" 

2 

3from typing import Annotated 

4 

5from fastapi import APIRouter, HTTPException, status 

6from fastapi.params import Depends 

7from kwai_bc_club.domain.club_coach import ClubCoachEntity 

8from kwai_bc_identity.users.user import UserEntity 

9 

10from kwai_api.dependencies import get_current_user 

11from kwai_api.security_dependencies import check_login, get_coach 

12 

13 

14router = APIRouter() 

15 

16 

17@router.get( 

18 "/validate", 

19 summary="Validate a current login", 

20 responses={ 

21 200: {"description": "The access token is still valid."}, 

22 401: {"description": "Not authorized."}, 

23 }, 

24) 

25async def validate( 

26 is_logged_in: Annotated[bool, Depends(check_login)], 

27): 

28 """Validate the user. 

29 

30 When the user has an expired access token it will automatically be renewed when the refresh token 

31 is still valid. 

32 """ 

33 if not is_logged_in: 

34 raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) 

35 

36 

37@router.get( 

38 "/validate/coach", 

39 summary="Validate a current login for a coach", 

40 responses={ 

41 200: {"description": "The access token is still valid."}, 

42 401: {"description": "Not authorized. The user was not logged in."}, 

43 403: {"description": "Forbidden. The user is not an administrator or a coach."}, 

44 }, 

45) 

46async def validate_coach( 

47 is_logged_in: Annotated[bool, Depends(check_login)], 

48 user: Annotated[UserEntity, Depends(get_current_user)], 

49 coach: Annotated[ClubCoachEntity, Depends(get_coach)], 

50): 

51 """Validate a coach session. 

52 

53 Renews the access token if necessary and checks if the user is a coach or an administrator. 

54 """ 

55 if not is_logged_in: 

56 raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) 

57 

58 if not user.admin and coach is None: 

59 raise HTTPException( 

60 status_code=status.HTTP_403_FORBIDDEN, 

61 detail="You must be an administrator or a coach.", 

62 )