Пример #1
0
def login():
    if not all(x in request.args for x in ['username', 'password']):
        raise ProcessingException(description='No username or password.',
                                  code=400)

    username = request.args['username']
    password = request.args['password']

    # generate a token
    token = uuid4().hex

    try:
        user = User.query.filter(User.username == username).one()

        if not bcrypt.verify(password, user.hashed_password):
            raise ProcessingException(description='Bad authentication.',
                                      code=401)
    except NoResultFound:
        raise ProcessingException(description='No user found.', code=400)
    except MultipleResultsFound:
        raise ProcessingException(description='Server state inconsistent.',
                                  code=500)

    # update token
    user.token = token
    db.session.commit()

    return jsonify(id=user.id, token=user.token)
Пример #2
0
def preprocess_make_user(data=None, **kw):
    if 'username' not in data:
        raise ProcessingException(description='No username provided.',
                                  code=400)

    if User.query.filter(User.username == data['username']).count() != 0:
        raise ProcessingException(description='Username not unique.', code=400)
Пример #3
0
def check_recaptcha(data, *args, **kwargs):
    if current_user.is_authenticated():
        if 'g-recaptcha-response' in data:
            del data['g-recaptcha-response']
        return
    # TODO: return if the user comes from a verified source
    if 'review_request_id' in data and 'review_request_token' in data:
        review_request = models.ReviewRequest.query.filter_by(
            id=data.get('review_request_id')).first()
        if review_request and review_request.token == data.get(
                'review_request_token'):
            if 'g-recaptcha-response' in data:
                del data['g-recaptcha-response']
            return
    recaptcha = data.get('g-recaptcha-response')
    if not recaptcha:
        raise ProcessingException(
            description=ExceptionMessages.MISSING_PARAM.format(
                param='g-recaptcha-response'),
            code=401)
    r = requests.post(current_app.config.get("RECAPTCHA_URL"),
                      data={
                          'secret': current_app.config.get("RECAPTCHA_SECRET"),
                          'response': recaptcha,
                          'remoteip': request.remote_addr
                      })
    if not (r and r.status_code == 200 and r.json()):
        raise ProcessingException(description=ExceptionMessages.CAPTCHA_FAIL,
                                  code=401)
    if not r.json().get('success'):
        raise ProcessingException(description=ExceptionMessages.CAPTCHA_FAIL,
                                  code=401)

    del data['g-recaptcha-response']
Пример #4
0
def upload_photo(hazard_id):
    if 'photo' not in request.files:
        raise ProcessingException(description='No photo', code=400)

    # get hazard by id
    try:
        hazard = Hazard.query \
            .options(joinedload(Hazard.user)) \
            .filter(Hazard.id == hazard_id).one()
    except NoResultFound:
        raise ProcessingException(description='No hazard matching id.',
                                  code=400)
    except MultipleResultsFound:
        raise ProcessingException(description='Server state inconsistent.',
                                  code=500)

    # ensure user owns hazard
    if hazard.user.id != g.user.id:
        raise ProcessingException(description='User does not own hazard',
                                  code=401)

    # set photo_id to hazard id + random string
    hid = '{:011d}'.format(hazard_id)
    rand = ''.join('{:02x}'.format(ord(x)) for x in os.urandom(16))

    hazard.photo_id = hid + rand
    db.session.commit()

    name = hazard.photo_id + '.jpg'
    s3_upload(name, request.files['photo'])

    return '', 204
Пример #5
0
def pre_create_order(data, *args, **kwargs):
    shop_id = data.get('shop_id')
    if not shop_id:
        raise ProcessingException(description='Shop id required', code=401)
    shop = models.Shop.query.filter_by(id=shop_id).first()
    if not shop.owner == current_user:
        raise ProcessingException(description='Not your shop', code=401)
    data['purchase_timestamp'] = unicode(datetime.datetime.utcnow())
