Exemple #1
0
def register():
    details = request.get_json()

    resultproxy = db.session.execute('SELECT * FROM users WHERE username = :1',
                                     {'1': details['username']})
    response = format_resp(resultproxy)
    if (len(response) == 1):
        return jsonify("Username Taken"), 401

    resultproxy = db.session.execute('SELECT * FROM users WHERE email = :1',
                                     {'1': details['email']})
    response = format_resp(resultproxy)
    if (len(response) == 1):
        return jsonify("Email Already Registered to Account"), 401

    hash_pw = pw.hash(details['password'])
    resultproxy = db.session.execute(
        'INSERT INTO users (username,hash,email) VALUES (:1, :2, :3) RETURNING username, id',
        {
            '1': details['username'],
            '2': hash_pw,
            '3': details['email']
        })
    response = format_resp(resultproxy)
    db.session.execute(
        'INSERT INTO balance (user_id,balance) VALUES (:1, 10000)',
        {'1': response[0]['id']})
    db.session.commit()
    resp = {'username': response[0]['username'], 'status': 200}

    return jsonify(resp)
Exemple #2
0
def portfolio():
    user_id = get_jwt_identity()
    username = db.session.execute('SELECT username FROM users WHERE id = :1',
                                  {'1': user_id})
    username_val = format_resp(username)
    balance = db.session.execute(
        'SELECT balance FROM balance WHERE user_id = :1', {'1': user_id})
    balance_val = format_resp(balance)
    balance_round = round(balance_val[0]['balance'], 2)
    equity = db.session.execute(
        'SELECT user_id, SUM(position) AS sum FROM portfolio GROUP BY user_id HAVING user_id = :1',
        {'1': user_id})
    equity_val = format_resp(equity)
    if len(equity_val) > 0:
        equity_round = round(equity_val[0]['sum'], 2)
        stocks = db.session.execute(
            'SELECT * FROM portfolio WHERE user_id = :1 ORDER BY name',
            {'1': user_id})
        stock_list = format_resp(stocks)
    else:
        equity_round = 0
        stock_list = []
    portfolio = {
        'cash': balance_round,
        'equity': equity_round,
        'portfolio': stock_list,
        'username': username_val[0]['username']
    }
    return jsonify(portfolio), 200
Exemple #3
0
def register():

    check = check_token()
    if check['error'] == True:
        return jsonify(check['message']), check['status']

    details = request.get_json()
    if 'username' not in details or type(details['username']) != str:
        return jsonify({
            'error':
            'Key \'username\' Not Present in Request Body or of Invalid Type (str expected)'
        }), 400

    uid = check['uid']

    try:
        result_proxy = db.session.execute(
            'INSERT INTO users (uid, username) VALUES (:1, :2) RETURNING username',
            {
                '1': uid,
                '2': details['username']
            })
        response = format_resp(result_proxy)
        db.session.commit()
    except sqlalchemy.exc.SQLAlchemyError:
        return jsonify({'error': 'Error Writing to Database'}), 500
    return jsonify(f"Welcome, {response[0]['username']}")
Exemple #4
0
def compare_auth():
    user_id = get_jwt_identity()
    total_breakdown = db.session.execute(
        'WITH sum AS (SELECT user_id, SUM(position) AS stock FROM portfolio GROUP BY 1) SELECT users.id, users.username, balance.balance, sum.stock FROM users INNER JOIN balance ON users.id = balance.user_id INNER JOIN sum ON users.id = sum.user_id WHERE users.id != :1',
        {'1': user_id})
    total_breakdown = format_resp(total_breakdown)

    for user in total_breakdown:
        portfolio_total = user['balance'] + user['stock']
        user['balance'] = user['balance'] / portfolio_total
        user['stock'] = user['stock'] / portfolio_total

    stock_breakdown = db.session.execute(
        'SELECT user_id, ticker, name, exchange, position FROM portfolio WHERE user_id != :1;',
        {'1': user_id})
    stock_breakdown = format_resp(stock_breakdown)
    stock_grouped = {}
    for stock in stock_breakdown:
        if stock['user_id'] in stock_grouped:
            stock_grouped[stock['user_id']].append(stock)
        else:
            stock_grouped[stock['user_id']] = [stock]

    for user_id in stock_grouped:
        user_list = stock_grouped[user_id]
        stock_total = 0
        for stock in user_list:
            stock_total += stock['position']
        for stock in user_list:
            stock['position'] = stock['position'] / stock_total

    auth_compare = []
    for user in total_breakdown:
        total_object = {'stock': user['stock'], 'balance': user['balance']}

        compare_object = {
            'id': user['id'],
            'username': user['username'],
            'total_breakdown': total_object,
            'stock_breakdown': stock_grouped[user['id']]
        }

        auth_compare.append(compare_object)

    return jsonify(auth_compare)
