Beispiel #1
0
    async def get(self):
        user_id = self.request.match_info['id']
        db = self.request.app['db']

        try:
            async with db.acquire() as conn:
                user_obj = await conn.execute(
                    sa.select([users, addresses], use_labels=True).select_from(
                        sa.join(users, addresses,
                                users.c.address_id == addresses.c.id)).where(
                                    users.c.id == user_id))
                data = await user_obj.first()
                result = {
                    'id': data.users_id,
                    'email': data.users_email,
                    'first_name': data.users_first_name,
                    'address': {
                        'city': data.addresses_city,
                        'street': data.addresses_street
                    },
                    'gender': data.users_gender,
                    'married': data.users_married,
                }
            return json_response(result)
        except AttributeError:
            return json_response(
                {"Error": f"User with id {user_id} does not exist"})
async def get(request):
    hmm_id = request.match_info["hmm_id"]

    if hmm_id != MOCK_HMM["id"]:
        return json_response({"message": "Not Found"}, status=404)

    return json_response(MOCK_HMM)
 async def get(self):
     try:
         users = await User.get_all(self.request.app.objects)
     except Exception as e:
         log.exception("Encountered error in %s (%s)", self.__class__, e)
         return json_response({'error': 'Something wrong'}, status=400)
     return json_response(users, status=200)
Beispiel #4
0
async def encrypt(request: Request) -> Response:
    request_json = await to_json(request)

    try:
        name = request_json['name']
        message = request_json['message']
    except KeyError:
        data = {'status': Status.invalid_json, 'reason': 'Invalid JSON.'}
        return json_response(data, status=HTTPStatus.BAD_REQUEST)

    try:
        public_key = keys.search(name)
    except (FileNotFoundError, ValueError):
        data = {
            'status': Status.key_not_found,
            'reason': 'Failed to found valid key '
            f'for "{name}".'
        }
        return json_response(data, status=HTTPStatus.BAD_REQUEST)

    result = messages.encrypt(message.encode(), public_key=public_key)
    data = {
        'status': Status.ok,
        'result': messages.encode(result).decode(),
        'name': name
    }
    return json_response(data)
Beispiel #5
0
    async def dispatch(self) -> Response:
        """
        The entry point for every request.
        """

        handler = self.get_handler_or_raise_405()
        await self.perform_authentication()
        await self.check_permissions()

        try:
            response = await handler()
        except HTTPException as e:
            raise e
        except JSONDecodeError as e:
            return json_response(
                status=HTTPStatus.BAD_REQUEST.value,
                data={
                    'code': 'internal_error',
                    'message': str(e),
                },
            )
        except Exception:
            return json_response(
                status=HTTPStatus.INTERNAL_SERVER_ERROR.value,
                data={
                    'code': 'internal_error',
                    'message': 'Internal error.',
                },
            )

        return response
 async def post(self):
     email = self.request.user['email']
     log.info(f"User {email} trying to modify self data")
     user_data = await self.request.json()
     if not set(user_data.keys()) == {
             'first_name', 'last_name', 'phone', 'bio', 'avatar_url'
     }:
         return json_response(
             {
                 'error':
                 "Request must consist all this fields: "
                 "'first_name', 'surname', 'phone', 'bio', 'avatar_url'"
             },
             status=400)
     owner = self.request.user.get('user_id')
     user_id = self.request.match_info['user_id']
     if int(user_id) != int(owner):
         return json_response({'error': 'You don`t have permission for it'},
                              status=403)
     try:
         await User.update_profile(self.request.app.objects, user_id,
                                   user_data)
     except DataError as e:
         log.exception("Encountered error in %s (%s)", self.__class__, e)
         return json_response({'error': 'Something wrong'}, status=400)
     return json_response('Success', status=200)
Beispiel #7
0
    async def get(self):
        params = self.request.rel_url.query
        if "auth" in params.keys():
            profile = await Profile.query.where(Profile.token == params["auth"]
                                                ).gino.first()
            if not profile:
                return json_response({
                    "success": False,
                    "info": "user not found"
                })

            await profile.update(token=General().generate_token()).apply()
            instance = {
                "id": profile.id,
                "country": profile.country,
                "city": profile.city,
                "phone": profile.phone,
                "email": profile.email,
                "auth": profile.token
            }

            return json_response({"success": True, "data": instance})
        else:
            return json_response({
                "success": False,
                "info": "parameter auth not found"
            })
