async def __call__(self, request: web.Request):
        auth = BasicAuth.decode(request.headers.get('Authorization'))
        if self.verify(auth.login, auth.password):
            json_data = await request.json()
            if not json_data:
                return web.Response(status=415)
            endpoint_config = self.__endpoint['config']
            if request.method.upper() not in [
                    method.upper() for method in endpoint_config['HTTPMethods']
            ]:
                return web.Response(status=405)
            try:
                log.info("CONVERTER CONFIG: %r", endpoint_config['converter'])
                converter = self.__endpoint['converter'](
                    endpoint_config['converter'])
                converted_data = converter.convert(
                    config=endpoint_config['converter'], data=json_data)
                self.send_to_storage(self.__name, converted_data)
                log.info("CONVERTED_DATA: %r", converted_data)
                return web.Response(status=200)
            except Exception as e:
                log.exception("Error while post to basic handler: %s", e)
                return web.Response(status=500)

        return web.Response(status=401)
Esempio n. 2
0
def _do_basic_auth_check(request):
    auth_header = request.headers.get(hdrs.AUTHORIZATION)
    if not auth_header:
        if "download_" in request.match_info.route.name:
            return Response(
                body=b"",
                status=401,
                reason="UNAUTHORIZED",
                headers={
                    hdrs.WWW_AUTHENTICATE: 'Basic realm=""',
                    hdrs.CONTENT_TYPE: "text/html; charset=utf-8",
                    hdrs.CONNECTION: "keep-alive",
                },
            )
        return

    try:
        auth = BasicAuth.decode(auth_header=auth_header)
    except ValueError:
        auth = None

    if not auth:
        return

    if auth.login is None or auth.password is None:
        return

    if (auth.login != request.app["username"]
            or auth.password != request.app["password"]):
        return

    return True
Esempio n. 3
0
async def statistic_receiver(request: Request):
    auth = request.headers.get("Authorization")

    if not auth:
        raise HTTPUnauthorized
    try:
        basic = BasicAuth.decode(auth)
    except ValueError:
        log.exception("Failed to parse basic auth")
        raise HTTPForbidden

    if request.app["password"] != basic.password:
        raise HTTPForbidden

    if request.app["login"] != basic.login:
        raise HTTPForbidden

    data = await request.read()

    bypass_headers = {
        header: request.headers.get(header)
        for header in BYPASS_HEADERS if header
    }
    request.app['queue'].append((data, bypass_headers))

    return Response(content_type="text/plain", status=HTTPStatus.ACCEPTED)
Esempio n. 4
0
    def _process_basic(self, request, addon):
        """Process login request with basic auth.

        Return a coroutine.
        """
        auth = BasicAuth.decode(request.headers[AUTHORIZATION])
        return self.sys_auth.check_login(addon, auth.login, auth.password)
Esempio n. 5
0
def _do_basic_auth_check(request: Request) -> Union[None, bool]:
    if "download_" not in request.match_info.route.name:
        return

    auth = None
    auth_header = request.headers.get(hdrs.AUTHORIZATION)
    if auth_header is not None:
        try:
            auth = BasicAuth.decode(auth_header=auth_header)
        except ValueError:
            pass

    if auth is None:
        try:
            auth = BasicAuth.from_url(request.url)
        except ValueError:
            pass

    if not auth:
        return Response(
            body=b"",
            status=401,
            reason="UNAUTHORIZED",
            headers={hdrs.WWW_AUTHENTICATE: 'Basic realm=""'},
        )

    if auth.login is None or auth.password is None:
        return

    if (auth.login != request.app["username"]
            or auth.password != request.app["password"]):
        return

    return True
Esempio n. 6
0
async def ldap_auth(request: web.Request) -> web.Response:
    ldap_uri = request.headers.get(LDAP_HEADERS.URI)
    ldap_user_dn_tpl = request.headers.get(LDAP_HEADERS.USER_DN_TEMPLATE)
    if not (ldap_uri and ldap_user_dn_tpl):
        logging.error("LDAP configuration headers missing.")
        return web.Response(status=400)

    auth_header = request.headers.get(hdrs.AUTHORIZATION)
    if not auth_header:
        logging.debug("Authorization header missing.")
        return challenge_response()
    auth = BasicAuth.decode(auth_header=auth_header, encoding="UTF-8")

    client = bonsai.LDAPClient(ldap_uri)
    client.set_credentials("SIMPLE",
                           user=ldap_user_dn_tpl.format(user=auth.login),
                           password=auth.password)
    try:
        async with client.connect(is_async=True) as conn:
            await conn.whoami()
            return web.Response(
                status=204, headers={"Cache-Control": "public, max-age=1800"})
    except bonsai.LDAPError as ex:
        logging.debug(repr(ex))
        return challenge_response()
