# Path: irisett/log.py
# def configure_logging(logtype: str, logfilename: Optional[str]=None, debug_logging: bool=False,
#                       rotate_length: int=1000000, max_rotated_files: int=250) -> None:
# def msg(logmsg: str, section: Optional[str]=None) -> None:
# def debug(logmsg: str, section: Optional[str]=None) -> None:
#     def log_msg(self, logmsg: str) -> None:
#     def log_debug(self, logmsg: str) -> None:
# class LoggingMixin:
# 
# Path: irisett/stats.py
# def get_section(section: Optional[str]) -> Dict[str, float]:
# def set(var: str, value: float, section: Optional[str] = None) -> None:
# def inc(var: str, section: Optional[str] = None) -> None:
# def dec(var: str, section: Optional[str] = None) -> None:
# def get_stats() -> Dict[str, float]:
# 
# Path: irisett/webmgmt/errors.py
# class WebMgmtError(Exception):
# class InvalidData(WebMgmtError):
# class PermissionDenied(WebMgmtError):
# class NotFound(WebMgmtError):
# class MissingLogin(WebMgmtError):
# 
# Path: irisett/errors.py
# class IrisettError(Exception):
#     def __str__(self) -> str:
#         if len(self.args) == 1:
#             ret = self.args[0]
#         else:
#             ret = str(self.__class__.__name__)
#         return ret


from typing import Optional, Callable, Any
from aiohttp import web
from irisett import (
    log,
    stats,
)
from irisett.webmgmt import (
    errors,
)
from irisett.errors import IrisettError
import base64
import binascii
    async def middleware_handler(request: web.Request) -> web.Response:
        stats.inc('num_calls', 'WEBMGMT')
        log.msg('Received request: %s' % request, 'WEBMGMT')
        return await handler(request)

    return middleware_handler


async def basic_auth_middleware_factory(app: web.Application, handler: Any) -> Callable:
    """Authentication.

    Uses HTTP basic auth to check that requests are including the required
    username and password.
    """
    async def middleware_handler(request: web.Request) -> web.Response:
        ok = False
        auth_token = request.headers.get('Authorization')
        if auth_token and auth_token.startswith('Basic '):
            auth_token = auth_token[6:]
            try:
                auth_bytes = base64.b64decode(auth_token)  # type: Optional[bytes]
            except binascii.Error:
                auth_bytes = None
            if auth_bytes:
                auth_str = auth_bytes.decode('utf-8', errors='ignore')
                if ':' in auth_str:
                    username, password = auth_str.split(':', 1)
                    if username == app['username'] and password == app['password']:
                        ok = True
        if not ok:

# Path: irisett/log.py
# def configure_logging(logtype: str, logfilename: Optional[str]=None, debug_logging: bool=False,
#                       rotate_length: int=1000000, max_rotated_files: int=250) -> None:
# def msg(logmsg: str, section: Optional[str]=None) -> None:
# def debug(logmsg: str, section: Optional[str]=None) -> None:
#     def log_msg(self, logmsg: str) -> None:
#     def log_debug(self, logmsg: str) -> None:
# class LoggingMixin:
# 
# Path: irisett/stats.py
# def get_section(section: Optional[str]) -> Dict[str, float]:
# def set(var: str, value: float, section: Optional[str] = None) -> None:
# def inc(var: str, section: Optional[str] = None) -> None:
# def dec(var: str, section: Optional[str] = None) -> None:
# def get_stats() -> Dict[str, float]:
# 
# Path: irisett/webmgmt/errors.py
# class WebMgmtError(Exception):
# class InvalidData(WebMgmtError):
# class PermissionDenied(WebMgmtError):
# class NotFound(WebMgmtError):
# class MissingLogin(WebMgmtError):
# 
# Path: irisett/errors.py
# class IrisettError(Exception):
#     def __str__(self) -> str:
#         if len(self.args) == 1:
#             ret = self.args[0]
#         else:
#             ret = str(self.__class__.__name__)
#         return ret


# Path: irisett/webmgmt/middleware.py
from typing import Optional, Callable, Any
from aiohttp import web
from irisett import (
    log,
    stats,
)
from irisett.webmgmt import (
    errors,
)
from irisett.errors import IrisettError
import base64
import binascii

    async def middleware_handler(request: web.Request) -> web.Response:
        stats.inc('num_calls', 'WEBMGMT')
        log.msg('Received request: %s' % request, 'WEBMGMT')
        return await handler(request)

    return middleware_handler


async def basic_auth_middleware_factory(app: web.Application, handler: Any) -> Callable:
    """Authentication.

    Uses HTTP basic auth to check that requests are including the required
    username and password.
    """
    async def middleware_handler(request: web.Request) -> web.Response:
        ok = False
        auth_token = request.headers.get('Authorization')
        if auth_token and auth_token.startswith('Basic '):
            auth_token = auth_token[6:]
            try:
                auth_bytes = base64.b64decode(auth_token)  # type: Optional[bytes]
            except binascii.Error:
                auth_bytes = None
            if auth_bytes:
                auth_str = auth_bytes.decode('utf-8', errors='ignore')
                if ':' in auth_str:
                    username, password = auth_str.split(':', 1)
                    if username == app['username'] and password == app['password']:
                        ok = True
        if not ok:

            log.msg('Unauthorized request: %s' % request, 'WEBMGMT')