def get_current_user(db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)) -> models.User: """Return the current user based on the bearer token from the header""" credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = utils.decode_access_token(token) except ExpiredSignatureError: msg = "Token has expired" logger.warning(msg) credentials_exception.detail = msg raise credentials_exception except PyJWTError as e: logger.warning(f"Error decoding JWT: {e}") raise credentials_exception username = payload.get("sub") if username is None: msg = "Missing subject claim in JWT" logger.warning(msg) credentials_exception.detail = msg raise credentials_exception user = crud.get_user_by_username(db, username) if user is None: msg = f"Unknown user {username}" logger.warning(msg) credentials_exception.detail = msg raise credentials_exception if not user.is_active: logger.warning(f"User {username} is inactive") raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user") return user
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, settings.SECRET_KEY, algorithms=settings.ALGORITHM) username: str = payload.get("sub") except ExpiredSignatureError: credentials_exception.detail = "ExpiredSignatureError" raise credentials_exception except DecodeError: raise credentials_exception if username is None: raise credentials_exception user = get_user(username=payload["sub"]) if user is None: raise credentials_exception return user
def test_connection(connection: Connection): exception = HTTPException( status_code=HTTP_503_SERVICE_UNAVAILABLE, detail="", ) if connection.connectable: return True else: exception.detail = new_connection.conn_error raise exception
def add_campaign(connection: Connection, campaign: str): exception = HTTPException( status_code=HTTP_409_CONFLICT, detail="A campaign with that name already exists", ) test_connection(connection) if campaign in connection.campaigns: raise exception if len(campaign) > 30: exception.status_code=HTTP_422_UNPROCESSABLE_ENTITY exception.detail="A campaign identifier must be no longer than 30 characters" raise exception if not "".join(campaign.split("_")).isalnum(): exception.status_code=HTTP_422_UNPROCESSABLE_ENTITY exception.detail="A campaign identifier must not contain special characters (only '_' are allowed)" raise exception db_name = "daqbroker_" + campaign connection.create_database(db_name) connection.get_databases() return connection.campaigns
async def validate_user(token: str = Depends(oauth2_scheme)) -> SessionAccount: 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]) email: str = payload.get("sub") session_timestamp = datetime.fromtimestamp(payload.get("exp")) current_timestamp = datetime.utcnow() if email is None: credentials_exception.detail = "Token without user" raise credentials_exception if current_timestamp > session_timestamp: credentials_exception.detail = "Session timeout" raise credentials_exception except JWTError: credentials_exception.detail = "JWT error decode" raise credentials_exception new_token = None account: SessionAccount = get_web_user(email) if account: new_token = create_access_token( data={"sub": account.email}, expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) ) if current_timestamp + timedelta(minutes=5) > session_timestamp \ else token if new_token is None: raise credentials_exception account.token = new_token return account
async def get_current_user(security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)): if security_scopes.scopes: authenticate_value = f'Bearer scope="{security_scopes.scope_str}"' else: authenticate_value = f"Bearer" credentials_exception = HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": authenticate_value}, ) try: # verify access token payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) username: str = payload.get("username") user_id: str = payload.get("user_id") if username is None: raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, user_id=user_id) except (PyJWTError, ValidationError): raise credentials_exception # user is (almost) authenticated user = UserRead(id=token_data.user_id) try: await user.get() except Exception as e: credentials_exception.detail = str(e) raise credentials_exception # validate scopes (dummy?) for scope in security_scopes.scopes: if scope not in token_data.scopes: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Not enough permissions", headers={"WWW-Authenticate": authenticate_value}, ) return user
async def get_current_user(token: str = Depends(oauth2_scheme), session= Depends(get_db)): credentials_exception = HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, get_secret_key(), algorithms=[ALGORITHM]) username: str = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) except PyJWTError as e: if type(e) == jwt.exceptions.ExpiredSignatureError: credentials_exception.detail = "Token expired" raise credentials_exception # with session_open(local_engine) as session: user = get_local_resources(db=session, Resource= User, key_vals= { "username":username }).first() if user is None: raise credentials_exception return user
def create(transaction: Transaction, session: Session = Depends(get_db), user_log: dict = Depends(validate_normal_user)): # TODO: ADD VALIDATE: CHECK USER CASH; IF TRANSACTION TYPE IS 2 user_sender_username = NULL else # user_sender_username != NULL # IF transaction type == 3 user_sender == log_user ex = HTTPException( status_code=HTTP_400_BAD_REQUEST, detail="Invalid transaction", ) if transaction.user_receiver_username == transaction.user_sender_username: raise ex transaction_type = OpTransaction.op_get_transaction_type( session, transaction.type_id) logged_usr = user_log.get("user_name") coin = get_and_save("CACHE_" + transaction.coin_id, OpCoin.op_get, Coin, session, cid=transaction.coin_id) if coin is None or coin.status == 0: ex.detail = "Invalid coin" raise ex if transaction_type is None: raise ex elif transaction_type.description == "DEBITO": if transaction.user_sender_username != logged_usr: raise ex elif transaction_type.description == "CARGA": if transaction.user_receiver_username != logged_usr or transaction.user_sender_username is not None: raise ex elif transaction_type.description == 'TRANSFERENCIA': if transaction.user_sender_username != logged_usr or transaction.user_receiver_username is None: raise ex return OpTransaction.op_create(session, transaction)
async def change_connection(conn_id: int, new_data: ConnectionInput, session=Depends(get_db)): connection = get_connection(session, conn_id, HTTP_404_NOT_FOUND, err_msg="Connection with id='" + str(conn_id) + "' not found") connection_dict = connection.dict() exception = HTTPException( status_code=HTTP_409_CONFLICT, detail="Attempting to change to already existing connection") if not connection: raise exception for attr, val in new_data.dict().items(): if val: connection_dict[attr] = val new_connection = Connection(**connection_dict) key_vals = { attr: getattr(new_connection, attr) for attr in ["hostname", "port", "type"] } new_connection_query = get_local_resources(db=session, Resource=Connection, key_vals=key_vals).first() if new_connection_query: raise exception new_connection_test = new_connection.test() if not new_connection_test[0]: exception.status_code = HTTP_503_SERVICE_UNAVAILABLE exception.detail = new_connection_test[1] raise exception return add_local_resource(db=session, Resource=Connection, user_input=new_data, r_id=connection.id)