def make_app(): fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) storage = EncryptedCookieStorage(secret_key=secret_key) session_midl = session_middleware(storage) middlewares = [session_midl] app = web.Application(loop=loop, middlewares=middlewares) setup(app, EncryptedCookieStorage(secret_key=secret_key)) app.on_startup.append(init_db) GraphQLView.attach(app, schema=schema, graphiql=True, enable_async=True) app['config'] = conf['db'] setup_routes(app) app.on_cleanup.append(close_db) return app
async def init(loop): # load config from yaml file conf = load_config(os.path.join(BASE_DIR, "config/dev.yml")) middle = [ session_middleware(EncryptedCookieStorage( conf['cookes']['secret_key'])), authorize, ] if DEBUG: middle.append(aiohttp_debugtoolbar.middleware) app = web.Application(loop=loop, middlewares=middle) sio.pg = await setup_pg(app, conf, loop) app['pg'] = sio.pg # Attach app to the Socket.io server sio.attach(app) # setup views and routes aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates'), context_processors=[aiohttp_jinja2.request_processor]) app.router.add_static('/static', 'static', name='static') # app.router.add_static('/css', os.path.join(BASE_DIR, "chat/chat_widget/css")) # app.router.add_static('/js', os.path.join(BASE_DIR, "chat/chat_widget/js")) # app.router.add_static('/fonts', os.path.join(BASE_DIR, "chat/chat_widget/fonts")) # route part for route in routes: app.router.add_route(route[0], route[1], route[2], name=route[3]) return app
async def init_app(): app = web.Application(debug=True, client_max_size=1024**2) secret_key = base64.urlsafe_b64decode(BaseConfig.secret_key) setup(app, EncryptedCookieStorage(secret_key)) aiohttp_jinja2.setup(app, loader=jinja2.PackageLoader(package_name="app", package_path="templates"), context_processors=[current_user_ctx_proccessor]) setup_routes(app) setup_api_routes(app) setup_static_routes(app) config = BaseConfig.load_config(args.config) app['config'] = config db_pool = await init_db(app) log.debug(app['config']) if args.reload: print() print("------------------------------") print("Start with code reload") aioreloader.start() return app
async def setup_space(self): await super().setup(self) # Make the staging directory await mkdir(self.staging_dir) setup_session( self, EncryptedCookieStorage(secret_key=self.secret_key.encode(), cookie_name='PYVOSPACE_COOKIE', domain=self.domain)) self.authentication = DBUserAuthentication(self['space_name'], self['db_pool']) setup_security( self, SessionIdentityPolicy(), DBUserNodeAuthorizationPolicy(self['space_name'], self['db_pool'], self.ngas_hostname, self.ngas_port, self.ngas_session)) self.router.add_route('POST', '/login', self.authentication.login, name='login') self.router.add_route('POST', '/logout', self.authentication.logout, name='logout')
def create_app(): fernet_key = fernet.Fernet.generate_key() SECRET_KEY = base64.urlsafe_b64decode(fernet_key) app = web.Application() # Инициализация БД engine = create_async_engine(DATABASE_URL, future=True, echo=True) app['DB ENGINE'] = engine app['DB SESSION'] = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession) app['USERS'] = {} # Инициализируем пустым словарем app['ROOMS'] = { '1': [], '2': [], '3': [], } # Добавить комнаты ключом ROOMS setup(app, EncryptedCookieStorage(SECRET_KEY)) # Параметризацию для сокетов сюда - будут комнаты app.add_routes([ web.get('/ws/{room_id}', websocket_handler), web.post('/signin', sign_in), web.get('/rooms', room_list) ]) return app
def __init__(self): self.static_config = load_config("./config/config.yaml") self.database_file = "./craftbeerpi.db" logger.info("Init CraftBeerPI") policy = auth.SessionTktAuthentication(urandom(32), 60, include_ip=True) middlewares = [web.normalize_path_middleware(), session_middleware(EncryptedCookieStorage(urandom(32))), auth.auth_middleware(policy), error_middleware] self.app = web.Application(middlewares=middlewares) self._setup_shutdownhook() self.initializer = [] self.bus = CBPiEventBus(self.app.loop, self) self.ws = CBPiWebSocket(self) self.job = JobController(self) self.actor = ActorController(self) self.sensor = SensorController(self) self.plugin = PluginController(self) self.system = SystemController(self) self.config = ConfigController(self) self.kettle = KettleController(self) self.step = StepController(self) self.dashboard = DashboardController(self) self.http_step = StepHttpEndpoints(self) self.http_sensor = SensorHttpEndpoints(self) self.http_config = ConfigHttpEndpoints(self) self.http_actor = ActorHttpEndpoints(self) self.http_kettle = KettleHttpEndpoints(self) self.http_dashboard = DashBoardHttpEndpoints(self) self.notification = NotificationController(self) self.login = Login(self)
def setup_app(): fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) app = web.Application( debug=True, middlewares=[ session_middleware(EncryptedCookieStorage(secret_key)), cas_middleware ] ) app['cas_client'] = cas.CASClientV3( server_url=CAS_SERVER_URL, service_url=SERVICE_NAME, extra_login_params=False, renew=False ) aiohttp_jinja2.setup( app, loader=jinja2.FileSystemLoader(os.path.join(PROJECT_ROOT, 'templates')) ) setup_routes(app) return app
def setup_sessions(app): #aoihttp_session expects the key to be decoded; but we're mounting a secret # that's automatically generated and made available to the app already # decoded hence for testing pass through the decoded data. secret_key = app['settings'].session_cookie_secret aiohttp_session.setup(app, EncryptedCookieStorage(secret_key))
async def init(loop): app = web.Application(loop=loop, middlewares=[ session_middleware( EncryptedCookieStorage(SECRET_KEY)), authorize, db_handler, aiohttp_debugtoolbar.middleware, ]) app['websockets'] = defaultdict(list) handler = app.make_handler() if DEBUG: aiohttp_debugtoolbar.setup(app, intercept_redirects=False) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates')) # route part for route in routes: app.router.add_route(route[0], route[1], route[2], name=route[3]) app.router.add_static('/static', 'static', name='static') # end route part # db connect app.db = await init_db(host=MYSQL_HOST, db=MYSQL_DB_NAME, user=MYSQL_USER, password=MYSQL_PASSWORD, loop=loop) # end db connect app.on_shutdown.append(on_shutdown) serv_generator = loop.create_server(handler, SITE_HOST, SITE_PORT) return serv_generator, handler, app
async def init_app(is_test=False): """Initialize the application server.""" app = web.Application() setup(app=app, storage=EncryptedCookieStorage(secret_key=settings.SECRET_KEY)) app.middlewares.append(user_middleware) ssl_object = ssl.create_default_context( capath=r"sertificates/rds-combined-ca-bundle.pem") ssl_object.check_hostname = False ssl_object.verify_mode = ssl.CERT_NONE app["pool"] = await asyncpg.create_pool(dsn=settings.DSN, ssl=ssl_object) aiohttp_jinja2.setup( app, loader=jinja2.FileSystemLoader('tmpl'), ) app.add_routes(views.routes) # app.router.add_static('/static/', path='/static/', name='static') app.config = settings await models.setup(app) app.on_cleanup.append(models.close) return app
def create_app(): app = web.Application() settings = Settings() app.update( name='server', settings=settings, static='/static/', ) app.on_startup.append(startup) app.on_cleanup.append(cleanup) secret_key = base64.urlsafe_b64decode(settings.COOKIE_SECRET) aiohttp_session.setup(app, EncryptedCookieStorage(secret_key)) setup_routes(app) setup_middlewares(app) cors = aiohttp_cors.setup(app, defaults={ "*": aiohttp_cors.ResourceOptions( allow_credentials=True, expose_headers="*", allow_methods="*", allow_headers="*", max_age=3600) }) for route in app.router.routes(): cors.add(route) return app
def add_routes(app, secret_key): handle_html.timeout = app["ini"].getint("sessions", "session_idle_timeout") cache_page.timeout = app["ini"].getint("sessions", "cached_page_timeout") #app.router.add_route('POST', '/pv/v1/', handle_v1) app.router.add_get('/', GET_frontpage) app.router.add_get('/index', GET_index) app.router.add_get('/login', GET_login) app.router.add_post('/login', POST_login) app.router.add_get('/settings', GET_settings) app.router.add_post('/settings', POST_settings) app.router.add_get('/mapmaker', GET_mapmaker) app.router.add_get('/map', GET_map) app.router.add_get('/admin', GET_admin) app.router.add_post('/admin', POST_admin) app.router.add_get('/report', GET_report) app.router.add_post('/report', POST_report) app.router.add_get('/mazetest', GET_test) app.router.add_static('/static/', path='static', name='static') session_setup(app, EncryptedCookieStorage(secret_key))
def client(loop, aiohttp_client): logging.getLogger('connexion.operation').setLevel('ERROR') options = { "swagger_ui": True } specification_dir = os.path.join(os.path.dirname(__file__), '..', 'auth_server', 'openapi') app = connexion.AioHttpApp(__name__, specification_dir=specification_dir, options=options) app.app.cleanup_ctx.extend([ get_public_key ]) db.init_app(app.app, config=dict( host=Const.DB_HOST, port=Const.DB_PORT, user=Const.DB_USER, password=Const.DB_PASSWORD, database=Const.DB_NAME )) app.add_api('openapi.yaml', pythonic_params=True, pass_context_arg_name='request') fernet_key = fernet.Fernet.generate_key() Const.SESSION_KEY = fernet_key secret_key = base64.urlsafe_b64decode(fernet_key) setup(app.app, EncryptedCookieStorage(secret_key, cookie_name='auth_session')) return loop.run_until_complete(aiohttp_client(app.app))
def main(): options = {"swagger_ui": True} specification_dir = os.path.join(os.path.dirname(__file__), 'openapi') app = connexion.AioHttpApp(__name__, specification_dir=specification_dir, options=options, server_args=dict(middlewares=[db])) setup(app.app, EncryptedCookieStorage(Fernet.generate_key().decode())) db.init_app(app.app, config=dict(host=Const.DB_HOST, port=Const.DB_PORT, user=Const.DB_USER, password=Const.DB_PASSWORD, database=Const.DB_NAME)) app.add_api('openapi.yaml', arguments={'title': 'DSM Auth server'}, pythonic_params=True, pass_context_arg_name='request') app.app.cleanup_ctx.extend([get_public_key]) app.app.on_startup.append(create_tables) app.run(port=8080)
def make_app(with_db=True) -> Application: app = web.Application() parts = urlparse(URI) setup( app, EncryptedCookieStorage(SECRET_KEY, max_age=MAX_AGE, secure=parts.scheme == "https")) if with_db: app.on_startup.append(init_db) app.on_startup.append(init_state) app.on_shutdown.append(shutdown) app.on_response_prepare.append(on_prepare) # Setup routes. for route in get_routes: app.router.add_get(route[0], route[1]) for route in post_routes: app.router.add_post(route[0], route[1]) app.router.add_static("/static", "static", append_version=True) app.middlewares.append(handle_404) return app
def __init__(self, type: str = "redis", name: str = "AIOHTTP_SESSION", backends: list = [], **kwargs): async def make_redis_pool(url, **kwargs: dict): kwargs['timeout'] = 1 return await aioredis.create_pool(url, **kwargs) if type == "redis": try: url = kwargs["url"] del kwargs["url"] except KeyError: raise Exception( "Error: For Redis Storage, you need session URL") self._pool = asyncio.get_event_loop().run_until_complete( make_redis_pool(url, **kwargs)) self._session_type = RedisStorage(self._pool, cookie_name=name) elif type == "cookie": try: secret_key = kwargs["secret_key"] except KeyError: fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) self._session_type = EncryptedCookieStorage(secret_key, cookie_name=name) # TODO: type memcached # configure backends for backend in backends: if backend == "hosts": obj = auth_hosts() elif backend == "session": obj = auth_users() self._backends.append(obj)
async def init_app() -> web.Application: """Initialize the async web application Returns ------- web.Application An instance of the aiohttp web app using the default loop. """ app = web.Application() aiohttp_jinja2.setup( app, loader=jinja2.PackageLoader("mach_prerelease", "views/templates"), ) fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) setup_session(app, EncryptedCookieStorage(secret_key)) app.router.add_get("/", IndexView.get) app.router.add_get("/static/styles", StaticFileHandler.get_styles) app.router.add_get("/static/scripts", StaticFileHandler.get_scripts) app.router.add_get("/static/assets", StaticFileHandler.get_assets) app.router.add_get("/static/favicon.ico", StaticFileHandler.get_favicon) app.router.add_post("/", IndexView.post) return app
async def start_webserver(self): app = web.Application() app.on_shutdown.append(self._on_shutdown) # настройка авторизации app.user_map = user_map fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) storage = EncryptedCookieStorage(secret_key, cookie_name='API_SESSION') setup_session(app, storage) policy = SessionIdentityPolicy() setup_security(app, policy, DictionaryAuthorizationPolicy(user_map)) # настройка маршрутов app.router.add_get("/", WebServer._index) app.router.add_get("/logo.svg", WebServer._logo) app.router.add_get("/client.js", WebServer._javascript) app.router.add_get("/login.html", WebServer._login_form) app.router.add_post("/login", WebServer._login) app.router.add_get("/logout", WebServer._logout) app.router.add_post("/offer", self._offer) app.router.add_get("/download/{name}", WebServer._download_file) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) # запуск веб-сервера runner = web.AppRunner(app) await runner.setup() self._server = web.TCPSite(runner, host="0.0.0.0", port=8080, ssl_context=self._ssl_context) await self._server.start()
def setup_session(app: web.Application): """ Inits and registers a session middleware in aiohttp.web.Application """ # secret key needed by EncryptedCookieStorage: is *bytes* key with length of *32* secret_key_bytes = app[APP_CONFIG_KEY]["session"]["secret_key"].encode( "utf-8") if len(secret_key_bytes) == 0: raise ValueError( "Empty %s.secret_key in config. Expected at least length 32") while len(secret_key_bytes) < 32: secret_key_bytes += secret_key_bytes # ------------------------------- # TODO: currently cfg and settings in place until former is dropped assert_valid_config(secret_key_bytes.decode("utf-8")) # nosec # ------------------------------- # EncryptedCookieStorage urlsafe_b64decode inside if passes bytes storage = EncryptedCookieStorage(secret_key=secret_key_bytes[:32], cookie_name="osparc.WEBAPI_SESSION") aiohttp_session.setup(app, storage)
async def init(loop): logging.basicConfig(level=logging.DEBUG) # maybe later add authorize middleware app = web.Application(loop=loop,middlewares=[ session_middleware(EncryptedCookieStorage(SECRET_KEY)), db_handler, ],debug=True) aiohttp_debugtoolbar.setup(app) handler = app.make_handler() aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates')) # route part app.router.add_static('/static', 'static', name='static') app.router.add_static('/node_modules', 'node_modules', name='static_dist') for api_route in API_ROUTES: app.router.add_route(api_route[0], api_route[1], api_route[2], name=api_route[3]) for route in routes: app.router.add_route(route[0], route[1], route[2], name=route[3]) # end route part # db connect app.client = ma.AsyncIOMotorClient(MONGO_HOST) app.db = app.client[MONGO_DB_NAME] # end db connect serv_generator = loop.create_server(handler, SITE_HOST, SITE_PORT) return serv_generator, handler, app
def init(loop, host='0.0.0.0', port=10000): from ircb.storeclient import initialize initialize() load_config() policy = auth.SessionTktAuthentication(settings.WEB_SALT, 60, include_ip=True) middlewares = [ session_middleware(EncryptedCookieStorage(settings.WEB_SALT)), auth.auth_middleware(policy) ] app = web.Application(middlewares=middlewares) app.router.add_route('GET', '/', index) app.router.add_route('*', '/api/v1/signup', SignupView, name='signup') app.router.add_route('*', '/api/v1/signin', SigninView, name='signin') app.router.add_route('*', '/api/v1/signout', SignoutView, name='signout') app.router.add_route('*', '/api/v1/networks', NetworkListView, name='networks') app.router.add_route('*', '/api/v1/network/{id}', NetworkView, name='network') app.router.add_route('PUT', '/api/v1/network/{id}/{action}', NetworkConnectionView, name='network_connection') srv = yield from loop.create_server( app.make_handler(logger=logger, access_log=logger), host, port) return srv
async def init(loop): app = web.Application(loop=loop, middlewares=[ session_middleware(EncryptedCookieStorage(SECRET_KEY)), authorize, db_handler, # aiohttp_debugtoolbar.middleware, ]) # route part for route in routes: app.router.add_route(route[0], route[1], route[2], name=route[3]) app.router.add_static('/static', 'static', name='static') # end route part # db connect app.client = ma.AsyncIOMotorClient(MONGO_HOST) app.db = app.client[MONGO_DB_NAME] # end db connect app.on_shutdown.append(on_shutdown) app['websockets'] = [] handler = app.make_handler() if DEBUG: aiohttp_debugtoolbar.setup(app) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates')) serv_generator = loop.create_server(handler, SITE_HOST, SITE_PORT) return serv_generator, handler, app
async def init(): # secret_key must be 32 url-safe base64-encoded bytes fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) app = web.Application(middlewares=[ session_middleware(EncryptedCookieStorage(secret_key)), authorize, db_handler, # aiohttp_debugtoolbar.middleware, ]) app['websockets'] = [] if DEBUG: aiohttp_debugtoolbar.setup(app) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates')) for (method, path, handler, name) in routes: app.router.add_route(method, path, handler, name=name) app.router.add_static('/static', 'static', name='static') # db connect app.client = motor_asyncio.AsyncIOMotorClient(MONGO_HOST) app.db = app.client[MONGO_DB_NAME] # end db connect app.on_shutdown.append(shutdown) return app
def init_gunicorn(): global mc middlewares = [] middlewares.append(db_handler()) if settings.debug: middlewares.append(session_middleware(SimpleCookieStorage())) else: middlewares.append( session_middleware(EncryptedCookieStorage(settings.session_key))) app = web.Application(middlewares=middlewares) aiohttp_jinja2.setup(app, loader=jinja2.FunctionLoader(load_templ)) # Memcache init app.mc = aiomcache.Client(settings.memcache['addr'], settings.memcache['port']) # Mongo init db_connect(app) union_routes(os.path.join(settings.tao_path, 'libs')) union_routes(os.path.join(settings.root_path, 'apps')) union_routes(os.path.join(settings.root_path), p=True) for res in routes: name = res[3] if name is None: name = '{}:{}'.format(res[0], res[2]) app.router.add_route(res[0], res[1], res[2], name=name) path = os.path.join(settings.root_path, 'static') app.router.add_static('/static/', path, name='static') return app
def setup_session(app): from aiohttp_session import setup from aiohttp_session.cookie_storage import EncryptedCookieStorage from hashlib import sha256 session_secret_hash = sha256(app['conf'].session_secret.encode()).digest() storage = EncryptedCookieStorage(session_secret_hash) setup(app, storage)
def main(args=None): main_dir = Path(__file__).parent.parent.resolve() with open(main_dir / 'logger.yaml', 'r') as stream: dictConfig(yaml.load(stream)) host = '0.0.0.0' port = 8000 sslcontext = None loop = asyncio.get_event_loop() loop.set_debug(True) server = web.Application() server.router.add_get('/', urls.index, name='index') server.router.add_get('/login', urls.login, name='login') #server.router.add_post('/query' , urls.query, name='query') # Where the templates are template_loader = jinja2.FileSystemLoader(str(main_dir / 'templates')) aiohttp_jinja2.setup(server, loader=template_loader) # Session middleware fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode( fernet_key) # 32 url-safe base64-encoded bytes session_setup(server, EncryptedCookieStorage(secret_key)) # ...and cue music LOG.info(f"Start BeaconUI server on {host}:{port}") web.run_app(server, host=host, port=port, shutdown_timeout=0, ssl_context=sslcontext)
def init(): BASE_DIR = os.getcwd() # 项目路径 STATIC_DIR = os.path.join(BASE_DIR, 'static') # 静态文件路径 TEMPLATE_DIR = os.path.join(BASE_DIR, 'template') # 模版HTML路径 app = aiohttp.web.Application(middlewares=[middleware_allow]) # routes = gb.var['routes'] secret_key = 'This is the default secret_key' secret_key = hashlib.md5(base64.b64encode( secret_key.encode())).hexdigest().encode() setup(app, EncryptedCookieStorage(secret_key)) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(TEMPLATE_DIR), variable_start_string='{{{', variable_end_string='}}}', enable_async=True, context_processors=[aiohttp_jinja2.request_processor]) app.router.add_static('/static/', path=STATIC_DIR, name='static') app.router.add_routes(routes) aiohttp_jinja2.get_env(app).globals.update(gb.var['templateFuncClassDic']) print( f"\033[1;32;45m*** creat {len(gb.var['global_route'].routes)} route ***\033[0m" ) app.router.add_routes(gb.var['global_route'].routes) return app
def create_app(*, settings: Settings=None): settings = settings or Settings() setup_logging() secret_key = base64.urlsafe_b64decode(settings.auth_key) app = web.Application(middlewares=( error_middleware, session_middleware(EncryptedCookieStorage(secret_key, cookie_name='mithra')), auth_middleware, )) app['settings'] = settings ctx = dict( COMMIT=os.getenv('COMMIT', '-'), RELEASE_DATE=os.getenv('RELEASE_DATE', '-'), SERVER_NAME=os.getenv('SERVER_NAME', '-'), ) index_html = (THIS_DIR / 'index.html').read_text() for key, value in ctx.items(): index_html = re.sub(r'\{\{ ?%s ?\}\}' % key, escape(value), index_html) app['index_html'] = index_html app.on_startup.append(startup) app.on_cleanup.append(cleanup) setup_routes(app) return app
def setup_session(self, key): if not key: key = base64.urlsafe_b64decode(Fernet.generate_key()) else: if isinstance(key, str): key = key.encode() setup(self.app, EncryptedCookieStorage(key))
def main(): app = web.Application() app['websockets'] = {} app['websockets_room'] = {} app['websockets_queue'] = {} app['config'] = SECRET_KEY client = AsyncIOMotorClient(MONGO_HOST) app['db'] = client['AioDB'] app.on_startup.append(start_back_tasks) app.on_startup.append(start_back_tasks_key) app.on_shutdown.append(stop_back_tasks) app.on_shutdown.append(shutdown) fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) aiohttp_jinja2.setup(app, loader=FileSystemLoader(BASE_DIR)) setup(app, EncryptedCookieStorage(secret_key)) for route in routes: app.router.add_route(route[0], route[1], route[2], name=route[3]) app['static_root_url'] = '/static' app.router.add_static('/static', 'static', name='static') logging.basicConfig(level=logging.DEBUG) #sll_certificate = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) #sll_certificate.load_cert_chain('domain_srv.crt', 'domain_srv.key') web.run_app(app)