1- from fastapi import status ,APIRouter
1+ from fastapi import status , APIRouter
22from fastapi .responses import JSONResponse
33from utils .jwt_manager import create_token
4- from schemas .user import User ,UserBase ,UserCreate
4+ from schemas .user import User , UserBase , UserCreate
55from config .database import Session
66from services .user import UserService
77from services .auth import Auth
88
99user_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 )
1016
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-
2217 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