Пример #6
0
def pre_notification_patch(instance_id, data, *args, **kwargs):
    if not instance_id:
        raise ProcessingException(description='Notification id requried!',
                                  code=401)
    notification = models.Notification.query.filter_by(id=instance_id).first()
    if not notification:
        raise ProcessingException(description='Review doesnt exist', code=401)
    data['is_read'] = True
Пример #7
0
def verify_product_url_exists(data, *args, **kwargs):
    product_url = data.get('url')
    product_name = data.get('name')
    if not product_url or not product_name:
        raise ProcessingException(description='Product url and name required',
                                  code=401)
    product_exists = models.Product.query.filter_by(url=product_url).first()
    if product_exists:
        raise ProcessingException(description='Product with that url exists',
                                  code=401)
Пример #8
0
def pre_post_answer(data, *args, **kwargs):
    question_id = data.get('to_question_id')
    if not question_id:
        raise ProcessingException(description='Question id required', code=401)
    question = models.Question.query.filter_by(id=question_id).first()
    if not question:
        raise ProcessingException(description='Question doesnt exist',
                                  code=401)
    shop_id = question.about_product.shop.id
    shop = models.Shop.query.filter_by(id=shop_id).first()
    if not shop.owner == current_user:
        raise ProcessingException(description='Not your shop', code=401)
    data['user_id'] = current_user.id
Пример #9
0
def login_user_if_possible(data, *args, **kwargs):
    if "user_email" in data and "user_password" in data:
        email = data["user_email"]
        password = data["user_password"]
        user = models.User.query.filter_by(email=email).first()
        if not user:
            raise ProcessingException(description='unauthorized', code=401)
        if not verify_password(password, user.password):
            raise ProcessingException(description='unauthorized', code=401)
        login_user(user)
        del data["user_password"]
        if 'user_name' in data:
            del data['user_name']
        del data['user_email']
        data["user_id"] = user.id
Пример #10
0
        def decorated(*args, **kwargs):

            if _g and _g.user and has_roles(_g.user, requirements):
                return f(*args, **kwargs)
            else:
                raise ProcessingException(description='Not authenticated!',
                                          code=401)
Пример #11
0
def post_preprocessor(data, **kwargs):
    form = CommentForm(data=data)
    if form.validate():
        return form.data
    else:
        raise ProcessingException(description='Invalid form submission.',
                                  code=400)
Пример #12
0
def prep(search_params=None, **kw):
    if search_params is None:
        return
    if 'filters' not in search_params:
        return
    filters = search_params['filters']
    if len(filters) != 1:
        return
    filter = filters[0]
    if 'name' not in filter:
        return
    if filter['name'] != 'scholar_id':
        return
    if filter['op'] != '==':
        return
    scholar_id = filter['val']
    publication = Publication.query.filter_by(scholar_id=scholar_id).first()
    if (publication is None or publication.retrieved_at is None):
        queue = taskqueue.Queue('publication-fetchers')
        task = taskqueue.Task(url='/publication/crawl',
                              params={'scholar_id': scholar_id})
        queue.add(task)
        raise ProcessingException(description='Try later.', code=202)
    elif (datetime.now() - publication.retrieved_at).days > 365:
        queue = taskqueue.Queue('publication-fetchers')
        task = taskqueue.Task(url='/publication/crawl',
                              params={'scholar_id': scholar_id})
        queue.add(task)
Пример #13
0
def process_new_user(data=None, **kw):
    if 'password' not in data:
        raise ProcessingException(description='No password.', code=400)

    password = data['password']
    data['hashed_password'] = bcrypt.encrypt(password, rounds=12, ident='2y')
    del data['password']
Пример #14
0
def is_authorized(*args, **kwargs):
    if 'token' not in request.args:
        raise ProcessingException(description='No token or user id.', code=400)

    token = request.args['token']

    try:
        user = User.query.filter(User.token == token).one()
    except NoResultFound:
        raise ProcessingException(description='Bad authentication.', code=401)
    except MultipleResultsFound:
        raise ProcessingException(description='Server state inconsistent.',
                                  code=500)

    # log this user in for the remainder of the request
    g.user = user
