def effective_principals(self, request): userid = self.authenticated_userid(request) if userid is not None: groups = group_finder(userid, request) # If the user is a moderator check the currently selected profile if len(groups) > 0 and "group:moderators" in groups: profile = get_current_profile(request) # Try to find the profile in the list of profiles associated to # current user profile_query = ( Session.query(Profile.code) .join(users_profiles) .join(User) .filter(User.username == userid) .filter(Profile.code == profile) ) try: profile_query.one() except NoResultFound: # Profile not found: User is not moderator for current # profile, remove group 'moderator' from principals principals = AuthTktAuthenticationPolicy.effective_principals(self, request) if "group:moderators" in principals: principals.remove("group:moderators") return principals # In all other cases use Pyramid's default authentication policy return AuthTktAuthenticationPolicy.effective_principals(self, request)
def unauthenticated_userid(self, request): if self._isOauth(request): return OauthAuthenticationPolicy.unauthenticated_userid( self, request) else: return AuthTktAuthenticationPolicy.unauthenticated_userid( self, request)
def forget(self, request): if self._isOauth(request): return OauthAuthenticationPolicy.forget( self, request) else: return AuthTktAuthenticationPolicy.forget( self, request)
def remember(self, request, principal, **kw): if self._isOauth(request): return OauthAuthenticationPolicy.remember( self, request, principal, **kw) else: return AuthTktAuthenticationPolicy.remember( self, request, principal, **kw)
def make_authn_policy(secret, cookie, callback=authenticate, timeout=None): ap = AuthTktAuthenticationPolicy( secret=secret, callback=callback, cookie_name=cookie, timeout=timeout) return ap
def main(): config = Configurator(root_factory=bootstrap, authentication_policy=AuthTktAuthenticationPolicy( 'seekr1t', callback=groupfinder)) config.include('pyramid_chameleon') config.scan("views") app = config.make_wsgi_app() return app
def include_authentication(config): settings = config.registry.settings debug = asbool(settings.get('auth.debug', 'false')) http_only = asbool(settings.get('auth.http_only', 'true')) authn_policy = AuthTktAuthenticationPolicy(settings['auth.secret'], debug=debug, http_only=http_only) config.set_authentication_policy(authn_policy)
def includeme(config): """Security-related configuration.""" auth_secret = os.environ.get('AUTH_SECRET') authn_policy = AuthTktAuthenticationPolicy(secret=auth_secret, hashalg='sha512') config.set_authentication_policy(authn_policy) authz_policy = ACLAuthorizationPolicy() config.set_authorization_policy(authz_policy)
def main(): config = Configurator( root_factory=bootstrap, authentication_policy=AuthTktAuthenticationPolicy('seekr1t'), ) config.scan("views") app = config.make_wsgi_app() return app
def _setup_ticket_policy(config, params): """ Setup Pyramid AuthTktAuthenticationPolicy. Notes: * Initial `secret` params value is considered to be a name of config param that represents a cookie name. * `auth_model.get_groups_by_userid` is used as a `callback`. * Also connects basic routes to perform authentication actions. :param config: Pyramid Configurator instance. :param params: Nefertari dictset which contains security scheme `settings`. """ from nefertari.authentication.views import (TicketAuthRegisterView, TicketAuthLoginView, TicketAuthLogoutView) log.info('Configuring Pyramid Ticket Authn policy') if 'secret' not in params: raise ValueError('Missing required security scheme settings: secret') params['secret'] = config.registry.settings[params['secret']] auth_model = config.registry.auth_model params['callback'] = auth_model.get_groups_by_userid config.add_request_method(auth_model.get_authuser_by_userid, 'user', reify=True) policy = AuthTktAuthenticationPolicy(**params) RegisterViewBase = TicketAuthRegisterView if config.registry.database_acls: class RegisterViewBase(ACLAssignRegisterMixin, TicketAuthRegisterView): pass class RamsesTicketAuthRegisterView(RegisterViewBase): Model = config.registry.auth_model class RamsesTicketAuthLoginView(TicketAuthLoginView): Model = config.registry.auth_model class RamsesTicketAuthLogoutView(TicketAuthLogoutView): Model = config.registry.auth_model common_kw = { 'prefix': 'auth', 'factory': 'nefertari.acl.AuthenticationACL', } root = config.get_root_resource() root.add('register', view=RamsesTicketAuthRegisterView, **common_kw) root.add('login', view=RamsesTicketAuthLoginView, **common_kw) root.add('logout', view=RamsesTicketAuthLogoutView, **common_kw) return policy
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ engine = engine_from_config(settings, 'sqlalchemy.') session_factory = session_factory_from_settings(settings) authn_policy = AuthTktAuthenticationPolicy( 's0secret!!', callback=groupfinder,) authz_policy = ACLAuthorizationPolicy() DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings, authentication_policy=authn_policy, authorization_policy=authz_policy, session_factory=session_factory, root_factory=Root) # using a custom request with user information config.set_request_factory(RequestWithUserAttribute) config.include('pyramid_mailer') config.add_translation_dirs( 'colander:locale/', 'deform:locale/', 'c3smembership:locale/') config.add_static_view('static', 'c3smembership:static', cache_max_age=3600) config.add_subscriber('c3smembership.subscribers.add_base_template', 'pyramid.events.BeforeRender') config.add_subscriber('c3smembership.subscribers.add_locale_to_cookie', 'pyramid.events.NewRequest') # home is /, the membership application form config.add_route('join', '/') # info pages config.add_route('disclaimer', '/disclaimer') config.add_route('faq', '/faq') config.add_route('statute', '/statute') config.add_route('manifesto', '/manifesto') # success and further steps config.add_route('success', '/success') config.add_route('success_check_email', '/check_email') config.add_route('verify_email_password', '/verify/{email}/{code}') config.add_route('success_pdf', '/C3S_SCE_AFM_{namepart}.pdf') # routes & views for staff config.add_route('dashboard', '/dashboard/{number}') config.add_route('detail', '/detail/{memberid}') config.add_route('switch_sig', '/switch_sig/{memberid}') config.add_route('switch_pay', '/switch_pay/{memberid}') config.add_route('delete_entry', '/delete/{memberid}') config.add_route('login', '/login') config.add_route('logout', '/logout') config.scan() return config.make_wsgi_app()
def includeme(config): from pyramid.authentication import AuthTktAuthenticationPolicy from pyramid.authorization import ACLAuthorizationPolicy authn_policy = AuthTktAuthenticationPolicy('seekt1t', hashalg='sha512') authz_policy = ACLAuthorizationPolicy() config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) config.add_view(test, name='test') config.add_view(x_view, name='x', permission='private')
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ # Load secret stuff from secret.ini. try: default_path = os.path.abspath("secret.ini") secret_path = settings.get('secret_config_path', default_path) # TODO: There is a better way to log this message than print. print "Reading secrets from %r" % secret_path parser = ConfigParser.ConfigParser() parser.read(secret_path) secret_config = dict(parser.items("github2fedmsg")) settings.update(secret_config) except Exception as e: # TODO: There is a better way to log this message than print. print 'Failed to load secret.ini. Reason: %r' % str(e) crappy_session_factory = UnencryptedCookieSessionFactoryConfig( settings['session.secret']) authn_policy = AuthTktAuthenticationPolicy(secret=settings['authnsecret'], hashalg='sha256') engine = engine_from_config(settings, 'sqlalchemy.') github2fedmsg.models.DBSession.configure(bind=engine) config = Configurator( settings=settings, root_factory=github2fedmsg.traversal.make_root, session_factory=crappy_session_factory, authentication_policy=authn_policy, #authorization_policy=authz_policy, ) # Make it so we can do "request.user" in templates. config.set_request_property(get_user, 'user', reify=True) config.include('pyramid_mako') config.add_mako_renderer('.mak') config.include('velruse.providers.github') config.add_github_login_from_settings() config.include('velruse.providers.openid') github2fedmsg.custom_openid.add_openid_login( config, realm=settings.get('velruse.openid.realm'), identity_provider=settings.get('velruse.openid.identifier'), ) config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('logout', '/logout') config.add_route('webhook', '/webhook') config.add_route('forget_github_token', '/forget_github_token') config.scan() return config.make_wsgi_app()
def includeme(config): config.set_root_factory(NewRoot) authn_secret = config.registry.settings['authn.secret'] authn_policy = AuthTktAuthenticationPolicy(authn_secret, hashalg="sha512") config.set_authentication_policy(authn_policy) authz_policy = ACLAuthorizationPolicy() config.set_authorization_policy(authz_policy)
def includeme(config): authn_policy = AuthTktAuthenticationPolicy('seekri1', hashalg='sha512') authz_policy = ACLAuthorizationPolicy() config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) config.set_default_permission('a') config.add_route('foo', '/foo') config.add_route('bar', '/bar') config.scan('pyramid.tests.pkgs.forbiddenview')
def includeme(config): """Authentication and authorization configuration.""" auth_secret = os.environ.get('AUTH_SECRET', 'secret authentication secret') authn_policy = AuthTktAuthenticationPolicy(secret=auth_secret, hashalg='sha512') config.set_authentication_policy(authn_policy) config.set_authorization_policy(ACLAuthorizationPolicy()) config.set_default_permission('view') config.set_root_factory(Root)
def auth_tuple(): '''Returns a tuple of 2 auth/auth objects, for configuration.''' from pyramid.authentication import AuthTktAuthenticationPolicy return (AuthTktAuthenticationPolicy('WeLoveCarlSagan', callback=find_groups, include_ip=True, timeout=60 * 60 * 3, reissue_time=60), None ) # ACLAuthorizationPolicy())
def includeme(config): from pyramid.authentication import AuthTktAuthenticationPolicy from pyramid.authorization import ACLAuthorizationPolicy authn_policy = AuthTktAuthenticationPolicy('seekr1t', hashalg='sha512') authz_policy = ACLAuthorizationPolicy() config._set_authentication_policy(authn_policy) config._set_authorization_policy(authz_policy) config.add_view(x_view, name='x', permission='private') config.add_view(forbidden_view, context=HTTPForbidden)
def includeme(config): from pyramid.authorization import ACLAuthorizationPolicy from pyramid.authentication import AuthTktAuthenticationPolicy authn_policy = AuthTktAuthenticationPolicy('seekt1t') authz_policy = ACLAuthorizationPolicy() config.scan('pyramid.tests.defpermbugapp') config._set_authentication_policy(authn_policy) config._set_authorization_policy(authz_policy) config.set_default_permission('private')
def includeme(config): authn_policy = AuthTktAuthenticationPolicy( 'sosecret', callback=groupfinder, ) config.set_authentication_policy(authn_policy) config.set_authorization_policy(ACLAuthorizationPolicy()) config.set_root_factory(Root)
def forget(self, request): nickname = request.authenticated_userid headers = Policy.forget(self, request) request.db['users'].find_and_modify( query={'nickname': nickname}, update={'$set': { 'logged_in': False }}) return headers
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ authn_policy = AuthTktAuthenticationPolicy( settings['auth.secret'], secure=True, http_only=True, timeout=int(settings['auth.timeout']), max_age=int(settings['auth.timeout']), callback=groupfinder) authz_policy = ACLAuthorizationPolicy() engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings, authentication_policy=authn_policy, authorization_policy=authz_policy, root_factory=Root) if config.get_settings().get('cors.preflight', None) == 'true': config.include('.cors') config.add_cors_preflight_handler() config.include("cornice") config.include('pyramid_mako') config.add_static_view('static', 'static', cache_max_age=3600) upload_dir = os.path.abspath(settings['upload_dir']) config.add_static_view('upload', upload_dir, cache_max_age=3600) config.add_renderer('jsonp', JSONP(param_name='callback')) config.scan(ignore=['modmod.scripts', 'modmod.tests']) config.include('.config') config.include('modmod.views') config.include('modmod.views.util') safile_settings = { 'file.storages': ['fs:' + settings['upload_dir']], 'fs.' + settings['upload_dir'] + '.asset_path': '/upload/', } pyramid_safile.init_factory(safile_settings) init_worker(settings, safile_settings) stripe.api_key = settings['stripe.api_key'] if not "CI" in os.environ and os.path.isfile( 'secret/fbServiceAccountKey.json'): cred = credentials.Certificate('secret/fbServiceAccountKey.json') default_firebase_app = firebase_admin.initialize_app(cred) signal.signal(signal.SIGINT, sigint_handler) signal.signal(signal.SIGTERM, sigint_handler) signal.signal(signal.SIGHUP, sigint_handler) return config.make_wsgi_app()
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine init_model() session_factory = session_factory_from_settings(settings) if 'localization' not in settings: settings['localization'] = 'id_ID.UTF-8' locale.setlocale(locale.LC_ALL, settings['localization']) if 'timezone' not in settings: settings['timezone'] = DefaultTimeZone config = Configurator(settings=settings, root_factory='webr.models.RootFactory', session_factory=session_factory) config.include('pyramid_beaker') config.include('pyramid_chameleon') authn_policy = AuthTktAuthenticationPolicy('sosecret', callback=group_finder, hashalg='sha512') authz_policy = ACLAuthorizationPolicy() config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) config.add_request_method(get_user, 'user', reify=True) config.add_request_method(get_title, 'title', reify=True) config.add_request_method(get_months, 'months', reify=True) config.add_notfound_view(RemoveSlashNotFoundViewFactory()) config.add_static_view('static', 'static', cache_max_age=3600) config.add_static_view('deform_static', 'deform:static') config.add_static_view('static_files', 'static_files', cache_max_age=3600) config.add_static_view('reports', 'reports') config.add_static_view('files', settings['static_files']) config.add_static_view('js', 'js') config.add_renderer('csv', '.tools.CSVRenderer') routes = DBSession.query(Route.kode, Route.path, Route.nama, Route.factory).all() for route in routes: if route.factory and route.factory != 'None': config.add_route( route.kode, route.path, factory=route.factory) #(route.factory).encode("utf8")) else: config.add_route(route.kode, route.path) if route.nama: titles[route.kode] = route.nama config.scan() return config.make_wsgi_app()
def createAuthFramework(config): settings = config.get_settings() # no timeout is default timeout = settings.get("authentication.session_timeout", 3600) if timeout in ["None", "null", ""]: timeout = None reissue_timeout = None if timeout is not None: timeout = float(timeout) reissue_timeout = float(timeout)/10.0 hashSecret = settings.get("authentication.secret", None) if hashSecret is None: # generate one as random hashSecret = str(base64.b85encode(bytes([random.randrange(0, 256) for _ in range(12)])), 'utf-8') authn_policy = AuthTktAuthenticationPolicy(hashSecret, hashalg='sha512', callback=groupfinder, timeout=timeout, reissue_time=reissue_timeout) authz_policy = ACLAuthorizationPolicy() config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) static_assets_login = os.path.join(repository_root, 'login') # that might come from peter_config # confusingly this is the same right now! static_assets_project = os.path.join(repository_root, 'example_external_project') from peter import peter p = peter(config, static_assets_login, static_assets_project, checkUserPassword=credentialsCheck, checkUserEmail=checkUserEmail, sendPasswordResetEmail=sendPasswordResetEmail, setNewPasswordHash=resetPassword, storeRequestToken=storeToken, retreiveRequestToken=retreiveToken, deleteRequestToken=invalidateToken, projectMinPermissions="view" ) # and now a catch-all which serves the project's static files config.add_route("protectedProject", "/*subpath", factory=RootFactory) config.add_view(p.staticAssetsProjectView, route_name="protectedProject")
def demo_app(global_config, **settings): """Return the example application for stucco_auth.""" from stucco_auth.models import get_root engine = sqlalchemy.engine_from_config(settings) Session = sqlalchemy.orm.sessionmaker(bind=engine) settings[SESSION_FACTORY_KEY] = Session session = Session() try: import stucco_evolution stucco_evolution.initialize(session.connection()) stucco_evolution.create_or_upgrade_packages(session.connection(), 'stucco_auth') tkt_secret = auth_tkt_secret(session) authentication_policy = AuthTktAuthenticationPolicy( tkt_secret.value, callback=security.lookup_groups) authorization_policy = ACLAuthorizationPolicy() config = Configurator(root_factory=get_root, settings=settings, authentication_policy=authentication_policy, authorization_policy=authorization_policy) config.add_renderer('.jinja2', pyramid_jinja2.renderer_factory) # Configure beaker session: import pyramid_beaker session_factory = \ pyramid_beaker.session_factory_from_settings(settings) config.set_session_factory(session_factory) config.include('stucco_auth.includeme') config.add_static_view('static', 'stucco_auth:static') config.add_view(context=IAuthRoot, renderer='welcome.jinja2') # event handler will only work if stucco_auth.tm is being used config.add_subscriber(new_request_listener, NewRequest) app = config.make_wsgi_app() tm = TM(app, Session) # For pshell compatibility: tm.registry, tm.threadlocal_manager, tm.root_factory = \ app.registry, app.threadlocal_manager, app.root_factory # In case database work was done during init: session.commit() except: session.rollback() raise finally: session.close() return tm
def main(global_config, **settings): engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings, root_factory='.resources.Root') config.include('pyramid_mako') # Security policies authn_policy = AuthTktAuthenticationPolicy(settings['service_app.secret'], callback=groupfinder, hashalg='sha512') authz_policy = ACLAuthorizationPolicy() config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) config.add_route('home', '/') config.add_route('landlord_login', '/landlord/login') config.add_route('landlord_logout', '/landlord/logout') config.add_route('landlord_register', '/landlord/reg') config.add_route('landlord_profile', '/landlord/profile') config.add_route('landlord_delete', '/landlord/delete') config.add_route('landlord_edit', '/landlord/edit') config.add_route('landlord_view_pending_orders', '/landlord/pending') config.add_route('landlord_view_orders', '/landlord/orders') config.add_route('landlord_confirm_order', '/landlord/order/{order_id}/confirm') # landlord address config.add_route('landlord_address_new', '/landlord/address/add') config.add_route('landlord_address_edit', '/landlord/address/{uid}/edit') config.add_route('landlord_address_view', '/landlord/address/{uid}/view') config.add_route('landlord_address_delete', '/landlord/address/{uid}/delete') # student config.add_route('student_login', '/student/login') config.add_route('student_logout', '/student/logout') config.add_route('student_register', '/student/reg') config.add_route('student_profile', '/student/profile') config.add_route('student_delete', '/student/delete') config.add_route('student_edit', '/student/{uid}/edit') config.add_route('student_view_pending_orders', '/student/{uid}/pending') config.add_route('student_view_orders', '/student/{uid}/orders') config.add_route('address_search', '/search') config.add_route('place_order', '/address/{uid}/order/place') config.add_route('confirm_order', 'order/{uid}/confirm') # config.add_route('login', '/') # config.add_route('login', '/login') # config.add_route('logout', '/logout') config.add_static_view('deform_static', 'deform:static/') config.add_static_view(name='static', path='service_app:static/') #config.add_static_view('static', 'static', 'service_app:static/') config.scan('.controllers') return config.make_wsgi_app()
def getAuthTktAuthenticationPolicy(): """Define the authentication policy for Tkt""" return AuthTktAuthenticationPolicy( Configuration.get('pyramid_authtkt_secret'), callback=Configuration.get('pyramid_authentication_callback'), cookie_name=Configuration.get('pyramid_authtkt_cookie_name'), secure=Configuration.get('pyramid_authtkt_secure'), timeout=Configuration.get('pyramid_authtkt_timeout'), max_age=Configuration.get('pyramid_authtkt_max_age'), debug=Configuration.get('pyramid_authentication_debug'))
def includeme(config): settings = config.registry.settings authn_policy = AuthTktAuthenticationPolicy(settings.get('auth.secret'), callback=group_finder) authz_policy = ACLAuthorizationPolicy() config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) config.set_root_factory(RootFactory) config.set_request_factory(RequestWithUserAttribute)
def includeme(config): """Security configureation for survivor_pool.""" auth_secret = os.environ.get('AUTH_SECRET', 'itsaseekrit') authn_policy = AuthTktAuthenticationPolicy(secret=auth_secret, hashalg='sha512') config.set_authentication_policy(authn_policy) authz_policy = ACLAuthorizationPolicy() config.set_authorization_policy(authz_policy) config.set_default_permission('private') config.set_root_factory(UserAuth)
def __init__(self, secret='key', callback=None): self.impl = { 'basic': AuthBasicAuthenticationPolicy(callback=callback), 'tk': AuthTktAuthenticationPolicy(secret, callback=callback, hashalg='sha512') } self.callback = callback
def includeme(config): """Security-related configuration.""" auth_secret = os.environ.get('AUTH_SECRET', '') authn_policy = AuthTktAuthenticationPolicy(secret=auth_secret, hashalg='sha512') config.set_authentication_policy(authn_policy) authz_policy = ACLAuthorizationPolicy() config.set_authorization_policy(authz_policy) config.set_default_permission('view') config.set_root_factory(MyRoot)
def includeme(config): # purposely sorta-randomly ordered (route comes after view naming it, # authz comes after views) config.add_view(aview) config.add_view(protectedview, name='protected', permission='view') config.add_view(routeview, route_name='aroute') config.add_route('aroute', '/route') config.set_authentication_policy(AuthTktAuthenticationPolicy('seekri1t')) config.set_authorization_policy(ACLAuthorizationPolicy()) config.include('pyramid.tests.pkgs.conflictapp.included')
def make_app(global_config, **settings): """Return the WSGI application.""" nginx_upload_progress = settings.get('poulda.nginx_upload_progress', 'false').lower() == 'true' if not nginx_upload_progress: from poulda.models import initialize_db initialize_db(settings['poulda.db_url']) config = Configurator(settings=settings) config.include('pyramid_chameleon') # Authentication and authorization policies auth_policy = AuthTktAuthenticationPolicy(settings['poulda.secret']) config.set_authentication_policy(auth_policy) authz_policy = AuthorizationPolicy() config.set_authorization_policy(authz_policy) # Views config.set_default_permission(PERMISSION_UPLOAD) config.add_static_view('static', 'static') config.add_route('home', '/') config.add_view('poulda.views.home', route_name='home', permission=NO_PERMISSION_REQUIRED) config.add_route('upload_form', '/upload', request_method='GET') config.add_view('poulda.views.upload_form', route_name='upload_form') config.add_route('upload', '/upload', request_method='POST') if nginx_upload_progress: upload_view = 'poulda.views.upload_with_nginx_upload_progress' else: upload_view = 'poulda.views.upload' config.add_view(upload_view, route_name='upload') if not nginx_upload_progress: # We need this view only if Nginx Upload Progress has been # disabled. config.add_route('progress', '/progress') config.add_view('poulda.views.progress', route_name='progress', renderer='json') config.add_route('success', '/success') config.add_view('poulda.views.success', route_name='success') config.add_route('login', '/login', request_method='POST') config.add_view('poulda.views.login', route_name='login', permission=NO_PERMISSION_REQUIRED) config.add_route('logout', '/logout') config.add_view('poulda.views.logout', route_name='logout') config.add_view('poulda.views.forbidden', context=HTTPForbidden, permission=NO_PERMISSION_REQUIRED) # Internationalization config.add_translation_dirs('poulda:locale') config.set_locale_negotiator('poulda.i18n.locale_negotiator') return config.make_wsgi_app()
def setup_ringo_security(config): settings = config.registry.settings timeout = get_auth_timeout(settings) + 5 secret = get_cookie_secret(settings) secure = settings.get("security.cookie_secure", "false") == "true" include_ip = settings.get("security.cookie_ip", "false") == "true" path = settings.get("security.cookie_path", "/") domain = settings.get("security.cookie_domain") httponly = settings.get("security.cookie_httponly", "false") == "true" cookie_name = settings.get("security.cookie_name", "auth_tkt") authn_policy = AuthTktAuthenticationPolicy(secret, secure=secure, hashalg='sha512', timeout=timeout, reissue_time=timeout / 10, callback=get_principals, include_ip=include_ip, path=path, domain=domain, http_only=httponly, cookie_name=cookie_name) authz_policy = ACLAuthorizationPolicy() config.set_authorization_policy(authz_policy) config.set_authentication_policy(authn_policy) # Make the user object available as attribute "user" in the request. # See http://docs.pylonsproject.org/projects/ \ # pyramid_cookbook/en/latest/auth/ \ # user_object.html config.add_request_method(get_user, 'user', reify=True) # Add subscriber to check the CSRF token in POST requests. You can # disable this for testing by setting the # "security.enable_csrf_check" config variable to "false". if settings.get('security.enable_csrf_check', 'true') != "false": config.add_subscriber(csrf_token_validation, ContextFound) # Refresh the auth cookie timeout on every request. On default this # would only happen on requests which needs # authentification/authorisation. As the authentification should be # valid as long the user shows some activity by triggering requests # this tween will refresh the timeout on every request. config.add_subscriber(refresh_auth_cookie, NewRequest) # Add tweens to add custom security headers. # http://ghaandeeonit.tumblr.com/post/65698553805/securing-your-pyramid-application if settings.get("security.header_secure", "true") == "true": config.add_tween('ringo.tweens.secure_headers.secure_headers_factory') if settings.get("security.header_clickjacking", "true") == "true": config.add_tween('ringo.tweens.clickjacking.clickjacking_factory') if settings.get("security.header_csp", "false") == "true": config.add_tween('ringo.tweens.csp.csp_factory') if get_anonymous_user(settings): log.info("Setting up anonymous access.") config.add_tween('ringo.tweens.anonymous_access.user_factory') else: config.add_tween('ringo.tweens.anonymous_access.ensure_logout')
def authenticated_userid(self, request): # First handle request made with HTTP Basic Authentication. # Such request can e.g. come from external clients like a QGIS plugin credentials = self._get_basicauth_credentials(request) if credentials is not None: if User.check_password(credentials["login"], credentials["password"]): # Return the user id if the login and password are correct return credentials["login"] else: raise HTTPUnauthorized() return AuthTktAuthenticationPolicy.authenticated_userid(self, request)
def remember(self, request, nickname): headers = Policy.remember(self, request, nickname) request.db['users'].find_and_modify( query={ 'nickname': nickname }, update={ '$set': { 'logged_in': True } } ) return headers
def forget(self, request): nickname = request.authenticated_userid headers = Policy.forget(self, request) request.db['users'].find_and_modify( query={ 'nickname': nickname }, update={ '$set': { 'logged_in': False } } ) return headers
def __init__(self, secret='cll_sec', cookie_name='cll_tkt', secure=False, include_ip=False, timeout=None, reissue_time=None, max_age=None, path="/", http_only=False, wild_domain=True, debug=False, hashalg=_marker, parent_domain=False, domain=None): if hashalg==_marker: hashalg="sha512" callback=auth_callback AuthTktAuthenticationPolicy.__init__(self, secret=secret, cookie_name=cookie_name, secure=secure, include_ip=include_ip, timeout=timeout, reissue_time=reissue_time, max_age=max_age, path=path, http_only=http_only, wild_domain=wild_domain, debug=debug, hashalg=hashalg, parent_domain=parent_domain, domain=domain)
def __init__(self, secret, realm='Realm', hardcoded=()): """ We need to initialise variables here for both forms of auth which we're planning on using. :param secret: A hashing secret for AuthTkt, which should be generated outside the Pyhton process. :param realm: The Basic Auth realm which is probably set to eos_db. :param hardcoded: Triplets of user:password:group that should not be looked up in the database. """ self.hardcoded = { x[0]: (x[1],x[2]) for x in hardcoded } #DELETE ME #self.check = check # Password check routine passed to the constructor. #self.realm = realm # Basic Auth realm. # Now initialise both Auth Policies. AuthTkt has sha256 specified in # place of the default MD5 in order to suppress warnings about # security. self.bap = BasicAuthAuthenticationPolicy(check=self.passwordcheck, realm=realm) self.tap = AuthTktAuthenticationPolicy(secret=secret, callback=self.groupfinder, cookie_name='auth_tkt', hashalg='sha256')
class HybridAuthenticationPolicy(): """ HybridAuthenticationPolicy. Called in the same way as other auth policies, but wraps Basic and AuthTkt. This policy also caches password lookups by remembering them in the request object. """ def __init__(self, secret, realm='Realm', hardcoded=()): """ We need to initialise variables here for both forms of auth which we're planning on using. :param secret: A hashing secret for AuthTkt, which should be generated outside the Pyhton process. :param realm: The Basic Auth realm which is probably set to eos_db. :param hardcoded: Triplets of user:password:group that should not be looked up in the database. """ self.hardcoded = { x[0]: (x[1],x[2]) for x in hardcoded } #DELETE ME #self.check = check # Password check routine passed to the constructor. #self.realm = realm # Basic Auth realm. # Now initialise both Auth Policies. AuthTkt has sha256 specified in # place of the default MD5 in order to suppress warnings about # security. self.bap = BasicAuthAuthenticationPolicy(check=self.passwordcheck, realm=realm) self.tap = AuthTktAuthenticationPolicy(secret=secret, callback=self.groupfinder, cookie_name='auth_tkt', hashalg='sha256') #Utility functions to interact with eos_db.server def groupfinder(self, username, request): """ Return the user group (just one) associated with the user. This uses a server function to check which group a user has been associated with. This provides the standard callback wanted by AuthTktAuthenticationPolicy. An alternative would be to encode the groups in the Tkt. The mapping of groups to actual capabilities is stored in views.PermissionsMap """ group = server.get_user_group(username) if group: return ["group:" + str(group)] def passwordcheck(self, login, password, request): """Password checking callback. """ hc = self.hardcoded if login in hc and hc[login][0] == password: return ['group:' + hc[login][1]] elif server.check_password(login, password): user_group = server.get_user_group(login) log.debug("Found user group %s" % user_group) return ['group:' + user_group] else: log.debug("Password chack failed for user %s" % login) return None def unauthenticated_userid(self, request): """ Return the userid parsed from the auth ticket cookie. If this does not exist, then check the basic auth header, and return that, if it exists. """ #Allow forcing the auth_tkt cookie. Helpful for JS calls. #Maybe move this to a callback so it only ever happens once? if request.headers.get('auth_tkt'): request.cookies['auth_tkt'] = request.headers['auth_tkt'] #Or, surely: return ( self.tap.unauthenticated_userid(request) or self.bap.unauthenticated_userid(request) ) def authenticated_userid(self, request): """ Return the Auth Ticket user ID if that exists. If not, then check for a user ID in Basic Auth. """ try: return request.cached_authenticated_userid except: #Proceed to look-up then pass #Allow forcing the auth_tkt cookie. if request.headers.get('auth_tkt'): request.cookies['auth_tkt'] = request.headers['auth_tkt'] request.cached_authenticated_userid = ( self.tap.unauthenticated_userid(request) or self.bap.unauthenticated_userid(request) ) return request.cached_authenticated_userid def effective_principals(self, request): """ Returns the list of effective principles from the auth policy under which the user is currently authenticated. Auth ticket takes precedence. """ try: return request.cached_effective_principals except: #Proceed to look-up then pass #Allow forcing the auth_tkt cookie. if request.headers.get('auth_tkt'): request.cookies['auth_tkt'] = request.headers['auth_tkt'] userid = self.tap.authenticated_userid(request) if userid: request.cached_effective_principals = self.tap.effective_principals(request) else: request.cached_effective_principals = self.bap.effective_principals(request) return request.cached_effective_principals def remember(self, request, principal, **kw): """Causes the session info to be remembered by passing the appropriate AuthTkt into the response. """ # We always rememeber by creating an AuthTkt, but only if there is something to remember # and if the user was not in the hard-coded list. if principal and principal not in self.hardcoded: return self.tap.remember(request, principal, **kw) else: return () def forget(self, request): """ Forget both sessions. """ return self.bap.forget(request) + self.tap.forget(request) def get_forbidden_view(self, request): """ Fire a 401 when authentication needed. """ # FIXME - this doesn't distinguish between unauthenticated and # unauthorized. Should it? if request.headers.get('auth_tkt'): return HTTPRequestTimeout() #print ("Access Forbidden") response = HTTPUnauthorized() response.headers.extend(self.bap.forget(request)) return response
def unauthenticated_userid(self, request): credentials = self._get_basicauth_credentials(request) if credentials is not None: return credentials["login"] return AuthTktAuthenticationPolicy.unauthenticated_userid(self, request)
def __init__(self, security_string, **kwargs): AuthTktAuthenticationPolicy.__init__(self, security_string, **kwargs)
def __init__(self, *args, **kwargs): OauthAuthenticationPolicy.__init__(self) AuthTktAuthenticationPolicy.__init__(self, *args, **kwargs)