Beispiel #1
0
def unfollow(id):
    user = User.query.get_or_404(id)
    if user is None:
        return bad_request('User does not exist')
    if user == token_auth.current_user():
        return bad_request('You cannot unfollow yourself')

    token_auth.current_user().unfollow(user)
    db.session.commit()
    return jsonify(user.to_dict(token_auth.current_user()))
Beispiel #2
0
def revoke_token():
    """
        Method to revoke a token granted during API authentication process

        :return: the response
        :rtype: werkzeug.wrappers.response.Response
    """

    token_auth.current_user().revoke_token()

    db.session.commit()

    return "", 204
Beispiel #3
0
def create_transaction():
    data = request.get_json() or {}
    if 'sender' not in data or not isinstance(data['sender'], int):
        return bad_request('Sender must not be empty or incorrect value')
    sender = User.query.get_or_404(data['sender'])
    if token_auth.current_user().id != sender.id:
        abort(403)
    if 'recipient' not in data or data['recipient'] == sender.email or \
            not User.query.filter_by(email=data['recipient']).first():
        return bad_request('You can not transfer yourself or empty value')
    if 'transfer_amount' not in data or not isinstance(data['transfer_amount'], (float, int)) or \
            data['transfer_amount'] <= 0.:
        return bad_request('Incorrect value of transfer amount')
    recipient = User.query.filter_by(email=data['recipient']).first()
    sender.bill = sender.bill - float(data['transfer_amount'])
    transfer_amount_base = float(
        data['transfer_amount']) / sender.currency_user.rate
    recipient_bill = recipient.bill / recipient.currency_user.rate
    transaction = Transaction(sender=sender.id,
                              recipient=recipient.email,
                              transfer_amount_base=transfer_amount_base,
                              sender_rate=sender.currency_user.rate)
    recipient.bill = (recipient_bill +
                      transfer_amount_base) * recipient.currency_user.rate
    db.session.add(transaction)
    db.session.commit()
    return jsonify(transaction.to_dict())
Beispiel #4
0
def upload_files():
    user = token_auth.current_user()
    if not user.verified:
        return error_response(403, 'Email not confirmed')

    if 'files' not in request.files:
        return bad_request('No files to upload')

    uploaded = []
    errors = []
    files = request.files.getlist('files')
    for file in files:
        file_data = upload_file(user, file)
        if 'error' in file_data:
            errors.append(file_data['error'])
            continue
        file_model = File()
        file_model.from_dict(file_data)
        db.session.add(file_model)
        db.session.commit()
        uploaded.append(file_model.to_dict())

    response = jsonify({'uploaded_files': uploaded, 'errors': errors})
    response.status_code = 201
    return response
Beispiel #5
0
def get_user_post():
    user_id = token_auth.current_user().id
    page = request.args.get('page', 1, type=int)
    per_page = min(request.args.get('per_page', 3, type=int), 100)
    data = Post.to_collection_dict(Post.query.filter_by(user_id=user_id), page,
                                   per_page, 'api.get_posts')
    return jsonify(data)
Beispiel #6
0
def update_user(id):
    """
        API that updates a specific user data. The user is identified through its id.

        :param id: the current user identifier
        :type id: int

        :return: the Response object containing the data (in JSON format)
        :rtype: flask.wrappers.Response
    """

    if token_auth.current_user().id != id:

        abort(403)

    user = User.query.get_or_404(id)
    data = request.get_json() or {}

    if "username" in data and data["username"] == user.username and User.query.filter_by(username = data["username"]).first():

        return bad_request("Please use a different username")

    if "github_login" in data and data["github_login"] == user.github_login and User.query.filter_by(github_login = data["github_login"]).first():

        return bad_request("Please use a different GitHub login")

    if "email" in data and data["email"] == user.email and User.query.filter_by(email = data["email"]).first():

        return bad_request("please use a different email address")

    user.from_dict(data, new_user = False)
    db.session.commit()

    return jsonify(user.to_dict())
Beispiel #7
0
def get_pinned_music_list():
    user = token_auth.current_user()
    page = request.args.get('page', 1, type=int)
    per_page = min(request.args.get('per_page', 5, type=int), 10)
    data = user.to_collection_dict(
                user.pinned_music, 
                page, per_page, 'api.get_pinned_music_list')
    return jsonify(data)
Beispiel #8
0
def remove_from_private_music_list(id):
    user = token_auth.current_user()
    music_item = MusicItem.query.get_or_404(id)
    if user.is_in_private_list(music_item) is None:
         return bad_request('Music video not found in private list')
    user.remove_private_music_item(music_item)
    db.session.commit()
    return '', 200
Beispiel #9
0
def update_item_stock():
    name = request.json['name']
    stock = request.json['stock']
    username = token_auth.current_user().username
    try:
        if update_stock(name, stock, username):
            return jsonify({'message': 'Item stock Updated '})
    except ItemNotFound:
        return jsonify({'message': 'Item Not found'})