Beispiel #8
0
    async def post(self):
        data = await self.request.json()
        await BaseView().save_cookie(self.request.headers["User-Agent"], [
            "{}: {},\r\n".format(key, value)
            for key, value in data.items() if key != "password"
        ], self.request.url.raw_path_qs)
        try:
            auth = data["auth"]
            if validate_email(auth):
                profile = await Profile.query.where(Profile.email == auth
                                                    ).gino.first()
            else:
                profile = await Profile.query.where(Profile.phone == auth
                                                    ).gino.first()
            password = General().crypt(data["password"])
            translator = await Translator.query.where(
                Translator.profile_id == profile.id).gino.first()
        except:
            return json_response({"error": "not found", "success": False})

        if profile.password == password and profile.is_active:
            await profile.update(token=General().generate_token()).apply()
            data = BaseProfileLogic().get_data(profile)
            return json_response(self.make_response(data, translator))
        else:
            return json_response({"error": "auth is wrong", "success": False})
Beispiel #9
0
async def get_file_exists(request):
    params = await request.json()
    print(params)
    path_param = params.get('path', None)
    filename = params.get('filename', None)
    if path_param is None:
        raise web.HTTPBadRequest(reason='not ok: path param missing')

    if filename is None:
        raise web.HTTPBadRequest(reason='not ok: filename param missing')

    subdir = None
    exists = False

    try:
        subdir = dirs_cache.get_subdir(path_param)
    except StopIteration:
        print('Subdir does not exist')
        return json_response({'exists': False})
    t_now = time_ns()
    fnamepath = PurePath(filename)
    exists = subdir.joinpath(fnamepath.name).exists()
    t_spent = (time_ns() - t_now) / 1e6
    print('exists', exists, 'time:', '{:.2f}'.format(t_spent) + 'ms')
    if exists:
        if not params.get('update_cache', None) is False:
            await BackgroundTask().run(check_update_fn_cache,
                                       (params, subdir, path_param))
    return json_response({'exists': exists})
async def register_user(request: web.Request) -> web.Response:
    """ Register user handler. Check if user already exist or create new user in database

    :param request: web request
    :return: web response in json format
    """
    json_data = await request.json()
    result = T.catch_error(REGISTER_TRAFARET, json_data)
    if isinstance(result, DataError):
        errors = result.as_dict()
        return json_response({'errors': errors}, status=400)

    async with request.app['db'].acquire() as connection:
        cursor = await connection.execute(
            users.select().where(users.c.email == json_data['email']))
        user_credentials = await cursor.fetchone()
        if user_credentials:
            return json_response({
                'message':
                'User with email {email} already exist'.format(
                    email=json_data['email'])
            })
        else:
            await connection.execute(users.insert().values(
                name=json_data['name'],
                last_name=json_data['last_name'],
                email=json_data['email'],
                password=generate_password_hash(json_data['password']),
            ))
            return json_response({
                'message':
                'User with email {email} register successfully'.format(
                    email=json_data['email'])
            })
Beispiel #11
0
    async def receive_updates(self, request: Request):
        """
        Handle updates from Telegram
        """

        body = await request.read()

        try:
            content = ujson.loads(body)
        except ValueError:
            return json_response(
                {
                    'error': True,
                    'message': 'Cannot decode body',
                }, status=400)

        logger.debug('Received from Telegram: %s', content)

        message = TelegramMessage(content, self)
        responder = TelegramResponder(content, self)
        await self._notify(message, responder)

        return json_response({
            'error': False,
        })
Beispiel #12
0
async def delete_recipe(req: Request):
    session: Session = await get_session(req)

    # check if user is logged in
    if not _logged_in(session):
        return json_response(USER_ERRORS.NOT_LOGGED_IN)

    u = _get_user_session(session)

    # check if user has permission
    if not u.type in EDIT_GRP:
        return json_response(USER_ERRORS.PERMISSION_DENIED)

    # get recipe by id
    try:
        r = recipe.get_by_id(req.match_info.get("id"))
    except RecipeError:
        return json_response(RECIPE_ERRORS.DOES_NOT_EXIST)

    # check if writer is the author of the recipe
    if not u.type == 'admin' and not r.author.id == u.id:
        return json_response(USER_ERRORS.PERMISSION_DENIED)

    r._recipe.delete()

    return json_response({'status': 'ok'})
