TelegramAktienBot/webservice/api_blueprint_user.py

90 lines
2.8 KiB
Python

import datetime
import os
import jwt
from apiflask import APIBlueprint, abort
from flask import jsonify
from db import db
from helper_functions import check_password, hash_password
from models import User
from scheme import UsersSchema, Token, LoginData
from 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():
res = []
for i in User.query.all():
res.append(i.as_dict())
return jsonify({"status": 200, "data": res})
@users_blueprint.route('/login', methods=['POST'])
@users_blueprint.output(Token(), 200)
@users_blueprint.input(schema=LoginData)
@users_blueprint.doc(summary="Login", description="Returns jwt token if username and password match, otherwise returns error")
def login(data):
check_if_user_data_exists(data)
username = data['username']
password = data['password']
user = db.session.query(User).filter_by(username=username).first()
if user is None: # Username doesn't exist
abort(500, message="Unable to login")
if not check_password(user.password, password): # Password incorrect
abort(500, message="Unable to login")
token = jwt.encode({'username': user.username, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=45)}, os.getenv('SECRET_KEY'), "HS256")
return jsonify({"status": 200, "text": "Successfully logged in", "data": {"token": token}})
@users_blueprint.route('/register', methods=['POST'])
@users_blueprint.output(UsersSchema(), 200)
@users_blueprint.input(schema=LoginData)
@users_blueprint.doc(summary="Register", description="Registers user")
def register(data):
check_if_user_data_exists(data)
username = data['username']
password = data['password']
user = db.session.query(User).filter_by(username=username).first()
if user is not None: # Username already exist
abort(500, message="Username already exist")
user = User(
username=username,
password=hash_password(password),
admin=False
)
db.session.add(user)
db.session.commit()
return jsonify({"status": 200, "text": "Successfully registered user", "data": user.as_dict()})
def check_if_user_data_exists(data):
if "username" not in data:
abort(400, message="Username missing")
if data['username'] == "" or data['username'] is None:
abort(400, message="Username missing")
if "password" not in data:
abort(400, message="Password missing")
if data['password'] == "" or data['password'] is None:
abort(400, message="Password missing")