def token_authenticator(request, response, verify_user, context=None, **kwargs): """Token verification Checks for the Authorization header and verifies using the verify_user function """ token = request.get_header('x-access-token') if token: if BlacklistedToken.objects(jwt=token).first(): raise hug.HTTPUnauthorized('Authentication Error', 'Token is blacklisted!') try: verified_token = verify_user(token) except TypeError: verified_token = verify_user(token, context) except jwt.exceptions.InvalidTokenError: raise hug.HTTPUnauthorized('Authentication Error', 'Token is invalid. Expired maybe?') if verified_token: return verified_token else: return False return None
def token_auth(request, response, **kwargs): if not config.require_authentication.get(): request.context['user'] = {'username': '******'} return True header = request.get_header('Authorization') if not header: raise hug.HTTPUnauthorized('Authentication Required', 'No Authorization header') schema, _, encoded_token = header.partition(' ') if schema.lower() != 'bearer': raise hug.HTTPUnauthorized('Invalid Authentication', 'Authorization schema must be Bearer') try: token = verify_token(encoded_token) except Exception as e: raise hug.HTTPUnauthorized('Invalid Authentication', str(e)) request.context['user'] = token return True
def logout_user(refresh_token: non_blacklisted_refresh_token, access_token: directives.access_token, requires=token_key_authentication): token = token_verify(refresh_token) user_id = token['identity_claim_key'] user = User.objects(id=user_id).first() if not user: raise hug.HTTPUnauthorized("Unauthorized", "Wrong token content") BlacklistedToken(jwt=access_token, refresh_token=refresh_token).save()
def refresh_user(refresh_token: non_blacklisted_refresh_token, requires=token_key_authentication): token = token_verify(refresh_token) user_id = token['identity_claim_key'] user = User.objects(id=user_id).first() if not user: raise hug.HTTPUnauthorized("Unauthorized", "Wrong token content") return dict(jwt=access_token_create(user))
def login_user(email: hug.types.text, password: hug.types.text): h = get_password_hash(password) user = User.objects(email=email, password_hash=h).first() if not user: raise hug.HTTPUnauthorized("Unauthorized", "Wrong password/email combination") return dict(jwt=access_token_create(user), refresh_token=refresh_token_create(user))