Example #1
0
    def authenticate(self, authorization: http.Header,
                     session: DjangoSession,
                     settings: Settings) -> typing.Union[None, Authenticated]:
        user_settings = get_settings(settings)
        token = self.get_credentials(authorization)

        if not token:
            return

        TokenModel = getattr(session, user_settings['TOKEN_MODEL'])
        UserModel = getattr(session, user_settings['USER_MODEL'])
        instance = TokenModel.objects.filter(token=token).first()
        if not instance:
            return

        now = datetime.datetime.now()
        difference = datetime.timedelta(days=user_settings['EXPIRY_TIME'])
        if user_settings['IS_EXPIRY_TOKEN'] and instance.created_at < (now - difference):
            return

        user = UserModel.objects.filter(id=instance.user_id).first()
        return Authenticated(
            username=getattr(user, user_settings['USERNAME_FIELD']),
            user=user
        )
Example #2
0
 def authenticate(self, authorization: Header):
     if authorization is None:
         return None
     scheme, token = authorization.split()
     if scheme.lower() != 'token':
         return None
     if token == 'Abigale@123$':
         return Authenticated('admin', user=User('admin', True))
Example #3
0
 def authenticate(self, authorization: http.Header, settings: Settings):
     if not authorization:
         raise Unauthorized()
     scheme, token = authorization.split()
     try:
         payload = jwt.decode(token,
                              settings['JWT_SECRET'],
                              algorithms=['HS256'])
         return Authenticated(payload['user_id'])
     except jwt.exceptions.InvalidTokenError:
         raise Unauthorized()
Example #4
0
    def authenticate(self, authorization: http.Header):
        """
        Determine the user associated with a request, using HTTP Basic Authentication.
        """
        if authorization is None:
            return None

        scheme, token = authorization.split()
        if scheme.lower() != 'basic':
            return None

        username, password = base64.b64decode(token).decode('utf-8').split(':')
        return Authenticated(username)
Example #5
0
    def authenticate(self, authorization: http.Header):
        if authorization is None:
            return None

        scheme, token = authorization.split()

        if scheme.lower() != 'bearer':
            return None

        if token != SECRET_KEY:
            return None

        return Authenticated('spider')
Example #6
0
 def authenticate(self, authorization: Header, mongo: Database):
     if authorization is None:
         return None
     scheme, token = authorization.split()
     if scheme.lower() != 'basic':
         return None
     token = base64.b64decode(token).decode("utf-8")
     username, password = token.split(":")
     user = mongo.users.find_one({"username": username, "password": password})
     if user is not None:
         username = user['username']
         is_admin = user['isAdmin']
         return Authenticated(username, user=User(username, is_admin))
Example #7
0
 def authenticate(self, authorization: http.Header, settings: Settings):
     jwt = get_jwt(authorization, settings)
     if jwt.payload == {}:
         raise AuthenticationFailed()
     jwt_settings = settings.get('JWT', {})
     uid = jwt.payload.get(jwt_settings.get('ID', 'id'), '')
     username = jwt.payload.get(jwt_settings.get('USERNAME', 'username'),
                                '')
     return Authenticated(username,
                          user={
                              'id': uid,
                              'name': username
                          },
                          token=jwt.token)
    def authenticate(self, authorization: http.Header, session: Session):
        """
        Determine the user associated with a request based on a token sent over the Authorization
        header.
        """
        if authorization is None:
            return None

        scheme, token = authorization.split()
        if scheme.lower() != 'token':
            return None

        user_token = session.Token.objects.filter(key=token).first()
        if not user_token:
            return None

        return Authenticated(user_token.user.username, user=user_token.user)
Example #9
0
    def authenticate(self, authorization: http.Header,
                     repository: repo.Repository):
        if authorization is None:
            return None

        scheme, token = authorization.split(' ', 1)
        if scheme.lower() != 'bearer':
            return None

        user = repository.find_token_user(token)
        if user is None:
            return None

        user = repository.find_token_user(token)
        if user is None:
            return None

        return Authenticated(user.email, user=user, token=token)
Example #10
0
    def authenticate(self, authorization: http.Header,
                     repository: repo.Repository):
        if authorization is None:
            return None

        scheme, token = authorization.split(' ', 1)
        if scheme.lower() != 'basic':
            return None

        username, password = base64.b64decode(token).decode('utf-8').split(
            ':', 1)
        user = repository.find_token_user(password)
        if user is None:
            return None

        if username != '' and username != user.email:
            return None

        return Authenticated(user.email, user=user, token=password)
Example #11
0
    def authenticate(self, authorization: http.Header, settings: Settings):
        if authorization is None:
            raise Unauthorized({
                'error_code': 'AuthorizationHeaderMissing',
                'message': "Authorization header is missing",
            })

        scheme, token = authorization.split(None, 1)
        if scheme.lower() != 'bearer':
            raise Forbidden({
                'error_code':
                'InvalidAuthorizationHeaderFormat',
                'message':
                'Authorization header is in invalid format, should be "Bearer TOKEN"',
            })

        try:
            token = jwt.decode(token,
                               key=self.pubkey,
                               audience=None,
                               options={'verify_aud': False})
        except jwt.InvalidTokenError as e:
            headers = {
                'WWW-Authenticate': 'Bearer error="invalid_token"',
            }
            raise Unauthorized(
                {
                    'error_code': 'InvalidAccessTokenError',
                    'message': "Access token is invalid: {token_error}",
                    'token_error': str(e),
                },
                headers=headers)

        if token['iss'] != settings['QVARN']['TOKEN_ISSUER']:
            headers = {
                'WWW-Authenticate': 'Bearer error="invalid_token"',
            }
            raise Unauthorized(
                {
                    'error_code':
                    'InvalidAccessTokenError',
                    'message':
                    "Access token is invalid: {token_error}",
                    'token_error':
                    'Expected issuer %s, got %s' %
                    (settings['QVARN']['TOKEN_ISSUER'], token['iss']),
                },
                headers=headers)

        if 'sub' not in token:
            headers = {
                'WWW-Authenticate': 'Bearer error="invalid_token"',
            }
            raise Unauthorized(
                {
                    'error_code': 'InvalidAccessTokenError',
                    'message': "Access token is invalid: {token_error}",
                    'token_error': 'Invalid subject (sub)',
                },
                headers=headers)

        return Authenticated('user', token=token)
Example #12
0
 def authenticate(self, session: Session):
     if 'username' in session:
         username = session['username']
         is_admin = session['isAdmin']
         return Authenticated(username, user=User(username, is_admin))