def update_user( *, db: Session = Depends(get_db), user_id: str, user_in: UserUpdate, environment: str = Depends(get_environment_from_token), current_user: UserInDB = Depends(check_superuser_or_admin), ): """ Update a user. """ user = get(db, user_id=user_id) if not user: return Response(json.dumps({ "messageCode": codes['db'], "title": "Erro no Banco de Dados", "message": ptBr['eUserNotFound'] }), status_code=404) if not user.is_active: return Response(json.dumps({ "messageCode": codes['db'], "title": "Erro no Banco de Dados", "message": ptBr['eUserNotActive'] }), status_code=404) if user.is_active: user = update(db, user=user, user_in=user_in.user_data) return user
def check_superuser_or_admin( db: Session = Depends(get_db), token: str = Security(reusable_oauth2) ): try: payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM]) token_data = TokenPayload(**payload) except PyJWTError: raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail="Token expirou/invalido" ) environment = token_data.environment env_user = db.query(EnvUser).\ filter_by(environment_id = str(environment), user_id = str(token_data.user_data.id)).first() user = crud_user.get(db, user_id=str(token_data.user_data.id)) if env_user: env_user = env_user.is_admin env_user = env_user if token_data.user_data.is_superuser or env_user: return user raise HTTPException( status_code=403, detail="Usuario não tem permissão" )
def read_user(user_id: int, db: Session = Depends(get_db)): """ Get a specific user by id. """ user = crud_user.get(db, user_id=user_id) if user is None: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="User not found") return user
def update_member_role( organization_id: int, user_id: int, *, role: str = Body(..., embed=True), auth=Depends(authorization("organizations:edit_member")), db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): roles_order = [ "admin", "owner", "manager", "contributor", "reader", "guest" ] if role not in roles_order: raise HTTPException(status_code=400, detail=f"This role : {role} does not exist") user_in_db = user.get(db, id=user_id) if not user_in_db: raise HTTPException(status_code=404, detail="User not found") # Convert to sqlalchemy obj to UserOut schema for hidding password user_in_db = UserOut(**user_in_db.as_dict()) current_user_roles = enforcer.get_roles_for_user_in_domain( str(current_user.id), str(organization_id)) if len(current_user_roles) > 0: current_user_role = current_user_roles[0] if roles_order.index(current_user_role) >= roles_order.index(role): raise HTTPException(status_code=403, detail="You can only set roles below yours") user_roles = enforcer.get_roles_for_user_in_domain(str(user_id), str(organization_id)) # Role exist for this user (it's a patch) if len(user_roles) > 0: user_role = user_roles[0] if roles_order.index(current_user_role) >= roles_order.index( user_role): raise HTTPException(status_code=403, detail="You can't edit a role above yours") enforcer.delete_roles_for_user_in_domain(str(user_id), user_role, str(organization_id)) enforcer.add_role_for_user_in_domain(str(user_id), role, str(organization_id)) # need ro reload handle new policy enforcer.load_policy() return dict(user_in_db, role=role)
def add_members( organization_id: int, *, invites: List[UserInvite] = Body(...), auth=Depends(authorization("organizations:add_members")), db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): try: members = crud.organization.get_members(db, id=organization_id) users_to_add = (invite for invite in invites if invite.email not in (u.get("email") for u in members)) for invite in users_to_add: user_in_db = user.get_by_email(db, email=invite.email) role = invite.role if invite.role else "guest" if not user_in_db: user_in_db = user.create( db, obj_in=UserCreate( full_name=invite.full_name, email=invite.email, password=pwd.genword(), ), ) else: organization_in_db = crud.organization.get(db, id=organization_id) if organization_in_db: send_new_invitation_email_task.delay( full_name=user_in_db.full_name, email_to=user_in_db.email, organization=organization_in_db.name, role=role) enforcer.add_role_for_user_in_domain( str(user_in_db.id), role, str(organization_id), ) enforcer.load_policy() return [ user for user in get_members( organization_id, auth=auth, db=db, current_user=current_user) if user.get("email") in (invite.email for invite in invites) ] except Exception as e: logging.error(e)
def read_user_by_id( user_id: int, current_user: User = Depends(get_current_user), db: Session = Depends(get_db), ) -> Any: """ Get a specific user by id. """ user_in_db = user.get(db, id=user_id) if user_in_db == current_user: return user_in_db if not user.is_superuser(current_user): raise HTTPException(status_code=400, detail="The user doesn't have enough privileges") return user_in_db
def get_current_user( db: Session = Depends(get_db), token: str = Security(reusable_oauth2) ): try: payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM]) token_data = TokenPayload(**payload) except PyJWTError: raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail="Token expirou/invalido" ) user = crud_user.get(db, user_id=token_data.user_data.id) print(user) if not user: raise HTTPException(status_code=404, detail="User not found") return user
def verify_auth(db: Session = Depends(get_db), auth: str = Depends(oauth2_scheme)) -> UserModel: unauthorized_exception = HTTPException(detail='Invalid token', status_code=401) try: payload = jwt.decode(auth, AUTH_SECRET, algorithms=[ALGORITHM]) user_id = payload.get('sub') except InvalidTokenError: raise unauthorized_exception if not user_id: raise unauthorized_exception user = get(db, user_id) if not user: raise unauthorized_exception return user
def update_user( *, db: Session = Depends(get_db), user_id: int, user_in: UserUpdate, current_user: User = Depends(get_current_user_if_is_superuser), ) -> Any: """ Update a user. """ user_in_db = user.get(db, id=user_id) if not user_in_db: raise HTTPException( status_code=404, detail="The user with this username does not exist in the system", ) user_in_db = user.update(db, db_obj=user_in_db, obj_in=user_in) return user_in_db
def generate_and_insert(self, db: Session, fk_user: int) -> Registration_Link: user_in_db = user.get(db=db, id=fk_user) registration_link_tmp = RegistrationLinkCreate( fk_user=fk_user, value=generate_registration_link_value(), creation_date=datetime.now(), ) new_registration_link = self.create(db=db, obj_in=registration_link_tmp) db.add(new_registration_link) db.commit() db.refresh(new_registration_link) if settings.EMAILS_ENABLED: send_new_registration_link_email(user_in_db.email, user_in_db.full_name, new_registration_link.value) return new_registration_link
def update_user( *, db: Session = Depends(get_db), user_id: int, user_in: UserUpdate, # pylint: disable=unused-argument current_user: UserInDB = Depends(get_current_active_superuser), ): """ Update a user. """ user = crud_user.get(db, user_id=user_id) if not user: raise HTTPException( status_code=HTTP_404_NOT_FOUND, detail="The user with this username does not exist in the system", ) user = crud_user.update(db, user=user, user_in=user_in) return user
def remove_member( organization_id: int, user_id: int, *, auth=Depends(authorization("organizations:remove_member")), db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): user_in_db = user.get(db, id=user_id) if not user_in_db: raise HTTPException(status_code=404, detail="User not found") current_roles = enforcer.get_roles_for_user_in_domain( str(user_id), str(organization_id)) for current_role in current_roles: enforcer.delete_roles_for_user_in_domain(str(user_id), current_role, str(organization_id)) return True
def delete_user( *, db: Session = Depends(get_db), user_id: str, current_user: UserInDB = Depends(check_superuser_or_admin), environment: str = Depends(get_environment_from_token) ): if current_user.is_superuser : user = get(db, user_id=user_id) if not user.is_active: return Response(json.dumps({ "messageCode": codes['validation'], "title": "Usuario já desativado.", "message": ptBr['eAlreadyDelete'] }), status_code=200) deactivating_user = deactivate_user(db, user=user) if deactivating_user: return Response(json.dumps({ "messageCode": codes['success'], "title": "Sucesso na Operação.", "message": ptBr['userDeleted'] }), status_code=200) else: return Response(json.dumps({ "messageCode": codes['db'], "title": "Erro", "message": ptBr['eNotDeleteUser'] }), status_code=404) else: return Response(json.dumps({ "messageCode": codes['authorization'], "title": "Erro de Autorização", "message": ptBr['eNotAuthorized'] }), status_code=401)