예제 #1
0
파일: web.py 프로젝트: shiroyuki/oriole
def protected():
    """
    Enforce the bearer token authentication

    .. note:: In this method, returning nothing will yield back to the request handling methods.
    """
    current_request: Request = request
    request_path = current_request.path
    request_method = current_request.method
    request.id = uuid.uuid4()
    request.claims = dict()
    request.user_id = None

    if request_method == 'OPTIONS':
        return _allow_cors(Response('', status=200, content_type='text/plain'))

    fc: FrontController = container.get(FrontController)

    if not fc.require_access_control(request_path[len(auto_path_prefix) + 1:]):
        logger.debug(
            f'REQUEST {request.id}: Request to {request_path} is extempted from authentication check.'
        )
        return

    try:
        bearer_token = current_request.headers['authorization']
    except KeyError:
        return _allow_cors(
            make_error_response('missing_bearer_token', status=401))

    if not bearer_token.startswith('Bearer '):
        return _allow_cors(
            make_error_response('bearer_token_required', status=401))

    authenticator: Authenticator = container.get(Authenticator)

    try:
        access_token = bearer_token[7:]
        request.claims = authenticator.decode_token(access_token)
        request.user_id = request.claims['sub']
    except InvalidTokenError:
        logger.warning(
            f'REQUEST {request.id}: Someone tried to use a fake token ("{access_token}").'
        )
        return _allow_cors(make_error_response('invalid_token', status=401))
    except ExpiredTokenError:
        logger.info(
            f'REQUEST {request.id}: Intercepted an expired token ("{access_token}").'
        )
        return _allow_cors(make_error_response('expired_token', status=401))
예제 #2
0
    def execute(self, args):
        authenticator: Authenticator = container.get(Authenticator)
        token = authenticator.encode_token(
            dict(sub=args.subject, scopes=args.scopes))

        print(f'Bearer Token: {token}')
        print(f'Claims: {authenticator.decode_token(token)}')
예제 #3
0
    def execute(self, args: Namespace):
        print(f'Importing from {args.export_file_path}...')

        rows: List[ExportedEntry] = []

        with open(args.export_file_path, 'r') as f:
            reader = csv.reader(f)
            read_header = False
            headers = []

            for row in reader:
                if not read_header:
                    read_header = True
                    headers.extend(row)
                    continue

                if not row:
                    continue

                rows.append(
                    ExportedEntry(**{
                        headers[i]: row[i].strip()
                        for i in range(len(headers))
                    }))

        storage: StorageService = container.get(StorageService)

        data = storage.load()
        default_tag = f'imported:{time()}'

        for row in rows:
            tags = [default_tag]

            if row.grouping:
                tags.append(row.grouping)

            if row.url == 'http://sn':
                data.notes.append(Note.make(row.name, row.extra, tags))
            else:
                if row.url == 'http://':
                    tags.append('local')
                else:
                    tags.append('web')
                    if re.search(r'^http://\d+(\.\d+){3}', row.url):
                        tags.append('intranet')
                    else:
                        tags.append('internet')
                data.credentials.append(
                    Credential.make(row.name, row.username, row.password,
                                    row.extra, tags))
        storage.save(data)
예제 #4
0
    def execute(self, args):
        # Designed to work behind a proxy server.
        service: KeymasterGRPCService = container.get(KeymasterGRPCService)
        server = grpc.server(ThreadPoolExecutor(max_workers=10))

        add_KeymasterServicer_to_server(service, server)

        server.add_insecure_port(f'[::]:{args.port}')
        server.start()

        print(f'Listening on port {args.port}...')

        try:
            while True:
                pass
        except KeyboardInterrupt:
            print('\rService terminating...')
        finally:
            server.stop(None)
            print('\rService terminated cleanly')
예제 #5
0
파일: web.py 프로젝트: shiroyuki/oriole
def delegate_to_front_controller(request_path):
    fc: FrontController = container.get(FrontController)

    method = str(request.method).lower()

    # List all available paths
    if request_path == 'all':
        if method != 'get':
            return make_error_response('method_not_allowed', status=405)
        return make_json_response(fc.route_map)

    # TODO Use fc.find_route
    route = None
    route_matches: re.Match = None

    for routing_pattern in fc.route_map:
        route_matches = re.match(routing_pattern, request_path)

        if route_matches:
            route = fc.route_map[routing_pattern]
            break
    # TODO ↑

    if not route:
        return make_error_response('endpoint_not_found', status=404)

    if not hasattr(route.handler, method):
        return make_error_response(
            'method_not_allowed',
            details=dict(handler_class_name=type(route.handler).__name__,
                         handler_module_name=type(route.handler).__module__,
                         method=method.upper()),
            status=405)

    handling_method = getattr(route.handler(), method)
    response = handling_method(**route_matches.groupdict())

    if isinstance(response, Response):
        return response

    return make_json_response(response)
예제 #6
0
                        os.path.join(os.getcwd(), 'config/app.yml')))
parser.add_argument('--debug',
                    '-d',
                    action='store_true',
                    help='Enable the debug mode')

args = parser.parse_args()

logger = LoggerFactory.get('oriole',
                           level=logging.DEBUG if args.debug else None)

logger.debug('Application Configuration File: %s', args.config_file)

with open(args.config_file) as f:
    config = yaml.load(f.read(), yaml.SafeLoader)

    fc: FrontController = container.get(FrontController,
                                        lock_down_enabled=False)

    fc.map(config['routes'])

    main_web_module_name = f'oriole.{config["backend"]}.web'

    try:
        web = importlib.import_module(main_web_module_name)
        web.main(args)
    except ImportError:
        raise UnknownBackendModeError(
            f'The "backend" configuration can only be either "sync" or "async".'
        )