|
| 1 | +from datetime import datetime, timedelta |
| 2 | +from bson.objectid import ObjectId |
| 3 | +from fastapi import APIRouter, Request, Response, status, Depends, HTTPException |
| 4 | +from pydantic import EmailStr |
| 5 | + |
| 6 | +from app import oauth2 |
| 7 | +from app.database import User |
| 8 | +from app.serializers import userEntity, userResponseEntity |
| 9 | +from .. import schemas, utils |
| 10 | +from app.oauth2 import AuthJWT |
| 11 | +from ..config import settings |
| 12 | + |
| 13 | + |
| 14 | +router = APIRouter() |
| 15 | +ACCESS_TOKEN_EXPIRES_IN = settings.ACCESS_TOKEN_EXPIRES_IN |
| 16 | +REFRESH_TOKEN_EXPIRES_IN = settings.REFRESH_TOKEN_EXPIRES_IN |
| 17 | + |
| 18 | + |
| 19 | +@router.post('/register', status_code=status.HTTP_201_CREATED, response_model=schemas.UserResponse) |
| 20 | +async def create_user(payload: schemas.CreateUserSchema): |
| 21 | + # Check if user already exist |
| 22 | + user = User.find_one({'email': payload.email.lower()}) |
| 23 | + if user: |
| 24 | + raise HTTPException(status_code=status.HTTP_409_CONFLICT, |
| 25 | + detail='Account already exist') |
| 26 | + # Compare password and passwordConfirm |
| 27 | + if payload.password != payload.passwordConfirm: |
| 28 | + raise HTTPException( |
| 29 | + status_code=status.HTTP_400_BAD_REQUEST, detail='Passwords do not match') |
| 30 | + # Hash the password |
| 31 | + payload.password = utils.hash_password(payload.password) |
| 32 | + del payload.passwordConfirm |
| 33 | + payload.role = 'user' |
| 34 | + payload.verified = True |
| 35 | + payload.email = payload.email.lower() |
| 36 | + payload.created_at = datetime.utcnow() |
| 37 | + payload.updated_at = payload.created_at |
| 38 | + result = User.insert_one(payload.dict()) |
| 39 | + new_user = userResponseEntity(User.find_one({'_id': result.inserted_id})) |
| 40 | + return {"status": "success", "user": new_user} |
| 41 | + |
| 42 | + |
| 43 | +@router.post('/login') |
| 44 | +def login(payload: schemas.LoginUserSchema, response: Response, Authorize: AuthJWT = Depends()): |
| 45 | + # Check if the user exist |
| 46 | + user = userEntity(User.find_one({'email': payload.email.lower()})) |
| 47 | + if not user: |
| 48 | + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, |
| 49 | + detail='Incorrect Email or Password') |
| 50 | + |
| 51 | + # Check if user verified his email |
| 52 | + if not user['verified']: |
| 53 | + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, |
| 54 | + detail='Please verify your email address') |
| 55 | + |
| 56 | + # Check if the password is valid |
| 57 | + if not utils.verify_password(payload.password, user['password']): |
| 58 | + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, |
| 59 | + detail='Incorrect Email or Password') |
| 60 | + |
| 61 | + # Create access token |
| 62 | + access_token = Authorize.create_access_token( |
| 63 | + subject=str(user["id"]), expires_time=timedelta(minutes=ACCESS_TOKEN_EXPIRES_IN)) |
| 64 | + |
| 65 | + # Create refresh token |
| 66 | + refresh_token = Authorize.create_refresh_token( |
| 67 | + subject=str(user["id"]), expires_time=timedelta(minutes=REFRESH_TOKEN_EXPIRES_IN)) |
| 68 | + |
| 69 | + # Store refresh and access tokens in cookie |
| 70 | + response.set_cookie('access_token', access_token, ACCESS_TOKEN_EXPIRES_IN * 60, |
| 71 | + ACCESS_TOKEN_EXPIRES_IN * 60, '/', None, False, True, 'lax') |
| 72 | + response.set_cookie('refresh_token', refresh_token, |
| 73 | + REFRESH_TOKEN_EXPIRES_IN * 60, REFRESH_TOKEN_EXPIRES_IN * 60, '/', None, False, True, 'lax') |
| 74 | + response.set_cookie('logged_in', 'True', ACCESS_TOKEN_EXPIRES_IN * 60, |
| 75 | + ACCESS_TOKEN_EXPIRES_IN * 60, '/', None, False, False, 'lax') |
| 76 | + |
| 77 | + # Send both access |
| 78 | + return {'status': 'success', 'access_token': access_token} |
| 79 | + |
| 80 | + |
| 81 | +@router.get('/refresh') |
| 82 | +def refresh_token(response: Response, Authorize: AuthJWT = Depends()): |
| 83 | + try: |
| 84 | + Authorize.jwt_refresh_token_required() |
| 85 | + |
| 86 | + user_id = Authorize.get_jwt_subject() |
| 87 | + if not user_id: |
| 88 | + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, |
| 89 | + detail='Could not refresh access token') |
| 90 | + user = userEntity(User.find_one({'_id': ObjectId(str(user_id))})) |
| 91 | + if not user: |
| 92 | + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, |
| 93 | + detail='The user belonging to this token no logger exist') |
| 94 | + access_token = Authorize.create_access_token( |
| 95 | + subject=str(user["id"]), expires_time=timedelta(minutes=ACCESS_TOKEN_EXPIRES_IN)) |
| 96 | + except Exception as e: |
| 97 | + error = e.__class__.__name__ |
| 98 | + if error == 'MissingTokenError': |
| 99 | + raise HTTPException( |
| 100 | + status_code=status.HTTP_400_BAD_REQUEST, detail='Please provide refresh token') |
| 101 | + raise HTTPException( |
| 102 | + status_code=status.HTTP_400_BAD_REQUEST, detail=error) |
| 103 | + |
| 104 | + response.set_cookie('access_token', access_token, ACCESS_TOKEN_EXPIRES_IN * 60, |
| 105 | + ACCESS_TOKEN_EXPIRES_IN * 60, '/', None, False, True, 'lax') |
| 106 | + response.set_cookie('logged_in', 'True', ACCESS_TOKEN_EXPIRES_IN * 60, |
| 107 | + ACCESS_TOKEN_EXPIRES_IN * 60, '/', None, False, False, 'lax') |
| 108 | + return {'access_token': access_token} |
| 109 | + |
| 110 | + |
| 111 | +@router.get('/logout', status_code=status.HTTP_200_OK) |
| 112 | +def logout(response: Response, Authorize: AuthJWT = Depends(), user_id: str = Depends(oauth2.require_user)): |
| 113 | + Authorize.unset_jwt_cookies() |
| 114 | + response.set_cookie('logged_in', '', -1) |
| 115 | + |
| 116 | + return {'status': 'success'} |
0 commit comments