コード例 #1
0
async def add_activity(request):
    data = await request.json()

    token = request.cookies.get('token')

    if not is_valid_token(token, data['user_id']):
        return web.HTTPUnauthorized()

    start_time = datetime.fromtimestamp(int(data['start_time']) / 1000,
                                        tz=local_tz).astimezone(
                                            tz.UTC).replace(tzinfo=None)
    end_time = datetime.fromtimestamp(int(data['end_time']) / 1000,
                                      tz=local_tz).astimezone(
                                          tz.UTC).replace(tzinfo=None)

    activity = await calendar.create_activity(
        user_id=int(data['user_id']),
        chat_id=int(data['chat_id']),
        start_time=start_time,
        duration=end_time - start_time,
        activity_type_id=data['activity_type_id'],
        subactivity_id=data['subactivity_id'])

    return web.json_response({'activity_id': activity.id})
コード例 #2
0
ファイル: handlers.py プロジェクト: CSCfi/metadata-submitter
    async def patch_user(self, req: Request) -> Response:
        """Update user object with a specific user ID.

        :param req: PATCH request
        :raises: HTTPUnauthorized if not current user
        :returns: JSON response containing user ID for updated user object
        """
        user_id = req.match_info["userId"]
        if user_id != "current":
            LOG.info(f"User ID {user_id} patch was requested")
            raise web.HTTPUnauthorized(reason="Only current user operations are allowed")
        db_client = req.app["db_client"]

        patch_ops = await self._get_data(req)
        self._check_patch_user(patch_ops)

        operator = UserOperator(db_client)

        current_user = get_session(req)["user_info"]
        user = await operator.update_user(current_user, patch_ops if isinstance(patch_ops, list) else [patch_ops])

        body = json.dumps({"userId": user})
        LOG.info(f"PATCH user with ID {user} was successful.")
        return web.Response(body=body, status=200, content_type="application/json")
コード例 #3
0
async def status_handler(request):
    auth = "PASSWORD"
    if str(request.headers['auth']) == auth:
        uname = platform.uname()
        os = f"{uname.system}"
        node = f"{uname.node}"
        release = f"{uname.release}"
        ver = f"{uname.version}"
        arch = f"{uname.machine}"
        boot_time_timestamp = psutil.boot_time()
        bt = datetime.fromtimestamp(boot_time_timestamp)
        start = f"{bt.year}/{bt.month}/{bt.day} {bt.hour}:{bt.minute}:{bt.second}"
        system = {
            "os": os,
            "node": node,
            "release": release,
            "ver": ver,
            "arch": arch,
            "start": start
        }
        cpufreq = psutil.cpu_freq()
        phys = str(psutil.cpu_count(logical=False))
        ctotal = str(psutil.cpu_count(logical=True))
        curfreq = f"{round(cpufreq.current,2)}Mhz"
        use = f"{psutil.cpu_percent()}%"
        cpu = {
            "curfreq": curfreq,
            "phys": phys,
            "total": ctotal,
            "curfreq": curfreq,
            "use": use
        }
        svmem = psutil.virtual_memory()
        mtotal = f"{get_size(svmem.total)}"
        avaliable = f"{get_size(svmem.available)}"
        used = f"{get_size(svmem.used)}"
        percnt = f"{svmem.percent}%"
        swap = psutil.swap_memory()
        swp = {
            'total': f"{get_size(swap.total)}",
            'free': f"{get_size(swap.free)}",
            'used': f"{get_size(swap.used)}",
            'percnt': f"{swap.percent}%"
        }
        mem = {
            'total': mtotal,
            'avaliable': avaliable,
            'used': used,
            'percnt': percnt,
            'swap': swp
        }
        if_addrs = psutil.net_if_addrs()
        for interface_name, interface_addresses in if_addrs.items():
            for address in interface_addresses:
                if interface_name == "eth0":
                    if str(address.family) == 'AddressFamily.AF_INET':
                        global name, ip, mask, bip
                        name = f"{interface_name}"
                        ip = f"{address.address}"
                        mask = f"{address.netmask}"
                        bip = f"{address.broadcast}"
        net = {'name': name, 'ip': ip, 'mask': mask, 'bip': bip}
        net_io = psutil.net_io_counters()
        bsent = f"{get_size(net_io.bytes_sent)}"
        brcved = f"{get_size(net_io.bytes_recv)}"
        io = {'sent': bsent, 'rcved': brcved}
        inf = {'sys': system, 'cpu': cpu, 'mem': mem, 'net': net, 'io': io}
        py = {'ver': str(sys.version), 'verinf': str(sys.version_info)}
        otherver = {
            'nginx': await nginx(),
            'apt': await apt(),
            'nano': await nano()
        }
        dat = {'sys': inf, 'py': py, 'other-versions': otherver}
        return web.json_response(dat)
    if str(request.headers['auth']) != auth:
        raise web.HTTPUnauthorized()
