Beispiel #1
0
def init(loop):
    redis_pool = yield from create_pool(('localhost', 6379))
    dbengine = yield from create_engine(user='******',
                                        password='******',
                                        database='aiohttp_security',
                                        host='127.0.0.1')
    app = web.Application(loop=loop)
    setup_session(app, RedisStorage(redis_pool))
    setup_security(app,
                   SessionIdentityPolicy(),
                   DBAuthorizationPolicy(dbengine))

    web_handlers = Web()
    yield from web_handlers.configure(app)

    handler = app.make_handler()
    srv = yield from loop.create_server(handler, '127.0.0.1', 8080)
    print("Server started at http://127.0.0.1:8080")
    return srv, app, handler
Beispiel #2
0
 async def apply(self, app, users):
     """
     Set up security on server boot
     :param app:
     :param users:
     :return: None
     """
     for group, u in users.items():
         self.log.debug('Created authentication group: %s' % group)
         for k, v in u.items():
             self.user_map[k] = self.User(
                 k,
                 v,
                 (group, 'app'),
             )
     app.user_map = self.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(self.user_map))
Beispiel #3
0
async def create_app():
    app = web.Application()
    app.add_routes([
        web.get('/', index, name='index'),
        web.get('/home', home, name='home'),
        web.static('/static/',
                   path=THIS_DIR / 'app/static',
                   append_version=True,
                   name='static'),
        web.static('/downloads/',
                   path=THIS_DIR / 'app/downloads',
                   show_index=True,
                   name='downloads'),
        web.static('/uploads/',
                   path=THIS_DIR / 'app/uploads',
                   show_index=True,
                   name='uploads')
    ])

    # Routes
    setup_auth_routes(app)
    setup_campaign_routes(app)
    setup_dashboard_routes(app)
    setup_agent_routes(app)
    setup_user_mgt_routes(app)
    setup_middleware(app)

    load = jinja2.FileSystemLoader(str(THIS_DIR / 'app/templates'))
    aiohttp_jinja2.setup(app, loader=load)
    app['name'] = 'thremulate'

    setup(app, EncryptedCookieStorage(secret_key))

    # Setting authentication and authorization
    setup_security(app, SessionIdentityPolicy(), DBAuthorizationPolicy())
    # aiohttp_debugtoolbar.setup(app)
    return app
Beispiel #4
0
async def init_app(config):

    app = web.Application()
    app['config'] = config

    setup_routes(app)

    db_pool = await init_db(app)

    redis_pool = await setup_redis(app)
    setup_session(app, RedisStorage(redis_pool))

    aiohttp_jinja2.setup(
        app,
        loader=jinja2.PackageLoader('for_templates', 'templates'),
        context_processors=[current_user_ctx_processor],
    )

    setup_security(app, SessionIdentityPolicy(),
                   DBAuthorizationPolicy(db_pool))

    log.debug(app['config'])

    return app
Beispiel #5
0
async def init(loop):
    redis_pool = await create_pool(('localhost', 6379))
    db_engine = await create_engine(user=settings.DB_USER,
                                    password=settings.DB_PASSWORD,
                                    database=settings.DATABASE,
                                    host=settings.DB_HOST)
    app = web.Application(loop=loop)
    app['engine'] = db_engine
    setup_debugtoolbar(app)
    setup_session(app, RedisStorage(redis_pool))
    setup_security(app,
                   SessionIdentityPolicy(),
                   DBAuthorizationPolicy(db_engine))
    setup_jinja2(app, loader=jinja2.FileSystemLoader('demo/templates'))

    auth_handlers = AuthHandlers()
    auth_handlers.configure(app)
    if settings.DEBUG:
        app.router.add_static('/static', path=str(PROJ_ROOT / 'static'))
    view_handlers = ViewsHandlers()
    view_handlers.configure(app)
    admin_config = str(PROJ_ROOT / 'static' / 'js')
    setup_admin(app, db_engine, admin_config)
    return app
Beispiel #6
0
async def init_app(config):
    app = web.Application()
    app['config'] = config

    db = await init_db(app)

    fernet_key = fernet.Fernet.generate_key()
    secret_key = base64.urlsafe_b64decode(fernet_key)

    db_url = construct_db_url(CONFIG['postgres'])
    engine = create_engine(db_url)

    create_tables(engine)

    setup_session(
        app,
        EncryptedCookieStorage(secret_key)
    )

    aiohttp_jinja2.setup(
        app,
        loader=jinja2.PackageLoader('url_shorter','templates'),
        context_processors=[current_user_ctx_processor],
        filters={'datetimeformat': datetimeformat}
    )

    setup_security(
        app,
        SessionIdentityPolicy(),
        DBAuthorizationPolicy(db)
    )

    setup_routes(app)
    app.on_startup.append(init_db)
    app.on_cleanup.append(close_pg)
    return app
