示例#1
0
def pre_check_duplicate_userid(instance_id=None, data=None, **kw):

    if "user_status" in data:
        if data['user_status'] == 2:
            pass
        else:
            check_token()
    else:
        check_token()

    if "user_pw" in data:
        data['user_pw'] = password_encoder_512(data['user_pw'])

    if "user_id" in data:
        chk_user = Users.query.filter(Users.user_id == data['user_id']).first()

        if instance_id is None:  # Post
            if chk_user is not None:
                raise ProcessingException(description="User ID is duplicated",
                                          code=413)
        else:  # Patch
            if (chk_user is not None) and (int(instance_id) != chk_user.id):
                raise ProcessingException(description="User ID is duplicated",
                                          code=413)

        data['token'] = generate_token(data['user_id'])
示例#2
0
    def post_order(**kwargs):
        current_user = User.query.filter_by(email=get_jwt_identity()).first()
        if not current_user:
            raise ProcessingException(
                description='Order could not be processed', code=500)
        request.json['user_id'] = current_user.id

        clean_unexpected(request, ['menu_item_id', 'user_id', 'quantity'])
        fields = request.json

        if fields.get('menu_item_id') is None:
            raise ProcessingException(description='Menu item id is required',
                                      code=400)

        # set a default quantity
        if fields.get('quantity') is None:
            request.json['quantity'] = 1

        menu_item = MenuItem.query.get(fields['menu_item_id'])
        if menu_item is None:
            raise ProcessingException(
                description='No menu item found for that menu_item_id',
                code=400)

        menu = Menu.query.get(menu_item.menu_id)
        if menu.day != datetime.utcnow().date():
            raise ProcessingException(description='This menu is expired',
                                      code=400)
示例#3
0
def check_information(data):
    """Ensures. a user has the rights to create/edit an abject
    in a specific organization.
    Checks also the validity of the submitted JSON object against the specified
    the JSON schema.
    """
    schema_id = data.get("schema_id", None)
    org_id = data.get("org_id", None)

    if org_id is None:
        raise ProcessingException(
            description="You must provide the id of an organization.",
            code=400)
    if org_id not in [org.id for org in current_user.organizations]:
        raise ProcessingException(
            description=
            "You are not allowed to create/edit object from this organization.",
            code=400,
        )

    if schema_id is None:
        raise ProcessingException(
            description="You must provide the id of a schema.", code=400)
    schema = Schema.query.filter(Schema.id == schema_id)
    if not schema.count():
        raise ProcessingException(description="Bad schema id", code=400)
    try:
        # check the validity of the submitted object
        # (note: an empty JSON object is validated by any schema)
        jsonschema.validate(data.get("json_object", {}),
                            schema.first().json_schema)
    except Exception:
        raise ProcessingException(
            description="The object submited is not validated by the schema.",
            code=400)
示例#4
0
    def post_meal(**kwargs):
        clean_unexpected(request, ['name', 'cost', 'quantity', 'img_path'])

        fields = request.json
        if fields.get('name') is None:
            raise ProcessingException(description='Name is required', code=400)

        if len(fields.get('name').strip()) == 0:
            raise ProcessingException(description='Invalid meal name',
                                      code=400)

        if fields.get('cost') is None:
            raise ProcessingException(description='Cost is required', code=400)

        if fields.get('img_path') is None:
            request.json['img_path'] = None

        try:
            float(fields.get('cost'))
        except:
            raise ProcessingException(description='Cost must be numeric',
                                      code=400)

        meal = Meal.query.filter_by(name=fields['name']).first()
        if meal:
            raise ProcessingException(description='Meal name must be unique',
                                      code=400)
示例#5
0
    def put_meal(instance_id=None, **kwargs):
        clean_unexpected(request, ['name', 'cost', 'quantity', 'img_path'])

        fields = request.json
        if len(fields) == 0:
            raise ProcessingException(description="Nothing to update",
                                      code=400)

        if 'name' in fields:
            if len(fields.get('name').strip()) == 0:
                raise ProcessingException(description='Invalid meal name',
                                          code=400)

            # check if another meal has the new name...
            meal = Meal.query.filter_by(name=fields['name']).first()
            if meal and meal.id != instance_id:
                raise ProcessingException(
                    description='Meal name must be unique', code=400)

        if 'cost' in fields:
            try:
                float(fields.get('cost'))
            except:
                raise ProcessingException(description='Cost must be numeric',
                                          code=400)
