def login_access_token( data: SessionLogin, db: Session = Depends(deps.get_db)) -> Any: """ Endpoint for access token """ user = crud_user.get_user_by_email(db, data.email) credentials_exception = HTTPException(status_code=400, detail="E-mail ou senha incorretos!") if not user: raise credentials_exception if not security.verify_password(data.password, user.hashed_password): raise credentials_exception if not user.is_active: raise HTTPException(status_code=401, detail="Este e-mail ainda não foi verificado. Verifique sua caixa de entrada") if not user.address and data.host == "web": raise HTTPException(status_code=401, detail="Versão web e apenas para cabeleireiros, porfavor user a versão mobile") session = { "user": jsonable_encoder(user), "token": security.generate_token(str(user.id), 'access', datetime.utcnow() + timedelta(days=1)) } return session
def authenticate_user(db, email: str, password: str): user = get_user_by_email(db, email) if not user: return False if not security.verify_password(password, user.hashed_password): return False return user
def update_user( data: UserUpdate, user: UserModel = Depends(deps.get_user), db: Session = Depends(deps.get_db), rdc: RedisCache = Depends(deps.get_redis) ) -> Any: """ Endpoint for update current user """ db_user = crud_user.get_user_by_email(db, data.email) if db_user and db_user.id != user.id: raise HTTPException(status_code=400, detail='Endereço de email já registrador!') data.avatar = user.avatar data.is_active = user.is_active if not data.address and user.address: data.address = user.address user = crud_user.update(db, user, data) rdc.invalidate_cache_provider(user) if user.address: #<-- if have an address, is a provider rdc.invalidate_cache_user(user) rdc.invalidate_cache_prefix("providers-list") return user
def create_user( data: UserCreate, background_tasks: BackgroundTasks, db: Session = Depends(deps.get_db), rdc: RedisCache = Depends(deps.get_redis) ) -> Any: """ Endpoint for create user """ user = crud_user.get_user_by_email(db, data.email) if user: raise HTTPException(status_code=400, detail='Endereço de email já registrador!') user = crud_user.create(db, data) rdc.invalidate_cache_prefix("providers-list") token = security.generate_token(str(user.id), "activate", datetime.utcnow() + timedelta(days=31)) background_tasks.add_task(mail.send_account_activation_email, user.name, user.email, token) return { 'detail': 'Enviamos um e-mail para você confirma seu cadastro, por favor verifique sua caixa de entrada.' }
def create_user(user: UserCreate, background_tasks: BackgroundTasks, db: Session = Depends(get_db)): db_user = crud_user.get_user_by_email(db=db, email=user.email) if db_user: raise HTTPException(status_code=400, detail="Email already registered") if settings.SMTP_SERVER != "your_stmp_server_here": background_tasks.add_task(send_email, user.email, message=f"You've created your account!") return crud_user.create_user(db=db, user=user)
def init() -> None: db = SessionLocal() user = get_user_by_email(db, email=config.SUPERUSER_EMAIL) if not user: create_user( db, UserCreate( email=config.SUPERUSER_EMAIL, password=config.SUPERUSER_PASSWORD, is_active=True, is_superuser=True, ), )
def sign_up_new_user(db, email: str, password: str): user = get_user_by_email(db, email) if user: return False new_user = create_user( db, UserCreate( email=email, password=password, is_active=True, is_superuser=False, ), ) return new_user
def request_forgot_password( data: SessionForget, background_tasks: BackgroundTasks, db: Session = Depends(deps.get_db) ) -> Any: """ Endpoint for recovery password """ user = crud_user.get_user_by_email(db, data.email) if not user: raise HTTPException(status_code=404, detail="Usuário não encontrado!") token = security.generate_token(str(user.id), "reset", datetime.utcnow() + timedelta(hours=2)) background_tasks.add_task(mail.send_reset_password_email, user.name, user.email, token) return {'detail': 'E-mail de recuperação enviado, por favor verifique sua caixa de entrada'}
def login_user(form_data: OAuth2RequestForm = Depends(), db: Session = Depends(get_db)): db_user: User = crud_user.get_user_by_email(db, email=form_data.useremail) if db_user is None: raise HTTPException(status_code=404, detail="User not found") if not verify_password(form_data.password, db_user.password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Bearer"}, ) else: access_token_expires = timedelta(minutes=120) jwt = create_access_token(data={"uuid": db_user.uuid}, expires_delta=access_token_expires) return {"access_token": jwt, "token_type": "bearer"}
def create_user(*, user_in: schemas.user.UserCreate, db: Session = Depends(deps.get_db)): """ Create new user. """ user_by_email = crud_user.get_user_by_email(db, email=user_in.email) if user_by_email: raise HTTPException( status_code=400, detail="The user with this email already exists in the system.") user_by_username = crud_user.get_user_by_username( db, username=user_in.username) if user_by_username: raise HTTPException( status_code=400, detail="The user with this username already exists in the system.") user = crud_user.create_user(db, user=user_in) return user
async def get_current_user( db=Depends(get_db), token: str = Depends(security.oauth2_scheme) ): credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail=Messages.CANT_VALIDATE_CREDENTIALS, headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode( token, config.SECRET_KEY, algorithms=[config.ALGORITHM] ) email: str = payload.get("sub") if email is None: raise credentials_exception permissions: str = payload.get("permissions") token_data = TokenData(email=email, permissions=permissions) except PyJWTError: raise credentials_exception user = get_user_by_email(db, token_data.email) if user is None: raise credentials_exception return user
def check_if_email_exists(email: str, db: Session = Depends(deps.get_db)): user_by_email = crud_user.get_user_by_email(db, email=email) if user_by_email: return {"exists": True} else: return {"exists": False}
def create_user(user: UserCreate, db: Session = Depends(get_db)): db_user: User = crud_user.get_user_by_email(db, email=user.email) if db_user: raise HTTPException(status_code=400, detail="Email already registered") return crud_user.create_user(db=db, user=user)