Esempio n. 1
0
async def profile_validation(request):
    """Simple email validation"""
    data = await request.json(loads=ujson.loads)
    user = User(data)

    try:
        user.validate()
    except ModelValidationError as e:
        logger.debug(e.messages['email'].messages)
        return Response({
            'valid': False,
            'errors': e.messages,
        },
                        status=status.HTTP_409_CONFLICT)

    return Response({'valid': True})
 def get(self, request):
     accident = request.session.query(Accident) \
         .options(joinedload('citations').joinedload('citation'),
                  joinedload('vehicles').joinedload('casualties')) \
         .get(request.match_info['accident_id'])
     if not accident:
         return HTTPNotFound()
     return Response(accident.to_json(request.app))
Esempio n. 3
0
    async def middleware(request):
        request.user = None
        token = request.headers.get('authorization', None)

        if token != 'abc123':
            return Response(status=status.HTTP_401_UNAUTHORIZED)

        # do user lookup here, maybe
        return await handler(request)
Esempio n. 4
0
async def get_user(request):
    user_id = request.match_info.get('id', None)
    logger.debug(user_id)

    pool = request.app['pool']
    # Take a connection from the pool.
    async with pool.acquire() as connection:
        # # Open a transaction.
        # async with connection.transaction(readonly=True):
        # Run the query passing the request argument.
        result = await connection.fetchrow(
            'SELECT * FROM accounts_user WHERE id=$1', user_id)

        if result:
            logger.debug(result)
            user = User(dict(result.items()))
            return Response(user.to_primitive())

    return Response(status=status.HTTP_404_NOT_FOUND)
Esempio n. 5
0
    async def get(self, **kw):
        response = {
            'invited_type': '',
            'invited_by': '',
        }

        query = dict(self.request.query)
        if not query:
            raise NoGetParameters
        data = InviteCodeSchema(strict=True).load(query).data
        invite_code = data['invite_code']

        user = await User.find_one({'personal_invite_code': invite_code})
        if user is not None:
            response['invited_type'] = 'personal'
            response['invited_by'] = str(user.pk)
            return Response(response)

        group_code = await InviteGroup.find_one({'code': invite_code})
        if group_code is not None:
            if group_code.available_uses > 0:
                group_code.available_uses -= 1
                await group_code.commit()

                response['invited_type'] = 'group'
                response['invited_by'] = str(group_code.pk)
                return Response(response)
            else:
                raise InviteGroupCodeLimitExpired

        invite_code_request = await GetInviteCodeRequest.find_one(
            {'code': invite_code})
        if invite_code_request is not None:
            response['invited_type'] = 'admin'
            response['invited_by'] = str(invite_code_request.pk)
            return Response(response)

        raise NoSuchInviteCode
Esempio n. 6
0
    def get(self, request):
        dimensions = [self.dimensions[d] for d in request.GET.getall('dimension')]
        filters = [self.filters[f] for f in request.GET.getall('filter')]
        values = [self.values[v] for v in request.GET.getall('value')]
        query = select(dimensions + values)
        for filter in filters:
            query = filter(query)
        query = query.group_by(*dimensions)
        query = query.order_by(*dimensions)
        query = query.limit(1000)
        a = request.session.execute(query).fetchall()
        print('\n'.join(','.join(map(str, x)) for x in a))

        return Response({})
Esempio n. 7
0
    async def get(self, **kw):
        me = self.request.user
        output_fields = (
            'id',
            'email',
            'photo',
            'current_location',
            'personal_invite_code',
            'bubbles',
            'is_active',
            'is_notifications_enabled',
        )

        me_schema = UserSchema(strict=True, only=output_fields)
        data = me_schema.dump(me).data
        return Response(data)
Esempio n. 8
0
    async def post(self, **kw):
        try:
            json_data = await self.request.json()
        except (AssertionError, ValueError):
            raise NotJSONData
        login_schema = UserSchema(strict=True, only=('email', 'password'))
        data = login_schema.load(json_data).data

        user = await User.find_one({'email': data['email']})
        if not user:
            raise NoSuchUser
        if not user.check_password(data['password']):
            raise WrongPassword

        payload = {
            'user_id': str(user.id),
            'exp': datetime.utcnow() + timedelta(days=JWT_EXP_DELTA_DAYS)
        }
        jwt_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM)
        return Response({'token': jwt_token.decode('utf-8')})
Esempio n. 9
0
    async def get(self, **kw):
        query = dict(self.request.query)
        pagination = self.request.pagination
        search = query.get('contains', None)
        tag_type = query.get('type', None)
        parent = query.get('parent', None)

        search_filter = {}
        if search is not None and tag_type in TAG_TYPES:
            search_filter['name'] = {
                '$regex': '.*{0}.*'.format(search),
                '$options': 'i'
            }
            search_filter['type'] = tag_type
            if parent is not None:
                search_filter['parent'] = parent
        else:
            raise NoGetParameters

        tags = TagSynonym.find(search_filter)
        tags = get_objects_with_pagination(tags, **pagination)
        tags = await tags.to_list(None)
        tags = [tag.parent_synonym for tag in tags]
        return Response(tags)
