def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings, root_factory=Root) # setup oidc auth and session store if requested config.include('pyramid_oidc', route_prefix='/oidc') # add openapi support config.include('pyramid_openapi') # add cors support config.include('pyramid_cors') config.add_cors_preflight_handler() # set up authentication authn_policy = OIDCBearerAuthenticationPolicy( # probably don't need callback, as we don't need any roles callback=keycloak_callback, ) config.set_authentication_policy(authn_policy) config.set_authorization_policy(ACLAuthorizationPolicy()) from .interfaces import ISwift from .utilities import Swift config.registry.registerUtility(Swift(settings), ISwift) # app specific stuff config.add_route(name='api_v1_stats', pattern='/api/v1/stat') config.add_route(name='api_v1_folders', pattern='/api/v1/folders') config.add_route(name='api_v1_files_tempurl', pattern='/api/v1/files/tempurl') config.add_route(name='api_v1_files', pattern='/api/v1/files') config.scan('.views') return config.make_wsgi_app()
def main(ip, port): config = Configurator() config.include('cors') config.add_cors_preflight_handler() config.add_route('old-service', '/old_service') config.add_view(old_service, route_name='old-service', renderer='json') config.add_route('dative-app', '/dative_app') config.add_view(dative_app, route_name='dative-app', renderer='json') config.add_route('old_state', '/olds/{old_id}/state') config.add_view(old_state, route_name='old_state', renderer='json') config.add_route('old', '/olds/{old_id}') config.add_view(old, route_name='old', renderer='json') config.add_route('olds', '/olds') config.add_view(olds, route_name='olds', renderer='json') config.add_route('sync_old_command', '/sync_old_commands/{command_id}') config.add_view(sync_old_command, route_name='sync_old_command', renderer='json') config.add_route('sync_old_commands', '/sync_old_commands') config.add_view(sync_old_commands, route_name='sync_old_commands', renderer='json') app = config.make_wsgi_app() logger.info(f'Serving at http://{ip}:{port}/') server = make_server(ip, port, app) server.serve_forever()
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): config = Configurator(settings=settings) config.include('pyramid_chameleon') config.include('.libs.cors') config.add_cors_preflight_handler() config.add_static_view(name='static', path='mangalt:static') config.add_route('home', '/') config.add_route('hello', '/howdy') config.scan('.views') return config.make_wsgi_app()
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('.cors') config.add_cors_preflight_handler() config.add_route('ocado', '/ocado/{query}') config.add_route('sainsburys', '/sainsburys/{query}') config.scan() return config.make_wsgi_app()
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('.cors') config.add_cors_preflight_handler() config.add_renderer('json', custom_json_renderer()) config.include('pyramid_jinja2') config.include('.models') config.include('.routes') config.scan() return config.make_wsgi_app()
def main(global_config, **settings): config = Configurator(settings=settings) config.include('pyramid_jinja2') config.include('.models') # https://gist.github.com/mmerickel/1afaf64154b335b596e4 config.include('.cors') config.add_cors_preflight_handler() config.include('.routes') config.include('.security') config.scan() 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 config = Configurator(settings=settings) config.include('pyramid_chameleon') config.include('pyramid_tm') config.include('dativetopserver.cors') config.add_cors_preflight_handler() config.add_route('old-service', '/old_service') config.add_view(v.old_service, route_name='old-service', renderer='json') config.add_route('dative-app', '/dative_app') config.add_view(v.dative_app, route_name='dative-app', renderer='json') config.add_route('old_state', '/olds/{old_id}/state') config.add_view(v.old_state, route_name='old_state', renderer='json') config.add_route('old', '/olds/{old_id}') config.add_view(v.old, route_name='old', renderer='json') config.add_route('olds', '/olds') config.add_view(v.olds, route_name='olds', renderer='json') config.add_route('sync_old_command', '/sync_old_commands/{command_id}') config.add_view(v.sync_old_command, route_name='sync_old_command', renderer='json') config.add_route('sync_old_commands', '/sync_old_commands') config.add_view(v.sync_old_commands, route_name='sync_old_commands', renderer='json') config.scan() return config.make_wsgi_app()
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('kore_task.cors.cors') config.add_cors_preflight_handler() config.add_subscriber(upload_size, NewRequest) config.add_subscriber(log, NewResponse) config.include('.models') config.include('.routes.routes') config.scan() return config.make_wsgi_app()
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('pyramid_jwt') config.set_jwt_authentication_policy('secret') config.include('abacus18.cors.cors') config.add_cors_preflight_handler() config.set_authorization_policy(ACLAuthorizationPolicy()) config.include('.models') config.include('.routes') config.scan() return config.make_wsgi_app()
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ SETTINGS = settings config = Configurator(settings=settings, ) config.include('pyramid_jinja2') config.include('.models') config.include('.cors') config.add_cors_preflight_handler() config.include('.routes') config.include('.security') config.include('..greggo') config.add_static_view('static', path='repoll:static') config.scan() return config.make_wsgi_app()
def serve(global_config, **settings): config = Configurator(settings=settings) config.add_view_deriver(authorization_view) config.include('.cors') config.add_cors_preflight_handler() logging.info('Initialising configuration...') Config().configure() logging.info('Initialising clients...') Clients().configure() # Scan the current Python Package for any @configuration_decorators config.scan() logging.info('WSGI App being returned...') return config.make_wsgi_app()
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ # Connect DB engine = engine_from_config(settings, 'sqlalchemy.') initialize_sql(engine) session_factory = session_factory_from_settings(settings) #redis # session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet') # authn_policy = AuthTktAuthenticationPolicy(secret='s0secret', # callback=groupfinder) authz_policy = ACLAuthorizationPolicy() config = Configurator( settings=settings, root_factory='testsite.security.RootFactory', # authentication_policy=authn_policy, authorization_policy=authz_policy, session_factory=session_factory, ) # Add automatic CORS responses config.include('.cors') config.add_cors_preflight_handler() # make sure to add this before other routes to intercept OPTIONS # Add JWT config.include('pyramid_jwt') config.set_jwt_authentication_policy('s0secret', callback=add_role_principals) # jinja_env = _get_or_build_default_environment(config.registry) # ?#?#? #config.set_request_factory(RequestWithUserAttribute) config.add_route('home', '/home') config.add_route('auth', '/auth') # config.add_view(hello_world, route_name='hello') # config.add_view(hello_world, route_name='hello') config.scan() return config.make_wsgi_app()
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ settings['sqlalchemy.url'] = settings['cn.dialect'] + quote_plus( settings['sqlalchemy.url']) engine = engine_from_config(settings, 'sqlalchemy.') dbConfig['url'] = settings['sqlalchemy.url'] dbConfig['siteName'] = settings['siteName'] DBSession.configure(bind=engine) Base.metadata.bind = engine Base.metadata.create_all(engine) Base.metadata.reflect(views=True, extend_existing=False) config = Configurator(settings=settings) config.include('.cors') config.add_cors_preflight_handler() config.add_static_view(name='static', path='static') # Add renderer for datetime objects json_renderer = JSON() json_renderer.add_adapter(datetime, datetime_adapter) json_renderer.add_adapter(Decimal, decimal_adapter) json_renderer.add_adapter(bytes, bytes_adapter) config.add_renderer('json', json_renderer) # Set up authentication and authorization includeme(config) config.set_root_factory(SecurityRoot) # Set the default permission level to 'read' config.set_default_permission('read') config.include('pyramid_tm') add_routes(config) config.scan() return config.make_wsgi_app()
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ settings['sqlalchemy.url'] = settings['cn.dialect'] + quote_plus(settings['sqlalchemy.url']) engine = engine_from_config(settings, 'sqlalchemy.') dbConfig['url'] = settings['sqlalchemy.url'] dbConfig['siteName'] = settings['siteName'] DBSession.configure(bind=engine) Base.metadata.bind = engine Base.metadata.create_all(engine) Base.metadata.reflect(views=True, extend_existing=False) config = Configurator(settings=settings) config.include('.cors') config.add_cors_preflight_handler() config.add_static_view(name='static', path='static') # Add renderer for datetime objects json_renderer = JSON() json_renderer.add_adapter(datetime, datetime_adapter) json_renderer.add_adapter(Decimal, decimal_adapter) json_renderer.add_adapter(bytes, bytes_adapter) config.add_renderer('json', json_renderer) # Set up authentication and authorization includeme(config) config.set_root_factory(SecurityRoot) # Set the default permission level to 'read' config.set_default_permission('read') config.include('pyramid_tm') add_routes(config) config.scan() return config.make_wsgi_app()
def web(global_config, **local_settings): """ This function returns a Pyramid WSGI application. """ settings = deepcopy(global_config) settings.update(local_settings) # set CFG object app_config = CFG(settings) app_config.configure_filedepot() settings["CFG"] = app_config configurator = Configurator(settings=settings, autocommit=True) # Add beaker session cookie tracim_setting_for_beaker = sliced_dict(settings, beginning_key_string="session.") tracim_setting_for_beaker["session.data_dir"] = app_config.SESSION__DATA_DIR tracim_setting_for_beaker["session.lock_dir"] = app_config.SESSION__LOCK_DIR session_factory = pyramid_beaker.session_factory_from_settings(tracim_setting_for_beaker) configurator.set_session_factory(session_factory) pyramid_beaker.set_cache_regions_from_settings(tracim_setting_for_beaker) # Add AuthPolicy configurator.include("pyramid_multiauth") policies = [] if app_config.REMOTE_USER_HEADER: policies.append( RemoteAuthentificationPolicy( remote_user_email_login_header=app_config.REMOTE_USER_HEADER ) ) policies.append( CookieSessionAuthentificationPolicy(reissue_time=app_config.SESSION__REISSUE_TIME) ) if app_config.API__KEY: policies.append( ApiTokenAuthentificationPolicy( api_key_header=TRACIM_API_KEY_HEADER, api_user_email_login_header=TRACIM_API_USER_EMAIL_LOGIN_HEADER, ) ) policies.append(TracimBasicAuthAuthenticationPolicy(realm=BASIC_AUTH_WEBUI_REALM)) # Hack for ldap if AuthType.LDAP in app_config.AUTH_TYPES: import ldap3 configurator.include("pyramid_ldap3") configurator.ldap_setup( app_config.LDAP_URL, bind=app_config.LDAP_BIND_DN, passwd=app_config.LDAP_BIND_PASS, use_tls=app_config.LDAP_TLS, use_pool=app_config.LDAP_USE_POOL, pool_size=app_config.LDAP_POOL_SIZE, pool_lifetime=app_config.LDAP_POOL_LIFETIME, get_info=app_config.LDAP_GET_INFO, ) configurator.ldap_set_login_query( base_dn=app_config.LDAP_USER_BASE_DN, filter_tmpl=app_config.LDAP_USER_FILTER, scope=ldap3.LEVEL, attributes=ldap3.ALL_ATTRIBUTES, ) configurator.include(add_cors_support) # make sure to add this before other routes to intercept OPTIONS configurator.add_cors_preflight_handler() # Default authorization : Accept anything. configurator.set_authorization_policy(AcceptAllAuthorizationPolicy()) authn_policy = MultiAuthenticationPolicy(policies) configurator.set_authentication_policy(authn_policy) # INFO - GM - 11-04-2018 - set default perm # setting default perm is needed to force authentification # mecanism in all views. configurator.set_default_permission(TRACIM_DEFAULT_PERM) # Override default request configurator.set_request_factory(TracimRequest) # Pyramids "plugin" include. configurator.include("pyramid_jinja2") # Add SqlAlchemy DB init_models(configurator, app_config) # set Hapic context = PyramidContext( configurator=configurator, default_error_builder=ErrorSchema(), debug=app_config.DEBUG ) hapic.set_context(context) # INFO - G.M - 2018-07-04 - global-context exceptions # Not found context.handle_exception(PageNotFound, HTTPStatus.NOT_FOUND) # Bad request context.handle_exception(WorkspaceNotFoundInTracimRequest, HTTPStatus.BAD_REQUEST) context.handle_exception(UserNotFoundInTracimRequest, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentNotFoundInTracimRequest, HTTPStatus.BAD_REQUEST) context.handle_exception(WorkspaceNotFound, HTTPStatus.BAD_REQUEST) context.handle_exception(UserDoesNotExist, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentNotFound, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentTypeNotExist, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentInNotEditableState, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentTypeNotAllowed, HTTPStatus.BAD_REQUEST) context.handle_exception(InvalidId, HTTPStatus.BAD_REQUEST) context.handle_exception(SameValueError, HTTPStatus.BAD_REQUEST) # Auth exception context.handle_exception(NotAuthenticated, HTTPStatus.UNAUTHORIZED) context.handle_exception(UserGivenIsNotTheSameAsAuthenticated, HTTPStatus.FORBIDDEN) context.handle_exception(UserAuthenticatedIsNotActive, HTTPStatus.FORBIDDEN) context.handle_exception(AuthenticationFailed, HTTPStatus.FORBIDDEN) context.handle_exception(InsufficientUserRoleInWorkspace, HTTPStatus.FORBIDDEN) context.handle_exception(InsufficientUserProfile, HTTPStatus.FORBIDDEN) # Internal server error context.handle_exception(OperationalError, HTTPStatus.INTERNAL_SERVER_ERROR) context.handle_exception(Exception, HTTPStatus.INTERNAL_SERVER_ERROR) # Add controllers session_controller = SessionController() system_controller = SystemController() user_controller = UserController() account_controller = AccountController() reset_password_controller = ResetPasswordController() workspace_controller = WorkspaceController() comment_controller = CommentController() html_document_controller = HTMLDocumentController() thread_controller = ThreadController() file_controller = FileController() folder_controller = FolderController() configurator.include(session_controller.bind, route_prefix=BASE_API_V2) configurator.include(system_controller.bind, route_prefix=BASE_API_V2) configurator.include(user_controller.bind, route_prefix=BASE_API_V2) configurator.include(account_controller.bind, route_prefix=BASE_API_V2) configurator.include(reset_password_controller.bind, route_prefix=BASE_API_V2) configurator.include(workspace_controller.bind, route_prefix=BASE_API_V2) configurator.include(comment_controller.bind, route_prefix=BASE_API_V2) configurator.include(html_document_controller.bind, route_prefix=BASE_API_V2) configurator.include(thread_controller.bind, route_prefix=BASE_API_V2) configurator.include(file_controller.bind, route_prefix=BASE_API_V2) configurator.include(folder_controller.bind, route_prefix=BASE_API_V2) if app_config.CALDAV__ENABLED: # FIXME - G.M - 2019-03-18 - check if possible to avoid this import here, # import is here because import AgendaController without adding it to # pyramid make trouble in hapic which try to get view related # to controller but failed. from tracim_backend.views.agenda_api.agenda_controller import AgendaController configurator.include(add_www_authenticate_header_for_caldav) # caldav exception context.handle_exception(CaldavNotAuthorized, HTTPStatus.FORBIDDEN) context.handle_exception(CaldavNotAuthenticated, HTTPStatus.UNAUTHORIZED) # controller radicale_proxy_controller = RadicaleProxyController( proxy_base_address=app_config.CALDAV__RADICALE_PROXY__BASE_URL, radicale_base_path=app_config.CALDAV__RADICALE__BASE_PATH, radicale_user_path=app_config.CALDAV__RADICALE__USER_PATH, radicale_workspace_path=app_config.CALDAV_RADICALE_WORKSPACE_PATH, ) agenda_controller = AgendaController() configurator.include(agenda_controller.bind, route_prefix=BASE_API_V2) configurator.include(radicale_proxy_controller.bind) if app_config.FRONTEND__SERVE: configurator.include("pyramid_mako") frontend_controller = FrontendController(app_config.FRONTEND__DIST_FOLDER_PATH) configurator.include(frontend_controller.bind) hapic.add_documentation_view("/api/v2/doc", "Tracim v2 API", "API of Tracim v2") return configurator.make_wsgi_app()
def web(global_config, **local_settings): """ This function returns a Pyramid WSGI application. """ settings = global_config settings.update(local_settings) # set CFG object app_config = CFG(settings) app_config.configure_filedepot() settings['CFG'] = app_config configurator = Configurator(settings=settings, autocommit=True) # Add AuthPolicy configurator.include("pyramid_beaker") configurator.include("pyramid_multiauth") policies = [] if app_config.REMOTE_USER_HEADER: policies.append( RemoteAuthentificationPolicy( remote_user_email_login_header=app_config.REMOTE_USER_HEADER, )) policies.append( CookieSessionAuthentificationPolicy( reissue_time=app_config.SESSION_REISSUE_TIME), # nopep8 ) if app_config.API_KEY: policies.append( ApiTokenAuthentificationPolicy( api_key_header=TRACIM_API_KEY_HEADER, api_user_email_login_header=TRACIM_API_USER_EMAIL_LOGIN_HEADER ), ) policies.append( TracimBasicAuthAuthenticationPolicy(realm=BASIC_AUTH_WEBUI_REALM), ) # Hack for ldap if AuthType.LDAP in app_config.AUTH_TYPES: import ldap3 configurator.include('pyramid_ldap3') configurator.ldap_setup(app_config.LDAP_URL, bind=app_config.LDAP_BIND_DN, passwd=app_config.LDAP_BIND_PASS, use_tls=app_config.LDAP_TLS, use_pool=app_config.LDAP_USE_POOL, pool_size=app_config.LDAP_POOL_SIZE, pool_lifetime=app_config.LDAP_POOL_LIFETIME, get_info=app_config.LDAP_GET_INFO) configurator.ldap_set_login_query( base_dn=app_config.LDAP_USER_BASE_DN, filter_tmpl=app_config.LDAP_USER_FILTER, scope=ldap3.LEVEL, attributes=ldap3.ALL_ATTRIBUTES) configurator.include(add_cors_support) # make sure to add this before other routes to intercept OPTIONS configurator.add_cors_preflight_handler() # Default authorization : Accept anything. configurator.set_authorization_policy(AcceptAllAuthorizationPolicy()) authn_policy = MultiAuthenticationPolicy(policies) configurator.set_authentication_policy(authn_policy) # INFO - GM - 11-04-2018 - set default perm # setting default perm is needed to force authentification # mecanism in all views. configurator.set_default_permission(TRACIM_DEFAULT_PERM) # Override default request configurator.set_request_factory(TracimRequest) # Pyramids "plugin" include. configurator.include('pyramid_jinja2') # Add SqlAlchemy DB configurator.include('.models.setup_models') # set Hapic context = PyramidContext( configurator=configurator, default_error_builder=ErrorSchema(), debug=app_config.DEBUG, ) hapic.set_context(context) # INFO - G.M - 2018-07-04 - global-context exceptions # Not found context.handle_exception(PageNotFound, HTTPStatus.NOT_FOUND) # Bad request context.handle_exception(WorkspaceNotFoundInTracimRequest, HTTPStatus.BAD_REQUEST) # nopep8 context.handle_exception(UserNotFoundInTracimRequest, HTTPStatus.BAD_REQUEST) # nopep8 context.handle_exception(ContentNotFoundInTracimRequest, HTTPStatus.BAD_REQUEST) # nopep8 context.handle_exception(WorkspaceNotFound, HTTPStatus.BAD_REQUEST) context.handle_exception(UserDoesNotExist, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentNotFound, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentTypeNotExist, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentInNotEditableState, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentTypeNotAllowed, HTTPStatus.BAD_REQUEST) context.handle_exception(InvalidId, HTTPStatus.BAD_REQUEST) context.handle_exception(SameValueError, HTTPStatus.BAD_REQUEST) # Auth exception context.handle_exception(NotAuthenticated, HTTPStatus.UNAUTHORIZED) context.handle_exception(UserAuthenticatedIsNotActive, HTTPStatus.FORBIDDEN) context.handle_exception(AuthenticationFailed, HTTPStatus.FORBIDDEN) context.handle_exception(InsufficientUserRoleInWorkspace, HTTPStatus.FORBIDDEN) # nopep8 context.handle_exception(InsufficientUserProfile, HTTPStatus.FORBIDDEN) # Internal server error context.handle_exception(OperationalError, HTTPStatus.INTERNAL_SERVER_ERROR) context.handle_exception(Exception, HTTPStatus.INTERNAL_SERVER_ERROR) # Add controllers session_controller = SessionController() system_controller = SystemController() user_controller = UserController() account_controller = AccountController() reset_password_controller = ResetPasswordController() workspace_controller = WorkspaceController() comment_controller = CommentController() html_document_controller = HTMLDocumentController() thread_controller = ThreadController() file_controller = FileController() folder_controller = FolderController() configurator.include(session_controller.bind, route_prefix=BASE_API_V2) configurator.include(system_controller.bind, route_prefix=BASE_API_V2) configurator.include(user_controller.bind, route_prefix=BASE_API_V2) configurator.include(account_controller.bind, route_prefix=BASE_API_V2) configurator.include(reset_password_controller.bind, route_prefix=BASE_API_V2) # nopep8 configurator.include(workspace_controller.bind, route_prefix=BASE_API_V2) configurator.include(comment_controller.bind, route_prefix=BASE_API_V2) configurator.include(html_document_controller.bind, route_prefix=BASE_API_V2) # nopep8 configurator.include(thread_controller.bind, route_prefix=BASE_API_V2) configurator.include(file_controller.bind, route_prefix=BASE_API_V2) configurator.include(folder_controller.bind, route_prefix=BASE_API_V2) if app_config.FRONTEND_SERVE: configurator.include('pyramid_mako') frontend_controller = FrontendController( app_config.FRONTEND_DIST_FOLDER_PATH) # nopep8 configurator.include(frontend_controller.bind) hapic.add_documentation_view( '/api/v2/doc', 'Tracim v2 API', 'API of Tracim v2', ) return configurator.make_wsgi_app()
def web(global_config: OrderedDict, **local_settings) -> Router: """ This function returns a Pyramid WSGI application. """ settings = deepcopy(global_config) settings.update(local_settings) # set CFG object app_config = CFG(settings) app_config.configure_filedepot() settings["CFG"] = app_config # Init plugin manager plugin_manager = init_plugin_manager(app_config) settings["plugin_manager"] = plugin_manager configurator = Configurator(settings=settings, autocommit=True) # Add beaker session cookie tracim_setting_for_beaker = sliced_dict(settings, beginning_key_string="session.") tracim_setting_for_beaker["session.data_dir"] = app_config.SESSION__DATA_DIR tracim_setting_for_beaker["session.lock_dir"] = app_config.SESSION__LOCK_DIR tracim_setting_for_beaker["session.httponly"] = app_config.SESSION__HTTPONLY tracim_setting_for_beaker["session.secure"] = app_config.SESSION__SECURE session_factory = pyramid_beaker.session_factory_from_settings(tracim_setting_for_beaker) configurator.set_session_factory(session_factory) pyramid_beaker.set_cache_regions_from_settings(tracim_setting_for_beaker) # Add AuthPolicy configurator.include("pyramid_multiauth") policies = [] if app_config.REMOTE_USER_HEADER: policies.append( RemoteAuthentificationPolicy(remote_user_login_header=app_config.REMOTE_USER_HEADER) ) policies.append(CookieSessionAuthentificationPolicy()) policies.append(QueryTokenAuthentificationPolicy()) if app_config.API__KEY: policies.append( ApiTokenAuthentificationPolicy( api_key_header=TRACIM_API_KEY_HEADER, api_user_login_header=TRACIM_API_USER_LOGIN_HEADER, ) ) policies.append(TracimBasicAuthAuthenticationPolicy(realm=BASIC_AUTH_WEBUI_REALM)) # Hack for ldap if AuthType.LDAP in app_config.AUTH_TYPES: import ldap3 configurator.include("pyramid_ldap3") configurator.ldap_setup( app_config.LDAP_URL, bind=app_config.LDAP_BIND_DN, passwd=app_config.LDAP_BIND_PASS, use_tls=app_config.LDAP_TLS, use_pool=app_config.LDAP_USE_POOL, pool_size=app_config.LDAP_POOL_SIZE, pool_lifetime=app_config.LDAP_POOL_LIFETIME, get_info=app_config.LDAP_GET_INFO, ) configurator.ldap_set_login_query( base_dn=app_config.LDAP_USER_BASE_DN, filter_tmpl=app_config.LDAP_USER_FILTER, scope=ldap3.LEVEL, attributes=ldap3.ALL_ATTRIBUTES, ) configurator.include(add_cors_support) # make sure to add this before other routes to intercept OPTIONS configurator.add_cors_preflight_handler() # Default authorization : Accept anything. configurator.set_authorization_policy(AcceptAllAuthorizationPolicy()) authn_policy = MultiAuthenticationPolicy(policies) configurator.set_authentication_policy(authn_policy) # INFO - GM - 11-04-2018 - set default perm # setting default perm is needed to force authentification # mechanism in all views. configurator.set_default_permission(TRACIM_DEFAULT_PERM) # Override default request configurator.set_request_factory(TracimRequest) # Pyramids "plugin" include. # Add SqlAlchemy DB init_models(configurator, app_config) # set Hapic context = TracimPyramidContext( configurator=configurator, default_error_builder=ErrorSchema(), debug=app_config.DEBUG ) hapic.set_context(context) # INFO - G.M - 2018-07-04 - global-context exceptions # Not found context.handle_exception(PageNotFound, HTTPStatus.NOT_FOUND) # Bad request context.handle_exception(WorkspaceNotFoundInTracimRequest, HTTPStatus.BAD_REQUEST) context.handle_exception(UserNotFoundInTracimRequest, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentNotFoundInTracimRequest, HTTPStatus.BAD_REQUEST) context.handle_exception(WorkspaceNotFound, HTTPStatus.BAD_REQUEST) context.handle_exception(UserDoesNotExist, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentNotFound, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentTypeNotExist, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentInNotEditableState, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentTypeNotAllowed, HTTPStatus.BAD_REQUEST) context.handle_exception(InvalidId, HTTPStatus.BAD_REQUEST) context.handle_exception(SameValueError, HTTPStatus.BAD_REQUEST) # Auth exception context.handle_exception(NotAuthenticated, HTTPStatus.UNAUTHORIZED) context.handle_exception(UserGivenIsNotTheSameAsAuthenticated, HTTPStatus.FORBIDDEN) context.handle_exception(UserAuthenticatedIsNotActive, HTTPStatus.FORBIDDEN) context.handle_exception(AuthenticationFailed, HTTPStatus.FORBIDDEN) context.handle_exception(InsufficientUserRoleInWorkspace, HTTPStatus.FORBIDDEN) context.handle_exception(InsufficientUserProfile, HTTPStatus.FORBIDDEN) # Internal server error context.handle_exception(OperationalError, HTTPStatus.INTERNAL_SERVER_ERROR) context.handle_exception(Exception, HTTPStatus.INTERNAL_SERVER_ERROR) # Add controllers session_controller = SessionController() system_controller = SystemController() user_controller = UserController() account_controller = AccountController() reset_password_controller = ResetPasswordController() workspace_controller = WorkspaceController() comment_controller = CommentController() configurator.include(session_controller.bind, route_prefix=BASE_API) configurator.include(system_controller.bind, route_prefix=BASE_API) configurator.include(user_controller.bind, route_prefix=BASE_API) configurator.include(account_controller.bind, route_prefix=BASE_API) configurator.include(reset_password_controller.bind, route_prefix=BASE_API) configurator.include(workspace_controller.bind, route_prefix=BASE_API) configurator.include(comment_controller.bind, route_prefix=BASE_API) app_lib = ApplicationApi(app_list=app_list) for app in app_lib.get_all(): app.load_controllers( app_config=app_config, configurator=configurator, route_prefix=BASE_API, context=context ) configurator.scan("tracim_backend.lib.utils.authentification") # TODO - G.M - 2019-05-17 - check if possible to avoid this import here, # import is here because import SearchController without adding it to # pyramid make trouble in hapic which try to get view related # to controller but failed. from tracim_backend.lib.search.search_factory import SearchFactory search_controller = SearchFactory.get_search_controller(app_config) configurator.include(search_controller.bind, route_prefix=BASE_API) if app_config.FRONTEND__SERVE: configurator.include("pyramid_mako") frontend_controller = FrontendController( dist_folder_path=app_config.FRONTEND__DIST_FOLDER_PATH, custom_toolbox_folder_path=app_config.FRONTEND__CUSTOM_TOOLBOX_FOLDER_PATH, cache_token=app_config.FRONTEND__CACHE_TOKEN, ) configurator.include(frontend_controller.bind) # INFO - G.M - 2019-11-27 - Include plugin custom web code plugin_manager.hook.web_include(configurator=configurator, app_config=app_config) hapic.add_documentation_view("/api/doc", "Tracim API", "API of Tracim") return configurator.make_wsgi_app()
def main(global_config, **settings): config = Configurator(settings=settings, root_factory=RootFactory) # adiciona metodos cross origin resource sharing (CORS) config.add_directive('add_cors_preflight_handler', add_cors_preflight_handler) config.add_route_predicate('cors_preflight', CorsPreflightPredicate) config.add_subscriber(add_cors_to_response, 'pyramid.events.NewResponse') config.add_cors_preflight_handler() # inclui dependencias config.include('pyramid_jinja2') config.include('pyramid_chameleon') config.include('pyramid_sqlalchemy') # escaneia views config.scan() # cria metadados de persistencia metadata.create_all() # adiciona rodas estaticas # config.add_static_view(name='static', path='zapizza.site:static') # todo: levar rotas para dentro de seus módulos # registro config.add_route('signup', '/signup') config.add_route('confirm', '/confirm') # login/logout config.add_route('login', '/login') config.add_route('logout', '/logout') config.add_route('authenticated', '/authenticated') # esqueci a senha config.add_route('pass_forgot', '/forgot') config.add_route('pass_reset', '/reset') # /user config.add_route('users_profile', '/user/{username}/profile', factory='.users.models.user_factory') # /tamanhos config.add_route('tamanhos', '/tamanhos', factory='.pizzas.tamanhos.models.tamanho_factory') config.add_route('tamanhos_edit', '/tamanhos/{hashid}', factory='.pizzas.tamanhos.models.tamanho_factory') config.add_route('tamanhos_enable', '/tamanhos/{hashid}/enable', factory='.pizzas.tamanhos.models.tamanho_factory') # /sabores config.add_route('sabores', '/sabores', factory='.pizzas.sabores.models.sabor_factory') config.add_route('sabores_edit', '/sabores/{hashid}', factory='.pizzas.sabores.models.sabor_factory') config.add_route('sabores_enable', '/sabores/{hashid}/enable', factory='.pizzas.sabores.models.sabor_factory') # /bordas config.add_route('bordas', '/bordas', factory='.pizzas.bordas.models.borda_factory') config.add_route('bordas_edit', '/bordas/{hashid}', factory='.pizzas.bordas.models.borda_factory') config.add_route('bordas_enable', '/bordas/{hashid}/enable', factory='.pizzas.bordas.models.borda_factory') # /adicionais config.add_route('adicionais', '/adicionais', factory='.adicionais.models.adicional_factory') config.add_route('adicionais_edit', '/adicionais/{hashid}', factory='.adicionais.models.adicional_factory') config.add_route('adicionais_enable', '/adicionais/{hashid}/enable', factory='.adicionais.models.adicional_factory') # /clientes config.add_route('clientes', '/clientes', factory='.clientes.models.cliente_factory') config.add_route('clientes_edit', '/clientes/{hashid}', factory='.clientes.models.cliente_factory') config.add_route('clientes_enable', '/clientes/{hashid}/enable', factory='.clientes.models.cliente_factory') # /clientes/enderecos config.add_route('enderecos', '/clientes/{cliHashid}/enderecos', factory='.clientes.enderecos.models.endereco_factory') config.add_route('enderecos_edit', '/clientes/{cliHashid}/enderecos/{endHashid}', factory='.clientes.enderecos.models.endereco_factory') # /clientes/telefones config.add_route('telefones', '/clientes/{cliHashid}/telefones', factory='.clientes.telefones.models.telefone_factory') config.add_route('telefones_edit', '/clientes/{cliHashid}/telefones/{telHashid}', factory='.clientes.telefones.models.telefone_factory') # /pedidos config.add_route('pedidos', '/pedidos', factory='.pedidos.models.pedido_factory') config.add_route('pedidos_edit', '/pedidos/{hashid}', factory='.pedidos.models.pedido_factory') config.add_route('pedidos_enable', '/pedidos/{hashid}/enable', factory='.pedidos.models.pedido_factory') # Factory da sessao session_secret = settings['session.secret'] session_factory = SignedCookieSessionFactory(session_secret) config.set_session_factory(session_factory) # Politicas de segurança authn_policy = AuthTktAuthenticationPolicy(settings['auth.secret'], callback=groupfinder, hashalg='sha512') authz_policy = ACLAuthorizationPolicy() config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) # Objeto User disponivel como um atributo de Request config.add_request_method(get_user, 'user', reify=True) # cria aplicacao return config.make_wsgi_app()
def web(global_config, **local_settings): """ This function returns a Pyramid WSGI application. """ settings = global_config settings.update(local_settings) # set CFG object app_config = CFG(settings) app_config.configure_filedepot() settings['CFG'] = app_config configurator = Configurator(settings=settings, autocommit=True) # Add BasicAuthPolicy authn_policy = BasicAuthAuthenticationPolicy( basic_auth_check_credentials, realm=BASIC_AUTH_WEBUI_REALM, ) configurator.include(add_cors_support) # make sure to add this before other routes to intercept OPTIONS configurator.add_cors_preflight_handler() # Default authorization : Accept anything. configurator.set_authorization_policy(AcceptAllAuthorizationPolicy()) configurator.set_authentication_policy(authn_policy) # INFO - GM - 11-04-2018 - set default perm # setting default perm is needed to force authentification # mecanism in all views. configurator.set_default_permission(TRACIM_DEFAULT_PERM) # Override default request configurator.set_request_factory(TracimRequest) # Pyramids "plugin" include. configurator.include('pyramid_jinja2') # Add SqlAlchemy DB configurator.include('.models') # set Hapic context = PyramidContext( configurator=configurator, default_error_builder=ErrorSchema(), debug=app_config.DEBUG, ) hapic.set_context(context) # INFO - G.M - 2018-07-04 - global-context exceptions # Not found context.handle_exception(NotFound, HTTPStatus.NOT_FOUND) # Bad request context.handle_exception(WorkspaceNotFoundInTracimRequest, HTTPStatus.BAD_REQUEST) # nopep8 context.handle_exception(UserNotFoundInTracimRequest, HTTPStatus.BAD_REQUEST) # nopep8 context.handle_exception(ContentNotFoundInTracimRequest, HTTPStatus.BAD_REQUEST) # nopep8 context.handle_exception(WorkspaceNotFound, HTTPStatus.BAD_REQUEST) context.handle_exception(UserDoesNotExist, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentNotFound, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentTypeNotAllowed, HTTPStatus.BAD_REQUEST) context.handle_exception(InvalidId, HTTPStatus.BAD_REQUEST) # Auth exception context.handle_exception(NotAuthenticated, HTTPStatus.UNAUTHORIZED) context.handle_exception(UserNotActive, HTTPStatus.FORBIDDEN) context.handle_exception(AuthenticationFailed, HTTPStatus.FORBIDDEN) context.handle_exception(InsufficientUserRoleInWorkspace, HTTPStatus.FORBIDDEN) # nopep8 context.handle_exception(InsufficientUserProfile, HTTPStatus.FORBIDDEN) # Internal server error context.handle_exception(OperationalError, HTTPStatus.INTERNAL_SERVER_ERROR) context.handle_exception(Exception, HTTPStatus.INTERNAL_SERVER_ERROR) # Add controllers session_controller = SessionController() system_controller = SystemController() user_controller = UserController() workspace_controller = WorkspaceController() comment_controller = CommentController() html_document_controller = HTMLDocumentController() thread_controller = ThreadController() file_controller = FileController() configurator.include(session_controller.bind, route_prefix=BASE_API_V2) configurator.include(system_controller.bind, route_prefix=BASE_API_V2) configurator.include(user_controller.bind, route_prefix=BASE_API_V2) configurator.include(workspace_controller.bind, route_prefix=BASE_API_V2) configurator.include(comment_controller.bind, route_prefix=BASE_API_V2) configurator.include(html_document_controller.bind, route_prefix=BASE_API_V2) # nopep8 configurator.include(thread_controller.bind, route_prefix=BASE_API_V2) configurator.include(file_controller.bind, route_prefix=BASE_API_V2) hapic.add_documentation_view( '/api/v2/doc', 'Tracim v2 API', 'API of Tracim v2', ) return configurator.make_wsgi_app()
def web(global_config, **local_settings): """ This function returns a Pyramid WSGI application. """ settings = global_config settings.update(local_settings) # set CFG object app_config = CFG(settings) app_config.configure_filedepot() settings['CFG'] = app_config configurator = Configurator(settings=settings, autocommit=True) # Add AuthPolicy configurator.include("pyramid_beaker") configurator.include("pyramid_multiauth") policies = [] if app_config.REMOTE_USER_HEADER: policies.append( RemoteAuthentificationPolicy( remote_user_email_login_header=app_config.REMOTE_USER_HEADER, ) ) policies.append( CookieSessionAuthentificationPolicy( reissue_time=app_config.SESSION_REISSUE_TIME), # nopep8 ) if app_config.API_KEY: policies.append( ApiTokenAuthentificationPolicy( api_key_header=TRACIM_API_KEY_HEADER, api_user_email_login_header=TRACIM_API_USER_EMAIL_LOGIN_HEADER ), ) policies.append( TracimBasicAuthAuthenticationPolicy( realm=BASIC_AUTH_WEBUI_REALM ), ) # Hack for ldap if AuthType.LDAP in app_config.AUTH_TYPES: import ldap3 configurator.include('pyramid_ldap3') configurator.ldap_setup( app_config.LDAP_URL, bind=app_config.LDAP_BIND_DN, passwd=app_config.LDAP_BIND_PASS, use_tls=app_config.LDAP_TLS, use_pool=app_config.LDAP_USE_POOL, pool_size=app_config.LDAP_POOL_SIZE, pool_lifetime=app_config.LDAP_POOL_LIFETIME, get_info=app_config.LDAP_GET_INFO ) configurator.ldap_set_login_query( base_dn=app_config.LDAP_USER_BASE_DN, filter_tmpl=app_config.LDAP_USER_FILTER, scope=ldap3.LEVEL, attributes=ldap3.ALL_ATTRIBUTES ) configurator.include(add_cors_support) # make sure to add this before other routes to intercept OPTIONS configurator.add_cors_preflight_handler() # Default authorization : Accept anything. configurator.set_authorization_policy(AcceptAllAuthorizationPolicy()) authn_policy = MultiAuthenticationPolicy(policies) configurator.set_authentication_policy(authn_policy) # INFO - GM - 11-04-2018 - set default perm # setting default perm is needed to force authentification # mecanism in all views. configurator.set_default_permission(TRACIM_DEFAULT_PERM) # Override default request configurator.set_request_factory(TracimRequest) # Pyramids "plugin" include. configurator.include('pyramid_jinja2') # Add SqlAlchemy DB configurator.include('.models.setup_models') # set Hapic context = PyramidContext( configurator=configurator, default_error_builder=ErrorSchema(), debug=app_config.DEBUG, ) hapic.set_context(context) # INFO - G.M - 2018-07-04 - global-context exceptions # Not found context.handle_exception(PageNotFound, HTTPStatus.NOT_FOUND) # Bad request context.handle_exception(WorkspaceNotFoundInTracimRequest, HTTPStatus.BAD_REQUEST) # nopep8 context.handle_exception(UserNotFoundInTracimRequest, HTTPStatus.BAD_REQUEST) # nopep8 context.handle_exception(ContentNotFoundInTracimRequest, HTTPStatus.BAD_REQUEST) # nopep8 context.handle_exception(WorkspaceNotFound, HTTPStatus.BAD_REQUEST) context.handle_exception(UserDoesNotExist, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentNotFound, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentTypeNotExist, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentInNotEditableState, HTTPStatus.BAD_REQUEST) context.handle_exception(ContentTypeNotAllowed, HTTPStatus.BAD_REQUEST) context.handle_exception(InvalidId, HTTPStatus.BAD_REQUEST) context.handle_exception(SameValueError, HTTPStatus.BAD_REQUEST) # Auth exception context.handle_exception(NotAuthenticated, HTTPStatus.UNAUTHORIZED) context.handle_exception(UserAuthenticatedIsNotActive, HTTPStatus.FORBIDDEN) context.handle_exception(AuthenticationFailed, HTTPStatus.FORBIDDEN) context.handle_exception(InsufficientUserRoleInWorkspace, HTTPStatus.FORBIDDEN) # nopep8 context.handle_exception(InsufficientUserProfile, HTTPStatus.FORBIDDEN) # Internal server error context.handle_exception(OperationalError, HTTPStatus.INTERNAL_SERVER_ERROR) context.handle_exception(Exception, HTTPStatus.INTERNAL_SERVER_ERROR) # Add controllers session_controller = SessionController() system_controller = SystemController() user_controller = UserController() account_controller = AccountController() reset_password_controller = ResetPasswordController() workspace_controller = WorkspaceController() comment_controller = CommentController() html_document_controller = HTMLDocumentController() thread_controller = ThreadController() file_controller = FileController() folder_controller = FolderController() configurator.include(session_controller.bind, route_prefix=BASE_API_V2) configurator.include(system_controller.bind, route_prefix=BASE_API_V2) configurator.include(user_controller.bind, route_prefix=BASE_API_V2) configurator.include(account_controller.bind, route_prefix=BASE_API_V2) configurator.include(reset_password_controller.bind, route_prefix=BASE_API_V2) # nopep8 configurator.include(workspace_controller.bind, route_prefix=BASE_API_V2) configurator.include(comment_controller.bind, route_prefix=BASE_API_V2) configurator.include(html_document_controller.bind, route_prefix=BASE_API_V2) # nopep8 configurator.include(thread_controller.bind, route_prefix=BASE_API_V2) configurator.include(file_controller.bind, route_prefix=BASE_API_V2) configurator.include(folder_controller.bind, route_prefix=BASE_API_V2) if app_config.FRONTEND_SERVE: configurator.include('pyramid_mako') frontend_controller = FrontendController(app_config.FRONTEND_DIST_FOLDER_PATH) # nopep8 configurator.include(frontend_controller.bind) hapic.add_documentation_view( '/api/v2/doc', 'Tracim v2 API', 'API of Tracim v2', ) return configurator.make_wsgi_app()