示例#6
0
文件: query.py 项目: lyfgift/IMS
def permission_check(*args, **kwargs):
    """
    restless全局preprocessor.
    签名校验
    验证当前表最低访问权限
    """
    # print('###########permission_check#################')
    try:
        id = int(request.args.get('module_id', None))
        sign = base64.b64decode(request.args.get('signature',
                                                 None))  # sign通过base64编码上传
        if id is None:
            raise ProcessingException('module id is required', 400)
        if sign is None:
            raise ProcessingException('signature is required', 400)
        mod = module_manager(id)  # 实例化module_manager
    except Exception:
        raise ProcessingException('module_id is invalid', 400)
    v = mod.verify(sign)
    if not v:
        raise ProcessingException('sign verify failed', 403)
    table = request.path.split('/')[2]
    if not mod.have_query_permission(table):
        raise ProcessingException('query is refused', 403)
    request.mod = mod
    request.table = table
示例#7
0
def game_patch_single_preprocessor(instance_id=None, data=None, **kw):
    hangman = Hangman.query.get(instance_id)

    if hangman == None:
        raise ProcessingException(
            description="Game {} does not exist".format(instance_id), code=404)

    if hangman.user_id != get_jwt_identity():
        raise ProcessingException(
            description="User doesn't own game {}".format(instance_id),
            code=403)

    if hangman.status != 'ACTIVE':
        raise ProcessingException(
            description="Game {} is not playable".format(instance_id),
            code=422)

    try:
        hangman.set_user_guess(data['user_guess'])
    except Exception as e:
        raise ProcessingException(description=str(e), code=422)

    # Filter data dictionary
    accepted_keys = ['user_guess']
    # Can not iterate and delete dict keys since data.keys() returns iterable so we convert to list
    for key in list(data.keys()):
        if key not in accepted_keys:
            del data[key]
示例#8
0
    def put_order(instance_id=None, **kwargs):
        current_user = User.query.filter_by(email=get_jwt_identity()).first()
        if not current_user:
            raise ProcessingException(
                description='Order could not be processed', code=500)

        order = Order.query.get(instance_id)
        if order.user_id != current_user.id:
            raise ProcessingException(
                description='This user cannot edit this order', code=401)

        clean_unexpected(request, ['menu_item_id', 'quantity'])
        fields = request.json

        if 'menu_item_id' in fields:
            menu_item = MenuItem.query.get(fields['menu_item_id'])
            if menu_item is None:
                raise ProcessingException(
                    description='No menu item found for that menu_item_id',
                    code=400)

            menu = Menu.query.get(menu_item.menu_id)
            if menu.day != datetime.utcnow().date():
                raise ProcessingException(description='This menu is expired',
                                          code=400)
示例#9
0
    def post_menu_item(**kwargs):
        clean_unexpected(request, ['meal_id', 'menu_id'])
        fields = request.json

        if fields.get('meal_id') is None:
            raise ProcessingException(description='Meal id is required',
                                      code=400)

        if fields.get('menu_id') is None:
            raise ProcessingException(description='Menu id is required',
                                      code=400)

        meal = Meal.query.get(fields['meal_id'])
        if not meal:
            raise ProcessingException(
                description='No meal found for that meal_id', code=400)

        menu = Menu.query.get(fields['menu_id'])
        if not menu:
            raise ProcessingException(
                description='No menu found for that menu_id', code=400)

        menu_item = MenuItem.query.filter_by(menu_id=menu.id,
                                             meal_id=meal.id).first()
        if menu_item:
            raise ProcessingException(
                description='This menu item already exists', code=400)
def user_auth_func(instance_id=None, **kw):
    if not instance_id:
        raise ProcessingException(description='Not Authorized', code=401)
    if not instance_id == current_user.get_id():
        raise ProcessingException(description='Not Authorized', code=401)
    if not current_user.is_authenticated:
        raise ProcessingException(description='Not Authorized', code=401)
示例#11
0
    def put_menu_item(instance_id=None, **kwargs):
        clean_unexpected(request, ['meal_id', 'menu_id'])
        fields = request.json

        if len(fields) == 0:
            raise ProcessingException(description='Nothing to update',
                                      code=400)

        if 'meal_id' in fields:
            meal = Meal.query.get(fields['meal_id'])
            if not meal:
                raise ProcessingException(
                    description='No meal found for that meal_id', code=400)

        if 'menu_id' in fields:
            menu = Menu.query.get(fields['menu_id'])
            if not menu:
                raise ProcessingException(
                    description='No menu found for that menu_id', code=400)

        # ensure the same menu item is not added twice...
        menu_item = MenuItem.query.filter_by(menu_id=menu.id,
                                             meal_id=meal.id).first()
        if menu_item and instance_id != menu_item.id:
            raise ProcessingException(
                description='This menu item already exists', code=400)