Esempio n. 10
0
async def index(request):
    return Response('Hi There')
Esempio n. 11
0
 async def get(self, **kw):
     me = self.request.user
     me_schema = UserSchema(strict=True)
     data = me_schema.dump(me).data
     return Response(data)
Esempio n. 12
0
 def get(self, request):
     return Response(request.app['reference-data'])
Esempio n. 13
0
def index(request):
    return Response({'message': 'Hello ' + request.GET.get('name', 'World')})
Esempio n. 14
0
def index(request):
    return Response('Welcome!')
    def get(self, request):
        query = request.session.query(Accident) #.options(joinedload('citations').joinedload('citation'),
                                                #         joinedload('vehicles').joinedload('casualties'))

        try:
            page = int(request.GET.get('p') or 1)
            if page < 1:
                raise HTTPNotFound
        except ValueError:
            raise HTTPBadRequest

        if request.GET.get('news') == 'yes':
            query = query.filter(Accident.citations.any())

        if 'sort' in request.GET:
            query = query.order_by(*request.GET.getall('sort'))

        if request.GET.get('dateTimeLower'):
            try:
                datetime_lower = dateutil.parser.parse(request.GET['dateTimeLower'])
            except ValueError:
                raise HTTPBadRequest
            else:
                query = query.filter(Accident.date_and_time >= datetime_lower)
        if request.GET.get('dateTimeUpper'):
            try:
                datetime_upper = dateutil.parser.parse(request.GET['dateTimeUpper'])
            except ValueError:
                raise HTTPBadRequest
            else:
                query = query.filter(Accident.date_and_time < datetime_upper)

        if 'severity' in request.GET:
            query = query.filter(Accident.severity_id.in_(request.GET.getall('severity')))

        highway_authorities = list(filter(None, request.GET.getall('highwayAuthority', ())))
        if highway_authorities:
            query = query.filter(Accident.highway_authority_id.in_(highway_authorities))

        police_forces = list(filter(None, request.GET.getall('policeForce', ())))
        if police_forces:
            query = query.filter(Accident.police_force_id.in_(police_forces))

        if 'policeAttended' in request.GET:
            query = query.filter(Accident.police_attended == (request.GET.get('policeAttended') == 'yes'))

        if 'involvedVehicleType' in request.GET:
            vehicle_types = set(map(int, request.GET.getall('involvedVehicleType')))
            vehicle_types = '{:0100b}'.format(sum(1 << vt for vt in vehicle_types))
            query = query.filter((Accident.involved_vehicle_types.op('&')(vehicle_types)) == vehicle_types)

        if 'involvedCasualtyType' in request.GET:
            casualty_types = set(map(int, request.GET.getall('involvedCasualtyType')))
            casualty_types = '{:0100b}'.format(sum(1 << ct for ct in casualty_types))
            query = query.filter((Accident.involved_casualty_types.op('&')(casualty_types)) == casualty_types)

        if 'bbox' in request.GET:
            x1, y1, x2, y2 = map(float, request.GET['bbox'].split(','))
            query = query.filter(Accident.location.contained(
                'SRID=4326;POLYGON(({x1} {y1}, {x1} {y2}, {x2} {y2}, {x2} {y1}, {x1} {y1}))'.format(x1=x1,
                                                                                                    y1=y1,
                                                                                                    x2=x2,
                                                                                                    y2=y2)))

        count = query.count()
        page_count = max(1, math.ceil(count / self.page_size))

        query = query.offset((page - 1) * self.page_size).limit(self.page_size)

        data = {
            'page': page,
            'count': count,
            'pageCount': page_count,
            '_links': {
                'self': {'href': request.path_qs},
            },
            '_embedded': {
                'item': [a.to_json(request.app) for a in query.all()]
            },
        }

        # Add pagination links
        qs = request.GET.copy()
        qs.pop('p', None)
        qs = tuple(qs.items())
        if page > 1:
            data['_links']['prev'] = {'href': '?' + urlencode(qs + (('p', str(page - 1)),))}
        if page < page_count:
            data['_links']['next'] = {'href': '?' + urlencode(qs + (('p', str(page + 1)),))}

        return Response(data)
Esempio n. 16
0
 def get(self, request):
     return Response({'message': 'Welcome to the API!'})
Esempio n. 17
0
async def hello(request):
    return Response({'message': "Hello, world!"})
Esempio n. 18
0
async def version(request):
    return Response({'version': __version__})