def check_field_length(value, length, _greater=True, _lesser=False):
    if _greater and len(value) < length:
        raise BadRequest(
            'Field must be greater than {} characters'.format(length))

    if _lesser and len(value) > length:
        raise BadRequest(
            'Field must be lesser than {} characters'.format(length))
def check_bio_field(value):
    min_value = min(len(value), MIN_USER_BIO_LENGTH)
    max_value = max(len(value), MAX_USER_BIO_LENGTH)

    if min_value != MIN_USER_BIO_LENGTH:
        raise BadRequest('Bio must be at least 4 characters')

    if max_value != MAX_USER_BIO_LENGTH:
        raise BadRequest('Bio must be less than 140 characters')

    return min_value == max_value
    def __validate_location_creation_params(self, request_data):
        required_params = {'longitude', 'latitude'}
        missing_required_params = required_params - set(request_data.keys())
        if missing_required_params:
            raise BadRequest('{} are missing.'.format(missing_required_params))

        return self.__check_locations_params(request_data)
Beispiel #4
0
    def __check_post_params(self, request_data):
        comments_enabled = request_data.get('comments_enabled')
        if comments_enabled is not None:
            check_boolean_field(comments_enabled)

        text = request_data.get('text')
        if text is not None:
            check_field_length(text, MIN_POST_TEXT_LENGTH)

        location_uid = request_data.get('location_uid')
        location = Location.get_active(uid=location_uid)
        if bool(location_uid) != bool(location):
            raise ResourceNotFound('`location_uid` not found')

        request_blobs = request_data.get('blobs')
        if not isinstance(request_blobs, list):
            raise BadRequest('`blobs` must be an array')

        post_slides = []
        for blob_uid in request_blobs:
            try:
                blob = Blob.get_active(uid=blob_uid)
                post_slides.append(blob)
            except :
                raise ResourceNotFound('Blob `{}` not found'.format(blob_uid))

        return dict(
            post_slides=post_slides,
            comments_enabled=comments_enabled,
            location=location,
            text=text)
Beispiel #5
0
def register():
    try:
        username = request.json.get('username', '')
        password = request.json.get('password', '')
        if not username:
            raise ValueError('Username is required.')
        elif not password:
            raise ValueError('Password is required.')
    except Exception as e:
        raise BadRequest(message=e)

    conn = current_app.db_engine.connect()
    query = select([users.c.password]).where(users.c.username == username)
    result = conn.execute(query)
    row = result.fetchone()
    result.close()

    if row:
        raise UnprocessableEntity(
            'User {} is already registered.'.format(username))

    result = conn.execute(users.insert().returning(users.c.id,
                                                   users.c.username),
                          username=username,
                          password=generate_password_hash(password))
    user = result.fetchone()
    return jsonify(code=200,
                   data={
                       'user': {
                           'id': user[users.c.id],
                           'username': user[users.c.username],
                       },
                   })
    def get(self, hash_tag):
        """Retrieve posts about an hashtag"""
        request_args = get_current_request_args()

        scope = request_args.get('scope') or DEFAULT_HASH_TAG_FETCH_SCOPE
        if scope not in HASH_TAG_RETRIEVAL_SCOPES:
            raise BadRequest(
                '`scope` must be one of {}'.format(HASH_TAG_RETRIEVAL_SCOPES))

        hash_tag = HashTag.get_not_deleted(hash_tag=hash_tag)
        if hash_tag is None:
            raise ResourceNotFound('Hash tag not found')

        hash_tag_details = {
            'meta': lambda x: {
                'data': None,
                'meta': None
            },
            'posts': lambda y: {
                'data': None,
                'meta': None
            },
            'followers': lambda z: {
                'data': None,
                'meta': None
            }
        }

        scoped_details = hash_tag_details[scope]()

        return api_success_response(**scoped_details)
def check_username_field(value):
    regex_ = r'^[a-zA-Z0-9_.]+$'

    pattern = re.compile(regex_)

    if not pattern.match(value):
        raise BadRequest(
            "Username can have only '_', '.' and alphanumeric characters")
    def __validate_conversation_creation_params(self, request_data):
        required_params = {'users'}
        missing_required_params = required_params - set(request_data.keys())

        if missing_required_params:
            raise BadRequest('{} is missing'.format(missing_required_params))

        return self.__check_conversation_creation_params(request_data)
Beispiel #9
0
    def __validate_story_creation_params(self, request_data):
        required_params = {'blob_uid'}

        missing_required_params = required_params - set(request_data.keys())
        if missing_required_params:
            raise BadRequest('{} required to create a user are missing'.format(
                required_params))

        return self.__check_story_params(request_data)
Beispiel #10
0
    def __validate_collection_creation_params(self, request_data):
        required_params = {'name'}

        missing_required_params = required_params - set(request_data.keys())
        if missing_required_params:
            raise BadRequest(
                'Missing required params: {}'.format(missing_required_params))

        return self.__check_collections_params(request_data)
    def __validate_user_creation_params(self, request_data):
        required_params = {'username', 'password'}

        missing_required_params = required_params - set(request_data.keys())
        if missing_required_params:
            raise BadRequest('{} required to create a user are missing'.format(
                required_params))

        return self.__check_user_params(request_data)
Beispiel #12
0
def search_photos(search_term):
    if search_term not in search_terms:
        raise BadRequest(
            f"one of {search_terms} is required. got = {search_term}")

    cache = app.cache
    result = cache.get_term(search_term)

    return jsonify(result), 200