コード例 #4
0
def check_admin(request: web.Request) -> None:
    if not is_admin(request):
        raise web.HTTPUnauthorized()
コード例 #5
0
    async def convert(self, request: web.Request):
        try:
            snowflake = int(request.match_info['snowflake'])
        except:
            raise web.HTTPBadRequest(reason="Malformed request")

        if request.method == "GET":
            logging.info(f"Received request to view info on bot {snowflake}")
            snowflake = int(snowflake)
            resp = dict((await self.get_botdata(snowflake))[0])
            return web.json_response(resp)
        else:
            try:
                if "Authorization" not in request.headers:
                    raise web.HTTPUnauthorized(
                        reason="Failed to provide token!"
                    )  # Token was omitted from the headers

                token = request.headers["Authorization"]  # The user token
                snowflake = int(snowflake)  # The bot snowflake
                req = f"""SELECT * FROM userdata WHERE token = '{token.replace("'", "''")}';"""
                async with self.pool.acquire() as connection:
                    response = await connection.fetch(
                        req)  # Get bots and webhook / gather type
                if response:
                    bots, type = response[0]["bots"], response[0]["type"]
                    if snowflake not in bots:  # That bot is not associated with that token
                        raise web.HTTPUnauthorized(
                            reason="That snowflake is not valid!")

                    formdata = await request.post()

                    async with self.pool.acquire() as connection:
                        name = await connection.fetchval(
                            f"""SELECT name FROM botdata WHERE id = {snowflake};"""
                        )  # Get the bot's name
                        url = await connection.fetchval(
                            f"""SELECT url FROM botdata WHERE name = '{formdata["to_bot"].replace("'", "''")}';"""
                        )  # Get the URL of the bot we're sending to
                    if url is None:  # That bot is not in our database!
                        raise web.HTTPBadRequest(
                            reason="That is an invalid bot!")

                    payload = {
                        "from_bot": name,
                        "amount": formdata["amount"],
                        "to_bot": formdata["to_bot"],
                        "server_id": formdata["server_id"]
                    }
                    dumped = json.dumps(payload, indent=4)

                    logging.info(
                        f"Received request to convert {formdata['amount']} from {name} "
                        f"to {formdata['to_bot']} on server {formdata['server_id']}"
                    )
                    if type is 0:  # If using webhooks
                        try:
                            await self.session.post(
                                url, json=dumped
                            )  # Post the payload to the other bot's URL
                        except Exception as e:
                            raise web.HTTPInternalServerError(
                                reason=
                                "An error occurred forwarding to the bot!")

                    return web.json_response(payload)
                else:  # If we don't get a response from the given token, the token doesn't exist
                    raise web.HTTPUnauthorized(reason="Invalid token!")
            except web.HTTPException:
                raise
            except:  # Generic error catching, always gives 400 cause how could it be _my_ issue?
                return web.HTTPBadRequest(reason="An error occurred!")