Beispiel #7
0
def cli(ctx, config):
    ctx.ensure_object(dict)
    middleware = session_middleware(SimpleCookieStorage(httponly=False))

    app = web.Application(middlewares=[middleware])
    app.name = 'main'

    app['config'] = get_real_config('polls.yaml', config)
    app.on_startup.append(init_mysql)
    app.on_startup.append(init_queue)

    app.on_cleanup.append(close_mysql)
    app.on_cleanup.append(close_queue)

    load_plugins(app)

    aiohttp_jinja2.setup(
        app, loader=jinja2.FileSystemLoader(map(str, app['config']['template_dirs'])))

    # security
    policy = SessionIdentityPolicy()
    setup_security(app, policy, SimpleAuthPolicy())

    ctx.obj['APP'] = app
Beispiel #8
0
async def init_app(argv=None):

    app = web.Application(client_max_size=128 * 1024 *
                          1024)  # max client payload of 128MB

    # create db connection on startup, close on exit
    try:
        db_pool = await init_pg(app)
        app.on_cleanup.append(close_pg)
    except Exception as err:
        logging.debug(msg=err)
        raise

    # use key to sign cookie
    env_key = base64.urlsafe_b64encode(
        bytes(os.environ.get('3DEPOSIT_SECRET_KEY'), 'utf-8'))
    secret_key = base64.urlsafe_b64decode(env_key)
    setup_session(app, EncryptedCookieStorage(secret_key))

    aiohttp_jinja2.setup(
        app,
        loader=jinja2.PackageLoader('gateway'),
        context_processors=[current_user_ctx_processor],
    )

    setup_security(app, SessionIdentityPolicy(),
                   DBAuthorizationPolicy(db_pool))

    # setup views and routes
    setup_routes(app)

    # logging
    logging.basicConfig(level=logging.DEBUG, filename='./data/gateway.log')
    logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    return app
Beispiel #9
0
async def create_app(config):
    app = web.Application()

    app["config"] = config
    aiohttp_jinja2.setup(app,
                         loader=jinja2.PackageLoader("cardsstore",
                                                     "templates"))
    setup_routes(app)

    # secret_key must be 32 url-safe base64-encoded bytes
    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()
    app["db"] = await aioredis.create_pool(config["database_uri"])
    setup_security(app, policy, DictionaryAuthorizationPolicy(app["db"]))
    app.on_startup.append(on_start)

    app.on_cleanup.append(on_shutdown)

    return app
Beispiel #10
0
def main():
    """
    Read config and launch asterios server.
    """
    config = get_config()
    for level_package in config['level_package']:
        MetaLevel.load_level(level_package)

    app = web.Application(middlewares=[error_middleware])
    setup_routes(app)
    app['config'] = config

    if config.get('authentication'):
        user_map = {
            config['authentication']['superuser']['login']: {
                'login': config['authentication']['superuser']['login'],
                'password': config['authentication']['superuser']['password'],
                'role': 'superuser'
            }
        }
        setup_security(app, BasicAuthIdentityPolicy(user_map),
                       AuthorizationPolicy(user_map))

    web.run_app(app, host=config['host'], port=config['port'])
Beispiel #11
0
async def create_app():
    config = read_configuration_file()
    db_pool = await attach_db(config)

    app = web.Application(middlewares=[error_middleware, babel_middleware])
    app["config"] = config
    app["db-pool"] = db_pool

    app["mailer"] = MassMailer()

    # beware of order !
    setup_session(app)
    setup_security(
        app,
        SessionIdentityPolicy(),
        DBAuthorizationPolicy(db_pool)
    )
    app.middlewares.append(aiohttp_session_flash.middleware)

    template_dir = op.join(op.dirname(op.abspath(__file__)), "templates")
    aiohttp_jinja2.setup(
        app,
        loader=FileSystemLoader(template_dir),
        context_processors=(
            aiohttp_session_flash.context_processor,
            authorized_userid_context_processor
        )
    )
    jinja2_env = aiohttp_jinja2.get_env(app)
    jinja2_env.globals['_'] = _

    setup_routes(app)

    app.on_cleanup.append(cleanup)

    return app
