Beispiel #1
0
 def login(self, user_id: UUID) -> TestClient:
     """
     Authenticates given user by creating access token and setting it as
     the Authorization header.
     """
     token = security.create_access_token(str(user_id))
     self.headers.update({"Authorization": f"Bearer {token}"})
     return self
async def login(form_data: OAuth2PasswordRequestForm = Depends(),
                db: Session = Depends(deps.get_db)):
    user = authenticate_user(db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                            detail="Incorrect username or password",
                            headers={"WWW-Authenticate": "Bearer"})
    access_token = create_access_token({"sub": user.email})
    return {"access_token": access_token, "token_type": "bearer"}
def login_access_token(db: Session = Depends(dependency.get_db),
                       form_data: OAuth2PasswordRequestForm = Depends()):
    user = validators.authenticate_user(db,
                                        email=form_data.username,
                                        password=form_data.password)
    if not user:
        raise HTTPException(status_code=400,
                            detail="Incorrect email or password")
    return {
        "access_token": security.create_access_token(subject=user.id),
        "token_type": "bearer",
    }
def login_access_token(db: Session = Depends(get_db),
                       form_data: OAuth2PasswordRequestForm = Depends()):
    user = crud.authenticate_user(db,
                                  email=form_data.username,
                                  password=form_data.password)
    if not user:
        raise HTTPException(status_code=400,
                            detail="Incorrect email or password")
    # Maybe add expiration to token here if deemed necessary
    return {
        "access_token": create_access_token(user.id),
        "token_type": "bearer"
    }
Beispiel #5
0
def login_access_token(db: Session = Depends(get_db),
                       form: OAuth2PasswordRequestForm = Depends()):
    user = crud.user.authenticate(db,
                                  username=form.username,
                                  password=form.password)
    if user is None:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Invalid credentials.",
        )
    result = {
        "access_token": security.create_access_token(str(user.id)),
        "token_type": "bearer",
    }
    return result
Beispiel #6
0
def login_access_token(db: Session = Depends(deps.get_db),
                       form_data: OAuth2PasswordRequestForm = Depends()):
    """
    OAuth2 compatible token login, get an access token for future requests.
    """
    user = crud.authenticate_user(db,
                                  email=form_data.username,
                                  password=form_data.password)
    if not user:
        raise HTTPException(status_code=400,
                            detail="Incorrect email or password")
    return {
        "access_token":
        security.create_access_token(subject=f"user:{user.id}"),
        "token_type": "bearer",
    }
Beispiel #7
0
def login_device_token(db: Session = Depends(deps.get_db),
                       pairing_code: auth_schemas.PairingCode = Depends()):
    """
    Get an access token for future device requests
    """
    device: devices_models.Device = crud.get_device_by_pairing_code(
        db, pairing_code.pairing_code)
    if not device:
        raise HTTPException(status_code=400, detail="Incorrect pairing code")
    if not device.paired:
        crud.update_device_paired_state(db, device.id, paired=True)
    return {
        "access_token":
        security.create_access_token(subject=f"device:{device.id}"),
        "token_type": "bearer",
    }
Beispiel #8
0
async def get_tokens(
        form_data: OAuth2PasswordRequestForm = Depends(),
        db_client: AsyncIOClient = Depends(deps.db_client),
):
    """Grant new access token for a given credentials."""
    username = form_data.username.lower()
    try:
        uid, password = await crud.user.get_password(db_client,
                                                     username=username)
    except errors.UserNotFound as exc:
        raise exceptions.InvalidCredentials() from exc

    if not security.verify_password(form_data.password, password):
        raise exceptions.InvalidCredentials()

    return Tokens(access_token=security.create_access_token(str(uid)))
Beispiel #9
0
def login_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(deps.get_db)):
    """
    OAuth2 compatible token login, get an access token for future requests
    """
    user = crud_user.authenticate_user(db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    elif not crud_user.is_active(user):
        raise HTTPException(status_code=400, detail="Inactive user")
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = security.create_access_token(data={"sub": user.username}, expires_delta=access_token_expires)
    return {"access_token": access_token, "token_type": "bearer", "expiresIn": settings.ACCESS_TOKEN_EXPIRE_MINUTES}
Beispiel #10
0
def login_access_token(db: Session = Depends(deps.get_db),
                       form_data: OAuth2PasswordRequestForm = Depends()
                       ) -> Any:
    user = crud.authenticate(db,
                             email=form_data.username,
                             password=form_data.password)
    if not user:
        raise (HTTPException(status_code=400,
                             detail="Incorrect Login Details"))
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)

    return {
        "access_token":
        create_access_token(data={"sub": user.email},
                            expires_delta=access_token_expires),
        "token_type":
        "bearer",
    }
