Esempio n. 1
0
def sign_up_valid(form):
    if not (form.get("username", None) or form.get("mobile", None)
            or form.get("email", None)):

        raise flask_restless.ProcessingException(description=u'用户名/手机/电子邮件 错误',
                                                 code=400)
    elif not form.get("password", None):
        raise flask_restless.ProcessingException(description=u'密码 错误',
                                                 code=400)
    else:
        form["password"] = hash_password(form.get("password", None))
Esempio n. 2
0
def pre_get_many(search_params=None, **kwargs):
    if search_params is None:
        search_params = {}
    if not search_params.get('order_by'):
        # Impose the default reverse-chronological order if order_by is not explicitly given.
        search_params['order_by'] = [{'field': 'id', 'direction': 'desc'}]

    if 'filters' not in search_params:
        search_params['filters'] = []
    query_params = flask.request.args

    if len(query_params.getlist('year')) > 1:
        raise flask_restless.ProcessingException(
            description='More than one year specified.')
    year = query_params.get('year')
    if year:
        if not YEAR_PATTERN.match(year):
            raise flask_restless.ProcessingException(
                description="Invalid year '{}'.".format(year))
        search_params['filters'].append(
            dict(name='title', op='like', val='{}%'.format(year)))

    if len(query_params.getlist('team')) > 1:
        raise flask_restless.ProcessingException(
            description='More than one team specified.')
    team = query_params.get('team')
    if team:
        search_params['filters'].append(dict(name='team', op='==', val=team))

    if len(query_params.getlist('stage')) > 1:
        raise flask_restless.ProcessingException(
            description='More than one stage specified.')
    stage = query_params.get('stage')
    if stage:
        if stage == 'special':
            search_params['filters'].append(
                dict(name='special', op='==', val=True))
        else:
            search_params['filters'].append(
                dict(name='stage', op='==', val=stage))

    if len(query_params.getlist('member')) > 1:
        raise flask_restless.ProcessingException(
            description='More than one member specified.')
    member = query_params.get('member')
    if member:
        search_params['filters'].append(
            dict(name='performers', op='like', val='%{},%'.format(member)))
Esempio n. 3
0
def auth():
    username = flask.request.json.get('username')
    password = flask.request.json.get('password')

    # check if the user is in any of the tables
    matches = Customer.query.filter_by(username=username,
                                       password=password).all()
    matches += Deliveryperson.query.filter_by(username=username,
                                              password=password).all()
    matches += Restaurant.query.filter_by(username=username,
                                          password=password).all()
    if len(matches) > 0:
        # generate a token (this is obviously an insecure way of doing so)
        token = md5(password.encode('utf-8')).hexdigest()
        # store token in database
        dbentry = Token(username=username, token=token)
        db.session.add(dbentry)
        db.session.commit()

        # hand the token to the API client
        return flask.jsonify(token=token)

    # no matching user found
    raise flask_restless.ProcessingException(description='Not Authorized',
                                             code=401)
Esempio n. 4
0
def auth_func(**kw):
    token = flask.request.headers.get('Authorization')
    # search token in databasae
    matches = Token.query.filter_by(token=token).all()
    if len(matches) == 0:
        raise flask_restless.ProcessingException(description='Not Authorized',
                                                 code=401)
Esempio n. 5
0
def post_deployment_preprocessor(data=None, **kw):
    """
    It verifies that an executable can be uploaded to the testbed
    """

    # We verify the id is in the right format
    if 'testbed_id' in data:
        if 'executable_id' in data:

            # We verify that the testbed exists in the database
            testbed = db.session.query(Testbed).filter_by(
                id=data['testbed_id']).first()

            if testbed:
                # We verify now that the executable_id is present in the db
                executable = db.session.query(Executable).filter_by(
                    id=data['executable_id']).first()

                if executable:
                    # We verify that the testbed is on-line
                    if testbed.on_line:
                        pass
                    else:
                        raise flask_restless.ProcessingException(
                            description=
                            'Testbed is off-line, this process needs to be performed manually',
                            code=403)
                else:
                    raise flask_restless.ProcessingException(
                        description=
                        'No executable found with that id in the database',
                        code=400)
            else:
                raise flask_restless.ProcessingException(
                    description='No testbed found with that id in the database',
                    code=400)
        else:
            raise flask_restless.ProcessingException(
                description='Missing executable_id field in the inputed JSON',
                code=400)
    else:
        raise flask_restless.ProcessingException(
            description='Missing testbed_id field in the inputed JSON',
            code=400)
