Пример #1
0
def add_new_article():
    if current_user.is_authenticated:
        if not request.json:
            return error_response(400, 'Incorrect type')

        if not current_user.remove_date:
            title = request.json['title']
            body = request.json['body']
            try:
                end_date = request.json['end_date']
                if not check_dates(end_date):
                    logger.warning(f'user:{current_user.id} - add action failed with error: {e}')
                    return error_response(406, f'Date {end_date} lower')
            except:
                end_date = calculate_end_date()
            article = Article(title=title, body=body, user_id=current_user.id, end_date=end_date)                
            db.session.add(article)
            db.session.commit()
            article = Article.query.order_by(Article.create_date.desc()).filter_by(user_id=current_user.id).first()
            mark_article_deleted.apply_async(args=[article.id], eta=days_to_mark(article.end_date))
            logger.info(f'user:{current_user.username} - add new article')
            return jsonify({'Success':'Artlicle has been added'})
        else:
            return error_response(401, f'User {user.username} has been blocked')
    else:
        return error_response(401)
Пример #2
0
def receive_object():
    #extract request data or none
    data = request.get_json() or {}
    #check if required fields exist (auth_token, and item_token)
    if 'auth_token' not in data or 'item_token' not in data:
        return bad_request('Auth token and item token must be included')
    #authorise user from token
    user = User.check_auth_token(data['auth_token'])
    #check if user is authorised and is ssame as item's recipient
    if not user:
        return error_response(401, 'User not authorised.')
    #get required item
    recipient, item = Item.decode_item_token(data['item_token'])
    #check if item and recipient were found
    if item and recipient:
        #if user is same as item's recipient
        if recipient is user:
            item.owner = user
            db.session.commit()
            #create response
            response = jsonify(
                {'message': "Object was succesfully transfered."})
            response.status_code = 200
            return response
        else:
            return error_response(403, 'Resource is forbidden.')

    else:
        return error_response(404, 'Item not found.')
Пример #3
0
def send_object():
    #extract request data or none
    data = request.get_json() or {}
    #check if required fields exist
    if 'token' not in data or 'id' not in data or 'login' not in data:
        return bad_request('Token, id and login fields must be included')
    #get required item
    item = Item.query.get(data['id'])
    #check if the recipient exists
    recipient = User.query.filter_by(login=data['login']).first()
    if not item or not recipient:
        return error_response(404, "Item or recipient doesn't exist.")
    #get user from token
    user = User.check_auth_token(data['token'])
    #check if user was found and if he is owner of the item
    if user and user is item.owner:
        response = jsonify({
            'message':
            'Item token generated.',
            'item_token':
            item.generate_item_token(data['login']).decode(),
        })
        response.status_code = 200
        return response
    else:
        return error_response(403, 'Please log in.')
Пример #4
0
def new_transaction():
    data = request.get_json()

     # 400: bad request check
    if data is None:
        return errors.bad_request('expected json data in body')
    required = ['file_hash', 'author_key', 'signature']
    if not all(k in data for k in required):
        return errors.bad_request(
            'missing values, must provide file_hash, author_key, signature')

    # check if txn already exists in blockchain
    file = File.query.filter_by(file_hash=data['file_hash']).first()
    if file is not None:
        return errors.error_response(403, 'file already exists')

    # check if txn already exists in txn pool
    for txn in blockchain.transaction_pool:
        if data['file_hash'] == txn.file_hash:
            return errors.error_response(
                403, 'file in transaction pool, wait for block to be mined')

    blockchain.add_transaction(data)
    respone = {'message': 'Transaction will be added to Block #{}'.format(
        blockchain.current_block.index + 1
    )}
    return jsonify(respone), 201