Beispiel #13
0
 async def get(self):
     pin_id = self.request.match_info['pin_id']
     try:
         pin = await Pin.get_info(self.request.app.objects, pin_id)
     except Exception as e:
         log.exception("Encountered error in %s (%s)", self.__class__, e)
         return json_response({'error': 'Error read pin'}, status=400)
     return json_response(pin, status=200)
 async def delete(self):
     if await self.owner:
         if await self.check_owner():
             return await super().delete()
         return json_response({self.RESPONSE_HEADER: '403: Forbidden'},
                              status=403)
     return json_response({self.RESPONSE_HEADER: '401: Unauthorized'},
                          status=401)
Beispiel #15
0
async def get_recipe(req: Request):
    # get recipe by id
    try:
        r = recipe.get_by_id(req.match_info.get("id"))
    except RecipeError:
        return json_response(RECIPE_ERRORS.DOES_NOT_EXIST)

    return json_response({"recipe": r.to_dict()})
Beispiel #16
0
async def grecaptcha_dummy(request):
    data = await request.post()
    request['log_msg'] = 'grecaptcha {response}'.format(**data)
    if data['response'] == '__ok__':
        return json_response(dict(success=True, hostname='127.0.0.1'))
    elif data['response'] == '__400__':
        return json_response({}, status=400)
    else:
        return json_response(dict(success=False, hostname='127.0.0.1'))
Beispiel #17
0
async def grecaptcha(request):
    data = await request.post()
    request.app['log'][-1] = ('grecaptcha', data['response'])
    if data['response'] == '__ok__':
        return json_response(dict(success=True, hostname='127.0.0.1'))
    elif data['response'] == '__400__':
        return json_response({}, status=400)
    else:
        return json_response(dict(success=False, hostname='127.0.0.1'))
Beispiel #18
0
async def grecaptcha(request):
    data = await request.post()
    request.app['log'].append(('grecaptcha', data['response']))
    if data['response'] == '__ok__':
        return json_response(dict(success=True, score=1))
    elif data['response'] == '__low_score__':
        return json_response(dict(success=True, score=0.1))
    else:
        return json_response(dict(success=False))
Beispiel #19
0
async def post_recipe_image(req: Request):
    session: Session = await get_session(req)

    # check if user is logged in
    if not _logged_in(session):
        return json_response(USER_ERRORS.NOT_LOGGED_IN)

    u = _get_user_session(session)

    # check if user has permission
    if not u.type in EDIT_GRP:
        return json_response(USER_ERRORS.PERMISSION_DENIED)

    # get recipe by id
    try:
        r = recipe.get_by_id(req.match_info.get("id"))
    except RecipeError:
        return json_response(RECIPE_ERRORS.DOES_NOT_EXIST)

    # check if writer is the author of the recipe
    if not u.type == 'admin' and not r.author.id == u.id:
        return json_response(USER_ERRORS.PERMISSION_DENIED)
    """ data = await req.post()
    img = data["image"]
    ctype = img.content_type

    _LOGGER.info(ctype)

    r._recipe.image.put(img.file, content_type=ctype) """

    reader = await req.multipart()

    # get image field
    field = await reader.next()
    assert field.name == "image"
    ctype = field.headers[aiohttp.hdrs.CONTENT_TYPE]

    _LOGGER.info(ctype)

    # delete saved image and create a new file
    r._recipe.image.delete()
    r._recipe.image.new_file(content_type=ctype)

    # upload file in chunks
    size = 0
    while True:
        chunk = await field.read_chunk()
        if not chunk:
            break
        size += len(chunk)
        r._recipe.image.write(chunk)

    # close new file and save recipe doc
    r._recipe.image.close()
    r._recipe.save()

    return json_response({"status": "ok", "size": size})
Beispiel #20
0
async def user_logout(req: Request):
    session = await get_session(req)

    if 'user' in session and session.get('user') is not None:
        _remove_user_session(session)

        return json_response({"status": "ok"})

    return json_response(USER_ERRORS.NOT_LOGGED_IN)