Esempio n. 6
0
def patch_execution_preprocessor(instance_id=None, data=None, **kw):
    """
    It allows to change the status of a running execution
    """

    execution = db.session.query(Execution).filter_by(id=instance_id).first()

    if execution:

        if 'status' in data:
            if data['status'] == Execution.__status_cancel__:
                url = execution.execution_configuration.testbed.endpoint
                executor.cancel_execution(execution, url)
            elif data['status'] == Execution.__status_stop__ or data[
                    'status'] == Execution.__status_restart__:
                if (execution.status == Execution.__status_running__
                        or execution.status == Execution.__status_restarted__
                        or execution.status == Execution.__status_restart__
                    ) and data['status'] == Execution.__status_stop__:
                    executor.stop_execution(execution)
                elif (execution.status == Execution.__status_stopped__
                      or execution.status == Execution.__status_stop__
                      ) and data['status'] == Execution.__status_restart__:
                    executor.restart_execution(execution)
                else:
                    description = 'Execution is not in right state'
                    raise flask_restless.ProcessingException(
                        description=description, code=409)
            else:
                raise flask_restless.ProcessingException(
                    description='No valid state to try to change', code=409)
        elif 'add_resource' in data:
            executor.add_resource(execution)
        elif 'remove_resource' in data:
            executor.remove_resource(execution)
        else:
            raise flask_restless.ProcessingException(
                description=
                'No status, remove_resource, or add_resource field in the payload',
                code=409)
    else:
        raise flask_restless.ProcessingException(
            description='No execution by the given id', code=409)
Esempio n. 7
0
def post_testbed_preprocessor(data=None, **kw):
    """
    It checks the data in the testbed payload to check if it is possible to
    add nodes to if necessaryexi
    """

    if 'nodes' in data:
        create = can_create_the_node(testbed=data)

        if not create['create']:
            raise flask_restless.ProcessingException(
                description=create['reason'], code=405)
Esempio n. 8
0
def check_permissions(**kw):
    if current_user.sysadmin == 1:
        return
    # extracting tablename from URL
    table_name = request.path.split("/")[-1:][0]
    curr_user = current_user.id if hasattr(current_user, "id") else None
    table = tables.query.filter(func.lower(tables.name) == table_name).first()
    permission = permissions.query.filter_by(table_id=table.id,
                                             user_id=curr_user).first()
    if permission is None:
        raise flask_restless.ProcessingException(code=401)
    if request.method == "GET" and permission.read_flag == 1:
        return
    elif request.method == "PUT" and permission.edit_flag == 1:
        return
    elif request.method == "POST" and permission.edit_flag == 1:
        return
    elif request.method == "DELETE" and permission.delete_flag == 1:
        return
    else:
        raise flask_restless.ProcessingException(code=401)
Esempio n. 9
0
def put_testbed_preprocessor(instance_id=None, data=None, **kw):
    """
    It is going to check if the testbed allows the creation of nodes
    """

    if instance_id != None:

        if 'nodes' in data:
            create = can_create_the_node(testbed_id=instance_id)

            if not create['create'] and create['reason'] != no_testbed:
                raise flask_restless.ProcessingException(
                    description=create['reason'], code=405)