Пример #15
0
def authorize_modelrun(id):
    modelrun = ModelRun.query.get(id)
    #print modelrun
    #raise ProcessingException(description='You are not authorized to access this ModelRun', code=401)
    if modelrun and modelrun.user_id != current_identity.id:
        raise ProcessingException(
            description='You are not authorized to access this ModelRun',
            code=401)
Пример #16
0
    def get_allergies_by_list(list_of_ids):
        AllergyArray = db.session.query(Allergy).filter(
            Allergy.id.in_(list_of_ids)).all()

        if len(list_of_ids) != len(AllergyArray):
            raise ProcessingException(
                description='Invalid allergy_id in array', code=400)
        return AllergyArray
Пример #17
0
 def logged_in(cls, **kwargs):
     user_logged_in = False
     if not current_user.is_authenticated():
         raise ProcessingException(
             description='Not Authorized. Please log in first.', code=401)
     elif current_user.is_authenticated():
         user_logged_in = True
     return user_logged_in
Пример #18
0
    def get_categories_by_list(list_of_ids):
        CategoryArray = db.session.query(Category).filter(
            Category.id.in_(list_of_ids)).all()

        if len(list_of_ids) != len(CategoryArray):
            raise ProcessingException(
                description='Invalid category_id in array', code=400)
        return CategoryArray
Пример #19
0
def malt_verify(data):
    errors = []
    verify_is_set(data, "name", errors)
    verify_is_number(data, "ppg", errors)
    verify_is_number(data, "color", errors)

    if errors:
        raise ProcessingException(message=errors, status_code=400)
Пример #20
0
def brew_put_preprocessor(instid, data):

    brew = Brew.query.get(instid)
    print brew.user_id

    if not g.user.is_authenticated() or brew.user_id != g.user.id:
        raise ProcessingException(message='Not Authorized', status_code=401)

    return data
Пример #21
0
 def basic_crm_admin(cls, **kwargs):
     user_logged_in = cls.logged_in()
     allowable_roles = ('basic', 'super', 'master')
     if user_logged_in:
         if current_user.crm_role not in allowable_roles:
             raise ProcessingException(
                 description=
                 'Not Authorized. Basic CRM admin permissions or higher '
                 'required.',
                 code=401)
Пример #22
0
 def master_oms_admin(cls, **kwargs):
     user_logged_in = cls.logged_in()
     allowable_roles = ('master')
     if user_logged_in:
         if current_user.oms_role not in allowable_roles:
             raise ProcessingException(
                 description=
                 'Not Authorized. Master OMS admin permissions or higher '
                 'required.',
                 code=401)
Пример #23
0
 def super_admin(cls, **kwargs):
     user_logged_in = cls.logged_in()
     allowable_roles = ('super', 'master')
     if user_logged_in:
         if current_user.admin_role not in allowable_roles:
             raise ProcessingException(
                 description=
                 'Not Authorized. Super administrative permissions or higher '
                 'required.',
                 code=401)
Пример #24
0
def check_if_user_exists(data, *args, **kwargs):
    if current_user.is_authenticated():
        data["user_id"] = current_user.id
        return
    user_name = data.get('user_name')
    user_email = data.get('user_email')
    user_legacy_email = None
    if 'user_legacy_email' in data:
        user_legacy_email = data.get('user_legacy_email')
        del data['user_legacy_email']

    if not user_name:
        raise ProcessingException(
            description=ExceptionMessages.MISSING_PARAM.format(
                param='user_name'),
            code=401)

    if not user_email:
        raise ProcessingException(
            description=ExceptionMessages.MISSING_PARAM.format(
                param='user_email'),
            code=401)

    user, is_new = models.User.get_or_create_by_email(
        email=user_email,
        role_name=Constants.REVIEWER_ROLE,
        user_legacy_email=user_legacy_email,
        name=user_name)
    if not is_new:
        # TODO maybe display a passwd field if user is not new?
        raise ProcessingException(description=ExceptionMessages.USER_EXISTS %
                                  user_email,
                                  code=401)

    db.session.add(user)
    db.session.commit()
    login_user(user)

    if 'user_name' in data:
        del data['user_name']
    del data['user_email']
    data['user_id'] = user.id