def make_app(loop):
    app = web.Application(loop=loop)
    setup_session(app, SimpleCookieStorage())
    setup_security(app, SessionIdentityPolicy(), Autz())
    return app
Beispiel #13
0
async def setup(app):
    setup_security(app, IDENTITY_POLICY(), AUTHORIZATION_POLICY())
Beispiel #14
0
async def start():
    """Initialize App

    This function is the entry point for wrappers that take an app factory
    as argument, notably gunicorn:

    $ gunicorn bioconda_utils.bot:init_app \
      --worker-class aiohttp.worker.GunicornWebWorker \
      --reload
    """
    utils.setup_logger('bioconda_utils', LOGLEVEL, prefix="")
    logger.info("Starting bot (version=%s)", VERSION)

    app = aiohttp.web.Application()
    app['name'] = BOT_NAME

    # Set up session storage
    fernet_key = fernet.Fernet.generate_key()
    secret_key = base64.urlsafe_b64decode(fernet_key)
    session_store = EncryptedCookieStorage(secret_key)
    setup_session(app, session_store)

    # Set up security
    setup_security(app, SessionIdentityPolicy(), AuthorizationPolicy(app))

    # Set up jinja2 rendering
    loader = jinja2.PackageLoader('bioconda_utils', 'templates')
    aiohttp_jinja2.setup(app,
                         loader=loader,
                         context_processors=[jinja_defaults],
                         filters={'markdown': jinja2_filter_markdown})

    # Set up error handlers
    app.middlewares.append(handle_errors)

    # Prepare persistent client session
    app['client_session'] = aiohttp.ClientSession()

    # Create Github client
    app['ghappapi'] = GitHubAppHandler(app['client_session'], BOT_NAME,
                                       APP_KEY, APP_ID, APP_CLIENT_ID,
                                       APP_CLIENT_SECRET)

    # Create Gitter Client (background process)
    app['gitter_listener'] = GitterListener(app, GITTER_TOKEN, GITTER_CHANNELS,
                                            app['client_session'],
                                            app['ghappapi'])

    # Add routes collected above
    app.add_routes(web_routes)

    # Set up static files
    utils_path = os.path.dirname(os.path.dirname(__file__))
    app.router.add_static("/css", os.path.join(utils_path, 'templates/css'))

    # Close session - this needs to be at the end of the
    # on shutdown pieces so the client session remains available
    # until everything is done.
    async def close_session(app):
        await app['client_session'].close()

    app.on_shutdown.append(close_session)

    return app
Beispiel #15
0
def init_app(config) -> web.Application:
    # db pool
    db_config = {
        'database': config['db']['database'],
        'user': config['db']['user'],
        'password': config['db']['password'],
        'host': config['db']['host'],
        'port': config['db']['port'],
    }
    time.sleep(10)
    pool = Pool(db_config)

    # components
    repos = {
        'article_repository': ArticleRepository(pool),
        'user_repository': UserRepository(pool)
    }

    # To make sure that we are connected to db
    repos['article_repository'].now()

    searcher = HackerNewsSearcher()
    services = {
        'user_service': UserService(repos['user_repository']),
        'hacker_news_searcher': searcher,
        'article_service': ArticleService(repos['article_repository'],
                                          searcher),
        'token_service': TokenService(config, repos['user_repository'])
    }

    controllers = {
        'auth_controller':
        AuthController(services['user_service'], services['token_service'],
                       config['fe_redirect']),
        'article_controller':
        ArticleController(services['article_service']),
        'user_controller':
        UserController()
    }

    # web configuration
    app = web.Application(middlewares=[auth_middleware])
    app['config'] = config

    # setup routes
    app.add_routes([
        web.post('/users/authenticate', controllers['auth_controller'].auth),
        web.post('/users/register', controllers['auth_controller'].signin),
        web.get('/users/githubsso', controllers['auth_controller'].githubsso),
        web.get('/articles', controllers['article_controller'].get_all),
        web.post('/articles', controllers['article_controller'].find_article),
        web.delete('/articles',
                   controllers['article_controller'].remove_article_by_id)
    ])
    # cors
    cors = aiohttp_cors.setup(app,
                              defaults={
                                  '*':
                                  aiohttp_cors.ResourceOptions(
                                      allow_credentials=True,
                                      expose_headers="*",
                                      allow_headers="*",
                                  )
                              })

    # Configure CORS on all routes.
    for route in list(app.router.routes()):
        cors.add(route)

    # security
    setup_security(app, JWTIdentityPolicy(secret=config['secret']),
                   PyFeedsAuthorizationPolicy(services['user_service']))

    return app
