Tests
- Improved directory structure - Added functional and unit tests
This commit is contained in:
67
api/app/__init__.py
Normal file
67
api/app/__init__.py
Normal file
@@ -0,0 +1,67 @@
|
||||
from flask import current_app
|
||||
from apiflask import APIFlask
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from flask_cors import CORS
|
||||
|
||||
from app.blueprints.keyword import keyword_blueprint
|
||||
from app.blueprints.portfolio import portfolio_blueprint
|
||||
from app.blueprints.shares import shares_blueprint
|
||||
from app.blueprints.transactions import transaction_blueprint
|
||||
from app.blueprints.telegram import telegram_blueprint
|
||||
from app.blueprints.user import users_blueprint
|
||||
from app.helper_functions import hash_password
|
||||
from app.models import *
|
||||
|
||||
|
||||
def create_app(config_filename=None):
|
||||
load_dotenv()
|
||||
|
||||
# Create Flask app load app.config
|
||||
application = APIFlask(__name__, openapi_blueprint_url_prefix='/api')
|
||||
application.config.from_pyfile(config_filename)
|
||||
|
||||
CORS(application, resources={r"*": {"origins": "*"}})
|
||||
|
||||
application.app_context().push()
|
||||
|
||||
db.init_app(application)
|
||||
|
||||
# api blueprints
|
||||
application.register_blueprint(keyword_blueprint)
|
||||
application.register_blueprint(shares_blueprint)
|
||||
application.register_blueprint(transaction_blueprint)
|
||||
application.register_blueprint(portfolio_blueprint)
|
||||
application.register_blueprint(users_blueprint)
|
||||
application.register_blueprint(telegram_blueprint)
|
||||
|
||||
@application.before_first_request
|
||||
def init_database():
|
||||
db.create_all()
|
||||
|
||||
if current_app.config['BOT_EMAIL'] is not None and current_app.config['BOT_USERNAME'] is not None and current_app.config['BOT_PASSWORD'] is not None:
|
||||
if db.session.query(User).filter_by(email=current_app.config['BOT_EMAIL']).first() is None: # Check if user already exist
|
||||
bot = User(
|
||||
email=current_app.config['BOT_EMAIL'],
|
||||
username=current_app.config['BOT_USERNAME'],
|
||||
password=hash_password(current_app.config['BOT_PASSWORD']),
|
||||
admin=False
|
||||
)
|
||||
db.session.add(bot)
|
||||
db.session.commit()
|
||||
|
||||
if current_app.config['ADMIN_EMAIL'] is not None and current_app.config['ADMIN_USERNAME'] is not None and current_app.config['ADMIN_PASSWORD'] is not None:
|
||||
if db.session.query(User).filter_by(email=current_app.config['ADMIN_EMAIL']).first() is None: # Check if user already exist
|
||||
admin = User(
|
||||
email=current_app.config['ADMIN_EMAIL'],
|
||||
username=current_app.config['ADMIN_USERNAME'],
|
||||
password=hash_password(current_app.config['ADMIN_PASSWORD']),
|
||||
admin=True
|
||||
)
|
||||
db.session.add(admin)
|
||||
db.session.commit()
|
||||
|
||||
return application
|
||||
|
||||
|
||||
app = create_app("config/flask.cfg")
|
21
api/app/auth.py
Normal file
21
api/app/auth.py
Normal file
@@ -0,0 +1,21 @@
|
||||
from flask import current_app
|
||||
|
||||
import jwt
|
||||
from apiflask import HTTPTokenAuth
|
||||
|
||||
auth = HTTPTokenAuth()
|
||||
|
||||
|
||||
@auth.verify_token
|
||||
def verify_token(token):
|
||||
if token is None:
|
||||
return False
|
||||
|
||||
if ':' in token: # Bot token
|
||||
token = token.split(":")[0]
|
||||
|
||||
try:
|
||||
jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=["HS256"])
|
||||
return True
|
||||
except jwt.PyJWTError:
|
||||
return False
|
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
|
26
api/app/config/flask.cfg
Normal file
26
api/app/config/flask.cfg
Normal file
@@ -0,0 +1,26 @@
|
||||
import os
|
||||
from app.schema import BaseResponseSchema
|
||||
|
||||
# Flask settings
|
||||
SECRET_KEY = os.getenv('SECRET_KEY', 'secret string')
|
||||
|
||||
|
||||
# Flask-SQLAlchemy settings
|
||||
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://" + os.getenv('MYSQL_USER') + ":" + os.getenv('MYSQL_PASSWORD') + "@" + os.getenv('MYSQL_HOST') + ":" + os.getenv('MYSQL_PORT', '3306') + "/" + os.getenv('MYSQL_NAME', 'aktienbot')
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False # Avoids SQLAlchemy warning
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {
|
||||
'pool_size': 100,
|
||||
'pool_recycle': 240 # 4 minutes
|
||||
}
|
||||
|
||||
# openapi/Swagger config
|
||||
BASE_RESPONSE_DATA_KEY = "data"
|
||||
BASE_RESPONSE_SCHEMA = BaseResponseSchema
|
||||
|
||||
BOT_EMAIL = os.getenv('BOT_EMAIL')
|
||||
BOT_USERNAME = os.getenv('BOT_USERNAME')
|
||||
BOT_PASSWORD = os.getenv('BOT_PASSWORD')
|
||||
|
||||
ADMIN_EMAIL = os.getenv('ADMIN_EMAIL')
|
||||
ADMIN_USERNAME = os.getenv('ADMIN_USERNAME')
|
||||
ADMIN_PASSWORD = os.getenv('ADMIN_PASSWORD')
|
26
api/app/config/flask_test.cfg
Normal file
26
api/app/config/flask_test.cfg
Normal file
@@ -0,0 +1,26 @@
|
||||
import os
|
||||
from app.schema import BaseResponseSchema
|
||||
|
||||
# Flask settings
|
||||
SECRET_KEY = os.getenv('SECRET_KEY', 'secret string')
|
||||
|
||||
|
||||
# Flask-SQLAlchemy settings
|
||||
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://" + os.getenv('MYSQL_USER') + ":" + os.getenv('MYSQL_PASSWORD') + "@" + os.getenv('MYSQL_HOST') + ":" + os.getenv('MYSQL_PORT', '3306') + "/" + os.getenv('MYSQL_NAME', 'aktienbot_test')
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False # Avoids SQLAlchemy warning
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {
|
||||
'pool_size': 100,
|
||||
'pool_recycle': 240 # 4 minutes
|
||||
}
|
||||
|
||||
# openapi/Swagger config
|
||||
BASE_RESPONSE_DATA_KEY = "data"
|
||||
BASE_RESPONSE_SCHEMA = BaseResponseSchema
|
||||
|
||||
BOT_EMAIL = os.getenv('BOT_EMAIL')
|
||||
BOT_USERNAME = os.getenv('BOT_USERNAME')
|
||||
BOT_PASSWORD = os.getenv('BOT_PASSWORD')
|
||||
|
||||
ADMIN_EMAIL = os.getenv('ADMIN_EMAIL')
|
||||
ADMIN_USERNAME = os.getenv('ADMIN_USERNAME')
|
||||
ADMIN_PASSWORD = os.getenv('ADMIN_PASSWORD')
|
3
api/app/db.py
Normal file
3
api/app/db.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
|
||||
database = SQLAlchemy()
|
78
api/app/helper_functions.py
Normal file
78
api/app/helper_functions.py
Normal file
@@ -0,0 +1,78 @@
|
||||
from flask import current_app
|
||||
|
||||
import bcrypt
|
||||
import jwt
|
||||
from apiflask import abort
|
||||
from flask import request, jsonify
|
||||
|
||||
from app.db import database as db
|
||||
from app.models import User
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt())
|
||||
|
||||
|
||||
def check_password(hashed_password, user_password):
|
||||
return bcrypt.checkpw(user_password, hashed_password)
|
||||
|
||||
|
||||
def get_email_from_token_data():
|
||||
if 'Authorization' in request.headers:
|
||||
token = request.headers['Authorization'].split(" ")
|
||||
|
||||
if len(token) < 2:
|
||||
return None
|
||||
else:
|
||||
token = token[1]
|
||||
|
||||
if token is not None:
|
||||
if ':' in token: # Maybe bot token, check if token valid and return username after ":" then
|
||||
telegram_user_id = token.split(":")[1]
|
||||
token = token.split(":")[0]
|
||||
|
||||
try:
|
||||
if jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=["HS256"])['email'] == current_app.config['BOT_EMAIL']:
|
||||
res = db.session.query(User).filter_by(telegram_user_id=telegram_user_id).first()
|
||||
|
||||
if res is not None:
|
||||
return res.as_dict()['email']
|
||||
else:
|
||||
return None
|
||||
else:
|
||||
return None
|
||||
except jwt.PyJWTError:
|
||||
return None
|
||||
|
||||
else: # "Normal" token, extract username from token
|
||||
try:
|
||||
return jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=["HS256"])['email']
|
||||
except jwt.PyJWTError:
|
||||
return None
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def get_email_or_abort_401():
|
||||
# get username from jwt token
|
||||
email = get_email_from_token_data()
|
||||
|
||||
if email is None: # If token not provided or invalid -> return 401 code
|
||||
abort(401, message="Unable to login")
|
||||
|
||||
return email
|
||||
|
||||
|
||||
def abort_if_no_admin():
|
||||
if not is_user_admin():
|
||||
abort(401, message="Only admin users can access this")
|
||||
|
||||
|
||||
def is_user_admin():
|
||||
email = get_email_or_abort_401()
|
||||
|
||||
return db.session.query(User).filter_by(email=email).first().admin
|
||||
|
||||
|
||||
def make_response(data, status=200, text=""):
|
||||
return jsonify({"status": status, "text": text, "data": data})
|
51
api/app/models.py
Normal file
51
api/app/models.py
Normal file
@@ -0,0 +1,51 @@
|
||||
from app.db import database as db
|
||||
|
||||
|
||||
class User(db.Model):
|
||||
__tablename__ = 'users'
|
||||
email = db.Column('email', db.String(255), primary_key=True, nullable=False, unique=True)
|
||||
password = db.Column('password', db.BINARY(60), nullable=False)
|
||||
username = db.Column('username', db.String(255), nullable=False, server_default='')
|
||||
telegram_user_id = db.Column('telegram_user_id', db.String(255), nullable=True, server_default='')
|
||||
admin = db.Column('admin', db.Boolean(), server_default='0')
|
||||
|
||||
def as_dict(self):
|
||||
return {
|
||||
"email": self.email,
|
||||
"username": self.username,
|
||||
"telegram_user_id": self.telegram_user_id,
|
||||
"admin": self.admin
|
||||
}
|
||||
|
||||
|
||||
class Transaction(db.Model):
|
||||
__tablename__ = 'transactions'
|
||||
t_id = db.Column('t_id', db.Integer(), nullable=False, unique=True, primary_key=True)
|
||||
email = db.Column('email', db.String(255), db.ForeignKey('users.email', ondelete='CASCADE'))
|
||||
symbol = db.Column('symbol', db.String(255))
|
||||
time = db.Column('time', db.DateTime())
|
||||
count = db.Column('count', db.Integer())
|
||||
price = db.Column('price', db.Float())
|
||||
|
||||
def as_dict(self):
|
||||
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
|
||||
|
||||
|
||||
class Keyword(db.Model):
|
||||
__tablename__ = 'keywords'
|
||||
s_id = db.Column('s_id', db.Integer(), nullable=False, unique=True, primary_key=True)
|
||||
email = db.Column('email', db.String(255), db.ForeignKey('users.email', ondelete='CASCADE'))
|
||||
keyword = db.Column('keyword', db.String(255))
|
||||
|
||||
def as_dict(self):
|
||||
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
|
||||
|
||||
|
||||
class Share(db.Model):
|
||||
__tablename__ = 'shares'
|
||||
a_id = db.Column('a_id', db.Integer(), nullable=False, unique=True, primary_key=True)
|
||||
email = db.Column('email', db.String(255), db.ForeignKey('users.email', ondelete='CASCADE'))
|
||||
symbol = db.Column('symbol', db.String(255))
|
||||
|
||||
def as_dict(self):
|
||||
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
|
111
api/app/schema.py
Normal file
111
api/app/schema.py
Normal file
@@ -0,0 +1,111 @@
|
||||
from apiflask import Schema
|
||||
from apiflask.fields import Integer, String, Boolean, Field, Float
|
||||
from marshmallow import validate
|
||||
from marshmallow.fields import Email
|
||||
|
||||
|
||||
class BaseResponseSchema(Schema):
|
||||
text = String()
|
||||
status = Integer()
|
||||
data = Field()
|
||||
|
||||
|
||||
class UsersSchema(Schema):
|
||||
admin = Boolean()
|
||||
password = String()
|
||||
username = String()
|
||||
telegram_user_id = String()
|
||||
email = Email()
|
||||
|
||||
|
||||
class AdminDataSchema(Schema):
|
||||
email = Email()
|
||||
admin = Boolean()
|
||||
|
||||
|
||||
class TokenSchema(Schema):
|
||||
token = String()
|
||||
|
||||
|
||||
class LoginDataSchema(Schema):
|
||||
email = Email()
|
||||
password = String()
|
||||
|
||||
|
||||
class RegisterDataSchema(Schema):
|
||||
email = Email()
|
||||
username = String()
|
||||
password = String()
|
||||
|
||||
|
||||
class UpdateUserDataSchema(Schema):
|
||||
username = String(required=False)
|
||||
password = String(required=False)
|
||||
|
||||
|
||||
class DeleteUserSchema(Schema):
|
||||
email = Email()
|
||||
|
||||
|
||||
class ChangePasswordSchema(Schema):
|
||||
old_password = String()
|
||||
new_password = String()
|
||||
|
||||
|
||||
class ChangeUsernameSchema(Schema):
|
||||
new_username = String()
|
||||
|
||||
|
||||
class KeywordSchema(Schema):
|
||||
keyword = String()
|
||||
|
||||
|
||||
class SymbolSchema(Schema):
|
||||
symbol = String()
|
||||
|
||||
|
||||
class TransactionSchema(Schema):
|
||||
symbol = String()
|
||||
time = String(validate=validate.Regexp(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z"))
|
||||
count = Integer()
|
||||
price = Float()
|
||||
|
||||
|
||||
class TelegramIdSchema(Schema):
|
||||
telegram_user_id = String()
|
||||
|
||||
|
||||
class DeleteSuccessfulSchema(Schema):
|
||||
pass
|
||||
|
||||
|
||||
class KeywordResponseSchema(Schema):
|
||||
keyword = String()
|
||||
s_id = Integer()
|
||||
email = Email()
|
||||
|
||||
|
||||
class SymbolResponseSchema(Schema):
|
||||
symbol = String()
|
||||
s_id = Integer()
|
||||
email = Email()
|
||||
|
||||
|
||||
class PortfolioShareResponseSchema(Schema):
|
||||
count = Integer()
|
||||
last_transaction = String()
|
||||
|
||||
|
||||
class TransactionResponseSchema(Schema):
|
||||
email = Email()
|
||||
symbol = String()
|
||||
time = String()
|
||||
count = Integer()
|
||||
price = Float()
|
||||
|
||||
|
||||
class PortfolioResponseSchema(Schema):
|
||||
symbol = String()
|
||||
last_transaction = String()
|
||||
count = Integer()
|
||||
# price = Float()
|
Reference in New Issue
Block a user