示例#1
0
def test_jwt_encode() -> None:
    payload = {'email': '*****@*****.**'}
    token = jwt.encode(payload, 'jwt-secret', algorithm='HS256').decode(encoding='UTF-8')
    secret = 'jwt-secret'
    encoded_jwt = JWT.encode(payload=payload, secret=secret)
    assert encoded_jwt == token

    encoded_jwt = JWT.encode(payload=payload, secret=secret, algorithm='HS512')
    assert encoded_jwt != token
    token = jwt.encode(payload, 'jwt-secret', algorithm='HS512').decode(encoding='UTF-8')
    assert encoded_jwt == token
def test_authenticate_fails_without_valid_date_payload(user, ss):
    perimed_jwt = JWT.encode(
        get_payload(user, {'seconds': -8}), settings['JWT']['SECRET'])
    header = "Bearer " + perimed_jwt
    engine = MapistarJWTAuthentication()
    with pytest.raises(AuthenticationFailed):
        engine.authenticate(header, settings, ss)
def testautheticate_pass_with_valid_jwt(user, ss):
    valid_jwt = JWT.encode(
        get_payload(user, {'seconds': 8}), settings['JWT']['SECRET'])
    header = "Bearer " + valid_jwt
    engine = MapistarJWTAuthentication()
    authed = engine.authenticate(header, settings, ss)
    assert authed.user == user
示例#4
0
def login(credentials: LoginSchema, jwt: JWT) -> str:
    """
    View d'authentification

    Args:
        credentials: credentials username/password
        jwt: JWT componement pour l'encodage du payload

    Toutes les erreurs "raise"

    Returns:
        token
    """

    user = User.get(username=credentials["username"])

    if not user or not user.check_password(credentials["password"]):
        raise exceptions.Forbidden("Incorrect username or password.")

    if not user.actif:
        raise exceptions.Forbidden("Utilisateur inactif")

    payload = {
        "id": user.id,
        "username": user.username,
        "iat": pendulum.now(),
        "exp": pendulum.now() + pendulum.Duration(seconds=1000),
    }
    token = jwt.encode(payload)
    if token is None:
        raise exceptions.ConfigurationError("échec de l'encodage jwt")

    return token
def test_user_is_not_active(user, ss):
    valid_jwt = JWT.encode(
        get_payload(user, {'seconds': 8}), settings['JWT']['SECRET'])
    header = "Bearer " + valid_jwt
    user.is_active = False
    user.save()
    engine = MapistarJWTAuthentication()
    with pytest.raises(Forbidden):
        engine.authenticate(header, settings, ss)
def test_invalid_user(ss):
    a = MagicMock()
    a.id = 35135135135151
    valid_jwt = JWT.encode(
        get_payload(a, {'seconds': 8}), settings['JWT']['SECRET'])
    header = "Bearer " + valid_jwt
    engine = MapistarJWTAuthentication()
    with pytest.raises(BadRequest):
        engine.authenticate(header, settings, ss)
示例#7
0
def client(user):
    """
    Authenticated client
    """
    SECRET = settings['JWT'].get('SECRET')

    token = JWT.encode(get_payload(user, {'seconds': 60}), secret=SECRET)
    c = TestClient(app_fix())
    c.headers['Authorization'] = "Bearer " + token
    return c
示例#8
0
def login(user: str, pwd: str, settings: Settings) -> Response:

    user_logged = authenticate(username=user, password=pwd)
    if not user_logged:
        raise Forbidden("Utilisateur inactif, mauvais login/mot de passe")

    SECRET = settings['JWT'].get('SECRET')

    payload = get_payload(user_logged, settings['JWT'].get('PAYLOAD_DURATION'))

    token = JWT.encode(payload, secret=SECRET)

    return Response({'token': token}, status=201)
示例#9
0
def login(user: str, pwd: str, settings: Settings) -> dict:
    # do some check with your database here to see if the user is authenticated
    if user != USER['user'] or pwd != USER['pwd']:
        raise Forbidden('invalid credentials')
    SECRET = settings['JWT'].get('SECRET')
    payload = {
        'username': user,
        'iat': datetime.datetime.utcnow(),
        'exp': datetime.datetime.utcnow() +
        datetime.timedelta(minutes=60)  #  ends in 60 minutes
    }
    token = JWT.encode(payload, secret=SECRET)
    return {'token': token}
def test_payload_returned_is_empty(user, ss, monkeypatch):
    def return_empty_dict(*args):
        a = MagicMock()
        a.payload = {}
        return a

    monkeypatch.setattr('users.authentication.get_jwt', return_empty_dict)
    valid_jwt = JWT.encode(
        get_payload(user, {'seconds': 8}), settings['JWT']['SECRET'])
    header = "Bearer " + valid_jwt

    engine = MapistarJWTAuthentication()
    with pytest.raises(AuthenticationFailed):
        engine.authenticate(header, settings, ss)
示例#11
0
def login(data: UserData, jwt: JWT) -> dict:
    # do some check with your database here to see if the user is authenticated
    if data.email != USERS_DB['email'] or data.password != USERS_DB['password']:
        raise exceptions.Forbidden('Incorrect username or password.')
    payload = {
        'id': USERS_DB['id'],
        'username': USERS_DB['email'],
        'iat': datetime.datetime.utcnow(),
        'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60)  # ends in 60 minutes
    }
    token = jwt.encode(payload)
    if token is None:
        # encoding failed, handle error
        raise exceptions.BadRequest()
    return {'token': token}
示例#12
0
def test_unknown_algorithm_passed_to_encode() -> None:
    payload = {'some': 'payload'}
    with pytest.raises(exceptions.ConfigurationError):
        JWT.encode(payload=payload, secret='jwt-secret', algorithm='unknown-algorithm')
示例#13
0
def test_no_secret_passed_to_encode() -> None:
    payload = {'some': 'payload'}
    with pytest.raises(exceptions.ConfigurationError):
        JWT.encode(payload=payload)