Esempio n. 7
0
    async def _validate_auth(self, request):
        """Validate Basic-Auth in a request."""
        basic_auth = request.headers.get('Authorization')
        if not basic_auth:
            return False

        auth = BasicAuth.decode(basic_auth)
        return await self.is_valid_auth(auth.login, auth.password)
Esempio n. 8
0
    async def basic_auth(request, handler):
        basic_auth = request.headers.get('Authorization')
        if basic_auth:
            auth = BasicAuth.decode(basic_auth)
            if handler.auth_role in check_passwd(pwd_db, auth.login, auth.password):
                return await handler(request)

        headers = {'WWW-Authenticate': 'Basic realm="XXX"'}
        return web.HTTPUnauthorized(headers=headers)
 def parse_auth_header(self, request):
     auth_header = request.headers.get(hdrs.AUTHORIZATION)
     if not auth_header:
         return None
     try:
         auth = BasicAuth.decode(auth_header=auth_header)
     except ValueError:
         auth = None
     return auth
Esempio n. 10
0
def parse_auth_header(request):
    auth_header = request.headers.get("Authorization")
    if not auth_header:
        return None
    try:
        auth = BasicAuth.decode(auth_header)
    except ValueError:
        auth = None
    return auth
def check_access(auth_dict: dict, header_value: str) -> bool:

    auth = BasicAuth.decode(header_value)

    if auth.login not in auth_dict:
        return False
    if auth.password != auth_dict.get(auth.login):
        return False

    return True
Esempio n. 12
0
    async def basic_auth(request, handler):
        if request.path == '/ping':
            return await handler(request)

        auth_info = request.headers.get('Authorization')
        if auth_info:
            auth = BasicAuth.decode(auth_info)
            if auth.login != USER_NAME or not check_key(key, auth.password):
                return await handler(request)

        headers = {'WWW-Authenticate': 'Basic realm="XXX"'}
        return web.HTTPUnauthorized(headers=headers)
Esempio n. 13
0
async def get_basic_protected_str(request: web.Request):
    logger.info(auth=request.headers.get("Authorization"))
    auth_info = request.headers.get("authorization", "")
    if not auth_info:
        raise web.HTTPForbidden()
    try:
        auth = BasicAuth.decode(auth_info)
    except ValueError:
        logger.exception(f"Failed to decode auth data {auth_info}")
        raise web.HTTPBadRequest()
    if auth.login != "emu" and auth.password != "wars":
        raise web.HTTPForbidden()
    return web.Response(text="you have made it through")
Esempio n. 14
0
 async def authenticate(self, request):
     session = await get_session(request)
     auth_request = request.headers.get('AUTHORIZATION', None)
     logger.debug('authentication: {}'.format(auth_request))
     if auth_request is not None:
         try:
             creds = BasicAuth.decode(auth_request)
             if creds.password == self.credentials.get(creds.login, ''):
                 logger.debug('Authenticated user: {}'.format(creds.login))
                 session['authenticated'] = 'True:{}'.format(creds.login)
                 return web.Response(body='logged in'.encode('utf-8'))
         except ValueError as e:
             pass
     return web.Response(body='login error'.encode('utf-8'))
Esempio n. 15
0
async def auth_check(request, handler):
    if 'ADMIN_USER' not in os.environ or 'ADMIN_PASSWORD' not in os.environ:
        raise Exception('Admin login credentials not set')

    if 'Authorization' not in request.headers:
        raise HTTPUnauthorized()

    auth = BasicAuth.decode(request.headers['Authorization'])
    if (auth.login != os.environ['ADMIN_USER'] or
            auth.password != os.environ['ADMIN_PASSWORD']):
        raise HTTPUnauthorized()

    response = await handler(request)
    return response
Esempio n. 16
0
async def is_worker(db, request: web.Request) -> Optional[str]:
    auth_header = request.headers.get(aiohttp.hdrs.AUTHORIZATION)
    if not auth_header:
        return None
    auth = BasicAuth.decode(auth_header=auth_header)
    async with db.acquire() as conn:
        val = await conn.fetchval(
            "select 1 from worker where name = $1 "
            "AND password = crypt($2, password)",
            auth.login,
            auth.password,
        )
        if val:
            return auth.login
    return None