示例#12
0
def auth_func(*args, **kw):
    """
    Pre-processor used to check if a user is authenticated.
    """
    if current_user.is_authenticated:
        return

    user = None
    if request.headers.get("Authorization", False):
        token = request.headers.get("Authorization").split(" ")[1]
        user = User.query.filter(User.apikey == token).first()

    if request.authorization:
        user = User.query.filter(
            User.login == request.authorization.username).first()
        if user and not user.check_password(request.authorization.password):
            raise ProcessingException("Couldn't authenticate your user",
                                      code=401)

    if not user:
        raise ProcessingException("Couldn't authenticate your user", code=401)
    if not user.is_active:
        raise ProcessingException("Couldn't authenticate your user", code=401)

    login_user_bundle(user)
示例#13
0
    def patch_single_preprocessor(admin, instance_id=None, data=None, **kw):
        """Accepts two arguments, `instance_id`, the primary key of the
        instance of the model to patch, and `data`, the dictionary of fields
        to change on the instance.

        """
        if instance_id and int(instance_id) not in get_group_ids(admin):
            raise ProcessingException(description='', code=404)
        if 'name' in data:
            if not group_regex.match(data['name']):
                raise ProcessingException(description='Accented and special characters are forbidden, except hyphen', code=400)
    def post_preprocessor(admin, data=None, **kw):
        """Accepts a single argument, `data`, which is the dictionary of
        fields to set on the new instance of the model.

        """
        if 'group_id' not in data or 'action_id' not in data:
            raise ProcessingException(description='', code=400)

        if data['group_id'] not in get_group_ids(admin) or \
           data['action_id'] not in get_action_ids(admin):
            raise ProcessingException(description='', code=403)
示例#15
0
def check_token_single(search_params=None, **kw):
    parser = reqparse.RequestParser()
    parser.add_argument("token", type=str, location="headers")
    token = parser.parse_args()["token"]

    if token is None:
        raise ProcessingException(description="Not Authorized", code=410)

    user = Users.query.filter_by(token=token).first()
    if user is None:
        raise ProcessingException(description="Not Authorized", code=411)
示例#16
0
    def post_menu(**kwargs):
        clean_unexpected(request, ['category'])
        fields = request.json

        if fields.get('category') is None:
            raise ProcessingException(description='Category is required',
                                      code=400)

        if fields.get('category') not in \
                [MenuType.BREAKFAST, MenuType.LUNCH, MenuType.SUPPER]:
            raise ProcessingException(description='Unknown meal type',
                                      code=400)
示例#17
0
    def put_menu(instance_id=None, **kwargs):
        clean_unexpected(request, ['category'])
        fields = request.json

        if fields.get('category') is None:
            raise ProcessingException(description='Nothing to update',
                                      code=400)

        if fields.get('category') not in \
                [MenuType.BREAKFAST, MenuType.LUNCH, MenuType.SUPPER]:
            raise ProcessingException(description='Unknown meal type',
                                      code=400)
示例#18
0
def auth_required(data=None, **kwargs):
    if 'Authorization' in request.headers:
        token = request.headers.get('Authorization')
    elif data and 'token' in data:
        token = data.pop('token', None)
    else:
        raise ProcessingException(description="Authorization Token Required",
                                  code=401)
    user = User.verify_auth_token(token)
    if not user:
        raise ProcessingException(description="Invalid Authorization Token",
                                  code=401)
    g.user = user
示例#19
0
    def patch_single_preprocessor(admin, instance_id=None, data=None, **kw):
        """Accepts two arguments, `instance_id`, the primary key of the
        instance of the model to patch, and `data`, the dictionary of fields
        to change on the instance.

        """
        if instance_id and int(instance_id) not in get_contact_ids(admin):
            raise ProcessingException(description='', code=404)
        if 'phone_number' in data:
            if not valid_prefix_number(data['phone_number'],
                                       config.sms.prefix_filter):
                raise ProcessingException(
                    description='Phone number prefix not allowed', code=422)
示例#20
0
def auth(**kw):
    # Keyword parameter 'token' is used for download authentication.
    if ('token' not in request.args) and ('auth' not in request.headers):
        raise ProcessingException(description='Unauthorized.')
    try:
        token = request.args.get('token', None) or request.headers['auth']
        data = ser.loads(token.encode('ascii'))
    except BadSignature:
        raise ProcessingException(description='Oops, something went wrong with your token...')
    except SignatureExpired:
        raise ProcessingException(description='Your token has expired.', code=400)

    g.user = User.query.filter_by(username=data['username']).first()
示例#21
0
def preprocessors_patch(instance_id=None, data=None, **kargs):
    user_cant_change = ["admin", "clid", "id_",
                        "originated_calls", "received_calls, tunel"]
    admin_cant_change = ["id_", "originated_calls", "received_calls"]
    if current_user.is_admin:
        for x in data.keys():
            if x in admin_cant_change:
                raise ProcessingException(description='Forbidden', code=403)
    elif current_user.username == instance_id:
        for x in data.keys():
            if x in user_cant_change:
                raise ProcessingException(description='Forbidden', code=403)
    else:
        raise ProcessingException(description='Forbidden', code=403)