Exemple #5
0
def test():
    decoded_token = auth.verify_id_token(
        "eyJhbGciOiJSUzI1NiIsImtpZCI6IjIzNzA1ZmNmY2NjMTg4Njg2ZjhhZjkyYWJiZjAxYzRmMjZiZDVlODMiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vdGVzdC01YjA0ZSIsImF1ZCI6InRlc3QtNWIwNGUiLCJhdXRoX3RpbWUiOjE2MDI2ODA3MDAsInVzZXJfaWQiOiJENFBlNFh3SHAwWm1Tc283ZWs0amN1NWZuWUgyIiwic3ViIjoiRDRQZTRYd0hwMFptU3NvN2VrNGpjdTVmbllIMiIsImlhdCI6MTYwMjY4MDcwOCwiZXhwIjoxNjAyNjg0MzA4LCJlbWFpbCI6InVzZXIxQHRlc3QuY29tIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJmaXJlYmFzZSI6eyJpZGVudGl0aWVzIjp7ImVtYWlsIjpbInVzZXIxQHRlc3QuY29tIl19LCJzaWduX2luX3Byb3ZpZGVyIjoicGFzc3dvcmQifX0.nKnsEa8QEOGq2vlkMPa3k-NRWUeUpoBl4gqXYDKNOrId8EDqwU_a-mvOwIxoR-wVmGyEeUCpbx7TQEm8jzJxERNiOPiyCeEvcrcdR_ofeSQffj2DQVl8okLkVf5ff9yJ8OrRTszSKRl3CLeoSR9gBBfIhWoZiJPXKga1W-GorbTyv7qFMjDzgCejVbge7z0axaD9teNtOMd1aq-bGIYO7njJCHVfUd0xiCj9mYwEo5ckUtlOFti5L-AcRxAgIuIByUFiPtQuF24TGralRRlIsgAylfqVrDu-hAB2aBWKtL7IV7Et4Wjgfc6CDyxDwYuR7RLhDKHuCh3wO-EGBmKBYQ"
    )
    uid = decoded_token['uid']
    resultproxy = db.session.execute(
        'SELECT username FROM users WHERE uid = :1', {'1': uid})
    response = format_resp(resultproxy)
    return jsonify(response[0])
Exemple #6
0
def login():
    details = request.get_json()
    resultproxy = db.session.execute('SELECT * FROM users WHERE username = :1',
                                     {'1': details['username']})
    response = format_resp(resultproxy)

    if len(response) == 0:
        return jsonify('User Does Not Exist'), 401
    else:
        if (pw.verify(details['password'], response[0]['hash'])):
            token = create_access_token(identity=response[0]["id"],
                                        expires_delta=False)

            check_ticker = {}
            result_proxy = db.session.execute(
                'SELECT id, ticker FROM portfolio WHERE user_id= :1',
                {'1': response[0]["id"]})
            stocks = format_resp(result_proxy)
            req_token = os.getenv("TOKEN")
            for stock in stocks:
                if (stock['ticker'] in check_ticker):
                    db.session.execute(
                        'UPDATE portfolio SET price = :1 WHERE id = :2', {
                            '1': check_ticker[stock['ticker']] + 1,
                            '2': stock['id']
                        })
                    db.session.commit()
                else:
                    response = requests.get(
                        f"https://cloud.iexapis.com/stable/stock/{stock['ticker']}/quote?token={req_token}"
                    )
                    response_dict = response.json()
                    new_price = response_dict['latestPrice']
                    db.session.execute(
                        'UPDATE portfolio SET price = :1 WHERE id = :2', {
                            '1': new_price,
                            '2': stock['id']
                        })
                    db.session.commit()
                    check_ticker[stock['ticker']] = new_price

            return jsonify(token=token), 200
        else:
            return jsonify("Password Incorrect"), 401
