Tests
- Improved directory structure - Added functional and unit tests
This commit is contained in:
0
api/app/blueprints/__init__.py
Normal file
0
api/app/blueprints/__init__.py
Normal file
91
api/app/blueprints/keyword.py
Normal file
91
api/app/blueprints/keyword.py
Normal file
@@ -0,0 +1,91 @@
|
||||
import os
|
||||
|
||||
from apiflask import APIBlueprint, abort
|
||||
|
||||
from app.db import database as db
|
||||
from app.helper_functions import make_response, get_email_or_abort_401
|
||||
from app.auth import auth
|
||||
from app.schema import KeywordResponseSchema, KeywordSchema, DeleteSuccessfulSchema
|
||||
from app.models import Keyword
|
||||
|
||||
keyword_blueprint = APIBlueprint('keyword', __name__, url_prefix='/api')
|
||||
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
|
||||
|
||||
|
||||
@keyword_blueprint.route('/keyword', methods=['POST'])
|
||||
@keyword_blueprint.output(KeywordResponseSchema(many=True), 200)
|
||||
@keyword_blueprint.input(schema=KeywordSchema)
|
||||
@keyword_blueprint.auth_required(auth)
|
||||
@keyword_blueprint.doc(summary="Add new keyword", description="Adds new keyword for current user")
|
||||
def add_keyword(data):
|
||||
email = get_email_or_abort_401()
|
||||
|
||||
if not check_if_keyword_data_exists(data):
|
||||
abort(400, message="Keyword missing")
|
||||
|
||||
key = data['keyword']
|
||||
|
||||
check_keyword = db.session.query(Keyword).filter_by(keyword=key, email=email).first()
|
||||
if check_keyword is None:
|
||||
# Keyword doesn't exist yet for this user
|
||||
new_keyword = Keyword(
|
||||
email=email,
|
||||
keyword=key
|
||||
)
|
||||
db.session.add(new_keyword)
|
||||
db.session.commit()
|
||||
|
||||
return make_response(new_keyword.as_dict(), 200, "Successfully added keyword")
|
||||
else:
|
||||
abort(500, message="Keyword already exist for this user")
|
||||
|
||||
|
||||
@keyword_blueprint.route('/keyword', methods=['DELETE'])
|
||||
@keyword_blueprint.output(DeleteSuccessfulSchema, 200)
|
||||
@keyword_blueprint.input(schema=KeywordSchema)
|
||||
@keyword_blueprint.auth_required(auth)
|
||||
@keyword_blueprint.doc(summary="Removes existing keyword", description="Removes existing keyword for current user")
|
||||
def remove_keyword(data):
|
||||
email = get_email_or_abort_401()
|
||||
|
||||
if not check_if_keyword_data_exists(data):
|
||||
abort(400, message="Keyword missing")
|
||||
|
||||
key = data['keyword']
|
||||
|
||||
check_keyword = db.session.query(Keyword).filter_by(keyword=key, email=email).first()
|
||||
|
||||
if check_keyword is None:
|
||||
return abort(500, "Keyword doesn't exist for this user")
|
||||
else:
|
||||
db.session.query(Keyword).filter_by(keyword=key, email=email).delete()
|
||||
db.session.commit()
|
||||
|
||||
return make_response({}, 200, "Successfully removed keyword")
|
||||
|
||||
|
||||
@keyword_blueprint.route('/keywords', methods=['GET'])
|
||||
@keyword_blueprint.output(KeywordResponseSchema(many=True), 200)
|
||||
@keyword_blueprint.auth_required(auth)
|
||||
@keyword_blueprint.doc(summary="Returns all keywords", description="Returns all keywords for current user")
|
||||
def get_keywords():
|
||||
email = get_email_or_abort_401()
|
||||
|
||||
return_keywords = []
|
||||
keywords = db.session.query(Keyword).filter_by(email=email).all()
|
||||
|
||||
if keywords is not None:
|
||||
for row in keywords:
|
||||
return_keywords.append(row.as_dict())
|
||||
|
||||
return make_response(return_keywords, 200, "Successfully loaded keywords")
|
||||
|
||||
|
||||
def check_if_keyword_data_exists(data):
|
||||
if "keyword" not in data:
|
||||
return False
|
||||
|
||||
if data['keyword'] == "" or data['keyword'] is None:
|
||||
return False
|
||||
|
||||
return True
|
33
api/app/blueprints/portfolio.py
Normal file
33
api/app/blueprints/portfolio.py
Normal file
@@ -0,0 +1,33 @@
|
||||
import os
|
||||
|
||||
from apiflask import APIBlueprint
|
||||
|
||||
from app.schema import PortfolioResponseSchema
|
||||
from app.db import database as db
|
||||
from app.helper_functions import make_response, get_email_or_abort_401
|
||||
from app.auth import auth
|
||||
|
||||
portfolio_blueprint = APIBlueprint('portfolio', __name__, url_prefix='/api')
|
||||
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
|
||||
|
||||
|
||||
@portfolio_blueprint.route('/portfolio', methods=['GET'])
|
||||
@portfolio_blueprint.output(PortfolioResponseSchema(many=True), 200)
|
||||
@portfolio_blueprint.auth_required(auth)
|
||||
@portfolio_blueprint.doc(summary="Returns portfolio", description="Returns all shares of current user")
|
||||
def get_portfolio():
|
||||
email = get_email_or_abort_401()
|
||||
|
||||
return_portfolio = []
|
||||
transactions = db.session.execute("SELECT symbol, SUM(count), SUM(price), MAX(time) FROM `transactions` WHERE email = '" + email + "' GROUP BY symbol;").all()
|
||||
|
||||
if transactions is not None:
|
||||
for row in transactions:
|
||||
return_portfolio.append({
|
||||
"symbol": row[0],
|
||||
"count": row[1],
|
||||
# "price": row[2],
|
||||
"last_transaction": row[3]
|
||||
})
|
||||
|
||||
return make_response(return_portfolio, 200, "Successfully loaded symbols")
|
91
api/app/blueprints/shares.py
Normal file
91
api/app/blueprints/shares.py
Normal file
@@ -0,0 +1,91 @@
|
||||
import os
|
||||
|
||||
from apiflask import APIBlueprint, abort
|
||||
|
||||
from app.auth import auth
|
||||
from app.db import database as db
|
||||
from app.helper_functions import make_response, get_email_or_abort_401
|
||||
from app.models import Share
|
||||
from app.schema import SymbolSchema, SymbolResponseSchema, DeleteSuccessfulSchema
|
||||
|
||||
shares_blueprint = APIBlueprint('share', __name__, url_prefix='/api')
|
||||
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
|
||||
|
||||
|
||||
@shares_blueprint.route('/share', methods=['POST'])
|
||||
@shares_blueprint.output(SymbolResponseSchema(many=True), 200)
|
||||
@shares_blueprint.input(schema=SymbolSchema)
|
||||
@shares_blueprint.auth_required(auth)
|
||||
@shares_blueprint.doc(summary="Add new symbol", description="Adds new symbol for current user")
|
||||
def add_symbol(data):
|
||||
email = get_email_or_abort_401()
|
||||
|
||||
if not check_if_symbol_data_exists(data):
|
||||
abort(400, message="Symbol missing")
|
||||
|
||||
symbol = data['symbol']
|
||||
|
||||
check_share = db.session.query(Share).filter_by(symbol=symbol, email=email).first()
|
||||
if check_share is None:
|
||||
# Keyword doesn't exist yet for this user
|
||||
new_symbol = Share(
|
||||
email=email,
|
||||
symbol=symbol
|
||||
)
|
||||
db.session.add(new_symbol)
|
||||
db.session.commit()
|
||||
|
||||
return make_response(new_symbol.as_dict(), 200, "Successfully added symbol")
|
||||
else:
|
||||
abort(500, "Symbol already exist for this user")
|
||||
|
||||
|
||||
@shares_blueprint.route('/share', methods=['DELETE'])
|
||||
@shares_blueprint.output(DeleteSuccessfulSchema, 200)
|
||||
@shares_blueprint.input(schema=SymbolSchema)
|
||||
@shares_blueprint.auth_required(auth)
|
||||
@shares_blueprint.doc(summary="Removes existing symbol", description="Removes existing symbol for current user")
|
||||
def remove_symbol(data):
|
||||
email = get_email_or_abort_401()
|
||||
|
||||
if not check_if_symbol_data_exists(data):
|
||||
abort(400, message="Symbol missing")
|
||||
|
||||
symbol = data['symbol']
|
||||
|
||||
check_share = db.session.query(Share).filter_by(symbol=symbol, email=email).first()
|
||||
|
||||
if check_share is None:
|
||||
abort(500, "Symbol doesn't exist for this user")
|
||||
else:
|
||||
db.session.query(Share).filter_by(symbol=symbol, email=email).delete()
|
||||
db.session.commit()
|
||||
|
||||
return make_response({}, 200, "Successfully removed symbol")
|
||||
|
||||
|
||||
@shares_blueprint.route('/shares', methods=['GET'])
|
||||
@shares_blueprint.output(SymbolResponseSchema(many=True), 200)
|
||||
@shares_blueprint.auth_required(auth)
|
||||
@shares_blueprint.doc(summary="Returns all symbols", description="Returns all symbols for current user")
|
||||
def get_symbol():
|
||||
email = get_email_or_abort_401()
|
||||
|
||||
return_symbols = []
|
||||
symbols = db.session.query(Share).filter_by(email=email).all()
|
||||
|
||||
if symbols is not None:
|
||||
for row in symbols:
|
||||
return_symbols.append(row.as_dict())
|
||||
|
||||
return make_response(return_symbols, 200, "Successfully loaded symbols")
|
||||
|
||||
|
||||
def check_if_symbol_data_exists(data):
|
||||
if "symbol" not in data:
|
||||
return False
|
||||
|
||||
if data['symbol'] == "" or data['symbol'] is None:
|
||||
return False
|
||||
|
||||
return True
|
40
api/app/blueprints/telegram.py
Normal file
40
api/app/blueprints/telegram.py
Normal file
@@ -0,0 +1,40 @@
|
||||
import os
|
||||
|
||||
from apiflask import APIBlueprint, abort
|
||||
|
||||
from app.db import database as db
|
||||
from app.helper_functions import make_response, get_email_or_abort_401
|
||||
from app.auth import auth
|
||||
from app.schema import TelegramIdSchema, UsersSchema
|
||||
from app.models import User
|
||||
|
||||
telegram_blueprint = APIBlueprint('telegram', __name__, url_prefix='/api')
|
||||
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
|
||||
|
||||
|
||||
@telegram_blueprint.route('/telegram', methods=['POST'])
|
||||
@telegram_blueprint.output(UsersSchema(many=False), 200)
|
||||
@telegram_blueprint.input(schema=TelegramIdSchema)
|
||||
@telegram_blueprint.auth_required(auth)
|
||||
@telegram_blueprint.doc(summary="Connects telegram user id", description="Connects telegram user id to user account")
|
||||
def add_keyword(data):
|
||||
email = get_email_or_abort_401()
|
||||
|
||||
if not check_if_telegram_user_id_data_exists(data):
|
||||
abort(400, message="User ID missing")
|
||||
|
||||
query_user = db.session.query(User).filter_by(email=email).first()
|
||||
query_user.telegram_user_id = data['telegram_user_id']
|
||||
db.session.commit()
|
||||
|
||||
return make_response(query_user.as_dict(), 200, "Successfully connected telegram user")
|
||||
|
||||
|
||||
def check_if_telegram_user_id_data_exists(data):
|
||||
if "telegram_user_id" not in data:
|
||||
return False
|
||||
|
||||
if data['telegram_user_id'] == "" or data['telegram_user_id'] is None:
|
||||
return False
|
||||
|
||||
return True
|
103
api/app/blueprints/transactions.py
Normal file
103
api/app/blueprints/transactions.py
Normal file
@@ -0,0 +1,103 @@
|
||||
import os
|
||||
import datetime
|
||||
|
||||
from apiflask import abort, APIBlueprint
|
||||
|
||||
from app.db import database as db
|
||||
from app.helper_functions import make_response, get_email_or_abort_401
|
||||
from app.models import Transaction
|
||||
from app.schema import TransactionSchema, TransactionResponseSchema
|
||||
from app.auth import auth
|
||||
|
||||
transaction_blueprint = APIBlueprint('transaction', __name__, url_prefix='/api')
|
||||
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
|
||||
|
||||
|
||||
@transaction_blueprint.route('/transaction', methods=['POST'])
|
||||
@transaction_blueprint.output(TransactionResponseSchema(), 200)
|
||||
@transaction_blueprint.input(schema=TransactionSchema)
|
||||
@transaction_blueprint.auth_required(auth)
|
||||
@transaction_blueprint.doc(summary="Adds new transaction", description="Adds new transaction for current user")
|
||||
def add_transaction(data):
|
||||
email = get_email_or_abort_401()
|
||||
|
||||
if not check_if_symbol_data_exists(data):
|
||||
abort(400, "Symbol missing")
|
||||
|
||||
if not check_if_time_data_exists(data):
|
||||
abort(400, "Time missing")
|
||||
|
||||
if not check_if_count_data_exists(data):
|
||||
abort(400, "Count missing")
|
||||
|
||||
if not check_if_price_data_exists(data):
|
||||
abort(400, "Price missing")
|
||||
|
||||
new_transaction = Transaction(
|
||||
email=email,
|
||||
symbol=data['symbol'],
|
||||
time=datetime.datetime.strptime(data['time'], '%Y-%m-%dT%H:%M:%S.%fZ'),
|
||||
count=data['count'],
|
||||
price=data['price']
|
||||
)
|
||||
db.session.add(new_transaction)
|
||||
db.session.commit()
|
||||
|
||||
return make_response(new_transaction.as_dict(), 200, "Successfully added transaction")
|
||||
|
||||
|
||||
@transaction_blueprint.route('/transactions', methods=['GET'])
|
||||
@transaction_blueprint.output(TransactionSchema(), 200)
|
||||
@transaction_blueprint.auth_required(auth)
|
||||
@transaction_blueprint.doc(summary="Returns all transactions", description="Returns all transactions for current user")
|
||||
def get_transaction():
|
||||
email = get_email_or_abort_401()
|
||||
|
||||
return_transactions = []
|
||||
transactions = db.session.query(Transaction).filter_by(email=email).all()
|
||||
|
||||
if transactions is not None:
|
||||
for row in transactions:
|
||||
return_transactions.append(row.as_dict())
|
||||
|
||||
return make_response(return_transactions, 200, "Successfully loaded transactions")
|
||||
|
||||
|
||||
def check_if_symbol_data_exists(data):
|
||||
if "symbol" not in data:
|
||||
return False
|
||||
|
||||
if data['symbol'] == "" or data['symbol'] is None:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def check_if_time_data_exists(data):
|
||||
if "time" not in data:
|
||||
return False
|
||||
|
||||
if data['time'] == "" or data['time'] is None:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def check_if_count_data_exists(data):
|
||||
if "count" not in data:
|
||||
return False
|
||||
|
||||
if data['count'] == "" or data['count'] is None:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def check_if_price_data_exists(data):
|
||||
if "price" not in data:
|
||||
return False
|
||||
|
||||
if data['price'] == "" or data['price'] is None:
|
||||
return False
|
||||
|
||||
return True
|
218
api/app/blueprints/user.py
Normal file
218
api/app/blueprints/user.py
Normal file
@@ -0,0 +1,218 @@
|
||||
import datetime
|
||||
import os
|
||||
from flask import current_app
|
||||
|
||||
import jwt
|
||||
from apiflask import APIBlueprint, abort
|
||||
|
||||
from app.db import database as db
|
||||
from app.helper_functions import check_password, hash_password, abort_if_no_admin, make_response, get_email_or_abort_401
|
||||
from app.models import User
|
||||
from app.schema import UsersSchema, TokenSchema, LoginDataSchema, AdminDataSchema, DeleteUserSchema, RegisterDataSchema, UpdateUserDataSchema
|
||||
from app.auth import auth
|
||||
|
||||
users_blueprint = APIBlueprint('users', __name__, url_prefix='/api')
|
||||
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
|
||||
|
||||
|
||||
@users_blueprint.route('/users', methods=['GET'])
|
||||
@users_blueprint.output(UsersSchema(many=True), 200)
|
||||
@users_blueprint.auth_required(auth)
|
||||
@users_blueprint.doc(summary="Get all users", description="Returns all existing users as array")
|
||||
def users():
|
||||
abort_if_no_admin()
|
||||
|
||||
res = []
|
||||
for i in User.query.all():
|
||||
res.append(i.as_dict())
|
||||
|
||||
return make_response(res, 200, "Successfully received all users")
|
||||
|
||||
|
||||
@users_blueprint.route('/user', methods=['GET'])
|
||||
@users_blueprint.output(UsersSchema(), 200)
|
||||
@users_blueprint.auth_required(auth)
|
||||
@users_blueprint.doc(summary="Get current user", description="Returns current user")
|
||||
def user():
|
||||
email = get_email_or_abort_401()
|
||||
|
||||
res = db.session.query(User).filter_by(email=email).first().as_dict()
|
||||
|
||||
return make_response(res, 200, "Successfully received current user data")
|
||||
|
||||
|
||||
@users_blueprint.route('/user/login', methods=['POST'])
|
||||
@users_blueprint.output(TokenSchema(), 200)
|
||||
@users_blueprint.input(schema=LoginDataSchema)
|
||||
@users_blueprint.doc(summary="Login", description="Returns jwt token if username and password match, otherwise returns error")
|
||||
def login(data):
|
||||
if not check_if_password_data_exists(data):
|
||||
abort(400, "Password missing")
|
||||
|
||||
if not check_if_email_data_exists(data):
|
||||
abort(400, "Email missing")
|
||||
|
||||
email = data['email']
|
||||
password = data['password']
|
||||
|
||||
query_user = db.session.query(User).filter_by(email=email).first()
|
||||
|
||||
if query_user is None: # email doesn't exist
|
||||
abort(500, message="Unable to login")
|
||||
|
||||
if not check_password(query_user.password, password.encode("utf-8")): # Password incorrect
|
||||
abort(500, message="Unable to login")
|
||||
|
||||
if query_user.email == current_app.config['BOT_EMAIL']:
|
||||
token = jwt.encode({'email': query_user.email, 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=365)}, current_app.config['SECRET_KEY'], "HS256")
|
||||
else:
|
||||
token = jwt.encode({'email': query_user.email, 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1)}, current_app.config['SECRET_KEY'], "HS256")
|
||||
|
||||
return make_response({"token": token}, 200, "Successfully logged in")
|
||||
|
||||
|
||||
@users_blueprint.route('/user/register', methods=['POST'])
|
||||
@users_blueprint.output(UsersSchema(), 200)
|
||||
@users_blueprint.input(schema=RegisterDataSchema)
|
||||
@users_blueprint.doc(summary="Register", description="Registers user")
|
||||
def register(data):
|
||||
if not check_if_email_data_exists(data):
|
||||
abort(400, "Email missing")
|
||||
|
||||
if not check_if_username_data_exists(data):
|
||||
abort(400, "Username missing")
|
||||
|
||||
if not check_if_password_data_exists(data):
|
||||
abort(400, "Password missing")
|
||||
|
||||
email = data['email']
|
||||
username = data['username']
|
||||
password = data['password']
|
||||
|
||||
query_user = db.session.query(User).filter_by(email=email).first()
|
||||
|
||||
if query_user is not None: # Username already exist
|
||||
abort(500, message="Email already exist")
|
||||
|
||||
new_user = User(
|
||||
email=email,
|
||||
username=username,
|
||||
password=hash_password(password),
|
||||
admin=False
|
||||
)
|
||||
db.session.add(new_user)
|
||||
db.session.commit()
|
||||
|
||||
return make_response(new_user.as_dict(), 200, "Successfully registered user")
|
||||
|
||||
|
||||
@users_blueprint.route('/user', methods=['PUT'])
|
||||
@users_blueprint.output({}, 200)
|
||||
@users_blueprint.input(schema=UpdateUserDataSchema)
|
||||
@users_blueprint.auth_required(auth)
|
||||
@users_blueprint.doc(summary="Update user", description="Changes password and/or username of current user")
|
||||
def update_user(data):
|
||||
email = get_email_or_abort_401()
|
||||
|
||||
query_user = db.session.query(User).filter_by(email=email).first()
|
||||
|
||||
if check_if_password_data_exists(data):
|
||||
query_user.password = hash_password(data['password'])
|
||||
|
||||
if check_if_username_data_exists(data):
|
||||
query_user.username = data['username']
|
||||
|
||||
db.session.commit()
|
||||
|
||||
return make_response({}, 200, "Successfully updated user")
|
||||
|
||||
|
||||
@users_blueprint.route('/user/setAdmin', methods=['PUT'])
|
||||
@users_blueprint.output({}, 200)
|
||||
@users_blueprint.input(schema=AdminDataSchema)
|
||||
@users_blueprint.auth_required(auth)
|
||||
@users_blueprint.doc(summary="Set user admin state", description="Set admin state of specified user")
|
||||
def set_admin(data):
|
||||
abort_if_no_admin() # Only admin users can do this
|
||||
|
||||
if not check_if_email_data_exists(data):
|
||||
abort(400, "Email missing")
|
||||
|
||||
if not check_if_admin_data_exists(data):
|
||||
abort(400, "Admin data missing")
|
||||
|
||||
email = data['email']
|
||||
admin = data['admin']
|
||||
|
||||
query_user = db.session.query(User).filter_by(email=email).first()
|
||||
|
||||
if query_user is None: # Username doesn't exist
|
||||
abort(500, message="Unable to update user")
|
||||
|
||||
query_user.admin = admin
|
||||
db.session.commit()
|
||||
|
||||
return make_response({}, 200, "Successfully updated users admin rights")
|
||||
|
||||
|
||||
@users_blueprint.route('/user', methods=['DELETE'])
|
||||
@users_blueprint.output({}, 200)
|
||||
@users_blueprint.input(schema=DeleteUserSchema)
|
||||
@users_blueprint.auth_required(auth)
|
||||
@users_blueprint.doc(summary="Delete user", description="Deletes user by username")
|
||||
def delete_user(data):
|
||||
if not check_if_email_data_exists(data):
|
||||
abort(400, "Email missing")
|
||||
|
||||
email = data['email']
|
||||
|
||||
if email == get_email_or_abort_401(): # Username is same as current user
|
||||
db.session.query(User).filter_by(email=email).delete()
|
||||
db.session.commit()
|
||||
else: # Delete different user than my user -> only admin users
|
||||
abort_if_no_admin()
|
||||
|
||||
db.session.query(User).filter_by(email=email).delete()
|
||||
db.session.commit()
|
||||
|
||||
return make_response({}, 200, "Successfully removed user")
|
||||
|
||||
|
||||
def check_if_email_data_exists(data):
|
||||
if "email" not in data:
|
||||
return False
|
||||
|
||||
if data['email'] == "" or data['email'] is None:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def check_if_password_data_exists(data):
|
||||
if "password" not in data:
|
||||
return False
|
||||
|
||||
if data['password'] == "" or data['password'] is None:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def check_if_username_data_exists(data):
|
||||
if "username" not in data:
|
||||
return False
|
||||
|
||||
if data['username'] == "" or data['username'] is None:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def check_if_admin_data_exists(data):
|
||||
if "admin" not in data:
|
||||
return False
|
||||
|
||||
if data['admin'] == "" or data['admin'] is None:
|
||||
return False
|
||||
|
||||
return True
|
Reference in New Issue
Block a user