コード例 #6
0
 async def wrapped(request, userdata, *args, **kwargs):
     if userdata['is_developer'] == 1:
         return await fun(request, userdata, *args, **kwargs)
     raise web.HTTPUnauthorized()
コード例 #7
0
    async def get(self):
        # Если мы сюда попали, значит проверка json пройдена:
        # проверка авторизации
        auth = self.request.headers.get('Authorization')
        if auth is None:
            raise web.HTTPUnauthorized()  # not authorization

        # проверка пользователя
        # подготовка к декодированию:
        auth_for_64decode = auth.split(' ')
        pre_credential = (base64.b64decode(
            auth_for_64decode[1])).decode('utf-8')

        credential = pre_credential.split(':')
        username = credential[0]  # логин
        passw = credential[1]  # пароль

        # проверка credential
        pg_pool = self.request.app['pg_pool']
        # подключаемя к БД и забираем инфу
        async with pg_pool.acquire() as conn:
            async with conn.cursor() as cursor:
                await cursor.execute(
                    f'SELECT * from public.user where username like \'{username}\''
                )
                result = await cursor.fetchone()
                # если есть такой username?
                if result:
                    # проверка пароля
                    if check_password(result[3], passw):
                        try:
                            # Внимание! Двойные кавычки здесь не пройдут!
                            if result[4] == True:
                                #это админ
                                sql_expr = 'SELECT * FROM public.advert'
                            else:
                                sql_expr = f'SELECT * FROM public.advert JOIN public.user ON public.user.id=public.advert.user_id WHERE user_id={result[0]}'
                            await cursor.execute(sql_expr)
                            result = await cursor.fetchall()

                        except my_exception.DBSelectError:
                            if config.DEBUG:
                                print('Ошибка cursor.execute(query)')
                            raise web.HTTPBadRequest
                        # psycopg2.ProgrammingError: commit cannot be used in asynchronous mode
                        # conn.commit()
                        response = []
                        #если был запрос конкретного объявления
                        advert_id = self.request.match_info.get(
                            'advs_id')  # получаем номер объявления
                        if advert_id != None:
                            advert_id = int(advert_id)

                        for res in result:
                            item = {}
                            item['title'] = res[1]
                            item['body'] = res[2]
                            item['user_id'] = res[4]
                            if advert_id:
                                if res[0] == advert_id:
                                    response.append(item)
                            else:
                                response.append(item)
                        return web.json_response(response)

                    else:
                        print('Неверный пароль!')
                        raise web.HTTPUnauthorized()

                else:  # не нашли такого пользователя
                    print('Нет такого пользователя!')
                    raise web.HTTPNotFound()
コード例 #8
0
    async def post(self):
        # res = json.dumps({"answer": "Попытка создать пользователя!"}, ensure_ascii=False)
        # return web.json_response(res, headers={"Content-Language":"ru-RU, en", "Accept-Language":"ru-RU, en"})

        #Если мы сюда попали, значит проверка json пройдена:
        # проверка авторизации
        auth = self.request.headers.get('Authorization')
        if auth is None:
            raise web.HTTPUnauthorized()  # not authorization

        # проверка роли и пароля администратора
        # подготовка к декодированию:
        auth_for_64decode = auth.split(' ')
        pre_credential = (base64.b64decode(
            auth_for_64decode[1])).decode('utf-8')

        credential = pre_credential.split(':')
        username = credential[0]  # логин
        passw = credential[1]  # пароль

        # проверка credential
        pg_pool = self.request.app['pg_pool']
        # подключаемя к БД и забираем инфу
        async with pg_pool.acquire() as conn:
            async with conn.cursor() as cursor:
                await cursor.execute(
                    f'SELECT * from public.user where username like \'{username}\''
                )
                result = await cursor.fetchone()
                # если есть такой username?
                if result:
                    # если username является admin
                    if result[4] == True:
                        print('Admin!!')
                        # проверка пароля
                        if check_password(result[3], passw):
                            # сохраняем запись о пользователе в БД
                            json_req = await self.request.json()
                            username = json_req.get('username')
                            password = set_password(json_req.get('password'))
                            email = json_req.get('email')

                            try:
                                #Внимание! Двойные кавычки здесь не пройдут!
                                sql_expr = "INSERT INTO public.user (username, email, password_hash) VALUES (\'%s\',\'%s\',\'%s\')" % (
                                    username, email, password)
                                await cursor.execute(sql_expr)
                                #result=await cursor.fetchall()
                            except my_exception.DBInsertError:
                                if config.DEBUG:
                                    print('Ошибка cursor.execute(query)')
                                raise web.HTTPBadRequest
                            else:
                                #psycopg2.ProgrammingError: commit cannot be used in asynchronous mode
                                await conn.commit()
                                res = []
                                item = {}
                                item['user'] = username
                                item['email'] = email
                                res.append(item)
                                return web.json_response(res)

                        else:
                            print('Неверный пароль Admin!')
                            raise web.HTTPUnauthorized()
                    else:
                        print('Пользователь не является Admin!')
                        raise web.HTTPUnauthorized()

                else:  # не нашли такого пользователя
                    raise web.HTTPNotFound()
