Esempio n. 1
0
async def login(form: LoginForm, repos: RepoDict = Depends(get_repos)):
    '''Trades username and password for an access token (custom implementation)'''
    try:
        uc = uc_user_login.LoginUseCase(repos['user'], repos['refresh_token'])
        uc_req = uc_user_login.LoginRequest(login=form.login,
                                            password=form.password)
        return await uc.execute(uc_req)

    except uc_user_login.InvalidCredsError:
        return JSONResponse(
            status_code=HTTP_401_UNAUTHORIZED,
            content={
                'code': 'incorrect_credentials',
                'msg': 'Incorrect username or password',
            },
        )

    except uc_user_login.UserLockedError:
        return JSONResponse(
            status_code=HTTP_401_UNAUTHORIZED,
            content={
                'code': 'user_locked',
                'msg': 'User is locked',
            },
        )
async def test_fail_user_not_found(uc_req):
    '''Should throw InvalidCredsError if user is not found'''
    # Create mocks
    user_repo = mock.Mock(UserRepo)
    user_repo.get_by_login.return_value = None
    rt_repo = mock.Mock(RefreshTokenRepo)

    # Call usecase
    uc = uc_user_login.LoginUseCase(user_repo, rt_repo)
    tokens = None
    with pytest.raises(uc_user_login.InvalidCredsError):
        tokens = await uc.execute(uc_req)

    # Assert results
    user_repo.get_by_login.assert_called_with('testuser')
    user_repo.update_last_login.assert_not_called()
    assert tokens is None
async def test_success_case_insensitive(create_access_token, uc_req,
                                        test_user):
    '''Should return an access and refresh token'''
    # Create mocks
    user_repo = mock.Mock(UserRepo)
    user_repo.get_by_login.return_value = test_user
    rt_repo = mock.Mock(RefreshTokenRepo)
    rt_repo.create_token.return_value = RefreshToken(
        user_id=test_user.id,
        secret='TestRefreshToken',
    )
    create_access_token.return_value = 'TestAccessToken'

    # Call usecase
    uc = uc_user_login.LoginUseCase(user_repo, rt_repo)
    tokens = await uc.execute(uc_req)

    # Assert results
    user_repo.get_by_login.assert_called_with('testuser')
    user_repo.update_last_login.assert_called_with(test_user.id)
    create_access_token.assert_called_with(user_id=test_user.id)
    rt_repo.create_token.assert_called_with(test_user.id)
    assert tokens.access_token == 'TestAccessToken'
    assert tokens.refresh_token == f'{test_user.id}:TestRefreshToken'
Esempio n. 4
0
async def login_for_access_token(creds: OAuth2PasswordRequestForm = Depends(),
                                 repos: RepoDict = Depends(get_repos)):
    '''Trades username and password for an access token (oauth2: password grant)'''
    try:
        uc = uc_user_login.LoginUseCase(repos['user'], repos['refresh_token'])
        uc_req = uc_user_login.LoginRequest(login=creds.username,
                                            password=creds.password)
        tokens = await uc.execute(uc_req)
        return LoginResponse(access_token=tokens.access_token,
                             token_type="bearer")

    except uc_user_login.InvalidCredsError:
        raise HTTPException(
            status_code=HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )

    except uc_user_login.UserLockedError:
        raise HTTPException(
            status_code=HTTP_401_UNAUTHORIZED,
            detail="User is locked",
            headers={"WWW-Authenticate": "Bearer"},
        )