class MyAuthenticationPolicy(object): implements(IAuthenticationPolicy) def __init__(self, settings): self.cookie = AuthTktCookieHelper(settings['auth.secret']) def remember(self, request, principal, **kw): return self.cookie.remember(request, principal, **kw) def forget(self, request): return self.cookie.forget(request) def unauthenticated_userid(self, request): result = self.cookie.identify(request) if result: return result['userid'] def authenticated_userid(self, request): uid = self.unauthenticated_userid(request) # check that the user actually exists if uid in USERS: return uid def effective_principals(self, request): principals = [Everyone] uid = self.authenticated_userid(request) if uid: principals += [Authenticated, 'u:%s' % uid] principals.extend(('g:%s' % g for g in GROUPS.get(uid, []))) return principals
class MySecurityPolicy: def __init__(self, secret): self.authtkt = AuthTktCookieHelper(secret) self.identity_cache = RequestLocalCache(self.load_identity) def load_identity(self, request): identity = self.authtkt.identify(request) if identity is None: return None userid = identity['userid'] user = request.dbsession.query(models.User).get(userid) return user def identity(self, request): return self.identity_cache.get_or_create(request) def authenticated_userid(self, request): user = self.identity(request) if user is not None: return user.id def remember(self, request, userid, **kw): return self.authtkt.remember(request, userid, **kw) def forget(self, request, **kw): return self.authtkt.forget(request, **kw)
class SambaAdminAuthenticationPolicy: def __init__(self, secret): self.authtkt = AuthTktCookieHelper(secret=secret) def identity(self, request): identity = self.authtkt.identify(request) if identity is not None: return identity def authenticated_userid(self, request): identity = self.identity(request) if identity is not None: return identity['userid'] def remember(self, request, userid, **kw): return self.authtkt.remember(request, userid, **kw) def forget(self, request, **kw): return self.authtkt.forget(request, **kw) def effective_principals(self, request): principals = [Everyone] userid = self.authenticated_userid(request) if userid: principals += [Authenticated, str(userid)] #user=request.user #print("El user es %s" % user) #if user is not None: # principals.extend(('group:%s' % g for g in user.groups)) return principals
class KFHLogAuthenticationPolicy(object): def __init__(self, secret): self.cookie = AuthTktCookieHelper(secret, cookie_name='auth_tkt', secure=False, include_ip=False, timeout=None, reissue_time=None, max_age=None, hashalg='sha512') def unauthenticated_userid(self, request): result = self.cookie.identify(request) if result: return result['userid'] def remember(self, request, userid, **kw): return self.cookie.remember(request, userid, **kw) def forget(self, request): return self.cookie.forget(request) def authenticated_userid(self, request): user = request.user if user: return user.name def effective_principals(self, request): principals = [Everyone] userid = self.authenticated_userid(request) if userid: principals.append(Authenticated) principals.append(userid) return principals
class MySecurityPolicy: def __init__(self, secret): self.authtkt = AuthTktCookieHelper(secret) self.acl = ACLHelper() def identity(self, request): identity = self.authtkt.identify(request) if identity is not None and identity['userid'] in USERS: return identity def authenticated_userid(self, request): identity = self.identity(request) if identity is not None: return identity['userid'] def remember(self, request, userid, **kw): return self.authtkt.remember(request, userid, **kw) def forget(self, request, **kw): return self.authtkt.forget(request, **kw) def permits(self, request, context, permission): principals = self.effective_principals(request) return self.acl.permits(context, principals, permission) def effective_principals(self, request): principals = [Everyone] identity = self.identity(request) if identity is not None: principals.append(Authenticated) principals.append('u:' + identity['userid']) principals.extend(GROUPS.get(identity['userid'], [])) return principals
class SambaSecurityPolicy: def __init__(self, secret): self.helper = AuthTktCookieHelper(secret) self.samba_server=SambaServer.getInstance() def identity(self, request): # define our simple identity as None or a dict with userid and principals keys identity = self.helper.identify(request) if identity is None: return None userid = identity['userid'] # identical to the deprecated request.unauthenticated_userid # verify the userid, just like we did before with groupfinder principals = self.groupfinder(userid, request) # assuming the userid is valid, return a map with userid and principals if principals is not None: return { 'userid': userid, 'principals': principals, } return None def groupfinder(self,userid, request): # The View requires to create an ACL to allow # or refuse the access to the screen. This should # return a group such that it would be authorized # for the view. The list of groups should be # retrieved from Samba and check if the user # has the Administrators group. if userid is not None: return [ "group:admin" ] return None def authenticated_userid(self, request): # defer to the identity logic to determine if the user id logged in # and return None if they are not identity = request.identity if identity is not None: return identity['userid'] def permits(self, request, context, permission): # use the identity to build a list of principals, and pass them # to the ACLHelper to determine allowed/denied identity = request.identity principals = set([Everyone]) if identity is not None: principals.add(Authenticated) principals.add(identity['userid']) principals.update(identity['principals']) return ACLHelper().permits(context, principals, permission) def remember(self, request, userid, **kw): return self.helper.remember(request, userid, **kw) def forget(self, request, **kw): return self.helper.forget(request, **kw)
def cli_gen_ticket(): env = bootstrap(sys.argv[1]) secret = env['registry'].settings.get('lawn_secret') if not secret: print "No secret configured." return helper = AuthTktCookieHelper(secret, 'lawn') cookie_value = helper.remember(env['request'], IDENTITY)[0][1] assert cookie_value.startswith('lawn="') print cookie_value.split(';')[0][6:-1]
def cli_gen_ticket(): env = bootstrap(sys.argv[1]) secret = env['registry'].settings.get('lawn_secret') if not secret: print "No secret configured." return helper = AuthTktCookieHelper(secret, 'lawn') cookie_value = helper.remember(env['request'], IDENTITY)[0][1] assert cookie_value.startswith('lawn=') print cookie_value.split(';')[0][5:].strip('"')
class AuthTktIdentifier: """ An identifier for storing the currently authenticated principal in an authtkt cookie. Uses pyramid.authentication.AuthTktCookieHelper. """ def __init__(self, secret, cookie_name='auth_tkt', secure=False, include_ip=False, timeout=None, reissue_time=None, max_age=None, path="/", http_only=False, wild_domain=True): """ Initialize the identifier. Takes the same arguments as pyramid.authentication.AuthTktCookieHelper. """ self.cookie = AuthTktCookieHelper(secret, cookie_name=cookie_name, secure=secure, include_ip=include_ip, timeout=timeout, reissue_time=reissue_time, max_age=max_age, http_only=http_only, path=path, wild_domain=wild_domain) def identify(self, request): """ Return the username of the remembered user. :param request: The WSGI request. :return: The username of the remembered user. """ identifier = self.cookie.identify(request) return identifier['userid'] if identifier else None def remember(self, request, username, **kw): """ Return the headers necessary for remembering the principal. :param request: The WSGI request. :param username: The username to remember. :param kw: Additional identifier parameters. :return: A list of headers to add to the response. """ return self.cookie.remember(request, username, **kw) def forget(self, request): """ Return the headers necessary for forgetting any remembered principal. :param request: The WSGI request. :return: A list of headers to add to the response. """ return self.cookie.forget(request)
def get_off_my_lawn_unless_you_know_the_secret_handshake(request): helper = AuthTktCookieHelper(secret, 'lawn', max_age=TEN_YEARS) identity = helper.identify(request) if not identity: trythisone = request.copy() trythisone.cookies['lawn'] = trythisone.path_info.strip('/') identity = helper.identify(trythisone) if identity: response = HTTPFound(request.application_url) response.headers.extend(helper.remember(request, IDENTITY)) return response if identity and identity['userid'] == IDENTITY: return handler(request) return get_off_my_lawn(request)
class SecurityPolicy: def __init__(self, secret): self.authtkt = AuthTktCookieHelper(secret=secret) def identity(self, request): identity = self.authtkt.identify(request) if identity is not None and identity['userid'] in USERS: return identity def authenticated_userid(self, request): identity = self.identity(request) if identity is not None: return identity['userid'] def remember(self, request, userid, **kw): return self.authtkt.remember(request, userid, **kw) def forget(self, request, **kw): return self.authtkt.forget(request, **kw)
class MySecurityPolicy: def __init__(self, secret): self.authtkt = AuthTktCookieHelper(secret) self.identity_cache = RequestLocalCache(self.load_identity) self.acl = ACLHelper() def load_identity(self, request): identity = self.authtkt.identify(request) if identity is None: return None userid = identity['userid'] user = request.dbsession.query(models.User).get(userid) return user def identity(self, request): return self.identity_cache.get_or_create(request) def authenticated_userid(self, request): user = self.identity(request) if user is not None: return user.id def remember(self, request, userid, **kw): return self.authtkt.remember(request, userid, **kw) def forget(self, request, **kw): return self.authtkt.forget(request, **kw) def permits(self, request, context, permission): principals = self.effective_principals(request) return self.acl.permits(context, principals, permission) def effective_principals(self, request): principals = [Everyone] user = self.identity(request) if user is not None: principals.append(Authenticated) principals.append('u:' + str(user.id)) principals.append('role:' + user.role) return principals
class OpenWifiAuthPolicy(CallbackAuthenticationPolicy): def __init__(self, settings): self.cookie = AuthTktCookieHelper( settings.get('auth.secret'), cookie_name = settings.get('auth.token') or 'auth_tkt', secure = asbool(settings.get('auth.secure')), timeout = asint(settings.get('auth.timeout')), reissue_time = asint(settings.get('auth.reissue_time')), max_age = asint(settings.get('auth.max_age')), ) def remember(self, request, userid, **kw): return self.cookie.remember(request, userid, **kw) def forget(self, request): return self.cookie.forget(request) # callback to verify login def callback(self, userid, request): from openwifi.models import DBSession, User, ApiKey groups = [] request.user = None request.apikey = None if userid.startswith('apikey:'): apikey_key = userid[7:] apikey = DBSession.query(ApiKey).filter(ApiKey.key == apikey_key).first() groups.append('group:apikey') if not apikey: return None request.apikey = apikey if userid.startswith('user:'******'group:users') if not user: return None request.user = user if user.is_admin: groups.append('group:admin') if userid == 'group:client_side': groups.append('group:client_side') from openwifi import node_context if type(request.context) == node_context: nodes = get_nodes(request) for node in nodes: groups.append('node:'+str(node.uuid)) return groups def unauthenticated_userid(self, request): # check for api key if 'key' in request.GET: return 'apikey:' + request.GET['key'] # check for client side certificate if all(key in request.headers for key in ["X-Forwarded-Proto", "Verified"]): if request.headers["X-Forwarded-Proto"] == "https" and \ request.headers["Verified"] == "SUCCESS": return 'group:client_side' # check for cookie for login result = self.cookie.identify(request) if result: return 'user:'******'userid']
class YSSAuthenticationPolicy(object): """A :app:`Pyramid` :term:`authentication policy`. Obtains data from a Pyramid "auth ticket" cookie. Allows for users who are *identified* (have valid credentials) but not *authenticated* (can be verified against a real user object in the 'principals' service). Constructor Arguments ``secret`` The secret (a string) used for auth_tkt cookie signing. Required. ``cookie_name`` Default: ``auth_tkt``. The cookie name used (string). Optional. ``secure`` Default: ``False``. Only send the cookie back over a secure conn. Optional. ``include_ip`` Default: ``False``. Make the requesting IP address part of the authentication data in the cookie. Optional. ``timeout`` Default: ``None``. Maximum number of seconds which a newly issued ticket will be considered valid. After this amount of time, the ticket will expire (effectively logging the user out). If this value is ``None``, the ticket never expires. Optional. ``reissue_time`` Default: ``None``. If this parameter is set, it represents the number of seconds that must pass before an authentication token cookie is automatically reissued as the result of a request which requires authentication. The duration is measured as the number of seconds since the last auth_tkt cookie was issued and 'now'. If this value is ``0``, a new ticket cookie will be reissued on every request which requires authentication. A good rule of thumb: if you want auto-expired cookies based on inactivity: set the ``timeout`` value to 1200 (20 mins) and set the ``reissue_time`` value to perhaps a tenth of the ``timeout`` value (120 or 2 mins). It's nonsensical to set the ``timeout`` value lower than the ``reissue_time`` value, as the ticket will never be reissued if so. However, such a configuration is not explicitly prevented. Optional. ``max_age`` Default: ``None``. The max age of the auth_tkt cookie, in seconds. This differs from ``timeout`` inasmuch as ``timeout`` represents the lifetime of the ticket contained in the cookie, while this value represents the lifetime of the cookie itself. When this value is set, the cookie's ``Max-Age`` and ``Expires`` settings will be set, allowing the auth_tkt cookie to last between browser sessions. It is typically nonsensical to set this to a value that is lower than ``timeout`` or ``reissue_time``, although it is not explicitly prevented. Optional. ``path`` Default: ``/``. The path for which the auth_tkt cookie is valid. May be desirable if the application only serves part of a domain. Optional. ``http_only`` Default: ``False``. Hide cookie from JavaScript by setting the HttpOnly flag. Not honored by all browsers. Optional. ``wild_domain`` Default: ``True``. An auth_tkt cookie will be generated for the wildcard domain. Optional. ``debug`` Default: ``False``. If ``debug`` is ``True``, log messages to the Pyramid debug logger about the results of various authentication steps. The output from debugging is useful for reporting to maillist or IRC channels when asking for support. ``hashalg`` Default: ``sha512`` (the literal string). Any hash algorithm supported by Python's ``hashlib.new()`` function can be used as the ``hashalg``. Cookies generated by different instances of AuthTktAuthenticationPolicy using different ``hashalg`` options are not compatible. Switching the ``hashalg`` will imply that all existing users with a valid cookie will be required to re-login. Objects of this class implement the interface described by :class:`pyramid.interfaces.IAuthenticationPolicy`. """ def __init__(self, secret, cookie_name='auth_tkt', secure=False, include_ip=False, timeout=None, reissue_time=None, max_age=None, path="/", http_only=False, wild_domain=True, hashalg='sha512', ): if hashalg == 'md5': #pragma NO COVER warnings.warn( 'The MD5 hash function is known to be ' 'susceptible to collision attacks. We recommend that ' 'you use the SHA512 algorithm instead for improved security.', DeprecationWarning, stacklevel=2 ) self.cookie = AuthTktCookieHelper( secret, cookie_name=cookie_name, secure=secure, include_ip=include_ip, timeout=timeout, reissue_time=reissue_time, max_age=max_age, http_only=http_only, path=path, wild_domain=wild_domain, hashalg=hashalg, ) def unauthenticated_userid(self, request): """ See IAuthenticationPolicy. """ result = self.cookie.identify(request) if result: userid = result['userid'] if isinstance(userid, str) and userid.startswith('persona:'): userid = userid[len('persona:'):] return userid def authenticated_userid(self, request): """ See IAuthenticationPolicy. """ context = request.context userid = self.unauthenticated_userid(request) if userid is None: return None if userid in (Authenticated, Everyone): #pragma NO COVER return None adapter = request.registry.queryMultiAdapter( (context, request), IUserLocator) if adapter is None: adapter = DefaultUserLocator(context, request) try: user = adapter.get_user_by_userid(userid) except ValueError: #pragma NO COVER user = None if user is not None: return userid def effective_principals(self, request): """ See IAuthenticationPolicy. """ context = request.context effective_principals = [Everyone] userid = self.unauthenticated_userid(request) if userid is None: return effective_principals if userid in (Authenticated, Everyone): #pragma NO COVER return None effective_principals.append(userid) effective_principals.append('system.Identified') adapter = request.registry.queryMultiAdapter( (context, request), IUserLocator) if adapter is None: adapter = DefaultUserLocator(context, request) try: user = adapter.get_user_by_userid(userid) except ValueError: user = None if user is not None: effective_principals.append(Authenticated) effective_principals.extend( adapter.get_groupids(userid)) return effective_principals def remember(self, request, principal, **kw): """ See IAuthenticationPolicy. """ return self.cookie.remember(request, principal, **kw) def forget(self, request): """ See IAuthenticationPolicy. """ return self.cookie.forget(request)
class AuthenticationPolicy(object): """ A :app:`Pyramid` :term:`authentication policy` which obtains data from a Pyramid "auth ticket" cookie. Constructor Arguments ``secret`` The secret (a string) used for auth_tkt cookie signing. Required. ``cookie_name`` Default: ``auth_tkt``. The cookie name used (string). Optional. ``secure`` Default: ``False``. Only send the cookie back over a secure conn. Optional. ``include_ip`` Default: ``False``. Make the requesting IP address part of the authentication data in the cookie. Optional. ``timeout`` Default: ``None``. Maximum number of seconds which a newly issued ticket will be considered valid. After this amount of time, the ticket will expire (effectively logging the user out). If this value is ``None``, the ticket never expires. Optional. ``reissue_time`` Default: ``None``. If this parameter is set, it represents the number of seconds that must pass before an authentication token cookie is automatically reissued as the result of a request which requires authentication. The duration is measured as the number of seconds since the last auth_tkt cookie was issued and 'now'. If this value is ``0``, a new ticket cookie will be reissued on every request which requires authentication. A good rule of thumb: if you want auto-expired cookies based on inactivity: set the ``timeout`` value to 1200 (20 mins) and set the ``reissue_time`` value to perhaps a tenth of the ``timeout`` value (120 or 2 mins). It's nonsensical to set the ``timeout`` value lower than the ``reissue_time`` value, as the ticket will never be reissued if so. However, such a configuration is not explicitly prevented. Optional. ``max_age`` Default: ``None``. The max age of the auth_tkt cookie, in seconds. This differs from ``timeout`` inasmuch as ``timeout`` represents the lifetime of the ticket contained in the cookie, while this value represents the lifetime of the cookie itself. When this value is set, the cookie's ``Max-Age`` and ``Expires`` settings will be set, allowing the auth_tkt cookie to last between browser sessions. It is typically nonsensical to set this to a value that is lower than ``timeout`` or ``reissue_time``, although it is not explicitly prevented. Optional. ``path`` Default: ``/``. The path for which the auth_tkt cookie is valid. May be desirable if the application only serves part of a domain. Optional. ``http_only`` Default: ``False``. Hide cookie from JavaScript by setting the HttpOnly flag. Not honored by all browsers. Optional. ``wild_domain`` Default: ``True``. An auth_tkt cookie will be generated for the wildcard domain. Optional. Objects of this class implement the interface described by :class:`pyramid.interfaces.IAuthenticationPolicy`. """ def __init__(self, secret, cookie_name='auth_tkt', callback = None, secure=False, include_ip=False, timeout=None, reissue_time=None, max_age=None, path="/", http_only=False, wild_domain=True): self.cookie = AuthTktCookieHelper( secret, cookie_name=cookie_name, secure=secure, include_ip=include_ip, timeout=timeout, reissue_time=reissue_time, max_age=max_age, http_only=http_only, path=path, wild_domain=wild_domain, ) self.secret = secret self.callback = callback def unauthenticated_userid(self, request): token = request.params.get('access_token') if token: t = Token() obj = t.decode(token) if obj: return obj['userid'] result = self.cookie.identify(request) if result: return result['userid'] def remember(self, request, principal, **kw): """ Accepts the following kw args: ``max_age=<int-seconds>, ``tokens=<sequence-of-ascii-strings>``""" return self.cookie.remember(request, principal, **kw) def forget(self, request): return self.cookie.forget(request) def authenticated_userid(self, request): if request.user: return request.user.id def effective_principals(self, request): principals = [Everyone] user = request.user if user: principals += [Authenticated, '%s' % user.id] if self.callback: principals.extend(('%s' % g for g in self.callback(user.id, request))) return principals
class AuthenticationPolicy(object): """ A :app:`Pyramid` :term:`authentication policy` which obtains data from a Pyramid "auth ticket" cookie. Constructor Arguments ``secret`` The secret (a string) used for auth_tkt cookie signing. Required. ``cookie_name`` Default: ``auth_tkt``. The cookie name used (string). Optional. ``secure`` Default: ``False``. Only send the cookie back over a secure conn. Optional. ``include_ip`` Default: ``False``. Make the requesting IP address part of the authentication data in the cookie. Optional. ``timeout`` Default: ``None``. Maximum number of seconds which a newly issued ticket will be considered valid. After this amount of time, the ticket will expire (effectively logging the user out). If this value is ``None``, the ticket never expires. Optional. ``reissue_time`` Default: ``None``. If this parameter is set, it represents the number of seconds that must pass before an authentication token cookie is automatically reissued as the result of a request which requires authentication. The duration is measured as the number of seconds since the last auth_tkt cookie was issued and 'now'. If this value is ``0``, a new ticket cookie will be reissued on every request which requires authentication. A good rule of thumb: if you want auto-expired cookies based on inactivity: set the ``timeout`` value to 1200 (20 mins) and set the ``reissue_time`` value to perhaps a tenth of the ``timeout`` value (120 or 2 mins). It's nonsensical to set the ``timeout`` value lower than the ``reissue_time`` value, as the ticket will never be reissued if so. However, such a configuration is not explicitly prevented. Optional. ``max_age`` Default: ``None``. The max age of the auth_tkt cookie, in seconds. This differs from ``timeout`` inasmuch as ``timeout`` represents the lifetime of the ticket contained in the cookie, while this value represents the lifetime of the cookie itself. When this value is set, the cookie's ``Max-Age`` and ``Expires`` settings will be set, allowing the auth_tkt cookie to last between browser sessions. It is typically nonsensical to set this to a value that is lower than ``timeout`` or ``reissue_time``, although it is not explicitly prevented. Optional. ``path`` Default: ``/``. The path for which the auth_tkt cookie is valid. May be desirable if the application only serves part of a domain. Optional. ``http_only`` Default: ``False``. Hide cookie from JavaScript by setting the HttpOnly flag. Not honored by all browsers. Optional. ``wild_domain`` Default: ``True``. An auth_tkt cookie will be generated for the wildcard domain. Optional. Objects of this class implement the interface described by :class:`pyramid.interfaces.IAuthenticationPolicy`. """ def __init__(self, secret, cookie_name='auth_tkt', secure=False, include_ip=False, timeout=None, reissue_time=None, max_age=None, path="/", http_only=False, wild_domain=True): self.cookie = AuthTktCookieHelper( secret, cookie_name=cookie_name, secure=secure, include_ip=include_ip, timeout=timeout, reissue_time=reissue_time, max_age=max_age, http_only=http_only, path=path, wild_domain=wild_domain, ) self.secret = secret def unauthenticated_userid(self, request): token = request.params.get('access_token') if token: t = Token() obj = t.decode(token) if obj: return obj['userid'] result = self.cookie.identify(request) if result: return result['userid'] def remember(self, request, principal, **kw): """ Accepts the following kw args: ``max_age=<int-seconds>, ``tokens=<sequence-of-ascii-strings>``""" return self.cookie.remember(request, principal, **kw) def forget(self, request): return self.cookie.forget(request) def authenticated_userid(self, request): if request.user: return request.user.id def effective_principals(self, request): principals = [Everyone] user = request.user if user: principals += [Authenticated, '%s' % user.id] if hasattr(user,'groups'): principals.extend(('g:%s' % g for g in user.groups)) return principals