def check_address_field(value):
    required_keys = {
        'street_address', 'lga', 'town', 'country', 'province', 'state',
        'zip_code'
    }

    missing_required_keys = required_keys - set(value.keys())

    if missing_required_keys:
        raise BadRequest('{} must be included in `address` fields'.format(
            missing_required_keys))
def check_phone_field(value):
    if value is None:
        return

    value = value.strip().strip('+').replace(' ', '').replace('-', '')

    try:
        if not value.isdigit():
            raise BadRequest('Phone number is invalid.')

        if len(value) == 10 and not value.startswith('0'):
            value = '234' + value
        elif len(value) == 11 and value.startswith('0'):
            value = '234' + value[1:]
        elif value.startswith('234') and len(value) == 13:
            pass
        else:
            raise BadRequest('Phone number is invalid.')

        return value

    except:
        raise BadRequest('Phone number is invalid.')
    def paginate(self,
                 page=None,
                 per_page=None,
                 error_out=False,
                 max_per_page=None,
                 use_request_args=True):
        app = current_app

        if use_request_args:
            # TODO:
            # This assumes pagination parameters are specified
            # as URL query parameters and not in body payload.
            params = request.args

            try:
                page = int(params.get('page', 0))
                per_page = int(params.get('per_page', 0))
            except (TypeError, ValueError):
                raise BadRequest('Pagination parameters should be integers.')

            page = page or app.config['PAGINATION_DEFAULT_PAGE']
            per_page = per_page or app.config['PAGINATION_DEFAULT_PER_PAGE']

        max_per_page = max_per_page or app.config['PAGINATION_DEFAULT_PER_PAGE']

        pagination = super(CustomQuery,
                           self).paginate(page=int(page),
                                          per_page=int(per_page),
                                          error_out=error_out,
                                          max_per_page=int(max_per_page))

        pagination.meta = {
            'pagination': {
                'previous_page':
                (pagination.prev_num if pagination.has_prev else None),
                'next_page':
                (pagination.next_num if pagination.has_next else None),
                'num_items':
                pagination.total,
                'num_pages':
                pagination.pages,
                'has_next_page':
                pagination.has_next,
                'has_previous_page':
                pagination.has_prev
            }
        }

        return pagination
Beispiel #16
0
def list_user_post(username):
    try:
        offset = int(request.args.get('offset', 0))
        limit = int(request.args.get('limit', 20))
        if limit <= 0:
            raise ValueError('Limit should be positive.')
        if limit > 50:
            raise ValueError('Limit should be under 50.')
    except Exception as e:
        raise BadRequest(message=e)

    conn = current_app.db_engine.connect()
    query = select([
        posts.c.id,
        posts.c.title,
        posts.c.created_ts,
        posts.c.updated_ts,
    ])\
        .select_from(posts.join(users, users.c.id == posts.c.author_id))\
        .where(users.c.username == username)\
        .order_by(posts.c.created_ts)\
        .offset(offset)\
        .limit(limit)
    count_query = select([func.count(posts.c.id)])\
        .select_from(posts.join(users, users.c.id == posts.c.author_id))\
        .where(users.c.username == username)

    raw_posts = conn.execute(query).fetchall()
    count = conn.execute(count_query).fetchone()[0]
    res_posts = []
    for row in raw_posts:
        res_posts.append({
            'id': row[posts.c.id],
            'title': row[posts.c.title],
            'created_ts': datetime.to_seconds(row[posts.c.created_ts]),
            'updated_ts': datetime.to_seconds(row[posts.c.updated_ts]),
        })
    return jsonify(code=200, data={
        'posts': res_posts,
        'meta': {
            'offset': offset,
            'limit': limit,
            'total': count,
        },
    })
Beispiel #17
0
def login():
    try:
        username = request.json.get('username', '')
        password = request.json.get('password', '')
        if not username:
            raise ValueError('Username is required.')
        elif not password:
            raise ValueError('Password is required.')
    except Exception as e:
        raise BadRequest(message=e)

    conn = current_app.db_engine.connect()
    query = select([
        users.c.id,
        users.c.username,
        users.c.password,
    ]).where(users.c.username == username)
    result = conn.execute(query)
    row = result.fetchone()
    result.close()

    if not row or not check_password_hash(row[users.c.password], password):
        raise Unauthorized('Unauthorized user.')

    identity = {
        'id': row[users.c.id],
        'username': row[users.c.username],
    }
    access_token = create_access_token(identity=identity)
    csrf_token = get_csrf_token(access_token)
    resp = jsonify(code=200,
                   data={
                       'user': identity,
                       'access_token': access_token,
                       'csrf_token': csrf_token,
                   })
    set_access_cookies(resp, access_token)
    return resp
def check_boolean_field(value):
    if not type(value) is bool:
        raise BadRequest('Boolean expected, not {}'.format(value))
def check_amount_field(value):
    try:
        float(value)
    except ValueError:
        raise BadRequest('{} is an invalid amount'.format(value))
def check_email_field(value):
    validator = Email()
    if not validator(value):
        raise BadRequest('`email` {} is invalid.'.format(value))
def check_coordinate_field(latitude=None, longitude=None):
    if latitude is not None and not -90 < latitude < 90:
        raise BadRequest('Latitude is invalid')

    if longitude is not None and not -180 < longitude < 180:
        raise BadRequest('Longitude is invalid')