Coverage for app/services/auth_service.py: 100%

28 statements  

« prev     ^ index     » next       coverage.py v7.6.12, created at 2025-05-02 02:49 +0000

1from flask import session 

2from app.controllers.database import client 

3from app.models.response import * 

4 

5AUTH_URL = "https://api.nickrucinski.com/auth/callback" 

6 

7def login_with_provider(provider: str): 

8 session.clear() # Ensure fresh session 

9 res = client.auth.sign_in_with_oauth( 

10 { 

11 "provider": provider, 

12 "options": { 

13 "redirect_to": AUTH_URL 

14 }, 

15 } 

16 ) 

17 return res 

18 

19def login_with_email( 

20 email: str, 

21 password: str, 

22): 

23 session.clear() # Ensure fresh session 

24 res = client.auth.sign_in_with_password( 

25 { 

26 "email": email, 

27 "password": password, 

28 } 

29 ) 

30 

31 return res 

32 

33def callback(code: str): 

34 """Handles OAuth callback and exchanges code for a session.""" 

35 try: 

36 res = client.auth.exchange_code_for_session({"auth_code": code}) 

37 return res 

38 except Exception as e: 

39 return error_response( 

40 "Authentication failed: {str(e)}", 

41 None, 

42 StatusCodes.UNAUTHORIZED 

43 ) 

44 

45def signout(user_id: str): 

46 """Signs out the user.""" 

47 try: 

48 client.auth.sign_out() 

49 return success_response( 

50 "Signout successful", 

51 None, 

52 StatusCodes.OK 

53 ) 

54 except Exception as e: 

55 return error_response( 

56 "Signout failed: {str(e)}", 

57 None, 

58 StatusCodes.UNAUTHORIZED 

59 ) 

60 

61def signup_with_email( 

62 email: str, 

63 password: str, 

64 first_name: str, 

65 last_name: str, 

66): 

67 """ 

68 Create a user in the database 

69 

70 Args: 

71 first_name (str): The first name of the user. 

72 last_name (str): The last name of the user. 

73 email (str): The email address of the user. 

74 password (str): The user's password (hashed before storage). 

75 

76 Returns: 

77 tuple: A tuple containing: 

78 - dict: The created user data (if successful). 

79 - int: HTTP status code (201 for success, 400 for errors, 500 for server errors). 

80 

81 Raises: 

82 Exception: If there is an issue with database insertion. 

83 """ 

84 # session.clear() # Ensure fresh session 

85 res = client.auth.sign_up( 

86 { 

87 "email": email, 

88 "password": password, 

89 } 

90 ) 

91 

92 client.table("users").insert({ 

93 "id": res.user.id, 

94 "first_name": first_name, 

95 "last_name": last_name, 

96 "email": email, 

97 "status": "ACTIVE", 

98 }).execute() 

99 

100 return res