Beispiel #16
0
import base64

from aiohttp import web
from aiohttp_session import session_middleware, setup
from aiohttp_swagger import setup_swagger
from cryptography import fernet
from aiohttp_security import setup as setup_security, SessionIdentityPolicy

from db import init_mongo, close_mongo
from middlewares import TokenStorage
from policy import SimpleAuthorizationPolicy
from settings import config
from views import routes

fernet_key = fernet.Fernet.generate_key()
secret_key = base64.urlsafe_b64decode(fernet_key)
middleware = session_middleware(TokenStorage(secret_key))
app = web.Application(middlewares=[middleware])

app.router.add_routes(routes)
setup_swagger(app, swagger_from_file="docs/swagger.yaml")

app['config'] = config

app.on_startup.append(init_mongo)
app.on_cleanup.append(close_mongo)

setup_security(app, SessionIdentityPolicy(), SimpleAuthorizationPolicy(app))

web.run_app(app)
def make_app(loop):
    app = web.Application(loop=loop)
    setup_session(app, SimpleCookieStorage())
    setup_security(app, SessionIdentityPolicy(), Autz())
    return app
Beispiel #18
0
sampleHandler = SampleHandler()
phenoHandler = PhenotypeHandler()
searchHandler = SearchHandler()
panelHandler = PanelHandler()
adminHandler = AdminHandler()


# Create a auth ticket mechanism that expires after SESSION_MAX_DURATION seconds (default is 86400s = 24h), and has a randomly generated secret. 
# Also includes the optional inclusion of the users IP address in the hash
key = base64.b64encode(PRIVATE_KEY32.encode()).decode()


# Create server app
app = web.Application()
setup_session(app, EncryptedCookieStorage(key, max_age=SESSION_MAX_DURATION, cookie_name="regovar_session"))
setup_security(app, SessionIdentityPolicy(session_key='regovar_session_token'), RegovarAuthorizationPolicy())
app['websockets'] = []
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(TEMPLATE_DIR)) 

# On shutdown, close all websockets
app.on_shutdown.append(on_shutdown)






# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
# ROUTES
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
app.router.add_route('GET',    "/welcome", apiHandler.welcome)                                                   # Get "welcome page of the rest API"
Beispiel #19
0
searchHandler = SearchHandler()
panelHandler = PanelHandler()
adminHandler = AdminHandler()

# Create a auth ticket mechanism that expires after SESSION_MAX_DURATION seconds (default is 86400s = 24h), and has a randomly generated secret.
# Also includes the optional inclusion of the users IP address in the hash
key = base64.b64encode(PRIVATE_KEY32.encode()).decode()

# Create server app
app = web.Application()
setup_session(
    app,
    EncryptedCookieStorage(key,
                           max_age=SESSION_MAX_DURATION,
                           cookie_name="regovar_session"))
setup_security(app, SessionIdentityPolicy(session_key='regovar_session_token'),
               RegovarAuthorizationPolicy())
app['websockets'] = []
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(TEMPLATE_DIR))

# On shutdown, close all websockets
app.on_shutdown.append(on_shutdown)

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# ROUTES
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
app.router.add_route('GET', "/welcome",
                     apiHandler.welcome)  # Get "welcome page of the rest API"
app.router.add_route('GET', "/config",
                     apiHandler.config)  # Get config of the server