コード例 #9
0
async def inner_auth(conn: aiopg.sa.connection.SAConnection,
                     request: 'Application.Request'):
    if not (user := await user_by_srv_token(conn, fetch_token(request))):
        raise web.HTTPUnauthorized() from None
コード例 #10
0
async def auth(request: 'Application.Request', project_id: Optional[str]):
    if not (srv_token := fetch_token(request)):
        logging.info("AUTHORIZATION header is missed")
        raise web.HTTPUnauthorized() from None
コード例 #11
0
    if not (srv_token := fetch_token(request)):
        logging.info("AUTHORIZATION header is missed")
        raise web.HTTPUnauthorized() from None

    async with request.app.db.acquire() as conn:
        if project_id:
            print("get_or_create_cloud_project_token_by_srv_token")
            cloud_token = await get_or_create_cloud_project_token_by_srv_token(
                conn, srv_token, project_id)
        else:
            print("get_or_update_cloud_domain_token_by_srv_token")
            cloud_token = await get_or_update_cloud_domain_token_by_srv_token(
                conn, srv_token)

    if not cloud_token:
        raise web.HTTPUnauthorized() from None
    return cloud_token


async def projects_handler(request: 'Application.Request'):
    cloud_token = await auth(request, None)
    print(cloud_token)

    headers = {"X-Auth-Token": cloud_token}

    async with aiohttp.ClientSession() as session:
        async with session.get(PROJECT_URL, headers=headers) as resp:
            resp = await resp.json()

    def inner():
        for proj in resp["projects"][1:]:
コード例 #12
0
ファイル: app.py プロジェクト: takeaway/python-sensor
def four_hundred_one(request):
    raise web.HTTPUnauthorized(reason="I must simulate errors.",
                               text="Simulated server error.")
コード例 #13
0
def route(request):

    session = yield from get_session(request)
    parameters = request.rel_url.query

    if 'uid' not in session:
        return web.HTTPUnauthorized()
    else:
        uid = session['uid']

    try:
        mid = int(parameters['mid'])
    except:
        return web.HTTPBadRequest()

    with (yield from request.app['pool']) as connect:

        cursor= yield from connect.cursor()

        yield from cursor.execute('''
            select
            overview.id,
            overview.romaji,
            overview.name,
            overview.affiliation,
            overview.introduction,
            overview.follows,
            overview.subscribes,
            follow.uid,
            subscription.uid
            from (
                select
                member.id,
                member.romaji,
                member.name,
                member.affiliation,
                member.introduction,
                member.follows,
                member.subscribes
                from member
                where member.id = %s
            ) overview
            left join follow on follow.uid = %s and follow.mid = overview.id
            left join subscription on subscription.uid = %s and subscription.mid = overview.id
        ''',(mid,uid,uid))

        data = yield from cursor.fetchone()
        yield from cursor.close()
        connect.close()

        if not data:
            return web.HTTPNotFound()

        json_back = {
            "mid": str(data[0]).zfill(4),
            "avatar": "/avatar/{}.jpg".format(data[1]),
            "name": data[2],
            "romaji": data[1],
            "affiliation": data[3],
            "introduction": data[4],
            "follows": data[5],
            "subscribes": data[6],
            "followed": True if data[7] else False,
            "subscribed": True if data[8] else False
        }

        return web.Response(text=tool.jsonify(json_back),content_type="application/json",charset="utf-8")
