def factory(force, realm=''): return BasicAuthMiddleware( username=USERNAME, password=PASSWORD, force=force, realm=realm, )
def setup_httprouter(self): @web.middleware async def set_header(request, handler): response = await handler(request) response.headers["X-Powered-By"] = f"hubot/{self.name}" return response user, pwd = environ.get("EXPRESS_USER"), environ.get( "EXPRESS_PASSWORD") stat = environ.get("EXPRESS_STATIC") addr = environ.get("EXPRESS_BIND_ADDRESS", "0.0.0.0") port = int(environ.get("EXPRESS_PORT", 8080)) mws = [set_header] if user and pwd: try: from aiohttp_basicauth import BasicAuthMiddleware except ImportError: self.logger.warn(f"`aiohttp_basicauth` is required", exc_info=True) else: mws.append(BasicAuthMiddleware(username=user, password=pwd)) self.server = _WebAppBuilder(addr, port, middlewares=mws) self.router = self.server.router if stat and Path(stat).is_dir(): self.router.add_static(stat, stat)
def start(self): loop = asyncio.get_event_loop() ssl_context = None if CONF.cert: ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) ssl_context.load_cert_chain(certfile=CONF.cert, keyfile=CONF.key) if CONF.username: auth = BasicAuthMiddleware(username=CONF.username, password=CONF.password) app = web.Application(middlewares=[auth]) else: app = web.Application() app.router.add_get('/console_log/{uuid}', self.handle_get_consolelog) web_server = app.make_handler() coro = asyncio.start_server(self.handle_telnet, CONF.host, CONF.port, ssl=ssl_context, loop=loop) webserv = loop.create_server(web_server, CONF.host, CONF.web_port, ssl=ssl_context) telnet_server = loop.run_until_complete(coro) rest_server = loop.run_until_complete(webserv) # Serve requests until Ctrl+C is pressed LOG.info("Serving telnet on %s", telnet_server.sockets[0].getsockname()) LOG.info("Serving rest api on %s", rest_server.sockets[0].getsockname()) LOG.info("Log directory: %s", CONF.serial_log_dir) try: loop.run_forever() except KeyboardInterrupt: pass # Close the server telnet_server.close() rest_server.close() loop.run_until_complete(telnet_server.wait_closed()) loop.run_until_complete(rest_server.wait_closed()) loop.close()
def main(): auth = [] if 'username' in os.environ and 'password' in os.environ: logging.info( '#############################################################') logging.info('Authorization is enabled.') logging.info('Your balenaCam is password protected.') logging.info( '#############################################################\n') auth.append( BasicAuthMiddleware(username=os.environ['username'], password=os.environ['password'])) else: logging.info( '#############################################################') logging.info('Authorization is disabled.') logging.info( 'Anyone can access your balenaCam, using the device\'s URL!') logging.info( 'Set the username and password environment variables to enable authorization.' ) logging.info( 'For more info visit: https://github.com/balena-io-playground/balena-cam' ) logging.info( '#############################################################\n') app = web.Application(middlewares=auth) app.on_shutdown.append(on_shutdown) app.router.add_get('/', server.index) app.router.add_get('/favicon.png', server.favicon) app.router.add_get('/balena-logo.svg', server.balena_logo) app.router.add_get('/balena-cam.svg', server.balena) app.router.add_get('/client.js', server.javascript) app.router.add_get('/style.css', server.stylesheet) app.router.add_post('/offer', offer) app.router.add_get('/mjpeg', mjpeg_handler) app.router.add_get('/ice-config', config) web.run_app(app, access_log=None, port=80)
import logging import os import docker from aiohttp import web from aiohttp_basicauth import BasicAuthMiddleware import aiohttp_cors DOCKER_IMAGE = os.getenv('DOCKER_IMAGE', 'kylemanna/openvpn') OVPN_DATA = os.getenv('OVPN_DATA', '/ovpn-data') SERVICE_USER = os.getenv('SERVICE_USER') SERVICE_PASSWORD = os.getenv('SERVICE_PASSWORD') SERVER_ADDRESS = os.getenv('SERVER_ADDRESS', '127.0.0.1') auth = BasicAuthMiddleware(username=SERVICE_USER, password=SERVICE_PASSWORD, force=False) def run_on_vpn_docker(command, environment=None): if environment is None: environment = [] client = docker.from_env() return client.containers.run( image=DOCKER_IMAGE, command=command, remove=True, detach=False, volumes={OVPN_DATA: { 'bind': '/etc/openvpn', 'mode': 'rw'
try: if os.environ['rotation'] == '1': flip = True except: pass auth = [] if 'username' in os.environ and 'password' in os.environ: print( '\n#############################################################') print('Authorization is enabled.') print('Your balenaCam is password protected.') print( '#############################################################\n') auth.append( BasicAuthMiddleware(username=os.environ['username'], password=os.environ['password'])) else: print( '\n#############################################################') print('Authorization is disabled.') print('Anyone can access your balenaCam, using the device\'s URL!') print( 'Set the username and password environment variables \nto enable authorization.' ) print( 'For more info visit: \nhttps://github.com/balena-io-playground/balena-cam' ) print( '#############################################################\n') # Factory to create peerConnections depending on the iceServers set by user
import urllib.parse from json import JSONDecodeError from urllib.parse import unquote from aiohttp import web from aiohttp_basicauth import BasicAuthMiddleware from lib.config import Config from lib.serverstate import ServerState from lib.socket import ClientManager from lib.util import safe_json_dumps from lib.webserver.auth import EnodoAuth from lib.webserver.basehandler import BaseHandler auth = BasicAuthMiddleware(username=None, password=None, force=False) class ApiHandlers: @classmethod def prepare(cls): EnodoAuth.auth.username = Config.basic_auth_username EnodoAuth.auth.password = Config.basic_auth_password @classmethod @EnodoAuth.auth.required async def get_monitored_series(cls, request): """Returns a list of monitored series Args: request (Request): aiohttp request Returns:
from aiohttp_basicauth import BasicAuthMiddleware from config import BAUTH_USERNAME, BAUTH_PASSWORD bauth = BasicAuthMiddleware(username=BAUTH_USERNAME, password=BAUTH_PASSWORD, force=False)
def run_server(ha_path, username, password, no_auth, port=9999, redis_host=None, redis_port=None, nocache=False): """Run the webserver.""" print("Custom-component-store is starting.") global REASON # pylint: disable=W0603 global REDIS_HOST # pylint: disable=W0603 global REDIS_PORT # pylint: disable=W0603 global NO_CACHE # pylint: disable=W0603 if ha_path: print(ha_path) os.environ["HA_CONFIG_PATH"] = ha_path if redis_host is None: REDIS_HOST = os.environ.get('REDIS_HOST') else: REDIS_HOST = redis_host if redis_host is None: REDIS_HOST = os.environ.get('REDIS_PORT') else: REDIS_PORT = redis_port if nocache is None: NO_CACHE = os.environ.get('NO_CACHE') else: NO_CACHE = nocache path = os.environ.get('HA_CONFIG_PATH', '/config') directory = path + '/custom_components' version_path = path + '/.HA_VERSION' version = 0 target = 86 if not no_auth: auth = BasicAuthMiddleware(username=username, password=password) app = web.Application(middlewares=[auth]) else: app = web.Application() if not os.path.exists(version_path): REASON = 'ha_not_found' elif not os.path.exists(path): REASON = 'no_path' else: with open(version_path) as version_file: version = version_file.readlines() version = int(version[0].split('.')[1]) if version < target: REASON = 'version' print("HA Version", version) if not os.path.exists(directory): os.makedirs(directory) if not NO_CACHE: redis = data.redis_connect() if not redis: REASON = 'redis_conn_error' else: print('Cache disabled...') if REASON is None: app.router.add_route('GET', r'/', installed_components_view) app.router.add_route('GET', r'/about', about_view) app.router.add_route('GET', r'/component/{component}', component_view) app.router.add_route('GET', r'/component/{component}/install', install_component) app.router.add_route('GET', r'/component/{component}/json', json) app.router.add_route('GET', r'/component/{component}/migrate', migrate_component) app.router.add_route('GET', r'/component/{component}/uninstall', uninstall_component) app.router.add_route('GET', r'/component/{component}/update', install_component) app.router.add_route('GET', r'/json', json) app.router.add_route('GET', r'/store', the_store_view) app.router.add_route('GET', r'/reloadinstalled', reloadinstalled) app.router.add_route('GET', r'/reloadstore', reloadstore) else: print("There was an issue starting", REASON) app.router.add_route('GET', r'/', error_view) app.router.add_route('GET', r'/{route}', error_view) web.run_app(app, port=port, print=None)
import json from aiohttp import web from aiohttp_basicauth import BasicAuthMiddleware from .services import ReceiptVerifier, ValidationException, InsertValueException auth = BasicAuthMiddleware() service = ReceiptVerifier() async def api_root(request): raise web.HTTPFound(location='/api/doc#/') async def sign_up(request): try: params = await request.json() response = await service.add_user(params) return web.Response(text=json.dumps(response), status=200) except json.JSONDecodeError as error: return web.Response(text=json.dumps(error.msg), status=400) except ValidationException as error: return web.Response(text=json.dumps(error.message), status=409) except InsertValueException as error: return web.Response(text=json.dumps(error.message), status=500) async def get_user_receipts(request): user_info = auth.parse_auth_header(request)
await asyncio.sleep(sleep_time_after) last_update_time = str(get_time_string_east8()) async def spider_core(): loop = asyncio.get_running_loop() while True: current_time = get_time_string_east8() print(current_time, "scaned list", end='') if current_time.hour in trade_time_utc8: print(',decide to work') scan_list = sql.get_all_monitor_target() for stockitem in scan_list: loop.create_task( fetch_once(stockitem, fetch_time_internal, min_fetch_internal)) await asyncio.sleep(fetch_time_internal) else: print(',decide to sleep') await asyncio.sleep(10) workingpath = os.path.dirname(os.path.abspath(__file__)) auth = BasicAuthMiddleware(username=auth_username, password=auth_password) app = web.Application(middlewares=[auth]) app.add_routes(routes) app.add_routes([web.static('/', os.path.join(workingpath, 'static'))]) loop = asyncio.get_event_loop() loop.create_task(spider_core()) loop.run_until_complete(web._run_app(app, host=run_host, port=run_port))