Esempio n. 1
0
class ApplicationHeaderAuthenticationPolicy(object):
    def __init__(
            self,
            application_name,
            header_key=None,
            cookie_key=None):

        self.application_name = application_name
        self.header_key = header_key

        self.cookie_key = cookie_key
        if self.cookie_key:
            self.cookie_profile = CookieProfile(
                cookie_name=self.cookie_key,
                path='/',
                serializer=SimpleSerializer())

        if not self.header_key and not self.cookie_key:
            raise ValueError('Please define a key for authentication validation. `header_key` or `cookie_key`')

    def get_authenticated_session(self, request):
        have_cache = hasattr(request, 'session_cache')
        if have_cache and 'authenticated' in request.session_cache:
            return request.session_cache['authenticated']

        authenticated = None
        authorization_string = self.unauthenticated_userid(request)
        if authorization_string:
            authorization_info = authorization_string.split('-', 1)
            authorization_type = authorization_info[0].lower()

            if (len(authorization_info) == 2
                    and authorization_info[1]
                    and authorization_type in ('token', 'apikey')):

                authenticated = (
                    getattr(request.applications, self.application_name)
                    .get_authorization(authorization_type, authorization_info[1]))

                if authenticated and not isinstance(authenticated, AuthenticatedSession):
                    session_type = authorization_type == 'token' and 'user' or authorization_type
                    authenticated = AuthenticatedSession(session_type, authenticated)

        if have_cache:
            request.session_cache['authenticated'] = authenticated
        return authenticated

    def authenticated_userid(self, request):
        return self.get_authenticated_session(request)

    def unauthenticated_userid(self, request):
        if self.header_key:
            userid = request.headers.get(self.header_key)
            if userid:
                return userid

        if self.cookie_key:
            userid = request.cookies.get(self.cookie_key)
            if userid:
                return userid

    def effective_principals(self, request):
        authenticated = self.get_authenticated_session(request)
        if not authenticated:
            return [Everyone, NotAuthenticated]
        else:
            return authenticated.get_principals()

    def remember(self, request, token):
        if self.cookie_key:
            return self.cookie_profile.get_headers('Token-%s' % token)
        else:
            return []

    def forget(self, request):
        if self.cookie_key:
            return self.cookie_profile.get_headers(None)
        else:
            return []