コード例 #14
0
    async def post(self):
        request = self.request
        user = await check_user_right(request)
        if not user:
            return web.HTTPUnauthorized()
        try:
            user_input = await request.json()
        except json.decoder.JSONDecodeError:
            return web.HTTPBadRequest()
        v = EpInputValidator(user_input)
        if not v.is_valid():
            return web.HTTPBadRequest()
        user_input = v.validated_data
        user_input['user_id'] = request.session.user_id
        user_input['type'] = get_type(user_input['link'])
        input_type = get_type(user_input['link'])
        if input_type == 'bilibili':
            if '/ss' in user_input['link']:
                return web.json_response({
                    'status':
                    'error',
                    'message':
                    'B站的视频应该是'
                    'https://www.bilibili.com/bangumi/play/ep(\\d), '
                    '/ss(\\d)结尾的那个地址不能精确定位到每集'
                })
        parser = server.website.get_website_parser(input_type)
        data = {
            'type': input_type,
            'user': request.session.user_id,
            'bgm_ep_id': user_input['ep_id'],
            'link': user_input['link'],
            'ep_id': parser.link_to_ep_id(user_input['link']),
        }

        await request.app.db.get_collection(
            mongo_collection_name.EP_INPUT_LOG).update_one(
                {'_id': user_input['ep_id']},
                {
                    '$push': {
                        str(request.session.user_id): {
                            'link': user_input['link'],
                            'ep_id': parser.link_to_ep_id(user_input['link']),
                        }
                    }
                },
                upsert=True,
            )
        print('after put object')
        # current_episode = await request.app.db
        #     .get_collection(mongo_collection_name.FINAL_BGM_EP_MAP)
        #     .find_one({'type': input_type, 'ep_id': user_input['ep_id']})
        if await is_authorized_user(request):
            await request.app.db.get_collection(
                mongo_collection_name.FINAL_BGM_EP_MAP).update_one(
                    {
                        'type': input_type,
                        'bgm_ep_id': user_input['ep_id']
                    },
                    {'$set': data},
                    upsert=True,
                )
        return web.json_response({'status': 'success'})
コード例 #15
0
 async def authentication_required_middleware(request, handler):
     if is_handler_authentication_exempt(handler):
         return await handler(request)
     if not await auth_svc.is_request_authenticated(request):
         raise web.HTTPUnauthorized()
     return await handler(request)