示例#22
0
def owner_single(instance_id=None, **kw):
    """
    Checks if the current user is the owner of the post.
    Raises an exception if not found or the current user isn't the user.
    Note that this fucntion should always be associated with the auth_required preprocessor.

    :param instance_id: The instance id of the post
    """
    post = Post.query.filter_by(id=instance_id).first()
    if post:
        if post.user != g.user:
            raise ProcessingException(description="Not Authorized", code=401)
    else:
        raise ProcessingException(description="Not Found", code=404)
示例#23
0
def token_check():
    auth = request.headers.get('Authorization')
    user = None
    if auth:
        user = models.User.verify_auth_token(auth)
        g.user = user
    if not auth:
        raise ProcessingException(
            "You must log in to view this page or perform this action",
            code=401)
    elif not user:
        raise ProcessingException("Token invalid or expired", code=401)

    return user
示例#24
0
    def patch_single_preprocessor(admin, instance_id=None, data=None, **kw):
        """Accepts two arguments, `instance_id`, the primary key of the
        instance of the model to patch, and `data`, the dictionary of fields
        to change on the instance.

        """
        if instance_id:
            if int(instance_id) != admin.id and get_role(admin) != 'admin':
                raise ProcessingException(description='', code=404)
            # enforce access level
            if get_role(admin) == 'supervisor':
                if 'phone_number' in data:
                    raise ProcessingException(description='You don\'t have permission to change your phone_number', code=401)
                if 'level' in data and data['level'] != 2:
                    raise ProcessingException(description='You don\'t have permission to change your access level', code=401)
                # special case: supervisor ask for changing sms quota
                if 'sms_quota' in data:
                    data['sms_quota'] = '!%s' % data['sms_quota']
                if 'recipient_filter' in data:
                    raise ProcessingException(description='You don\'t have permission to change sms recipient filter', code=401)
                if 'login' in data:
                    raise ProcessingException(description='You don\'t have permission to change your login', code=401)
                if 'auth_backend' in data:
                    raise ProcessingException(description='You don\'t have permission to change your authentication backend', code=401)
            else:
                if admin.id == int(instance_id) and 'auth_backend' in data and data['auth_backend'] != 'local':
                    raise ProcessingException(description='Administrator must be a local account')
            if 'password' in data:
                data['password'] = hash_password(data['password'])
            if 'phone_number' in data:
                if not valid_prefix_number(data['phone_number'], config.sms.prefix_filter):
                    raise ProcessingException(description='Phone number prefix not allowed', code=422)
示例#25
0
    def get_single_preprocessor(admin, instance_id=None, **kw):
        """Accepts a single argument, `instance_id`, the primary key of the
        instance of the model to get.

        """
        if instance_id and int(instance_id) not in get_contact_notify_ids(admin):
            raise ProcessingException(description='Bad instance', code=404)
示例#26
0
    def delete_single_preprocessor(admin, instance_id=None, **kw):
        """Accepts a single argument, `instance_id`, which is the primary key
        of the instance which will be deleted.

        """
        if instance_id and int(instance_id) not in get_contact_notify_ids(admin):
            raise ProcessingException(description='Bad instance', code=404)
示例#27
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)
示例#28
0
def authn_func(*args, **kw):
    if current_user.is_authenticated():
        # FIXME: check that session exists and is not expired
        pass
    else:
        raise ProcessingException(description='Not authenticated', code=401)
    return True
示例#29
0
    def preprocess_post(**kw):

        submitter = kw['data']['submitter']
        iban = kw['data']['iban']
        description = kw['data']['description']
        receipts = kw['data']['receipts']

        kw['data']['date'] = str(datetime.now())

        errors = []

        if len(submitter or '\0') == 0:
            errors.append('Nimi on pakollinen kenttä.')

        try:
            IBAN(iban or '\0')
        except ValueError:
            errors.append('IBAN ei ole validi.')

        if len(description or '\0') == 0:
            errors.append('Maksun peruste tulee antaa.')

        if len(receipts) == 0:
            errors.append('Tositteita ei löytynyt.')

        if len(errors) > 0:
            raise ProcessingException(description='\n'.join(errors))

        for r in receipts:
            Receipt.check(**r)

        nrs = []
        for r in receipts:
            nrs.append(Receipt.preprocess(**r))
        kw['data']['receipts'] = nrs
示例#30
0
def check_object_creation_permission(data):
    """Check if the user is authenticated and set the creator_id."""
    if not current_user.is_authenticated:
        raise ProcessingException(description="Not authenticated!", code=401)

    data["creator_id"] = current_user.id
    check_information(data)