Tests
- Improved directory structure - Added functional and unit tests
This commit is contained in:
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