Пример #5
0
def article_update(id):
        
    if current_user.is_authenticated:
        try:
            article = Article.query.get(id)
        except Exception as e:
            logger.warning(f'article:{id} - update action failed with error: {e}')
            return error_response(404, 'Article doesn\'t exist')
        if not current_user.remove_date:
            if current_user.id == article.user_id:
                if not article.remove_date:
                    update_data = {}
                    try:
                        title = request.json['title']
                        update_data['title'] = title
                    except:
                        pass
                    try:
                        body = request.json['body']
                        update_data['body'] = body
                    except:
                        pass
                    article = Article.query.filter_by(id = id).update(update_data)
                    db.session.commit()
                    logger.info(f'user:{current_user.username} - update article {id}')
                    return jsonify({'Success':'Article has been updated'})
                else:
                    return error_response(410, 'Article deleted')
            else:
                return error_response(403, 'Atricle from another user')
        else:
            return error_response(410, 'Deleted user')
    else:
        return error_response(401)
Пример #6
0
def delete_user(id):
    if id != get_jwt_identity():
        return error_response(403)
    if db.get_user(id) is None:
        return error_response(404)
    if db.delete_user(id) is False:
        return error_response(400)
    return "", 204
Пример #7
0
def create_ship():
    try:
        ship = ship_schema.loads(request.data)
    except ValidationError as err:
        return error_response(400, err.messages)
    ship = db.add_ship(ship)
    if ship is None:
        return error_response(400)
    response = jsonify(ship_schema.dump(ship))
    response.status_code = 201
    response.headers["Location"] = url_for("api.get_ship", id=ship.id)
    return response
Пример #8
0
def add_user():
    request_data = request.get_json()

    if not request_data:
        return bad_request("No input data provided")

    try:
        data = UserSchema().load(request_data)
    except ValidationError as err:
        return error_response(422, err.messages)

    email = data.get('email')
    password = data.get('password')
    firstname = data.get('firstname')
    lastname = data.get('lastname')
    username = data.get('username') or \
        f'{firstname}{lastname}_{int(random()*1e6)}'

    try:
        # check for existing user
        user_email = User.find_by_identity(data.get('email'))
        user_username = User.find_by_identity(data.get('username'))

        if user_email is None and user_username is None:
            # add new user to db
            user = User()
            user.firstname = firstname
            user.lastname = lastname
            user.username = username
            user.email = email
            user.password = password
            user.bio = data.get('bio')
            user.is_active = data.get('is_active') or False
            user.is_admin = data.get('is_admin') or False

            user.save()

            response = jsonify({
                'message': 'Successfully added new user.',
            })
            response.status_code = 201
            response.headers['Location'] = url_for(
                'users.get_user', id=user.id)
            return response
        else:
            return bad_request('Sorry. That user already exists.')

    # handle errors
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return error_response(500, 'Something went wrong, please try again.')
Пример #9
0
def create_user():
    try:
        user = user_schema.loads(request.data)
    except ValidationError as err:
        return error_response(400, err.messages)
    if db.get_user_by_name(user.name):
        return error_response(400, "User already exists.")
    user = db.add_user(user)
    if user is None:
        return error_response(400)
    response = jsonify(user_schema.dump(user))
    response.status_code = 201
    response.headers["Location"] = url_for("api.get_user", id=user.id)
    return response
Пример #10
0
def hook():
    data = request.get_json() or {}
    if 'method' not in data:
        return errors.error_response(400, 'Must Include Method.')

    method = data['method']
    if method not in supported_methods:
        return errors.error_response(400, f'Unsupported Method [{method}]')

    result = hooks.process_hook(data)
    if result:
        response = jsonify(result)
        response.status_code = 201
        return response
    return errors.error_response(500)
Пример #11
0
def get_job(id):
    job_info = jobs.get_job_status(id)

    if not job_info is None:
        return jsonify(job_info)
    else:
        return error_response(404, "job not found")
Пример #12
0
def test_error_response_has_all_basic_fields(app):
    response = error_response(404)
    assert response.status_code == 404
    assert response.is_json == True
    json = response.get_json()
    assert json != None
    assert "error" in json
Пример #13
0
def login():
    email = request.args.get('email')
    password_hash = request.args.get('password')
    user = User.query.filter_by(email=email).first_or_404()
    if user.check_password(password_hash):
        return jsonify(user.to_dict())
    else:
        return error_response(401, "Invalid login or password")
