示例#1
0
    def post(self):
        parser = reqparse.RequestParser(bundle_errors=True)

        parser.add_argument('username', location='form', required=True)
        parser.add_argument('password', location='form', required=True)

        args = parser.parse_args()

        username_to_check = str(repr(args['username'])[2:-1])
        password_to_check = str(repr(args['password'])[2:-1])

        # DB cursor
        cursor = get_db_cursor()

        cursor, registered_user = get_account_by_username_and_password(
            cursor=cursor,
            username=username_to_check,
            password=password_to_check)

        if app.config["SUPER_DEBUG"]:
            logger.debug("registered_user: " + registered_user.__repr__())

        if registered_user is None:
            flash('Wrong Credentials')
            return {}, 301, {'Location': api.url_for(resource=SignIn)}
        else:
            login_user(registered_user, remember=False)
            flash('Logged in successfully')
            return {}, 301, {'Location': api.url_for(resource=Home)}
示例#2
0
def create_post(post_id=None):
    if current_user.importance == 0:
        flash('У вас нет доступа к данной странице', 'error')
        return redirect(url_for('index'))
    if request.method == 'POST':
        json = request.form.to_dict()
        if post_id:
            response = requests.put(api.url_for(PostResource,
                                                post_id=post_id,
                                                _external=True),
                                    json=json)
        else:
            json['author_id'] = current_user.get_id()
            response = requests.post(api.url_for(PostResource, _external=True),
                                     json=json)
            post_id = response.json()['post_id']
            subscribe_new_post(post_id)
        if response:
            return redirect(url_for('post.view_post', post_id=post_id))
        else:
            return make_response(jsonify(response.json()), 400)
    if post_id:
        post = Post.get_query().get(post_id)
        if current_user.importance == 2 or post.author.get_id(
        ) == current_user.get_id():
            return render_template('new_post.html', post=post)
        else:
            flash('Вы не можете редактировать этот пост', 'error')
            return redirect(url_for('post.view_post', post_id=post_id))
    return render_template('new_post.html')
示例#3
0
def subscribe():
    user_id = current_user.get_id()
    if current_user.subscription:
        requests.put(api.url_for(UserResource, user_id=user_id, _external=True),
                     json={'subscription': False})
    else:
        requests.put(api.url_for(UserResource, user_id=user_id, _external=True),
                     json={'subscription': True})
    return make_response(jsonify({
        'subscribe_status': current_user.subscription
    }), 200)
示例#4
0
 def delete(self, user_id):
     abort_if_user_not_found(user_id)
     session = db_session.create_session()
     user = session.query(User).get(user_id)
     session.delete(user)
     session.commit()
     for level in session.query(Level).filter(Level.author == user_id).all():
         requests.delete(api.url_for(LevelResource, level_id=level.id, _external=True))
     for res in session.query(Result).filter(Result.author == user_id).all():
         requests.delete(api.url_for(ResultResource, result_id=res.id, _external=True))
     return jsonify({'success': "OK"})
示例#5
0
def registration():
    register_form = RegisterForm()
    title = 'Регистрация'
    if register_form.validate_on_submit():
        response = requests.post(api.url_for(UserResource, _external=True),
                                 json=request.form.to_dict())
        if response:
            flash('Регистрация прошла успешно', 'success')
            user = User.get_query().get(response.json()['user_id'])
            login_user(user)
            result = send_confirm_message(user)
            if result['status']:
                flash(result['message'], 'warning')
            else:
                flash(result['message'], 'success')
            return make_response(jsonify({
                'redirect': True,
                'redirect_url': url_for('main.index')
            }), 200)
        else:
            errors = response.json()
            errors.pop('recaptcha_field', None)
            return make_response(jsonify(errors), response.status_code)
    elif request.method == 'POST' and not register_form.validate_on_submit():
        errors = register_form.errors
        errors.pop('recaptcha_field', None)
        return make_response(jsonify({'message': errors}), 400)
    elif request.method == 'GET':
        return render_template('registration.html', register_form=register_form, title=title)
