def includeme(config): config.include('dashboard') config.commit() config.get_jinja2_environment().filters['friendly_group_name'] =\ friendly_group_name # hook up our submission handlers hook_submission_handlers() # request methods config.add_request_method(get_request_user, 'user', reify=True) config.add_request_method(is_current_path) # pyramid_jinja2 is already included by Dashboard config.add_jinja2_search_path("composting:templates") config.add_renderer('xlsx', 'composting.views.renderers.TablibXLSXRenderer') config.add_static_view('static', 'composting:static', cache_max_age=3600) config.add_static_view('docs', '../docs/_build/html', cache_max_age=3600) config.add_route('default', '/') config.add_route('auth', '/auth/{action}') config.add_route('oauth', '/oauth/{action}') config.add_route('municipalities', '/municipalities/*traverse', factory=MunicipalityFactory) config.add_route('submissions', '/submissions/*traverse', factory=SubmissionFactory) config.add_route('skips', '/skips/*traverse', factory=SkipFactory) config.add_route('users', '/users/*traverse', factory=UserFactory) config.scan()
def configure_helpers(config): def is_https(request): return request.environ.get('HTTP_X_FORWARDED_PROTO', '').lower() == 'https' def get_cleaver(request): """ For retrieving the A/B Testing toolkit Usage: cleaver = request.get_cleaver() button_size = cleaver( 'Button Size', ('Small', 12), ('Medium', 18), ('Large', 24) ) where each () is (name of variant, value returned by cleaver) and then to mark a conversion: cleaver.score('Button Size') """ cleaver = Cleaver( environ=request.environ, identity=lambda environ: request.session.get('session_uid'), backend=SQLAlchemyBackend(request.registry.settings['giza.cleaver_backend']), count_humans_only=False ) return cleaver config.add_request_method(is_https, str('is_https'), reify=True) config.add_request_method(get_cleaver)
def main(*args, **settings): from pyramid.config import Configurator from pyramid.events import NewRequest, ContextFound from pyramid.authentication import BasicAuthAuthenticationPolicy from pyramid.authorization import ACLAuthorizationPolicy from pyramid.renderers import JSON, JSONP logger.info('Start registry api...') read_users(settings['auth.file']) config = Configurator(autocommit=True, settings=settings, authentication_policy=BasicAuthAuthenticationPolicy( auth_check, __name__), authorization_policy=ACLAuthorizationPolicy(), root_factory=Root, route_prefix=ROUTE_PREFIX) config.include('pyramid_exclog') config.add_forbidden_view(forbidden) config.add_request_method(request_params, 'params', reify=True) config.add_request_method(authenticated_role, reify=True) config.add_renderer('prettyjson', JSON(indent=4)) config.add_renderer('jsonp', JSONP(param_name='opt_jsonp')) config.add_renderer('prettyjsonp', JSONP(indent=4, param_name='opt_jsonp')) config.add_subscriber(add_logging_context, NewRequest) config.add_subscriber(set_logging_context, ContextFound) config.add_subscriber(set_renderer, NewRequest) config.add_route('health', '/health') config.add_route('registry', '/registry/{param}.json') config.scan('openprocurement.medicines.registry.api.views') return config.make_wsgi_app()
def configure_auth(config): def get_current_user(request): # NOTE: we have to use unauthenticated_userid below. This just cracks open # the auth cookie and returns the id therein without further verification. # Specifically, we cannot use authenticated_userid because this will call # get_principals, defined below. This would cause infinite recursion. uid = unauthenticated_userid(request) user = logic.user.try_get(uid) if uid is not None else None return user def get_impersonator_user(request): uid = request.session.get('impersonator_id') user = logic.user.try_get(uid) if uid is not None else None return user def get_principals(user_id, request): """ Return the set of security principals for this request. None means unauthenticated, empty list means authenticated but has no principals associated. """ user = request.current_user impersonator = request.impersonator_user if user: principals = [str(user.id)] # at minimum, user is his own principal principals.extend(user.groups or []) if impersonator: principals.extend(impersonator.groups or []) principals = list(set(principals)) else: principals = None return principals the_settings = config.registry.settings policy = AuthTktAuthenticationPolicy( the_settings['giza.authn_secret'], hashalg='sha512', callback=get_principals, cookie_name=str(the_settings['giza.auth_cookie']) # can't be unicode ) config.set_authentication_policy(policy) config.set_authorization_policy(ACLAuthorizationPolicy()) config.add_request_method(get_current_user, str('current_user'), reify=True) config.add_request_method(get_impersonator_user, str('impersonator_user'), reify=True) session_cookie_name = str(the_settings['giza.session_cookie']) # can't be unicode session_secret = str(the_settings['giza.session_secret']) factory = UnencryptedCookieSessionFactoryConfig( session_secret, timeout=86400*365, cookie_max_age=86400*365, cookie_name=session_cookie_name, ) config.set_session_factory(factory)
def includeme(config): # Configure the standard library logging logging.config.dictConfig({ "version": 1, "disable_existing_loggers": False, "formatters": { "structlog": { "()": "warehouse.logging.StructlogFormatter", }, }, "handlers": { "primary": { "class": "logging.StreamHandler", "stream": "ext://sys.stdout", "formatter": "structlog", }, "sentry": { "class": "raven.handlers.logging.SentryHandler", "level": "ERROR", "dsn": config.registry.settings.get("sentry.dsn"), "release": config.registry.settings.get("warehouse.commit"), "transport": config.registry.settings.get("sentry.transport"), }, }, "root": { "level": config.registry.settings.get("logging.level", "INFO"), "handlers": ["primary", "sentry"], }, }) # Configure structlog structlog.configure( processors=[ structlog.stdlib.filter_by_level, structlog.stdlib.add_logger_name, structlog.stdlib.add_log_level, structlog.stdlib.PositionalArgumentsFormatter(), structlog.processors.StackInfoRenderer(), structlog.processors.format_exc_info, RENDERER, ], logger_factory=structlog.stdlib.LoggerFactory(), wrapper_class=structlog.stdlib.BoundLogger, cache_logger_on_first_use=True, ) # Give every request a unique identifier config.add_request_method(_create_id, name="id", reify=True) # Add a log method to every request. config.add_request_method(_create_logger, name="log", reify=True)
def main(global_config, **settings): logging.config.fileConfig(settings['logging.config'], disable_existing_loggers=False) """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings, root_factory='jungo.model.RootFactory') config.include('pyramid_chameleon') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/old-home') config.add_route('search', '/') config.add_route('common_interests', '/common-interests') config.add_route('profile', '/me') config.add_route('user', '/user/{username}') config.add_route('login', '/login') config.add_route('logout', '/logout') config.add_route('interest_match', '/interest-match/{username}/{interest_id}') config.add_route('api_add_user', '/api/user', request_method='POST') config.add_route('api_user', '/api/user/{username}', request_method='GET') config.add_route('api_add_interests', '/api/user/{username}/interests', request_method='POST') config.add_route('api_common_interests', '/api/common-interests', request_method='GET') authn_policy = AuthTktAuthenticationPolicy('super secret magic', callback=groupfinder, hashalg='sha512') authz_policy = ACLAuthorizationPolicy() config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) config.set_session_factory(session_factory) db_url = settings['mongo_uri'] config.registry.client = pymongo.MongoClient(db_url) def add_db(request): uri = urlparse.urlparse(db_url) db = config.registry.client[uri.path[1:]] if uri.username and uri.password: db.authenticate(uri.username, uri.password) return DataStore(db) add_db(None).create_indices() config.add_request_method(add_db, 'db', reify=True) config.scan() return config.make_wsgi_app()
def includeme(config): """Configure logging for the application""" logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'NOTSET', 'stream': 'ext://sys.stdout', }, }, 'root': { 'level': config.registry.settings.get('logging.level', 'INFO'), 'handlers': ['console'], }, }) structlog.configure( processors=[ structlog.stdlib.filter_by_level, structlog.stdlib.add_logger_name, structlog.stdlib.add_log_level, structlog.stdlib.PositionalArgumentsFormatter(), structlog.processors.StackInfoRenderer(), structlog.processors.format_exc_info, structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M.%S", utc=False), structlog.processors.KeyValueRenderer(), ], logger_factory=structlog.stdlib.LoggerFactory(), wrapper_class=structlog.stdlib.BoundLogger, ) logger = structlog.get_logger('press.logging') logger.info('logging configuration initialized') logger.debug('debug logging enabled') # Give every request a unique identifier. config.add_request_method(_create_id, name="id", reify=True) # Add a log method to every request. config.add_request_method(_create_logger, name="log", reify=True)
def includeme(config): config.include('pyramid_jinja2') config.add_jinja2_search_path("dashboard:templates") config.commit() # commit to allow access to jinja environment # request methods config.add_request_method(get_request_user, 'user', reify=True) config.get_jinja2_environment().filters['format_date'] = format_date config.get_jinja2_environment().filters['format_time'] = format_time config.get_jinja2_environment().filters['format_decimal'] = format_decimal config.get_jinja2_environment().filters['format_percent'] = format_percent config.get_jinja2_environment().filters['format_number'] = format_number config.get_jinja2_environment().filters['datetime'] = ( date_string_to_datetime) config.add_static_view('static', 'dashboard:static', cache_max_age=3600) config.add_route('default', '/') config.add_route('submissions', '/submissions/*traverse') config.scan()
def add_request_helpers(config): # add .user to requests and cache it with reify config.add_request_method(get_request_user, 'user', reify=True) config.add_request_method( can_access_clinics, 'can_access_clinics', reify=True) config.add_request_method(can_view_clinics, 'can_view_clinics', reify=True) config.add_request_method(can_list_clinics, 'can_list_clinics', reify=True) config.add_request_method( can_view_municipality, 'can_view_municipality', reify=True) config.add_request_method( can_create_period, 'can_create_period', reify=True) config.add_request_method(can_view_state, 'can_view_state', reify=True) config.add_request_method(can_list_state, 'can_list_state', reify=True) config.add_request_method(is_super_user, 'is_super_user', reify=True)