Exemple #7
0
def breakdown():
    check = check_token()
    if check['error'] == True:
        return jsonify(check['message']), check['status']

    uid = check['uid']

    try:
        month = int(request.args.get('month'))
        year = int(request.args.get('year'))

        if float(request.args.get('month')).is_integer() == False or float(
                request.args.get('year')).is_integer() == False:
            raise ValueError

        if month not in range(1, 13) or year not in range(
                1960,
                dt.now().year + 1) or (year == dt.now().year and month
                                       not in range(1,
                                                    dt.now().month + 1)):
            return jsonify({
                'error':
                'Key(s) \'month\' or \'year\' Outside of Acceptable Range'
            }), 400

    except (TypeError, ValueError):
        return jsonify({
            'error':
            'Key(s) \'month\' or \'year\' Not Present in Query String or of Invalid Type (int expected)'
        }), 400

    result_proxy = db.session.execute(
        'SELECT id, budget, description, category, cost, day FROM history WHERE user_uid = :1 AND month = :2 AND year = :3',
        {
            '1': uid,
            '2': month,
            '3': year
        })
    response = format_resp(result_proxy)

    if len(response) == 0:
        return jsonify({
            'error':
            f"No Entries Corresponding to Time Period {month}/{year}"
        }), 500

    grouped_history = {}

    for entry in response:
        if entry['category'] in grouped_history:
            grouped_history[entry['category']] += entry['cost']
        else:
            grouped_history[entry['category']] = entry['cost']

    return jsonify(grouped_history)
Exemple #8
0
def user():

    check = check_token()
    if check['error'] == True:
        return jsonify(check['message']), check['status']

    uid = check['uid']

    result_proxy = db.session.execute(
        'SELECT username, budget FROM users WHERE uid = :1', {'1': uid})
    response = format_resp(result_proxy)

    if len(response) == 0:
        return jsonify({'error': 'User Not Found'}), 404
    return jsonify(response[0])
Exemple #9
0
def compare_unauth():
    result_proxy = db.session.execute(
        'WITH sum AS (SELECT user_id, SUM(position) AS stock FROM portfolio GROUP BY 1) SELECT users.username, balance.balance, sum.stock FROM users INNER JOIN balance ON users.id = balance.user_id INNER JOIN sum ON users.id = sum.user_id'
    )
    response = format_resp(result_proxy)
    ratio_list = []
    for user in response:
        balance_ratio = user['balance'] / (user['balance'] + user['stock'])
        stock_ratio = user['stock'] / (user['balance'] + user['stock'])
        user_dict = {
            'username': user['username'],
            'balance': balance_ratio,
            'stock': stock_ratio
        }
        ratio_list.append(user_dict)
    return jsonify(ratio_list)
Exemple #10
0
def delete():
    check = check_token()
    if check['error'] == True:
        return jsonify(check['message']), check['status']

    uid = check['uid']

    try:
        db.session.execute('DELETE FROM history WHERE user_uid = :1',
                           {'1': uid})
        result_proxy = db.session.execute(
            'DELETE FROM users WHERE uid = :1 RETURNING username', {'1': uid})
        db.session.commit()
        response = format_resp(result_proxy)
        username = response[0]['username']
    except (sqlalchemy.exc.SQLAlchemyError, IndexError):
        return jsonify({'error': 'Error Writing to Database'}), 500
    return jsonify(f"{username} Permanently Deleted")
