def authenticate_user(db: Session, username: str, password: str): user = get_user_by_email(db, username) if not user: return False if not verify_password(password, user.password): return False return user
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): db_user = crud.get_user_by_email(db, email=user.email) if db_user: raise HTTPException(status_code=400, detail="Email already registered") db_user = crud.get_user_by_name(db, name=user.name) if db_user: raise HTTPException(status_code=400, detail="Name already registered") return crud.create_user(db=db, user=user)
async def login_user(user: schemas.UserLogin, db: Session = Depends(utils.get_db)): db_user = crud.get_user_by_email(db, email_id=user.email_id) if not db_user: raise HTTPException(status_code=400, detail="User not found") if db_user.passwd_hashed != user.passwd_hashed: raise HTTPException(status_code=401, detail="Incorrect password") return db_user
def create_user( user: UserCreate, db: Session = Depends(get_db), # current_user: User = Depends(get_admin_user), # This is commented for development and testin purposes ): db_user = crud.get_user_by_email(db, email=user.email) if db_user: raise HTTPException(status_code=400, detail="Email already registered") return crud.create_user(db=db, user=user)
async def update_user_password(user: schemas.UserPasswdUpdate, db: Session = Depends(utils.get_db)): db_user = crud.get_user_by_email(db, email_id=user.email_id) if not db_user: raise HTTPException(status_code=400, detail="User not found") if db_user.passwd_hashed != user.old_passwd_hashed: raise HTTPException(status_code=401, detail="Incorrect password") if db_user.passwd_hashed == user.new_passwd_hashed: raise HTTPException(status_code=400, detail="New password cannot be same as old") return crud.update_user_passwd(db=db, email_id=user.email_id, new_passwd_hashed=user.new_passwd_hashed)
async def get_current_user(token: str = Depends(oauth2_scheme)): credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) username: str = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) except PyJWTError: raise credentials_exception db = SessionLocal() user = get_user_by_email(db, email=token_data.username) db.close() if user is None: raise credentials_exception return user
def read_user_me(email: str, db: Session = Depends(get_db)): db_user = crud.get_user_by_email(db, email) if db_user is None: raise HTTPException(status_code=404, detail="User not found") return db_user
async def register_user(user: schemas.UserRegister, db: Session = Depends(utils.get_db)): db_user = crud.get_user_by_email(db, email_id=user.email_id) if db_user: raise HTTPException(status_code=400, detail="User already exists") return crud.create_user(db=db, user=user)