Custom Authentication Policy

Here is an example of a custom AuthenticationPolicy, based off of the native AuthTktAuthenticationPolicy, but with added groups support. This example implies you have a user attribute on your request (see Making A "User Object" Available as a Request Attribute) and that the user should have a groups relation on it:

 1from pyramid.authentication import AuthTktCookieHelper
 2from pyramid.security import Everyone, Authenticated
 3
 4class MyAuthenticationPolicy(object):
 5
 6    def __init__(self, settings):
 7        self.cookie = AuthTktCookieHelper(
 8            settings.get('auth.secret'),
 9            cookie_name=settings.get('auth.token') or 'auth_tkt',
10            secure=asbool(settings.get('auth.secure')),
11            timeout=asint(settings.get('auth.timeout')),
12            reissue_time=asint(settings.get('auth.reissue_time')),
13            max_age=asint(settings.get('auth.max_age')),
14        )
15
16    def remember(self, request, principal, **kw):
17        return self.cookie.remember(request, principal, **kw)
18
19    def forget(self, request):
20        return self.cookie.forget(request)
21
22    def unauthenticated_userid(self, request):
23        result = self.cookie.identify(request)
24        if result:
25            return result['userid']
26
27    def authenticated_userid(self, request):
28        if request.user:
29            return request.user.id
30
31    def effective_principals(self, request):
32        principals = [Everyone]
33        user = request.user
34        if user:
35            principals += [Authenticated, 'u:%s' % user.id]
36            principals.extend(('g:%s' % g.name for g in user.groups))
37        return principals

Thanks to raydeo for this one.