Exemple #11
0
def reset():
    check = check_token()
    if check['error'] == True:
        return jsonify(check['message']), check['status']

    uid = check['uid']

    try:
        db.session.execute('DELETE FROM history WHERE user_uid = :1',
                           {'1': uid})
        result_proxy = db.session.execute(
            'UPDATE users SET budget = null WHERE uid = :1 RETURNING username',
            {'1': uid})
        db.session.commit()
        response = format_resp(result_proxy)
    except sqlalchemy.exc.SQLAlchemyError:
        return jsonify({'error': 'Error Writing to Database'}), 500
    return jsonify(f"{response[0]['username']} Account Succesfully Reset")
Exemple #12
0
def budget():

    check = check_token()
    if check['error'] == True:
        return jsonify(check['message']), check['status']

    details = request.get_json()

    try:
        budget = float(details['budget'])

        if budget <= 0:
            raise ValueError

    except (TypeError, ValueError, KeyError):
        return jsonify({
            'error':
            'Key \'budget\' Not Present in Request Body or of Invalid Type (float expected)'
        }), 400

    uid = check['uid']

    try:
        result_proxy = db.session.execute(
            'UPDATE users SET budget = :1 WHERE uid = :2 RETURNING budget', {
                '1': budget,
                '2': uid
            })
        db.session.execute(
            'UPDATE history SET budget = :1 WHERE user_uid = :2 AND month = :3 AND year = :4',
            {
                '1': budget,
                '2': uid,
                '3': dt.now().month,
                '4': dt.now().year
            })
        response = format_resp(result_proxy)
        db.session.commit()
    except sqlalchemy.exc.SQLAlchemyError:
        return jsonify({'error': 'Error Writing to Database'}), 500

    return jsonify(
        f"Budget for {dt.now().month}/{dt.now().year} updated to £{format(budget,'.2f')}"
    )
Exemple #13
0
def spend():

    check = check_token()
    if check['error'] == True:
        return jsonify(check['message']), check['status']

    details = request.get_json()

    try:
        budget = float(details['budget'])
        description = details['description']
        category = details['category']
        cost = float(details['cost'])
        day = int(details['day'])
        month = int(details['month'])
        year = int(details['year'])

        if budget <= 0 or cost <= 0:
            raise ValueError

        if float(details['day']).is_integer() == False or float(
                details['month']).is_integer() == False or float(
                    details['year']).is_integer() == False:
            raise ValueError

        if day not in range(1, 32) or month not in range(
                1, 13) or year > dt.now().year:
            raise ValueError
        elif year == dt.now().year and month not in range(
                1,
                dt.now().month + 1):
            raise ValueError

        if type(description) != str or type(category) != str:
            raise TypeError
    except (TypeError, ValueError, KeyError):
        return jsonify({
            'error':
            'Requried Key(s) Missing in Request Body or of Invalid Type'
        }), 400

    uid = check['uid']

    try:
        result_proxy = db.session.execute(
            'INSERT INTO history (user_uid, budget, description, category, cost, day, month, year) VALUES (:1, :2, :3, :4, :5, :6, :7, :8) RETURNING description',
            {
                '1': uid,
                '2': budget,
                '3': description,
                '4': category,
                '5': cost,
                '6': day,
                '7': month,
                '8': year
            })
        response = format_resp(result_proxy)
        db.session.commit()
    except sqlalchemy.exc.SQLAlchemyError:
        return jsonify({'error': 'Error Writing to Database'}), 500

    return jsonify(
        f"Expenditure '{response[0]['description']}' added to history")
Exemple #14
0
def history():
    user_id = get_jwt_identity()
    result_proxy = db.session.execute(
        'SELECT * FROM history WHERE user_id = :1', {'1': user_id})
    response = format_resp(result_proxy)
    return jsonify(response)