コード例 #16
0
ファイル: atgu.py プロジェクト: saponas/hail
async def post_edit_resource(request, userdata):  # pylint: disable=unused-argument
    db = request.app['db']
    storage_client = request.app['storage_client']
    id = int(request.match_info['id'])
    old_record = await db.select_and_fetchone(
        '''
SELECT attachments FROM atgu_resources
WHERE id = %s;
''',
        (id),
    )
    if not old_record:
        raise web.HTTPNotFound()

    old_attachments = json.loads(old_record['attachments'])

    checked_csrf = False
    attachments = {}
    post = {}
    reader = aiohttp.MultipartReader(request.headers, request.content)
    while True:
        part = await reader.next()  # pylint: disable=not-callable
        if not part:
            break
        if part.name == '_csrf':
            # check csrf token
            token1 = request.cookies.get('_csrf')
            token2 = await part.text()
            if token1 is None or token2 is None or token1 != token2:
                log.info('request made with invalid csrf tokens')
                raise web.HTTPUnauthorized()
            checked_csrf = True
        elif part.name == 'attachment':
            if not checked_csrf:
                raise web.HTTPUnauthorized()
            attachment_id = await part.text()
            assert attachment_id in old_attachments
            attachments[attachment_id] = old_attachments[attachment_id]
        elif part.name == 'file':
            filename = part.filename
            if not filename:
                continue
            attachment_id = secret_alnum_string()
            async with await storage_client.insert_object(
                    BUCKET, f'atgu/attachments/{attachment_id}') as f:
                while True:
                    chunk = await part.read_chunk()
                    if not chunk:
                        break
                    await f.write(chunk)
            attachments[attachment_id] = filename
        else:
            post[part.name] = await part.text()

    if not checked_csrf:
        raise web.HTTPUnauthorized()

    now = time_msecs()
    await db.execute_update(
        '''
UPDATE atgu_resources SET
title = %s,
description = %s,
contents = %s,
tags = %s,
attachments = %s,
time_updated = %s
WHERE id = %s
''',
        (post['title'], post['description'], post['contents'], post['tags'],
         json.dumps(attachments), now, id),
    )

    return web.HTTPFound(deploy_config.external_url('atgu',
                                                    f'/resources/{id}'))
コード例 #17
0
ファイル: notebook.py プロジェクト: MariusDanner/hail
 async def wrapped(request, userdata, *args, **kwargs):
     if not userdata:
         if redirect:
             return web.HTTPFound(deploy_config.external_url('workshop', '/login'))
         raise web.HTTPUnauthorized()
     return await fun(request, userdata, *args, **kwargs)
コード例 #18
0
 async def raise_error(self, request):
     raise web.HTTPUnauthorized(
         headers={
             hdrs.WWW_AUTHENTICATE: 'Basic realm={}'.format(self._realm)
         },
     )
コード例 #19
0
    async def post(self):

        # Если мы сюда попали, значит проверка json пройдена:
        # проверка авторизации
        auth = self.request.headers.get('Authorization')
        if auth is None:
            raise web.HTTPUnauthorized()  # not authorization

        # проверка пользователя
        # подготовка к декодированию:
        auth_for_64decode = auth.split(' ')
        pre_credential = (base64.b64decode(
            auth_for_64decode[1])).decode('utf-8')

        credential = pre_credential.split(':')
        username = credential[0]  # логин
        passw = credential[1]  # пароль

        # проверка credential
        pg_pool = self.request.app['pg_pool']
        # подключаемя к БД и забираем инфу
        async with pg_pool.acquire() as conn:
            async with conn.cursor() as cursor:
                await cursor.execute(
                    f'SELECT * from public.user where username like \'{username}\''
                )
                result = await cursor.fetchone()
                # если есть такой username?
                if result:
                    # проверка пароля
                    if check_password(result[3], passw):
                        # сохраняем объявление в БД
                        json_req = await self.request.json()
                        title = json_req.get('title')
                        body = json_req.get('body')
                        user_id = result[0]

                        try:
                            # Внимание! Двойные кавычки здесь не пройдут!
                            sql_expr = f'INSERT INTO public.advert (title, body, user_id) VALUES (\'{title}\',\'{body}\',\'{user_id}\') RETURNING id'
                            await cursor.execute(sql_expr)
                            # здесь нужно создать селект-запрос сразу после INSERT
                        except my_exception.DBInsertError:
                            if config.DEBUG:
                                print('Ошибка cursor.execute(query)')
                            raise web.HTTPBadRequest

                        # psycopg2.ProgrammingError: commit cannot be used in asynchronous mode
                        #conn.commit()
                        res = []
                        item = {}
                        item['title'] = title
                        item['body'] = body
                        item['user_id'] = user_id
                        res.append(item)
                        return web.json_response(res)

                    else:
                        print('Неверный пароль!')
                        raise web.HTTPUnauthorized()

                else:  # не нашли такого пользователя
                    print('Нет такого пользователя!')
                    raise web.HTTPNotFound()