async def basic_auth(request, handler):
    auth_header = request.headers.get('Authorization')
    authorized = False
    if auth_header:
        auth = BasicAuth.decode(auth_header)
        authorized = \
            auth.login == os.getenv('VOLGACTF_FINAL_AUTH_CHECKER_USERNAME') and\
            auth.password == os.getenv('VOLGACTF_FINAL_AUTH_CHECKER_PASSWORD')

    if not authorized:
        headers = {
            'WWW-Authenticate': 'Basic realm="{0}"'.format('Protected area')
        }
        return web.HTTPUnauthorized(headers=headers)

    return await handler(request)
Esempio n. 18
0
async def create_advertisement(request: web.Request):
    auth_adv = BasicAuth.decode(auth_header=request.headers[hdrs.AUTHORIZATION])
    db_session = DBSession()
    new_advertisement = await request.json()
    title = new_advertisement["title"]
    description = new_advertisement["description"]
    date = datetime.datetime.now()
    creator = auth_adv.login
    new_advertisement = Advertisement(title=title, description=description, date=date, creator=creator)
    try:
        async with aiohttp.ClientSession():
            db_session.add(new_advertisement)
            db_session.commit()
    except IntegrityError:
        return web.json_response({"error": 'Ошибка при сохранении'})
    return web.Response(text='Объявление успешно добавлено')
Esempio n. 19
0
def get_security_data(request: web.Request, item: str, *,
                      oas: DictStrAny) -> Optional[Union[str, BasicAuth]]:
    """Get security data from request.

    Currently supported getting API Key & HTTP security data. OAuth & OpenID
    data not supported yet.
    """
    schema = oas["components"]["securitySchemes"].get(item)
    if not schema:
        return None

    security_type = schema["type"]
    if security_type == OPENAPI_SECURITY_API_KEY:
        location = schema["in"]
        name = schema["name"]

        # API Key from query string
        if location == "query":
            return request.rel_url.query.get(name)
        # API Key from headers
        if location == "header":
            return request.headers.get(name)
        # API Key from cookies
        if location == "cookie":
            return request.cookies.get(name)
    elif security_type == OPENAPI_SECURITY_HTTP:
        authorization_header = request.headers.get(AUTHORIZATION_HEADER)
        scheme = schema["scheme"]

        # Basic HTTP authentication
        if scheme == "basic":
            try:
                return BasicAuth.decode(auth_header=authorization_header)
            except ValueError:
                return None

        # Bearer authorization (JWT)
        if scheme == "bearer":
            stop = len(BEARER) + 1
            if (not authorization_header
                    or authorization_header[:stop].lower() != "bearer "):
                return None

            return authorization_header[stop:]

    return None
Esempio n. 20
0
async def update_advertisement(request: web.Request):
    auth_adv = BasicAuth.decode(auth_header=request.headers[hdrs.AUTHORIZATION])
    db_session = DBSession()
    updates = await request.json()
    adv_id = request.match_info['adv_id']
    adv_updates = db_session.query(Advertisement).filter(Advertisement.id == adv_id).first()
    if updates.get('title'):
        adv_updates.title = updates['title']
    if updates.get('description'):
        adv_updates.description = updates['description']
    adv_updates.date = datetime.datetime.now()
    async with aiohttp.ClientSession():
        if adv_updates.creator == auth_adv.login:
            db_session.commit()
            return web.Response(text=f'Объявление №{adv_id} отредактировано')
        else:
            raise web.HTTPNotFound(text=f"Редактировать объявление может только его автор")
Esempio n. 21
0
 async def handler(self, request):
     auth = BasicAuth.decode(request.headers.get('Authorization'))
     if auth is not None:
         try:
             user = self.users[auth.login]
         except KeyError:
             return web.Response(status=403)
         json = await request.json()
         if user.check_password(auth.password) and user.can_call(
                 json['method']):
             async with self.session.post(self.wallet_url,
                                          json=json) as wallet_resp:
                 return web.Response(status=wallet_resp.status,
                                     body=await wallet_resp.text())
         else:
             return web.Response(status=403)
     else:
         return web.Response(status=401)