Esempio n. 10
0
def patch_execution_script_preprocessor(instance_id=None, data=None, **kw):
    """
    It is going to start the execution of an application in the selected testbed
    """

    if 'launch_execution' in data:
        if data['launch_execution']:
            execution_script = db.session.query(
                ExecutionConfiguration).filter_by(id=instance_id).first()

            deployment = db.session.query(Deployment).filter_by(
                executable_id=execution_script.executable_id,
                testbed_id=execution_script.testbed_id).first()

            if not deployment:
                raise flask_restless.ProcessingException(
                    description=
                    'No deployment configured to execute the application',
                    code=409)

            elif not execution_script.testbed.on_line:
                raise flask_restless.ProcessingException(
                    description='Testbed does not allow on-line connection',
                    code=403)

            else:
                create_profile = False
                use_storaged_profile = False
                if 'create_profile' in data:
                    if data['create_profile']:
                        create_profile = True
                elif 'use_storaged_profile' in data:
                    if data['use_storaged_profile']:
                        if execution_script.profile_file:
                            use_storaged_profile = True

                executor.execute_application(execution_script, create_profile,
                                             use_storaged_profile)
Esempio n. 11
0
def check_user_mod(app, instance_id=None, data=None, **kw):  # pylint: disable=unused-argument
    """ Check authentication status """
    if not instance_id:
        raise flask_restless.ProcessingException(
            description='No instance ID specified', code=400)

    mod_subject = User.query.get(instance_id)
    if not mod_subject:
        raise flask_restless.ProcessingException(description='Unknown subject',
                                                 code=404)

    if current_user.is_anonymous:
        raise flask_restless.ProcessingException(
            description='Operation requires login.', code=401)

    if 'roles' in data:
        if not current_user.is_admin:
            raise flask_restless.ProcessingException(
                description='Only admins may edit roles', code=401)
    else:
        # check general modification constraints
        if not current_user.can_modify(mod_subject):
            raise flask_restless.ProcessingException(
                description='Operation not allowed', code=401)
Esempio n. 12
0
def post_and_patch_application_preprocessor(data=None, **kw):
    """
    It is going to start the execution of an application in the selected testbed
    """

    app_types = current.config['APP_TYPES']

    if 'application_type' in data:
        if data['application_type'] in app_types:
            pass
        else:
            raise flask_restless.ProcessingException(
                description='Application type ' + data['application_type'] +
                ' not supported',
                code=406)
Esempio n. 13
0
def post_patch_auth_func(**kw):
    if not current_identity.id != kw["data"]["user_id"]:
        raise flask_restless.ProcessingException(
            description='Not authenticated!', code=401)
    kw["data"]["updated_at"] = datetime.utcnow()
Esempio n. 14
0
def check_user_mod_many(app, search_params=None, data=None, **kwargs):  # pylint: disable=unused-argument
    """ Check authentication status """
    if current_user.is_anonymous or not current_user.is_admin:
        raise flask_restless.ProcessingException(description='Not Authorized',
                                                 code=401)
Esempio n. 15
0
def post_patch_many_auth_func(**kw):
    if not current_identity.auth != 0:
        raise flask_restless.ProcessingException(
            description='Not authenticated!', code=401)
Esempio n. 16
0
def pre_get_single(instance_id=None, **kwargs):
    raise flask_restless.ProcessingException(
        description='Single resource requests disabled.')
Esempio n. 17
0
def check_db_connectivity(**kw):
    if not check_tcp_socket(app.config['DATABASE_URL'], 3306):
        raise flask_restless.ProcessingException(
            description='Database Connectivity Error', code=500)
Esempio n. 18
0
def caching_preprocessor(**kwargs):
    key = cache_key()
    cached_result = cache.get(key)
    if cached_result:
        raise flask_restless.ProcessingException(
            response=json.loads(cached_result), code=200)
Esempio n. 19
0
def auth_func(**kwargs):
    if flask.request.headers.get('X-Secret-Key', '') != access_password:
        raise flask_restless.ProcessingException(
            description='Not authenticated!', code=401)
Esempio n. 20
0
def user_auth_func(**kw):
    if not current_identity.id != kw["data"]["user_id"]:
        raise flask_restless.ProcessingException(
            description='Not authenticated!', code=401)
Esempio n. 21
0
def get_user_list(**kw):
    if current_identity.auth != 0:
        raise flask_restless.ProcessingException(
            description='Not authenticated!', code=401)
Esempio n. 22
0
def check_role_mod():
    """ Check that current user can modify roles """
    if current_user.is_anonymous or not current_user.is_admin:
        raise flask_restless.ProcessingException(description='Not Authorized',
                                                 code=401)