Пример #14
0
def get_post(post_id):
    post_query = SINGLE_POST_QUERY_TEMPLATE.format(post_id)
    json_post = get_single_json_entity(post_query)
    if json_post:
        response = jsonify(json_post)
    else:
        response = error_response(404)
    return response
Пример #15
0
def get_forum(forum_id):
    json_forum = get_single_json_entity(
        FULL_FORUM_QUERY_TEMPLATE.format(forum_id))
    if json_forum:
        response = jsonify(json_forum)
    else:
        response = error_response(404)
    return response
Пример #16
0
def update_ship(id):
    try:
        ship = ship_schema.loads(request.data)
    except ValidationError as err:
        return error_response(400, err.messages)
    if db.get_ship(id) is None:
        return error_response(404)
    # "id" in request data is optional
    if ship.id == 0:
        ship.id = id
    # if "id" was provided in request data then it has to match the resource id
    if ship.id != id:
        return error_response(400, "Request data id has to match resource id.")
    if not db.update_ship(ship):
        return error_response(400)
    response = jsonify(ship_schema.dump(ship))
    return response
Пример #17
0
def get_thread(thread_id):
    thread_query = SINGLE_THREAD_QUERY_TEMPLATE.format(thread_id)
    json_thread = get_single_json_entity(thread_query)
    if json_thread:
        response = jsonify(json_thread)
    else:
        response = error_response(404)
    return response
Пример #18
0
def get_user(user_id):
    json_user = get_single_json_entity(
        FULL_USER_QUERY_TEMPLATE.format(user_id)
    )
    if json_user:
        response = jsonify(json_user)
    else:
        response = error_response(404)
    return response
Пример #19
0
def block_by_hash(block_hash):
    block = None
    for b in blockchain.blocks:
        if b.block_hash == block_hash:
            block = b
    if block is None:
        return errors.error_response(404, 'block not found')

    return jsonify(blockchain.blocks[block.index].to_dict(txns=True)), 200
Пример #20
0
def update_user(id):
    if id != get_jwt_identity():
        return error_response(403)
    try:
        user = user_schema.loads(request.data)
    except ValidationError as err:
        return error_response(400, err.messages)
    if db.get_user(id) is None:
        return error_response(404)
    # "id" in request data is optional
    if user.id == 0:
        user.id = id
    # if "id" was provided in request data then it has to match the resource id
    if user.id != id:
        return error_response(400, "Request data id has to match resource id.")
    if not db.update_user(user):
        return error_response(400)
    response = jsonify(user_schema.dump(user))
    return response
Пример #21
0
def login():
    if not request.is_json:
        return error_response(400)

    data = request.get_json()
    username = data.get("username")
    password = data.get("password")

    if not username or not password:
        return error_response(400, "Username or password missing.")

    user = db.get_user_by_name(username)

    if not user or user.password != password:
        return error_response(401, "Username or password invalid.")

    access_token = create_access_token(identity=user.id)
    refresh_token = create_refresh_token(identity=user.id)
    return jsonify(access_token=access_token, refresh_token=refresh_token)
Пример #22
0
def article_detail(id):
    try:
        article = Article.query.get(id)
    except Exception as e:
        logger.warning(f'article:{id} - get action failed with error: {e}')
        return error_response(404, 'Article doesn\'t exist')
    if article.remove_date:
        return error_response(410, 'Article has been deleted')
    obj = {
            'id': article.id,
            'create_date': article.create_date,
            'update_date': article.update_date,
            'remove_date': article.remove_date,
            'user_id': article.user,
            'title': article.title,
            'body': article.body,
            'end_date': article.end_date
        }
    return jsonify({'article':obj})
Пример #23
0
def verify_password(email, password):
  user = User.query.filter_by(email=email).first()
  if user is None:
    return False
  # save the authenticated user in g.current_user so that it can be from the API view functions
  # g is a global variable in flask that is valid till we finished processing a request
  g.current_user = user
  if user.check_password(password):
    return user.id
  else:
    return error_response(401)