Beispiel #10
0
def update_item_price():
    name = request.json['name']
    price = request.json['price']
    username = token_auth.current_user().username
    try:
        if update_price(name, price, username):
            return jsonify({'message': 'Item stock Updated '})
    except ItemNotFound:
        return jsonify({'message': 'Item Not found'})
Beispiel #11
0
def get_user_home_music_list():
    user = token_auth.current_user()
    pinned_music_ids = db.session.query(MusicItem.id).filter(
                        User.pinned_music).filter(User.id == user.id)
    page = request.args.get('page', 1, type=int)
    per_page = min(request.args.get('per_page', 20, type=int), 100)
    data = MusicItem.to_collection_dict(
                MusicItem.query.filter(~MusicItem.id.in_(pinned_music_ids)),
                page, per_page, 'api.get_user_home_music_list')
    return jsonify(data)
Beispiel #12
0
def ne_plus_suivre(id):
    current_user = token_auth.current_user()
    user = Utilisateur.query.filter_by(id=id).first()
    print(user.id)
    if user is None:
        return jsonify({'erreur': "utilisateur inexistant"})
    if user.id == current_user.id:
        return jsonify({'erreur': "utilisateur ne peut pas ne plus se suivre"})
    current_user.ne_plus_etre_partisan(user)
    db.session.commit()
    return jsonify({'suivre': 'ne_plus_suivre'})
Beispiel #13
0
def download_file(filename):
    user = token_auth.current_user()
    if not user.verified:
        return error_response(403, 'Email not confirmed')

    file = File.query.filter_by(fullname=filename, user_id=user.id).first()
    if not file:
        return error_response(404, 'File {} does not exist'.format(filename))
    return send_from_directory(user.get_dir(),
                               file.fullname,
                               as_attachment=True)
Beispiel #14
0
def list_files():
    user = token_auth.current_user()
    if not user.verified:
        return error_response(403, 'Email not confirmed')

    files = File.query.filter_by(user_id=user.id).all()
    response = {'files': []}
    if files:
        files_dict = [file.to_dict() for file in files]
        response['files'] = files_dict
    return response
Beispiel #15
0
def insert():
    name = request.json['name']
    price = request.json['price']
    stock = request.json['stock']
    username = token_auth.current_user().username

    try:
        if insert(name, price, stock, username):
            return jsonify({'message': 'Item inserted'})
    except ItemExists:
        return jsonify({'message': 'Item Already Exists'})
Beispiel #16
0
def get_transactions(id):
    if token_auth.current_user().id != id:
        abort(403)
    page = request.args.get('page', 1, type=int)
    per_page = min(request.args.get('per_page', 10, type=int), 100)
    data = Transaction.to_collection_dict(
        Transaction.query.filter_by(sender=id),
        page,
        per_page,
        'api.get_transactions',
        id=id)
    return jsonify(data)
Beispiel #17
0
def create_post():
    data = request.form.to_dict() or {}
    post = Post()

    if request.files:
        image = request.files["file"]
        image.save(os.path.join(
            current_app.config["IMAGE_UPLOADS"], image.filename))
        post.image_url = image.filename

    if 'title' not in data or 'body' not in data:
        return bad_request('must include title and body fields')

    post.user_id = token_auth.current_user().id
    post.from_dict(data)
    db.session.add(post)
    db.session.commit()
    response = jsonify(post.to_dict(token_auth.current_user()))
    response.status_code = 201
    response.headers['Location'] = url_for('api.get_post', id=post.id)
    return response
Beispiel #18
0
def update_post(id):
    post = Post.query.get_or_404(id)
    data = request.form.to_dict() or {}
    if request.files:
        image = request.files["file"]
        image.save(os.path.join(
            current_app.config["IMAGE_UPLOADS"], image.filename))
        post.image_url = image.filename
    else:
        post.image_url = ''
    post.from_dict(data)
    db.session.commit()
    return jsonify(post.to_dict(token_auth.current_user()))
Beispiel #19
0
def unpin_music(id):
    user = token_auth.current_user()
    music_item = MusicItem.query.get_or_404(id)
    if user.is_pinned(music_item) is None:
        return bad_request('Music video not found in pinned list')
    if music_item.pin_count is None:
        music_item.pin_count = 0
    else:
        setattr(music_item, 'pin_count', MusicItem.pin_count - 1)
    db.session.add(music_item)
    user.unpin_music_item(music_item)
    db.session.commit()
    return '', 204
Beispiel #20
0
def update_post(id):
    post = Post.query.get_or_404(id)

    if token_auth.current_user().id != post.user_id:
        abort(403)

    data = request.get_json() or {}
    if 'body' not in data:
        return bad_request('Must include body field')

    post.from_dict(data, new_post=False)
    db.session.commit()
    return jsonify(post.to_dict())
Beispiel #21
0
def update_user(id):
    if token_auth.current_user().id != id:
        abort(403)
    user = User.query.get_or_404(id)
    data = request.get_json() or {}
    if 'username' not in data and 'about_me' not in data:
        return bad_request('include username or about_me')
    if 'username' in data and User.query.filter_by(
            username=data['username']).first():
        return bad_request('This username already exists')
    user.from_dict(data)
    db.session.commit()
    return jsonify(user.to_dict())
