1
- from fastapi import status ,APIRouter
1
+ from fastapi import status , APIRouter
2
2
from fastapi .responses import JSONResponse
3
3
from utils .jwt_manager import create_token
4
- from schemas .user import User ,UserBase ,UserCreate
4
+ from schemas .user import User , UserBase , UserCreate
5
5
from config .database import Session
6
6
from services .user import UserService
7
7
from services .auth import Auth
8
8
9
9
user_router = APIRouter ()
10
+ db = Session ()
11
+
12
+
13
+ @user_router .post ('/users' , tags = ['Auth' ], response_model = User , status_code = status .HTTP_200_OK )
14
+ def create_user (user : UserCreate ):
15
+ check_user_exists (user )
10
16
11
- @user_router .post ('/users' ,tags = ['Auth' ],response_model = User ,status_code = status .HTTP_200_OK )
12
- def create_user (user :UserCreate ):
13
-
14
- db = Session ()
15
-
16
- result = UserService (db ).get_user_by_email (email = user .email )
17
-
18
- if result :
19
-
20
- return JSONResponse (status_code = status .HTTP_400_BAD_REQUEST ,content = {"message" :"User already exists" })
21
-
22
17
UserService (db ).create_user (user )
23
-
24
- return JSONResponse (status_code = status .HTTP_200_OK ,content = {"message" :"User created" })
25
-
26
-
27
- @user_router .post ('/login' ,tags = ['Auth' ],status_code = status .HTTP_200_OK )
28
- def login (user :UserCreate ):
29
-
30
- db = Session ()
31
- result = UserService (db ).get_user_by_email (email = user .email )
32
-
33
- if not (result and Auth ().verify_password (user .password ,result .password )):
34
-
35
- return JSONResponse (status_code = status .HTTP_401_UNAUTHORIZED ,content = {"message" :"Unauthorized" })
36
-
37
- token :str = create_token (user .dict ())
38
-
39
- return JSONResponse (status_code = status .HTTP_200_OK ,content = token )
18
+
19
+ return JSONResponse (status_code = status .HTTP_200_OK , content = {"message" : "User created" })
20
+
21
+
22
+ def check_user_exists (user ):
23
+ if UserService (db ).get_user_by_email (email = user .email ):
24
+ return JSONResponse (status_code = status .HTTP_400_BAD_REQUEST , content = {"message" : "User already exists" })
25
+
26
+
27
+ @user_router .post ('/login' , tags = ['Auth' ], status_code = status .HTTP_200_OK )
28
+ def login (user : UserCreate ):
29
+ validate_password (user )
30
+
31
+ token : str = create_token (user .dict ())
32
+
33
+ return JSONResponse (status_code = status .HTTP_200_OK , content = token )
34
+
35
+
36
+ def validate_password (user ):
37
+ user_found = UserService (db ).get_user_by_email (email = user .email )
38
+
39
+ if not (user_found and Auth ().verify_password (user .password , user_found .password )):
40
+ return JSONResponse (status_code = status .HTTP_401_UNAUTHORIZED , content = {"message" : "Unauthorized" })
0 commit comments