Пример #25
0
def verify_request_by_shop_owner(data, *args, **kwargs):
    shop_id = data.get('shop_id')
    if not shop_id:
        raise ProcessingException(
            description=ExceptionMessages.MISSING_PARAM.format(
                param='shop_id'),
            code=httplib.BAD_REQUEST)
    if not str(shop_id).isdigit():
        raise ProcessingException(
            description=ExceptionMessages.PARAM_NOT_INTEGER.format(
                param='shop_id'),
            code=httplib.BAD_REQUEST)
    shop = models.Shop.query.filter_by(id=shop_id).first()
    if not shop:
        raise ProcessingException(
            description=ExceptionMessages.INSTANCE_NOT_EXISTS.format(
                instance='shop', id=shop_id),
            code=httplib.BAD_REQUEST)
    if not shop.owner == current_user:
        raise ProcessingException(description=ExceptionMessages.NOT_YOUR_SHOP,
                                  code=httplib.UNAUTHORIZED)
Пример #26
0
def updated_since_filter(search_params=None, **kwargs):
    if 'updated_since' in request.args:
        #parse iso datetime
        try:
            date = dateutil.parser.parse(request.args.get('updated_since'))
        except (ValueError, TypeError):
            raise ProcessingException(message='Unable to parse updated_since parameter. Must be ISO datetime format')

        #filter on update time
        filt = dict(name='updated_at', op='gt', val=date)
        if 'filters' not in search_params:
            search_params['filters'] = []
        search_params['filters'].append(filt)
Пример #27
0
    def post_single_preprocessor(data=None, **kw):
        getReview = Review.query.filter(
            Review.user_id == current_user.id,
            Review.dish_id == data['dish_id']).first()
        if getReview is not None:
            raise ProcessingException(
                description=
                'Er is al een review gevonden voor deze gebruiker: Review met ID %r'
                % getReview.id,
                code=400)

        data['user_id'] = current_user.id
        return data
Пример #28
0
    def post_single_preprocessor(data=None, **kw):
        pass_length = 8

        # Check if provided email address already exists
        getUser = User.query.filter(User.email == data['email']).first()
        if getUser is not None:
            raise ProcessingException(
                description='Emailadres bestaat al: %r' % getUser.email,
                code=400
            )

        # Password length check
        if len(data['password']) < pass_length:
            raise ProcessingException(
                description='Wachtwoord moet minimaal %r tekens lang zijn' % pass_length,
                code=400
            )

        # Hash password
        data['password'] = HashValidator.hash(data['password'])
        data['credit'] = 200
        return data
Пример #29
0
def auth_func(*args, **kwargs):
    users = get_model('Users')
    access_token = request.values.get("access_token")

    # Less secure version
    user = users.query.filter_by(auth_key=access_token, active=True).first()

    # More secure version
    # uid = request.values.get("uid")
    # user = users.query.filter_by(auth_key=access_token, id=uid, active=True).first()

    if not user:
        raise ProcessingException('Not Authorized', 401)
Пример #30
0
    def post_single_preprocessor(data=None, **kw):
        getMeal = Meal.query.get(data['meal_id'])
        if getMeal is None:
            raise ProcessingException(description='Meal does not exist',
                                      code=400)

        if current_user.credit is None or current_user.credit < (
                data['amount_meals'] * getMeal.price):
            raise ProcessingException(
                description='Je hebt niet genoeg geld in je portemonnee!',
                code=400)

        if data['amount_meals'] > (getMeal.portions -
                                   getMeal.portions_claimed):
            raise ProcessingException(
                description=
                'Er zijn niet genoeg maaltijden om aan je te reserveren',
                code=400)

        data['total_amount'] = getMeal.price * data['amount_meals']
        data['user_id'] = current_user.id

        return data