app.router.add_route('GET', "/api", apiHandler.api)  # Get html test api page
app.router.add_route(
Beispiel #20
0
def setup_app(loop=asyncio.get_event_loop(), config=load_config()[0]):
    if config.get("sentry_dsn", None):
        sentry_sdk.init(
            dsn=config["sentry_dsn"],
            integrations=[AioHttpIntegration()],
            release=f"cherrydoor@{__version__}",
        )
    # create app
    app = web.Application(loop=loop)
    # make config accessible through the app
    app["config"] = config
    # setup database and add it to the app
    db = init_db(config, loop)
    app["db"] = db
    # create a token generator/validator and add make it accessible through the app
    api_tokens = ApiTokens(app, config.get("secret_key", ""))
    app["api_tokens"] = api_tokens

    app.on_startup.append(setup_db)
    # set up aiohttp-session with aiohttp-session-mongo for storage
    setup_session(
        app,
        MongoStorage(
            db["sessions"],
            max_age=None,
            cookie_name="session_id",
        ),
    )
    # set up aiohttp-security
    setup_security(
        app,
        SessionIdentityPolicy("uid", config.get("max_session_age", 31536000)),
        AuthorizationPolicy(app),
    )
    # set up secure.py
    secure_setup(app)
    app.middlewares.append(set_secure_headers)

    csrf_policy = aiohttp_csrf.policy.FormAndHeaderPolicy(
        CSRF_HEADER_NAME, CSRF_FIELD_NAME
    )
    csrf_storage = aiohttp_csrf.storage.SessionStorage(CSRF_SESSION_NAME)
    aiohttp_csrf.setup(app, policy=csrf_policy, storage=csrf_storage)
    # app.middlewares.append(aiohttp_csrf.csrf_middleware)

    load_and_connect_all_endpoints_from_folder(
        path=f"{os.path.dirname(os.path.realpath(__file__))}/api",
        app=app,
        version_prefix="api/v1",
    )
    redoc_url = "/api/v1/docs"
    setup_redoc(
        app,
        redoc_url=redoc_url,
        description=openapi_description,
        title="Cherrydoor API",
        page_title="Cherrydocs",
        openapi_info=get_openapi_documentation(overrides=openapi_overrides),
        redoc_options=redoc_options,
        contact=openapi_contact,
    )
    app["redoc_url"] = redoc_url
    app.router.add_routes(redoc_routes)
    setup_static_routes(app)

    jinja2_loader = PackageLoader("cherrydoor", "templates")
    setup_jinja2(app, loader=jinja2_loader, auto_reload=True)
    get_env(app).globals["sri"] = sri_for
    get_env(app).globals["csrf_field_name"] = CSRF_FIELD_NAME
    get_env(app).filters["vue"] = vue
    setup_routes(app)
    sio.attach(app)
    app.on_startup.append(setup_socket_tasks)

    return app
Beispiel #21
0
def init_security(app):
    policy = auth.SessionIdentityPolicy()
    setup_security(app, policy, auth.UserAuthenticationPolicy())
 def setup_security(self):
     secret_key = base64.urlsafe_b64decode(self.app['config']['session_secret'])
     setup_session(self.app, EncryptedCookieStorage(secret_key))
     setup_security(self.app, SessionIdentityPolicy(), FileAuthorizationPolicy(self.app['config']['users']))
Beispiel #23
0
 def maker(*args, **kwargs):
     app, client = yield from create_app_and_client(*args, **kwargs)
     setup_session(app, SimpleCookieStorage())
     setup_security(app, SessionIdentityPolicy(), Autz())
     return app, client
 def maker(*args, **kwargs):
     app, client = yield from create_app_and_client(*args, **kwargs)
     app.middlewares.append(session_middleware(SimpleCookieStorage()))
     setup_security(app, SessionIdentityPolicy(), Autz())
     return app, client
Beispiel #25
0
exceptions = error_factory(exceptions_html)

app = web.Application(middlewares=[db_handler,
                                   exceptions])

logger.info("Connect to db")
app.client = AsyncIOMotorClient(MONGO_CONNECT)
app.db = app.client["zrada"]

aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(str(HERE)+"/front/templates"))
redis_pool = loop.run_until_complete(make_redis_pool())

setup_session(app, RedisStorage(redis_pool))

setup_security(app,
               policy,
               SimpleJack_AuthorizationPolicy(app.db))


if DEBUG:
    logger.info("Setup aiohttp static")
    app.add_routes([web.static('/static', str(HERE) + "/front/static", show_index=True),
                    web.static('/avatars', str(HERE) + "/front/avatars", show_index=True)])

logger.info("Setup routes")
import_urls(app)    # Installing routes

async def shutdown(app: web.Application):
    app.client.close()  # database connection close
    await app.shutdown()
    await app.cleanup()
Beispiel #26
0
import base64
from cryptography import fernet
from sqlalchemy import create_engine

from middleware import json_content_type_middleware
from routes import setup_routes
from models import metadata
from utils import DBAuthorizationPolicy

engine = create_engine('sqlite:///../database.db')
metadata.create_all(engine)

fernet_key = fernet.Fernet.generate_key()
secret_key = base64.urlsafe_b64decode(fernet_key)

app = web.Application()
cors = aiohttp_cors.setup(app,
                          defaults={
                              "*":
                              aiohttp_cors.ResourceOptions(
                                  allow_methods=["GET", 'POST'],
                                  allow_credentials=True,
                                  expose_headers="*",
                                  allow_headers="*"),
                          })
setup_session(app, EncryptedCookieStorage(secret_key))
setup_security(app, SessionIdentityPolicy(), DBAuthorizationPolicy())

setup_routes(app, cors)

web.run_app(app, port=7000)