Beispiel #11
0
async def login_access_token(db: Session = Depends(get_db),
                             form_data: OAuth2PasswordRequestForm = Depends()):
    """
    OAuth2 compatible token login, get an access token for future requests
    """
    user = crud_user.authenticate(db,
                                  name=form_data.username,
                                  password=form_data.password)
    if not user:
        raise HTTPException(status_code=400,
                            detail="Incorrect email or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    return {
        "access_token":
        create_access_token(data={"user_id": user.id},
                            expires_delta=access_token_expires),
        "token_type":
        "bearer",
    }
Beispiel #12
0
def login_access_token(
        db: sa.orm.Session = get_db,
        form_data: OAuth2PasswordRequestForm = Depends(),
) -> Any:
    """
    OAuth2 compatible token login, get an access token for future requests
    """
    user = User.get_by_email(db, form_data.username)

    if user is None or not verify_password(user.password, form_data.password):
        raise HTTPException(status_code=400,
                            detail="Incorrect email or password")

    access_token_expires = timedelta(
        minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    return {
        "access_token":
        create_access_token(user.id, expires_delta=access_token_expires),
        "token_type":
        "bearer",
    }
Beispiel #13
0
def login_access_token(db: Session = Depends(deps.get_db),
                       form_data: OAuth2PasswordRequestForm = Depends()
                       ) -> Any:
    """
    OAuth2 compatible token login, get an access token for future requests
    """
    user = crud.user.authenticate(db,
                                  username=form_data.username,
                                  password=form_data.password)
    if not user:
        raise HTTPException(status_code=400,
                            detail="Incorrect username or password.")
    access_token_expires = timedelta(minutes=30)
    return {
        "access_token":
        security.create_access_token(user.id,
                                     expires_delta=access_token_expires),
        "token_type":
        "bearer",
        "user_id":
        user.id,
    }
Beispiel #14
0
async def login_access_token(
        con: AsyncIOConnection = Depends(db.get_con),
        form_data: OAuth2PasswordRequestForm = Depends(),
) -> Any:
    """
    OAuth2 compatible token login, get an access token for future requests
    """
    user = await crud.user.authenticate(con,
                                        email=form_data.username,
                                        password=form_data.password)
    if not user:
        raise HTTPException(status_code=400,
                            detail="Incorrect email or password")
    elif not user.is_active:
        raise HTTPException(status_code=400, detail="Inactive user")
    access_token_expires = timedelta(
        minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    token = schemas.Token(
        access_token=create_access_token(user.id,
                                         expires_delta=access_token_expires),
        token_type="bearer",
    )
    return token
Beispiel #15
0
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import database_exists, create_database, drop_database

from app.core.config import DATABASE_URL
from app.security import create_access_token

from sqlalchemy.ext.declarative import declarative_base

# test user config
TEST_USER = {
    "uid": "4288921a-f7ba-4c83-969f-54f30be4ee5f",
    "email": "*****@*****.**",
    "master_pwd": "password"
}

TEST_ACCESS_TOKEN = create_access_token(data=TEST_USER, expires_delta=None)

TEST_SQL = """
INSERT INTO 
    users 
VALUES (:uid, :email, crypt(:master_pwd, gen_salt('bf', 8)))
RETURNING uid;
"""

TEST_DB_URL = f"{DATABASE_URL}_test"


# run online migration through connection
def alembic_migration(migrations_path: str,
                      alembic_init_path: str = 'alembic.ini',
                      connection=None,
Beispiel #16
0
            status_code=status.HTTP_404_NOT_FOUND, 
            detail="email not found"
        )

    # authentication check
    if (user := crud_user.get_user(db, email=user_email, password=password)) is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, 
            detail="invalid email/password"
        )

    # generate payload and access token
    time_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    payload = { "user_info": user.dict(exclude_unset=True) }

    access_token = create_access_token(data=payload, expires_delta=time_expires)

    # set cookie
    response.set_cookie(
        key="access_token",
        value=access_token,
        httponly=True,
        max_age=time_expires.total_seconds(),
        expires=time_expires.total_seconds(),
        samesite="lax",
        secure=False,
    )

    return payload

### AUTHENTICATED 
Beispiel #17
0
async def refresh_token(curr_user_id: str = Depends(deps.current_user_id)):
    """Grant new access token based on current access token."""
    return Tokens(access_token=security.create_access_token(curr_user_id))