def get_user(token: Optional[str] = Depends(get_token)) -> Optional[UserAPI]: if token: # get user data token_data: Optional[TokenData] = token_validate(token) if token_data: user: UserAPI = UserAPI.parse_obj( User.get(id=token_data.sub).to_dict()) if user.is_active: return user return None
async def login(request: Request, form: OAuth2PasswordRequestForm = Depends()): """Create login page""" username: str = form.username password: str = form.password if User.get(username=username): user: Optional[UserAPI] = UserAPI.parse_obj( User.get(username=username).to_dict()) else: request.session[ "fail_login_message"]: str = f"Username '{username}' doesn't exist!" return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER) # validate user if not pwd_verify(password, user.password if user else ""): # raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid user or password") request.session[ "fail_login_message"]: str = f"Invalid Username or Password!" return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER) # build data data: TokenData = TokenData(sub=user.id, exp=time_utc_now() + timedelta(seconds=JWT_TOKEN_EXPIRE)) # generate token token: JWTToken = token_create(JWT_KEY, JWT_ALGORITHM, data) # save token value to the session request.session["token"] = token.access_token return RedirectResponse(url="/", status_code=status.HTTP_303_SEE_OTHER)
async def create_user( request: Request, data: UserAPI, user: Optional[UserAPI] = Depends(get_user)) -> Any: if user is None or user.role != UserRole.super: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Token"}, ) # check if such username exists if User.get(username=data.username): request.session["username_exists"] = f"Such Username already exists!" raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST) data.password = pwd_hash(data.password) data.projects = [ Project.get(id=project_id) for project_id in data.projects ] return UserAPI.parse_obj(User.create(data.dict()).to_dict())