Esempio n. 22
0
async def game_join(request):
    session = ServerSession.get_instance()
    auth_obj = BasicAuth.decode(request.headers['Authorization'])
    current_user = await session.validate_user_credentials(auth_obj.login, auth_obj.password)
    game_idn = request.match_info['game_idn']
    game = await session.get_game(game_idn)

    ws = web.WebSocketResponse()
    await ws.prepare(request)
    me = NetworkPlayer(ws, current_user['username'])

    if game.player1 is None:
        me.player_id = 1
        init_game(game)
        game.player1 = me
        my_player = game.game_player1
        await game.event.wait()
        await me.send_response(game.board.get_response())
    else:
        me.player_id = 2
        game.player2 = me
        my_player = game.game_player2
        game.event.set()
        await me.send_response(game.board.get_response())

    while True:
        try:
            msg = await me.receive()
            if msg.type == aiohttp.WSMsgType.text:
                data = json.loads(msg.data)
                x = int(data['x'])
                y = int(data['y'])
                response = game.board.make_move(my_player, x, y)
                if isinstance(response, GameException):
                    await me.send_exception(response.exception)
                else:
                    await game.player1.send_response(response)
                    await game.player2.send_response(response)
            else:
                break
        except CancelledError:
            break
    return ws
Esempio n. 23
0
async def advertisement_delete(request: web.Request):
    auth_adv = BasicAuth.decode(auth_header=request.headers[hdrs.AUTHORIZATION])
    db_session = DBSession()
    async with aiohttp.ClientSession():
        adv_id = request.match_info['adv_id']
        if adv_id.isdigit():
            adv_id = int(adv_id)
        else:
            raise web.HTTPBadRequest(text='Неверный запрос')
        adv_page = db_session.query(Advertisement).filter(Advertisement.id == adv_id).first()
        if adv_page:
            if adv_page.creator == auth_adv.login:
                db_session.delete(adv_page)
                db_session.commit()
                return web.Response(text=f'Объявление №{adv_id} удалено')
            else:
                raise web.HTTPNotFound(text=f"Удалять объявление может только его автор")
        else:
            raise web.HTTPNotFound(text=f"Объявление №{adv_id} отсутствует в базе")
Esempio n. 24
0
async def handler(request):
    try:
        typ = "text/html"
        data = ""
        if not request.method == "GET":
            return error(501, "not a get request")
        path = make_path(
            request.path)  # all paths starts with / and not having \
        realm = await check_protection(path)
        #print(path)
        if realm:
            #print("check if has auth head")
            if "Authorization" in request.headers:
                #print(request.headers["Authorization"])
                creds_in = BasicAuth.decode(
                    request.headers["Authorization"]
                )  # TODO: check if protocol is basic
                creds_needed = await find_credentials(realm)
                if not creds_in.login == creds_needed[
                        0] or not creds_in.password == creds_needed[1]:
                    return error(403, "username or password incorrect")
            else:
                return error(
                    401, "need credential of " + realm, {
                        "WWW-Authenticate":
                        'Basic realm="need credentials of ' + realm + '"'
                    })
        if os.path.isdir("." + path):
            data = handle_dir(path)
        elif os.path.isfile("." + path):
            typ, data = await handle_file("." + request.path, request.query
                                          )  # TODO: catch exception here
        else:
            return error(404, "page not found")
        response = web.Response(body=data,
                                status=200,
                                headers=std_headers(len(data), typ))
        return response
    except Exception as e:
        #print(e)
        return error(500, "server exception")
Esempio n. 25
0
async def rest_auth_middleware(request, handler):
    if request.method == 'POST':
        try:
            data = await request.json()
            request['data'] = data
        except:
            raise authentication_failed_response()
    elif request.method == 'GET':
        auth_header = request.headers.get('AUTHORIZATION')
        if auth_header is None:
            raise authentication_failed_response()
        base_auth = BasicAuth.decode(auth_header)
        data = dict(login=base_auth.login, password=base_auth.password)
    else:
        raise web.HTTPNotImplemented

    try:
        user = await auth(data['login'], data.pop('password', ''))
    except:
        raise authentication_failed_response()

    request['user'] = user
    if not user.is_authenticated:
        raise authentication_failed_response()

    resource = request.match_info.route.resource
    if resource:
        accepted = await _check_permission(request)
        if not accepted:
            raise web.HTTPForbidden(
                content_type='application/json',
                text=json.dumps({
                    'errors': [
                        'У Вас нет прав доступа к ресурсу, обратитесь к администратору',
                    ]
                }))

    return await handler(request)
Esempio n. 26
0
async def login(request):
    auth_obj = BasicAuth.decode(request.headers['Authorization'])
    await login_user(auth_obj.login, auth_obj.password)
    token = await ServerSession.get_instance().add_user_session(auth_obj.login)
    return Response(text=" { \"token\": \"" + token + "\" }")