コード例 #20
0
async def login(request):
    form = await request.post()
    email = form.get('email')
    password = form.get('password')

    # TODO: ensure right key in application's config?
    db_engine = request.app['db_engine']
    if await check_credentials(db_engine, email, password):
        # FIXME: build proper token and send back!
        response = web.json_response({
            'token': "eeeaee5e-9b6e-475b-abeb-66a000be8d03";, #g.current_user.generate_auth_token(expiration=3600), 
            'expiration': 3600})
        await remember(request, response, email)
        return response

    return web.HTTPUnauthorized(
        body=b'Invalid email/password combination')


@login_required
async def logout(request):
    response = web.Response(body=b'You have been logged out')
    await forget(request, response)
    return response


@has_permission("tester")
async def ping(request):
    """
      ---
      description: This end-point allow to test that service is up.
      tags:
コード例 #21
0
    async def put(self):
        # Если мы сюда попали, значит проверка json пройдена:
        # проверка авторизации
        auth = self.request.headers.get('Authorization')
        if auth is None:
            raise web.HTTPUnauthorized()  # not authorization

        # проверка пользователя
        # подготовка к декодированию:
        auth_for_64decode = auth.split(' ')
        pre_credential = (base64.b64decode(
            auth_for_64decode[1])).decode('utf-8')

        credential = pre_credential.split(':')
        username = credential[0]  # логин
        passw = credential[1]  # пароль

        # проверка credential
        pg_pool = self.request.app['pg_pool']
        # подключаемя к БД и забираем инфу
        async with pg_pool.acquire() as conn:
            async with conn.cursor() as cursor:
                await cursor.execute(
                    f'SELECT * from public.user where username like \'{username}\''
                )
                result = await cursor.fetchone()
                # если есть такой username?
                if result:
                    # проверка пароля
                    if check_password(result[3], passw):
                        # есть ли объявление таким id?
                        advert_id = self.request.match_info.get(
                            'advs_id')  # получаем номер объявления
                        if advert_id == None:
                            raise web.HTTPNotFound()
                        else:
                            advert_id = int(advert_id)

                        await cursor.execute(
                            f'SELECT id, user_id from public.advert where public.advert.id={advert_id}'
                        )
                        result_ad = await cursor.fetchone()
                        if result_ad == None:
                            raise web.HTTPNotFound()

                        # username только свои объявления обновляет. Admin Может все!)
                        if (result[4] == True) or (result[0] == result_ad[1]):
                            try:
                                # сохраняем обновление объявления в БД
                                json_req = await self.request.json()
                                title = json_req.get('title')
                                body = json_req.get('body')

                                sql_expr = f'UPDATE public.advert SET title=\'{title}\', body=\'{body}\' WHERE public.advert.id={advert_id}'
                                await cursor.execute(sql_expr)

                            except my_exception.DBUpdateError:
                                if config.DEBUG:
                                    print('Ошибка cursor.execute(query)')
                                raise web.HTTPBadRequest

                            response = []
                            item = {}
                            item['Result'] = 'Successful update'
                            item['title'] = title
                            item['body'] = body
                            item['advert_id'] = advert_id
                            response.append(item)

                            return web.json_response(response)
                        else:
                            if config.DEBUG:
                                print('Отсутствуют права на обновление!')
                            raise web.HTTPUnauthorized()

                    else:
                        if config.DEBUG:
                            print('Неверный пароль!')
                        raise web.HTTPUnauthorized()

                else:  # не нашли такого пользователя
                    if config.DEBUG:
                        print('Нет такого пользователя!')
                    raise web.HTTPNotFound()
コード例 #22
0
ファイル: auth.py プロジェクト: 1frag/stonehenge
async def callback_by_google(request: 'Request'):
    error = web.HTTPUnauthorized(
        body=b'Unauthorized, denied Google Authentication')
    if request.get('error', None):
        raise error
    opts = {
        'code': request.query.get('code'),
        'redirect_uri':
        request.app['config']['app']['domain'] + "/oauth/_google",
        'client_id': GOOGLE_CLIENT_ID,
        'client_secret': GOOGLE_CLIENT_SECRET,
        'grant_type': 'authorization_code',
    }

    ssl_context = ssl.create_default_context(cafile=certifi.where())

    async with aiohttp.ClientSession() as session:
        async with session.post(
                'https://oauth2.googleapis.com/token',
                data=opts,
                ssl=ssl_context,
        ) as resp:  # get access token
            if resp.status != 200:
                logger.info('status!=200, authorization failed %s', await
                            resp.text())
                raise error
            try:
                token_info = await resp.json()
            except json.JSONDecodeError as e:
                logger.info('obtain non-json format %s %s', await resp.text(),
                            e)
                raise error from None
            else:
                logger.debug(await resp.json())

        async with session.get(
                'https://www.googleapis.com/oauth2/v2/userinfo',
                headers={
                    'Authorization': 'Bearer ' + token_info['access_token']
                },
                ssl=ssl_context,
        ) as resp:  # get profile
            try:
                guser = await resp.json()
            except aiohttp.ContentTypeError as e:
                logger.info('obtain non-json format %s %s', await resp.text(),
                            e)
                raise error from None
            else:
                if 'error' in guser:
                    raise error
                logger.info(guser)

    try:
        async with request.app.db.acquire() as conn:
            user_id = await get_user_by_google(conn, guser['id'])
            await remember_user(request, user_id)
    except Exception as e:
        logger.debug(f'{e.__class__}: {e}')
    else:
        raise aiohttp.web.HTTPFound('/')

    try:
        cur_uuid = uuid.uuid4().hex
        session = await aiohttp_session.get_session(request)
        session['first_name'] = guser.get('given_name', '')
        session['last_name'] = guser.get('family_name', '')
        session['email'] = guser['email']
        session['way_aunt'] = 'google'
        session['key_pre_auth'] = cur_uuid

        save_data = {
            'auth': 'google',
            'email': guser['email'],
            'id_g_user': guser['id'],
            'access_token': token_info['access_token'],
        }
        await request.app.redis.set(cur_uuid, json.dumps(save_data))
    except Exception as e:
        logger.warning(f'{e}, {e.__class__}')

    return web.HTTPFound('/reg_next')
コード例 #23
0
 def on_error(self):
     raise web.HTTPUnauthorized(headers={'WWW-Authenticate': 'Basic'})
コード例 #24
0
async def basic(request: web.Request) -> web.Response:
    if "Authorization" in request.headers and request.headers[
            "Authorization"] == "Basic dGVzdDp0ZXN0":
        return web.json_response({"secret": 42})
    raise web.HTTPUnauthorized(text='{"detail": "Unauthorized"}',
                               content_type="application/json")
コード例 #25
0
def check_qa_reviewer(request: web.Request) -> None:
    if not is_qa_reviewer(request):
        raise web.HTTPUnauthorized()
コード例 #26
0
def handle_validation_error(error: ValidationError, *_):
    """
    Представляет ошибку валидации данных в виде HTTP ответа.
    """
    raise web.HTTPUnauthorized(reason='Request validation has failed')
コード例 #27
0
 async def handle_login_redirect(self, request, **kwargs):
     # Always reject and return 401
     raise web.HTTPUnauthorized(text='Automatic rejection')
コード例 #28
0
 async def wrapped(request):
     if not await is_authenticated(request):
         raise web.HTTPUnauthorized()
     return await f(request)
コード例 #29
0
 async def handler_unauthorized(request):
     raise web.HTTPUnauthorized()
コード例 #30
0
ファイル: __init__.py プロジェクト: darfire/aiologin
def _unauthorized(*args, **kwargs):
    raise web.HTTPUnauthorized()