Beispiel #22
0
def update_user(id):
    if token_auth.current_user().id != id:
        abort(403)
    user = User.query.get_or_404(id)
    data = request.get_json() or {}
    if ("username" in data and data["username"] != user.username
            and User.query.filter_by(username=data["username"]).first()):
        return bad_request("please use a different username")
    if ("email" in data and data["email"] != user.email
            and User.query.filter_by(email=data["email"]).first()):
        return bad_request("please use a different email address")
    user.from_dict(data, new_user=False)
    db.session.commit()
    return jsonify(user.to_dict())
Beispiel #23
0
def delete_file(filename):
    user = token_auth.current_user()
    if not user.verified:
        return error_response(403, 'Email not confirmed')

    file = File.query.filter_by(fullname=filename, user_id=user.id).first()
    if not file:
        return error_response(404, 'File {} does not exist'.format(filename))

    filepath = Path(file.path)
    filepath.unlink()
    db.session.delete(file)
    db.session.commit()
    return '', 204
Beispiel #24
0
def update_user(id):
 if token_auth.current_user().id != id:
  abort(403)
 user = User.query.get_or_404(id)
 data = request.get_json() or {}
 if 'username' in data and data['username'] != user.username and \
   User.query.filter_by(username=data['username'].lower()).first():
  return bad_request('please use a different username.')
 if 'email' in data and data['email'] != user.email and \
   User.query.filter_by(email=data['email']).first():
  return bad_request('Please use a different email address.')
 user.from_dict(data, new_user=False)
 db.session.commit()
 return jsonify(user.to_dict())
Beispiel #25
0
def create_post():
    data = request.get_json() or {}
    data['user_id'] = token_auth.current_user().id
    if 'body' not in data:
        return bad_request('Must include body field')

    post = Post()
    post.from_dict(data, new_post=True)
    db.session.add(post)
    db.session.commit()
    response = jsonify(user.to_dict())
    response.status_code = 201
    response.headers['Location'] = url_for('api.get_post', id=post.id)
    return response
Beispiel #26
0
def update_user(id):
    if token_auth.current_user().id != id:
        abort(403)
    user = User.query.get_or_404(id)
    data = request.get_json() or {}
    if 'username' in data and user.username != data['username']:
        if User.query.filter_by(username=data['username']).first():
            return bad_request('Username already taken')
    if 'email' in data and user.email != data['email']:
        if User.query.filter_by(email=data['email']).first():
            return bad_request('Email already taken')
    user.from_dict(data)
    db.session.commit()
    return jsonify(user.to_dict())
Beispiel #27
0
def update_user(id):
    if token_auth.current_user().id != id:
        abort(403)
    user = User.query.get_or_404(id)
    data = request.form.to_dict() or {}
    if request.files and request.files["file"]:
        image = request.files["file"]
        image.save(
            os.path.join(current_app.config["IMAGE_UPLOADS"], image.filename))
        user.image_url = image.filename
    elif request.files and request.files["filename"]:
        user.image_url = request.files["filename"]
    else:
        user.image_url = None

    if 'username' in data and data['username'] != user.username and \
            User.query.filter_by(username=data['username']).first():
        return bad_request('please use a different username')
    if 'email' in data and data['email'] != user.email and \
            User.query.filter_by(email=data['email']).first():
        return bad_request('please use a different email address')
    user.from_dict(data, new_user=False)
    db.session.commit()
    return jsonify(user.to_dict(token_auth.current_user()))
Beispiel #28
0
def get_user(id):
    """
        API that returns the data for a specific user identified through its id

        :param id: the current user identifier
        :type id: int

        :return: the Response object containing the data (in JSON format)
        :rtype: flask.wrappers.Response
    """

    if token_auth.current_user().id != id:

        abort(403)

    return jsonify(User.query.get_or_404(id).to_dict())
Beispiel #29
0
def update_user(id):
    """	Modify a user.

    Args:
        id (int): User ID.
    """
    if token_auth.current_user().id != id:
        abort(403)
    user = User.query.get_or_404(id)
    data = request.get_json() or {}
    if 'username' in data and data['username'] != user.username and \
            User.query.filter_by(username=data['username']).first():
        return bad_request('please use a different username')

    user.from_dict(data, new_user=False)
    db.session.commit()
    return jsonify(user.to_dict())
Beispiel #30
0
def create_music_item():
    data = request.get_json() or {}
    user = token_auth.current_user()
    if 'resource_type' not in data or 'resource_id' not in data:
        return bad_request('must include resource type and resource id fields')
    music_item = MusicItem.query.filter_by(resource_type=data['resource_type'], 
            resource_id=data['resource_id']).first()
    if music_item:
        if music_item.private == False: 
            return bad_request('Music video already publicly avaliable')
        if user.is_in_private_list(music_item): 
            return bad_request('Music video is already in private list')
    if music_item is None:
        music_item = MusicItem()
        music_item.from_dict(data, private=True)
    user.create_private_music_item(music_item)
    db.session.commit()
    return '', 201