示例#6
0
def delete_post(post_id):
    if current_user.importance == 0:
        return make_response(
            jsonify({'message': {
                'Ошибка': 'У вас нет прав не это действие'
            }}), 400)
    post = Post.get_query().get_or_404(post_id)
    if current_user.importance == 2 or post.author.get_id(
    ) == current_user.get_id():
        session = get_session()
        comments = post.comments.all()
        response = requests.delete(
            api.url_for(PostResource, post_id=post_id, _external=True))
        if not response:
            flash(response.json()['message'], 'error')
            return make_response(jsonify(response.json()),
                                 response.status_code)
        for comment in comments:
            session.delete(comment)
        session.commit()
        return make_response(jsonify({'status': 'OK'}), 200)
    else:
        return make_response(
            jsonify({'message': {
                'Ошибка': 'У вас нет прав не это действие'
            }}), 401)
    def post(self):
        # 接收前端发送的执行后台任务的请求
        # 接收前端发送来的userid、elementid
        elementid = request.json['elementid']
        userid = request.json['userid']
        # gather_subset="hardware" 只获取hardware的数据
        print(request.json)
        ansible_module_name = request.json['ansible_module_name']
        ansible_module_args = request.json['ansible_module_args']
        print(userid, "接收前端发送到后台的userid------")
        # 启动long_task后台任务,并将其放到celery中执行
        # iplist = ["192.168.204.131", "192.168.204.132", "192.168.204.133"]
        INVENTORY = current_app.config["INVENTORY_PATH"]
        ip_group = "ipv4_moniters"
        # runner的iplist参数可以使列表,也可以是inventory组名
        runner = Runner(resource=INVENTORY, ip_list=ip_group,
                        ansible_vault_key='devops')
        iplist = runner.get_all_hosts()
        module_name = ansible_module_name
        module_args = ansible_module_args
        # module_name = 'copy'
        # module_args = "src=%s dest=%s" % ('/tmp/1.txt', '/tmp/')
        str_ip_list = []
        for ip in iplist:
            str_ip_list.append(str(ip))

        task = long_task.delay(elementid, userid, iplist=str_ip_list, url=api.url_for(
            EventView, _external=True), module_name=module_name, module_args=module_args)
        return jsonify({"messege": "", "code": 200})
示例#8
0
def test_lookup_dictionaries(client):

    utils.generate_lookup_dict(_from='pli', to='en')

    data = {'from': 'pli', 'to': 'en'}
    res = client.get(api.url_for(LookupDictionaries, **data))

    assert res.status_code == 200
示例#9
0
def test_lookup_dictionaries(client):

    utils.generate_lookup_dict(_from='pli', to='en')

    data = {
        'from': 'pli',
        'to': 'en'
    }
    res = client.get(api.url_for(LookupDictionaries, **data))

    assert res.status_code == 200
示例#10
0
def user_page(users_id):
    abort_if_user_not_found(users_id)
    user_params = requests.get(api.url_for(UserResource, user_id=users_id, _external=True)).json()[
        'user']
    session = db_session.create_session()
    levels = []
    for level in session.query(Level).filter(Level.author == users_id):
        levels.append(level)
    return render_template('home_page.html', user_id=users_id, user_karma=user_params['karma'],
                           user_nick=user_params['nick'], user_levels=levels,
                           user_modified_date=user_params['modified_date'])
示例#11
0
def delete_level_page(level_id):
    abort_if_level_not_found(level_id)
    session = db_session.create_session()
    level = session.query(Level).get(level_id)
    if request.method == 'POST':
        requests.delete(api.url_for(LevelResource, level_id=level_id, _external=True))
        return redirect('/')
    if not current_user.is_authenticated:
        abort(401)
    if level.author == current_user.id:
        return render_template('delete_page.html', delete_text="This Level")
    abort(403)
示例#12
0
def edit_importance():
    user_id = request.form.get('user_id')
    user = User.get_query().get(user_id)
    if not user:
        return make_response(jsonify({
            'message': 'Пользователь не найден'
        }), 200)
    response = requests.put(api.url_for(UserResource, user_id=user_id, _external=True),
                            json=request.form.to_dict())
    if response:
        return make_response(jsonify({'message': 'status ok'}), 200)
    else:
        return make_response(jsonify(response.json()), 400)
示例#13
0
def test_suttaplex_list(client):
    utils.generate_html_text().save()
    utils.generate_blurb().save()
    utils.generate_po_markup().save()
    utils.generate_po_string().save()
    utils.generate_difficulty().save()
    roots = utils.generate_roots()
    roots.save()
    utils.generate_root_edges(roots).save()

    res = client.get(api.url_for(SuttaplexList, uid=roots[0].uid))

    assert res.status_code == 200
示例#14
0
def test_sutta_view(client):
    utils.generate_html_text().save()
    utils.generate_blurb().save()
    utils.generate_po_markup().save()
    utils.generate_po_string().save()
    utils.generate_difficulty().save()
    roots = utils.generate_roots()
    roots.save()
    utils.generate_root_edges(roots).save()

    res = client.get(api.url_for(Sutta, uid=roots[0].uid, author='sujato', lang='en'))

    assert res.status_code == 200
示例#15
0
def test_menu(client):
    roots = utils.generate_roots(amount=10)
    roots.save()
    edges = utils.generate_root_edges(roots)
    edges.save()

    res = client.get(api.url_for(Menu))

    data = res.json

    assert res.status_code == 200
    assert isinstance(data, list)
    assert all([isinstance(x, dict) for x in data])
示例#16
0
def test_menu(client):
    roots = utils.generate_roots(amount=10)
    roots.save()
    edges = utils.generate_root_edges(roots)
    edges.save()

    res = client.get(api.url_for(Menu))

    data = res.json

    assert res.status_code == 200
    assert isinstance(data, list)
    assert all([isinstance(x, dict) for x in data])
