Example #1
0
    def process_request(self, request_object):
        """Process Login Callback Request"""

        # Build the identity to be encoded in the jwt
        identity = {'account_id': request_object.account.id}
        if active_config.JWT_IDENTITY_CALLBACK:
            identity.update(request_object.account)

        # Get the encode key for the alg
        encode_key = active_config.SECRET_KEY
        if active_config.JWT_ALGORITHM in requires_cryptography:
            with open(active_config.JWT_PRIVATE_KEY) as fp:
                encode_key = fp.read()

        # Generate the jwt token and return in response
        token_data, access_token = encode_access_token(
            identity=identity,
            secret=encode_key,
            algorithm=active_config.JWT_ALGORITHM,
            expires_delta=active_config.JWT_ACCESS_TOKEN_EXPIRES,
            fresh=False,
            csrf=False,
            identity_claim_key=active_config.JWT_IDENTITY_CLAIM,
            user_claims=None,
            user_claims_key=None,
        )

        # Save the session to enable logout
        Session.create(session_key=f'token-{request_object.account.id}'
                       f'-{token_data["jti"]}',
                       session_data={},
                       expire_date=datetime.utcnow() +
                       active_config.JWT_ACCESS_TOKEN_EXPIRES)
        context.set_context({'jwt_data': token_data})
        return ResponseSuccess(Status.SUCCESS, {'access_token': access_token})
Example #2
0
    def _load_protean():
        """ Load the protean context with details from the request"""

        user_agent = request.headers.get('User-Agent', '')
        hashed_user_agent = hashlib.sha256(user_agent.encode())

        details = {
            'host_url': request.host_url,
            'url': request.url,
            'tenant_id': derive_tenant(request.url),
            'user_agent': user_agent,
            'user_agent_hash': hashed_user_agent.hexdigest(),
            'remote_addr': request.remote_addr
        }
        context.set_context(details)
Example #3
0
        def wrapped_f(*args, **kwargs):
            """ Actual function for checking authentication """
            # Perform the authentication
            response = perform_authentication()

            # If the task failed and authentication is not optional
            # then return unauthorized
            if not response.success and request.method != 'GET':
                renderer = perform_import(active_config.DEFAULT_RENDERER)
                error_message = {
                    'code': 401,
                    'message': {
                        '_entity': 'Authentication Failed'
                    }
                }
                logger.debug(
                    f'Authentication failed due to error: {response.value}')
                return renderer(error_message, 401, {})

            # Set the account on the request and call the actual function
            context.set_context(
                {'account': response.value if response.success else None})
            return f(*args, **kwargs)
Example #4
0
    def process_request(self, request_object):
        """Process Authentication Request"""
        # Get the decode key for the alg
        decode_key = active_config.SECRET_KEY
        if active_config.JWT_ALGORITHM in requires_cryptography:
            with open(active_config.JWT_PUBLIC_KEY) as fp:
                decode_key = fp.read()

        # Decode and validate the jwt
        try:
            jwt_data = decode_jwt(
                encoded_token=request_object.credentials,
                secret=decode_key,
                algorithm=active_config.JWT_ALGORITHM,
                identity_claim_key=active_config.JWT_IDENTITY_CLAIM)
        except (JWTDecodeError, DecodeError, ExpiredSignatureError) as e:
            return ResponseFailure(Status.UNAUTHORIZED,
                                   {'credentials': f'Invalid JWT Token. {e}'})

        # Find the identity in the decoded jwt
        identity = jwt_data.get(active_config.JWT_IDENTITY_CLAIM, None)
        try:
            account = Account.get(identity.get('account_id'))
        except ObjectNotFoundError:
            return ResponseFailure(
                Status.UNAUTHORIZED,
                {'username_or_email': 'Account does not exist'})

        # Make sure that the session exits
        session = Session.query.filter(
            session_key=f'token-{account.id}-{jwt_data["jti"]}', )
        if not session or session.first.expire_date < datetime.utcnow():
            return ResponseFailure(Status.UNAUTHORIZED,
                                   {'token': 'Invalid Token'})

        context.set_context({'jwt_data': jwt_data})
        return ResponseSuccess(Status.SUCCESS, account)