Пример #24
0
def article_delete(id):
    if current_user.is_authenticated:
        try:
            article = Article.query.get(id)
        except:
            logger.warning(f'article:{id} - delete action failed with error: {e}')
            return error_response(404, 'Article doesn\'t exist')
        if not current_user.remove_date:
            if current_user.id == article.user_id:
                if not article.remove_date:
                    article = Article.query.filter_by(id = id).update({'remove_date': datetime.utcnow()})
                    db.session.commit()
                    logger.info(f'user:{current_user.username} - delete article {id}')
                    return jsonify({'Success':'Article deleted'})
                else:
                    return error_response(410, 'Article deleted')
            else:
                return error_response(403, 'Atricle from another user')
        else:
            return error_response(410, 'Deleted user')
    else:
        return error_response(401)
Пример #25
0
def refresh_tokens():
    data = request.get_json() or {}
    if 'uuid' not in data:
        return bad_request('Must include UUID')
    try:
        if User.query.filter_by(uuid=uuid.UUID(data['uuid']).hex).count() == 0:
            raise ValueError()

    except ValueError:
        return error_response(403, 'Given UUID isn\'t registered')

    response = User.get_refresh_info(data)
    return response.json(), response.status_code
Пример #26
0
def delete_item(id):
    #extract request data or none
    data = request.get_json() or {}
    #check if required fields exist
    if 'token' not in data:
        return bad_request('Token field must be included')
    #get required item (id is passed in endpoint)
    item = Item.query.get(id)
    if not item:
        return error_response(404, 'Wrong item id.')
    #get user from token
    user = User.check_auth_token(data['token'])
    #check if user was found and if he is owner of the item
    if user and user is item.owner:
        #delete item
        db.session.delete(item)
        db.session.commit()
        #create response
        response = jsonify({'message': "Item deleted."})
        response.status_code = 200
        return response
    else:
        return error_response(403, 'Please log in.')
Пример #27
0
def get_objects():
    #extract request data or none
    data = request.get_json() or {}
    #check if required fields exist
    if 'token' not in data:
        return bad_request('Token field must be included')
    #get user from token
    user = User.check_auth_token(data['token'])
    if user:
        response = jsonify([item.to_dict() for item in user.items.all()])
        response.status_code = 200
        return response
    else:
        return error_response(403, 'Please log in.')
Пример #28
0
def remove_post(post_id):
    post_query = SINGLE_POST_QUERY_TEMPLATE.format(post_id)
    json_post = get_single_json_entity(post_query)
    if not json_post:
        return error_response(404)
    if token_auth.current_user().id != json_post['user_id']:
        abort(403)

    delete_post_query = f"""
    UPDATE post SET deleted = TRUE WHERE post.id = '{post_id}'
    """
    database.session.execute(delete_post_query)
    database.session.commit()
    response = jsonify({'status': 'OK'})
    return response
Пример #29
0
def get_user_posts(user_id):
    app.logger.debug(f'Receive request: {request.data}')
    query = A_USER_QUERY_TEMPLATE.format('id', user_id)
    json_user = get_single_json_entity(query)
    if not json_user:
        return error_response(404)

    posts_query = f"""
    SELECT post.id, post.text, post.creation_timestamp, post.user_id FROM post 
    WHERE post.user_id = {user_id} AND post.deleted = FALSE
    """
    query_result_proxy = database.session.execute(posts_query)
    database.session.commit()
    posts = [{k: v for k, v in row.items()} for row in query_result_proxy]
    response = jsonify({'user_posts': posts})
    return response
Пример #30
0
def chain_file_search(file_hash):
    response = {
        'search_for': file_hash,
        'file_found': False
    }

    file = File.query.filter_by(file_hash=file_hash).first()
    if file is None:
        return errors.error_response(404, 'file not found')
    else:
        response['file_found'] = True
        response['message'] = 'file found'
        txn = blockchain.blocks[file.block_index].transactions[file.txn_index]
        response['txn'] = txn.to_dict()
        response['timestamp'] = blockchain.blocks[file.block_index].timestamp
        return jsonify(response), 200