示例#17
0
def test_suttaplex_list(client):
    utils.generate_html_text().save()
    utils.generate_blurb().save()
    utils.generate_po_markup().save()
    utils.generate_po_string().save()
    utils.generate_difficulty().save()
    roots = utils.generate_roots()
    roots.save()
    utils.generate_root_edges(roots).save()

    res = client.get(api.url_for(SuttaplexList, uid=roots[0].uid))

    assert res.status_code == 200
示例#18
0
    def get(self, cr_id):

        try:
            endpoint = str(api.url_for(self, cr_id=cr_id))
        except Exception as exp:
            endpoint = str(__name__)

        try:
            api_key = request.headers.get('Api-Key')
        except Exception as exp:
            logger.error("No ApiKey in headers")
            logger.debug("No ApiKey in headers: " + repr(repr(exp)))
            return provideApiKey(endpoint=endpoint)

        try:
            cr_id = str(cr_id)
        except Exception as exp:
            raise ApiError(code=400,
                           title="Unsupported cr_id",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.debug("cr_id: " + repr(cr_id))

        # Get last Consent Status Record
        try:
            last_csr_object = get_last_cr_status(cr_id=cr_id)
        except Exception as exp:
            error_title = "Failed to get last Consent Status Record of Consent"
            logger.error(error_title + ": " + repr(exp))
            raise
        else:
            logger.debug("last_cr_status_object: " + last_csr_object.log_entry)

        # Response data container
        try:
            response_data = {}
            response_data['data'] = last_csr_object.to_record_dict
        except Exception as exp:
            logger.error('Could not prepare response data: ' + repr(exp))
            raise ApiError(code=500,
                           title="Could not prepare response data",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.info('Response data ready')
            logger.debug('response_data: ' + json.dumps(response_data))

        response_data_dict = dict(response_data)
        logger.debug('response_data_dict: ' + json.dumps(response_data_dict))
        return make_json_response(data=response_data_dict, status_code=200)
示例#19
0
def test_sutta_view(client):
    utils.generate_html_text().save()
    utils.generate_blurb().save()
    utils.generate_po_markup().save()
    utils.generate_po_string().save()
    utils.generate_difficulty().save()
    roots = utils.generate_roots()
    roots.save()
    utils.generate_root_edges(roots).save()

    res = client.get(
        api.url_for(Sutta, uid=roots[0].uid, author='sujato', lang='en'))

    assert res.status_code == 200
示例#20
0
 def delete(self, level_id):
     abort_if_level_not_found(level_id)
     session = db_session.create_session()
     level = session.query(Level).get(level_id)
     session.delete(level)
     session.commit()
     os.remove(os.path.abspath(f'static/levels/{level_id}.level'))
     for lev_app in session.query(LevelAppreciated).filter(
             LevelAppreciated.level_id == level_id).all():
         session.delete(lev_app)
     for res in session.query(Result).filter(Result.level_id == level_id).all():
         requests.delete(api.url_for(ResultResource, result_id=res.id, _external=True))
     session.commit()
     return jsonify({'success': "OK"})
示例#21
0
def test_parallels_view(client):
    utils.generate_html_text().save()
    utils.generate_po_markup().save()
    utils.generate_po_string().save()
    roots = utils.generate_roots()
    roots.save()

    uid = roots[0].uid

    utils.generate_relationships(roots).save()

    res = client.get(api.url_for(Parallels, uid=uid))

    assert res.status_code == 200
示例#22
0
def test_parallels_view(client):
    utils.generate_html_text().save()
    utils.generate_po_markup().save()
    utils.generate_po_string().save()
    roots = utils.generate_roots()
    roots.save()

    uid = roots[0].uid

    utils.generate_relationships(roots).save()

    res = client.get(api.url_for(Parallels, uid=uid))

    assert res.status_code == 200
def events_connect():
    print("前端websocket连接过来后,执行的第一个函数")
    # del current_app.clients[session['userid']]
    urls = api.url_for(
        EventView, _external=True)
    print(urls)
    userid = str(uuid.uuid4())
    print(userid, "生成新的userid")
    session['userid'] = userid
    current_app.clients[userid] = request.namespace
    print(current_app.clients, "打印所有的current_app.clients数据")
    # 将事件名为“userid”的数据({'userid': userid})发到前端
    emit('userid', {'userid': userid})
    # 将事件名为“status”的数据({'status': 'Connected user', 'userid': userid})发到前端
    emit('status', {'status': 'connected', 'userid': userid})
示例#24
0
def user_image():
    current_image = current_user.image_file
    if current_image:
        os.remove(f'app/static/{current_image}')
    data_image = request.form.get('image').split(',', maxsplit=1)
    format_img = data_image[0].split('/')[1].split(';')[0]
    base_64_srt = data_image[1]
    file_content = base64.b64decode(base_64_srt)
    url_file = f'app/static/img/users_avatar/{current_user.get_id()}.{format_img}'
    with open(url_file, mode='wb') as img_file:
        img_file.write(file_content)
    filename = f'img/users_avatar/{current_user.get_id()}.{format_img}'
    user_id = current_user.get_id()
    response = requests.put(api.url_for(UserResource, user_id=user_id, _external=True),
                            json={'image_file': filename})
    if response:
        return make_response(jsonify({'status': 'ok'}), 200)
    else:
        return make_response(jsonify({'status': 'error server'}), 400)
示例#25
0
    def get(self):
        try:
            endpoint = str(api.url_for(self))
        except Exception as exp:
            endpoint = str(__name__)

        logger.info("Authenticating user")

        auth = request.authorization
        if not auth or not self.check_basic_auth(auth.username, auth.password):
            return self.authenticate()
        else:
            logger.info("Authenticated")

        try:
            api_key = get_account_api_key(account_id=self.account_id)
        except ApiKeyNotFoundError as exp:
            error_title = "ApiKey not found for authenticated user"
            logger.error(error_title)
            logger.error(repr(exp))
            raise ApiError(code=404,
                           title=error_title,
                           detail=repr(exp),
                           source=endpoint)
        except Exception as exp:
            error_title = "Could not get ApiKey for authenticated user"
            logger.error(error_title)
            logger.error(repr(exp))
            raise ApiError(code=500,
                           title=error_title,
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.debug("account_id: " + str(self.account_id))
            logger.debug("api_key: " + str(api_key))

        response_data = {
            'Api-Key': api_key,
            'account_id': str(self.account_id)
        }

        return make_json_response(data=response_data, status_code=200)
示例#26
0
 def post(self):
     parser.add_argument("username",
                         required=True,
                         help="Username required")
     parser.add_argument("password",
                         required=True,
                         help="Password required")
     parser.add_argument("email", required=True, help="Email required")
     args = parser.parse_args()
     username = args.get("username")
     password = args.get("password")
     email = args.get("email")
     if (username == None or password == None or email == None):
         return jsonResponse({"error": "Information can't be null."}, 400)
     if (len(username) > 255 or len(password) > 255 or len(email) > 255):
         return jsonResponse(
             {
                 "error":
                 "The length of information can't excess 255 characters."
             }, 400)
     if User.query.filter_by(username=username).first() is not None:
         return jsonResponse({"error": "Username had been taken."}, 400)
     elif User.query.filter_by(email=email).first() is not None:
         return jsonResponse({"error": "Email had been taken."}, 400)
     newUser = User(username, password, email)
     token = serializer.dumps(UserSchema().dump(newUser),
                              salt="emailConfirmation")
     msg = Message("Confirm Email",
                   sender="*****@*****.**",
                   recipients=[email])
     link = api.url_for(EmailConfirmation, token=token, _external=True)
     msg.body = ("Click on the link:" + link + " to confirm your email.")
     try:
         mail.send(msg)
     except SMTPRecipientsRefused:
         return jsonResponse({"error": "Invalid email."}, 400)
     return jsonResponse({"message": "The email confirmation was sent."},
                         202)
示例#27
0
def edit_user():
    old_password = request.form.get('old_password', None)
    if old_password:
        if not current_user.confirmed:
            return make_response(jsonify({
                'message': {'Ошибка': 'Аккаунт не подтвержден'}
            }), 400)
        password_form = PasswordChange()
        if not password_form.validate_on_submit():
            return make_response(jsonify({
                'message': password_form.errors
            }), 400)
        if not current_user.check_password(old_password):
            return make_response(jsonify({
                'message': {'Ошибка': 'Неверный пароль'}
            }), 400)
    user_id = current_user.get_id()
    response = requests.put(api.url_for(UserResource, user_id=user_id, _external=True),
                            json=request.form.to_dict())
    if response:
        return make_response(jsonify({'message': 'status ok'}), 200)
    else:
        return make_response(jsonify(response.json()), 400)
示例#28
0
def recovery_password_last(token):
    email = confirm_token(token)
    if not email and request.method == 'GET':
        return redirect(url_for('main.index'))
    user = User.get_query().filter(User.email == email).first()
    recovery_form = RecoveryPasswordLast()
    if recovery_form.validate_on_submit():
        response = requests.put(api.url_for(UserResource, user_id=user.id, _external=True),
                                json=request.form.to_dict())
        if response:
            flash('Ваш пароль успешно изменен', 'success')
            return make_response(jsonify({
                'redirect': True,
                'redirect_url': url_for('main.index')
            }), 200)
        else:
            return make_response(jsonify(response.json()), 400)
    if request.method == 'GET':
        return render_template('recovery_password_last.html', recovery_form=recovery_form,
                               title='Новый пароль', token=token)
    return make_response(jsonify({
        'message': recovery_form.errors
    }), 400)
示例#29
0
    def get(self, account_id):

        try:
            endpoint = str(api.url_for(self, account_id=account_id))
        except Exception as exp:
            endpoint = str(__name__)

        try:
            api_key = request.headers.get('Api-Key')
        except Exception as exp:
            logger.error("No ApiKey in headers")
            logger.debug("No ApiKey in headers: " + repr(repr(exp)))
            return provideApiKey(endpoint=endpoint)

        try:
            account_id = str(account_id)
        except Exception as exp:
            raise ApiError(code=400, title="Unsupported account_id", detail=repr(exp), source=endpoint)

        # Response data container
        try:
            response_data = {}
            response_data['meta'] = {}
            response_data['meta']['activationInstructions'] = "Account Export"

            response_data['data'] = {}
            response_data['data']['type'] = "Account"
        except Exception as exp:
            logger.error('Could not prepare response data: ' + repr(exp))
            raise ApiError(code=500, title="Could not prepare response data", detail=repr(exp), source=endpoint)
        else:
            logger.info('Response data ready')
            logger.debug('response_data: ' + repr(response_data))

        response_data_dict = dict(response_data)
        logger.debug('response_data_dict: ' + repr(response_data_dict))
        return make_json_response(data=response_data_dict, status_code=201)
示例#30
0
    def get(self, account_id):
        try:
            endpoint = str(api.url_for(self, account_id=account_id))
        except Exception as exp:
            endpoint = str(__name__)

        try:
            api_key = request.headers.get('Api-Key')
        except Exception as exp:
            logger.error("No ApiKey in headers")
            logger.debug("No ApiKey in headers: " + repr(repr(exp)))
            return provideApiKey(endpoint=endpoint)

        try:
            account_id = str(account_id)
        except Exception as exp:
            raise ApiError(code=400,
                           title="Unsupported account_id",
                           detail=repr(exp),
                           source=endpoint)

        response_data = {'api_key': api_key, 'account_id': account_id}

        return make_json_response(data=response_data, status_code=200)
示例#31
0
    def post(self):
        '''Create new user'''
        args = self.parser.parse_args()

        if mongo.db.users.find_one({'email': args.email}):
            return {'message': 'email already in use'}, 422

        if app.config['REQUIRE_INVITE']:
            invite = mongo.db.invites.find_one({'inviteCode': args.inviteCode})
            if not invite:
                return {'message': 'invalid invite code'}, 422
            if invite['used']:
                return {'message': 'invite code is already used'}, 422
            invite['used'] = True
            invite['user'] = {'email': args.email, 'registered': time.time()}
            mongo.db.invites.save(invite)

        user = User(name=args.name, email=args.email, user_key=args.userKey)
        user.hash_password(args.password)
        mongo.db.users.insert(user.to_dict())

        return user.to_dict(with_password=False), 201, {
            'Location': api.url_for(UserApi, uid=user.uid, _external=True)
        }
示例#32
0
    def post(self, account_id):

        try:
            endpoint = str(api.url_for(self, account_id=account_id))
        except Exception as exp:
            endpoint = str(__name__)

        try:
            api_key = request.headers.get('Api-Key')
        except Exception as exp:
            logger.error("No ApiKey in headers")
            logger.debug("No ApiKey in headers: " + repr(repr(exp)))
            return provideApiKey(endpoint=endpoint)

        try:
            account_id = str(account_id)
        except Exception as exp:
            raise ApiError(code=400,
                           title="Unsupported account_id",
                           detail=repr(exp),
                           source=endpoint)

        # load JSON
        json_data = request.get_json()
        if not json_data:
            error_detail = {
                '0': 'Set application/json as Content-Type',
                '1': 'Provide json payload'
            }
            raise ApiError(code=400,
                           title="No input data provided",
                           detail=error_detail,
                           source=endpoint)
        else:
            logger.debug("json_data: " + json.dumps(json_data))

        # Validate payload content
        schema = NewServiceLink()
        schema_validation_result = schema.load(json_data)

        # Check validation errors
        if schema_validation_result.errors:
            logger.error("Invalid payload")
            raise ApiError(code=400,
                           title="Invalid payload",
                           detail=dict(schema_validation_result.errors),
                           source=endpoint)
        else:
            logger.debug("JSON validation -> OK")

        # Get slr payload
        try:
            slr_payload = json_data['data']['slr']['attributes']
        except Exception as exp:
            logger.error("Could not fetch slr payload from json")
            raise ApiError(code=400,
                           title="Could not fetch slr payload from json",
                           detail=repr(exp),
                           source=endpoint)

        # Get surrogate_id
        try:
            surrogate_id = json_data['data']['surrogate_id']
        except Exception as exp:
            logger.error("Could not fetch surrogate id from json")
            raise ApiError(code=400,
                           title="Could not fetch surrogate id from json",
                           detail=repr(exp),
                           source=endpoint)

        # Get code
        try:
            code = json_data['code']
        except Exception as exp:
            logger.error("Could not fetch code from json")
            raise ApiError(code=400,
                           title="Could not fetch code from json",
                           detail=repr(exp),
                           source=endpoint)

        # Sign SLR
        try:
            slr_signed_dict = sign_slr(account_id=account_id,
                                       slr_payload=slr_payload,
                                       endpoint=str(endpoint))
        except Exception as exp:
            logger.error("Could not sign SLR")
            logger.debug("Could not sign SLR: " + repr(exp))
            raise

        # Response data container
        try:
            response_data = {}
            response_data['code'] = code
            response_data['data'] = {}
            response_data['data']['slr'] = {}
            response_data['data']['slr']['type'] = "ServiceLinkRecord"
            response_data['data']['slr']['attributes'] = {}
            response_data['data']['slr']['attributes']['slr'] = slr_signed_dict
            response_data['data']['surrogate_id'] = surrogate_id
        except Exception as exp:
            logger.error('Could not prepare response data: ' + repr(exp))
            raise ApiError(code=500,
                           title="Could not prepare response data",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.info('Response data ready')
            logger.debug('response_data: ' + repr(response_data))

        response_data_dict = dict(response_data)
        logger.debug('response_data_dict: ' + repr(response_data_dict))
        return make_json_response(data=response_data_dict, status_code=201)
示例#33
0
    def get(self, account_id, service_id):

        try:
            endpoint = str(
                api.url_for(self, account_id=account_id,
                            service_id=service_id))
        except Exception as exp:
            endpoint = str(__name__)

        try:
            api_key = request.headers.get('Api-Key')
        except Exception as exp:
            logger.error("No ApiKey in headers")
            logger.debug("No ApiKey in headers: " + repr(repr(exp)))
            return provideApiKey(endpoint=endpoint)

        try:
            account_id = str(account_id)
        except Exception as exp:
            raise ApiError(code=400,
                           title="Unsupported account_id",
                           detail=repr(exp),
                           source=endpoint)

        try:
            service_id = str(service_id)
        except Exception as exp:
            raise ApiError(code=400,
                           title="Unsupported service_id",
                           detail=repr(exp),
                           source=endpoint)

        try:
            surrogate_id = get_surrogate_id_by_account_and_service(
                account_id=account_id,
                service_id=service_id,
                endpoint=endpoint)
        except IndexError as exp:
            raise ApiError(
                code=404,
                title="Nothing could not be found with provided information",
                detail=repr(exp),
                source=endpoint)
        except Exception as exp:
            logger.error('Could not get surrogate_id: ' + repr(exp))
            raise ApiError(code=500,
                           title="Could not get surrogate_id",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.debug('Got surrogate_id: ' + repr(surrogate_id))

        # Response data container
        try:
            response_data = {}
            response_data['data'] = {}

            response_data['data']['surrogate_id'] = {}
            response_data['data']['surrogate_id']['type'] = "SurrogateId"
            response_data['data']['surrogate_id']['attributes'] = surrogate_id
        except Exception as exp:
            logger.error('Could not prepare response data: ' + repr(exp))
            raise ApiError(code=500,
                           title="Could not prepare response data",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.info('Response data ready')
            logger.debug('response_data: ' + repr(response_data))

        response_data_dict = dict(response_data)
        logger.debug('response_data_dict: ' + repr(response_data_dict))
        return make_json_response(data=response_data_dict, status_code=200)
示例#34
0
    def post(self, account_id):

        try:
            endpoint = str(api.url_for(self, account_id=account_id))
        except Exception as exp:
            endpoint = str(__name__)

        try:
            api_key = request.headers.get('Api-Key')
        except Exception as exp:
            logger.error("No ApiKey in headers")
            logger.debug("No ApiKey in headers: " + repr(repr(exp)))
            return provideApiKey(endpoint=endpoint)

        try:
            account_id = str(account_id)
        except Exception as exp:
            raise ApiError(code=400,
                           title="Unsupported account_id",
                           detail=repr(exp),
                           source=endpoint)

        # load JSON
        json_data = request.get_json()
        if not json_data:
            error_detail = {
                '0': 'Set application/json as Content-Type',
                '1': 'Provide json payload'
            }
            raise ApiError(code=400,
                           title="No input data provided",
                           detail=error_detail,
                           source=endpoint)
        else:
            logger.debug("json_data: " + json.dumps(json_data))

        # Validate payload content
        schema = VerifyServiceLink()
        schema_validation_result = schema.load(json_data)

        # Check validation errors
        if schema_validation_result.errors:
            raise ApiError(code=400,
                           title="Invalid payload",
                           detail=dict(schema_validation_result.errors),
                           source=endpoint)
        else:
            logger.debug("JSON validation -> OK")

        ######
        # SLR
        ######
        #
        # Get slr
        try:
            slr = json_data['data']['slr']['attributes']['slr']
        except Exception as exp:
            raise ApiError(code=400,
                           title="Could not fetch slr from json",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.debug("Got slr: " + json.dumps(slr))

        # Get surrogate_id
        try:
            surrogate_id = json_data['data']['surrogate_id']['attributes'][
                'surrogate_id']
        except Exception as exp:
            raise ApiError(code=400,
                           title="Could not fetch surrogate id from json",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.debug("Got surrogate_id: " + str(surrogate_id))

        # Decode slr payload
        try:
            #print (json.dumps(json_data))
            slr_payload_encoded = slr['payload']
            slr_payload_encoded += '=' * (-len(slr_payload_encoded) % 4
                                          )  # Fix incorrect padding, base64
            slr_payload_decoded = b64decode(slr_payload_encoded).replace(
                '\\', '').replace('"{', '{').replace('}"', '}')
            slr_payload_dict = json.loads(slr_payload_decoded)
        except Exception as exp:
            raise ApiError(code=400,
                           title="Could not decode slr payload",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.debug("slr_payload_decoded: " + str(slr_payload_decoded))

        # Get service_link_record_id
        try:
            slr_id = slr_payload_dict['link_id']
        except Exception as exp:
            raise ApiError(
                code=400,
                title="Could not fetch service link record id from json",
                detail=repr(exp),
                source=endpoint)
        else:
            logger.debug("Got slr_id: " + str(slr_id))

        # Get service_id
        try:
            service_id = slr_payload_dict['service_id']
        except Exception as exp:
            raise ApiError(code=400,
                           title="Could not fetch service id from json",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.debug("Got service_id: " + str(service_id))

        # Get operator_id
        try:
            operator_id = slr_payload_dict['operator_id']
        except Exception as exp:
            raise ApiError(code=400,
                           title="Could not fetch operator id from json",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.debug("Got operator_id: " + str(operator_id))

        #######
        # Ssr
        #######
        #
        # Get ssr payload
        try:
            ssr_payload = json_data['data']['ssr']['attributes']
        except Exception as exp:
            raise ApiError(code=400,
                           title="Could not fetch ssr from json",
                           detail=repr(exp),
                           source=endpoint)

        # Get ssr_id
        try:
            ssr_id = ssr_payload['record_id']
        except Exception as exp:
            raise ApiError(code=400,
                           title="Could not fetch record_id from ssr_payload",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.debug("Got ssr_id: " + str(ssr_id))

        # Get ssr_status
        try:
            ssr_status = ssr_payload['sl_status']
        except Exception as exp:
            raise ApiError(code=400,
                           title="Could not fetch sl_status from ssr_payload",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.debug("Got ssr_status: " + str(ssr_status))

        # Get slr_id_from_ssr
        try:
            slr_id_from_ssr = ssr_payload['slr_id']
        except Exception as exp:
            raise ApiError(code=400,
                           title="Could not fetch slr_id from ssr_payload",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.debug("Got slr_id: " + str(slr_id))

        # Get prev_ssr_id
        try:
            prev_ssr_id = ssr_payload['prev_record_id']
        except Exception as exp:
            raise ApiError(
                code=400,
                title="Could not fetch prev_ssr_id from ssr_payload",
                detail=repr(exp),
                source=endpoint)
        else:
            logger.debug("Got prev_ssr_id: " + str(prev_ssr_id))

        # Get iat
        try:
            ssr_iat = int(ssr_payload['iat'])
        except Exception as exp:
            raise ApiError(code=400,
                           title="Could not fetch iat from ssr_payload",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.debug("Got iat: " + str(prev_ssr_id))

        #
        # Get code
        try:
            code = json_data['code']
        except Exception as exp:
            raise ApiError(code=400,
                           title="Could not fetch code from json",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.debug("Got code: " + str(code))

        ##
        ##
        # Check that slr and ssr payload are matching # TODO: Jatka slr:n ja ssr:n keskinäistä vertailua ja validointia
        if not slr_id == slr_id_from_ssr:
            detail_data = {
                'slr_id': str(slr_id),
                'slr_id_from_ssr': str(slr_id_from_ssr)
            }
            raise ApiError(code=409,
                           title="Service Link Record ID's are not matching",
                           detail=detail_data,
                           source=endpoint)

        ##
        ##
        # Verify Account owner's signature in Service Link Record
        try:
            slr_verified = verify_jws_signature_with_jwk(
                account_id=account_id, jws_json_to_verify=json.dumps(slr))
        except Exception as exp:
            logger.error(
                "Could not verify Account owner's signature in Service Link Record: "
                + repr(exp))
            raise ApiError(
                code=500,
                title=
                "Failed to verify Account owner's signature in Service Link Record",
                detail=repr(exp),
                source=endpoint)
        else:
            logger.info('Service Link Record verified')
            logger.info('Verification passed: ' + str(slr_verified))

        # Sign Ssr
        try:
            ssr_signed = sign_ssr(account_id=account_id,
                                  ssr_payload=ssr_payload,
                                  endpoint=str(endpoint))
        except Exception as exp:
            logger.error("Could not sign Ssr")
            logger.debug("Could not sign Ssr: " + repr(exp))
            raise

        # Store slr and ssr
        logger.info(
            "Storing Service Link Record and Service Link Status Record")
        try:
            slr_entry = ServiceLinkRecord(service_link_record=slr,
                                          service_link_record_id=slr_id,
                                          service_id=service_id,
                                          surrogate_id=surrogate_id,
                                          operator_id=operator_id,
                                          account_id=account_id)
        except Exception as exp:
            logger.error('Could not create Service Link Record object: ' +
                         repr(exp))
            raise ApiError(code=500,
                           title="Failed to create Service Link Record object",
                           detail=repr(exp),
                           source=endpoint)

        try:
            ssr_entry = ServiceLinkStatusRecord(
                service_link_status_record_id=ssr_id,
                status=ssr_status,
                service_link_status_record=ssr_signed,
                service_link_record_id=slr_id_from_ssr,
                issued_at=ssr_iat,
                prev_record_id=prev_ssr_id)
        except Exception as exp:
            logger.error(
                'Could not create Service Link Status Record object: ' +
                repr(exp))
            raise ApiError(
                code=500,
                title="Failed to create Service Link Status Record object",
                detail=repr(exp),
                source=endpoint)

        try:
            stored_slr_entry, stored_ssr_entry = store_slr_and_ssr(
                slr_entry=slr_entry,
                ssr_entry=ssr_entry,
                endpoint=str(endpoint))
        except Exception as exp:
            logger.error(
                "Could not store Service Link Record and Service Link Status Record"
            )
            logger.debug("Could not store SLR and Ssr: " + repr(exp))
            raise
        else:
            logger.info(
                "Stored Service Link Record and Service Link Status Record")
            logger.debug("stored_slr_entry: " + stored_slr_entry.log_entry)
            logger.debug("stored_ssr_entry: " + stored_ssr_entry.log_entry)

        # Response data container
        try:
            response_data = {}
            response_data['code'] = code

            response_data['data'] = {}

            response_data['data']['slr'] = stored_slr_entry.to_record_dict

            response_data['data']['ssr'] = stored_ssr_entry.to_record_dict

            response_data['data']['surrogate_id'] = surrogate_id
        except Exception as exp:
            logger.error('Could not prepare response data: ' + repr(exp))
            raise ApiError(code=500,
                           title="Could not prepare response data",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.info('Response data ready')
            logger.debug('response_data: ' + repr(response_data))

        response_data_dict = dict(response_data)
        logger.debug('response_data_dict: ' + repr(response_data_dict))
        return make_json_response(data=response_data_dict, status_code=201)
示例#35
0
    def get(self, cr_id):
        logger.info("CrStatus")
        try:
            endpoint = str(api.url_for(self, cr_id=cr_id))
        except Exception as exp:
            endpoint = str(__name__)

        try:
            logger.info("Fetching Api-Key from Headers")
            api_key = request.headers.get('Api-Key')
        except Exception as exp:
            logger.error("No ApiKey in headers: " + repr(repr(exp)))
            return provideApiKey(endpoint=endpoint)
        else:
            logger.info("Api-Key: " + api_key)

        try:
            cr_id = str(cr_id)
        except Exception as exp:
            error_title = "Unsupported cr_id"
            logger.error(error_title)
            raise ApiError(code=400,
                           title=error_title,
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.info("cr_id: " + cr_id)

        # Get last CSR ID from query parameters
        try:
            logger.info("Get last CSR ID from query parameters")
            last_csr_id = request.args.get('csr_id', None)
        except Exception as exp:
            error_title = "Unexpected error when getting last CSR ID from query parameters"
            logger.error(error_title + " " + repr(exp))
            raise ApiError(code=403,
                           title=error_title,
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.info("last_csr_id: " + repr(last_csr_id))

        # Get ConsentStatusRecords
        try:
            logger.info("Fetching ConsentStatusRecords")
            db_entries = get_csrs(cr_id=cr_id, last_csr_id=last_csr_id)
        except StandardError as exp:
            error_title = "ConsentStatusRecords not accessible"
            logger.error(error_title + ": " + repr(exp))
            raise ApiError(code=403,
                           title=error_title,
                           detail=repr(exp),
                           source=endpoint)
        except Exception as exp:
            error_title = "No ConsentStatusRecords found"
            logger.error(error_title + repr(exp))
            raise ApiError(code=404,
                           title=error_title,
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.info("ConsentStatusRecords Fetched")

        # Response data container
        try:
            db_entry_list = db_entries
            response_data = {}
            response_data['data'] = db_entry_list
        except Exception as exp:
            logger.error('Could not prepare response data: ' + repr(exp))
            raise ApiError(code=500,
                           title="Could not prepare response data",
                           detail=repr(exp),
                           source=endpoint)
        else:
            logger.info('Response data ready')
            logger.debug('response_data: ' + repr(response_data))

        response_data_dict = dict(response_data)
        logger.debug('response_data_dict: ' + repr(response_data_dict))
        return make_json_response(data=response_data_dict, status_code=200)
示例#36
0
def test_no_query(client):
    res = client.get(api.url_for(Search))
    assert res.status_code == 422
示例#37
0
def test_search(client):
    data = {
        'query': 'test'
    }
    res = client.get(api.url_for(Search, **data))
    assert res.status_code == 200
示例#38
0
def test_languages(client):
    languages = utils.generate_languages()
    languages.save()
    res = client.get(api.url_for(Languages))
    assert res.status_code == 200
示例#39
0
def test_lookup_dictionaries_no_query(client):
    res = client.get(api.url_for(LookupDictionaries))

    assert res.status_code == 422