Beispiel #21
0
 async def get(self):
     user_id = self.request.match_info['user_id']
     try:
         profile = await User.get_profile(self.request.app.objects, user_id)
     except DoesNotExist as e:
         log.exception("Encountered error in %s (%s)", self.__class__, e)
         return json_response({'error': 'Such user does not exist'},
                              status=400)
     return json_response(profile, status=200)
Beispiel #22
0
async def modules(request):
    """
    From logging properties find all `appName`s
    """
    res = request.app.config.modules
    if res:
        return json_response(res)
    res = await find_modules(request.app.config)
    return json_response(res)
Beispiel #23
0
 async def post(self):
     data = await self.request.post()
     url = data.get('url', None)
     channel = data.get('channel', None)
     if not url or not channel:
         return json_response({'result': 'Bad Request'})
     async with self.request.app['db'].acquire() as conn:
         await db.insert_model(conn, db.rss, channel=channel, url=url)
     return json_response({'result': 'SUCCESS'})
Beispiel #24
0
async def get_redis_data(request: Request) -> Response:
    """Получение всех данных из Redis."""
    key = request.match_info['key']
    redis_data = await RedisData.get(key, request.app['redis'])
    if not redis_data:
        return json_response(
            data={'errors': [f'Объект с ключом {key} не найден.']},
            status=NOT_FOUND.value,
        )
    return json_response(data=dict(redis_data))
Beispiel #25
0
async def facebook_siw(request):
    access_token = request.query['access_token']
    if access_token == '__ok__':
        return json_response(
            {'id': '123456', 'email': '*****@*****.**', 'first_name': None, 'last_name': 'Book'}
        )
    elif access_token == '__no_user__':
        return json_response({'id': '123456', 'first_name': None, 'last_name': 'Book'})
    else:
        return json_response({}, status=400)
Beispiel #26
0
 async def get(self):
     pin = self.request.match_info['pin_id']
     try:
         gallery = await Photo.get_pin_gallery(self.request.app.objects,
                                               pin=pin)
     except Exception as e:
         log.exception("Encountered error in %s (%s)", self.__class__, e)
         return json_response({'error': 'Error read photo gallery'},
                              status=400)
     return json_response(gallery, status=200)
Beispiel #27
0
 async def post(self):
     try:
         req = await self.request.json()
         logger.debug(f"{req}")
     except Exception as e:
         logger.warning(e)
         raise HTTPBadRequest()
     orders, assign_time = order_assign_handler.assign(req)
     if orders:
         return json_response({"orders": orders, "assign_time": assign_time})
     return json_response({"orders": orders})
Beispiel #28
0
    async def post(self) -> Response:
        """Сохранение данных в Redis."""
        try:
            redis_data: RedisData = RedisData.parse_raw(await
                                                        self.request.text())
        except ValidationError as error:
            return json_response(data={'errors': error.errors()},
                                 status=BAD_REQUEST.value)

        await redis_data.save(self.request.app['redis'])
        return json_response(data=dict(redis_data))
Beispiel #29
0
async def articles_handler(request, morph, charged_words):
    urls = request.query.get('urls')
    if not urls:
        return json_response(data={'error': 'no one urls'}, status=400)
    urls_list = urls.split(',')
    if len(urls_list) > 10:
        return json_response(data={'error': 'max urls count = 10'}, status=400)
    parse_result = await process_parse(urls_list, morph, charged_words)
    # json.dumps because  json_response body don't support ensure ascii
    result_data = json.dumps(parse_result, ensure_ascii=False)
    return json_response(text=result_data, status=200)
Beispiel #30
0
 async def post(self):
     credentials = await self.request.json()
     user = self.request.user.get('user_id')
     try:
         pin_id = await Pin.add_pin(self.request.app.objects,
                                    credentials,
                                    user=user)
     except Exception as e:
         log.exception("Encountered error in %s (%s)", self.__class__, e)
         return json_response({'error': 'Something wrong'}, status=400)
     return json_response({"pinId": pin_id}, status=200)
Beispiel #31
0
 async def get_echo(self, request):
     data = request.match_info.get('data')
     d = await self._client_a.echo(data)
     return json_response(text=d)