TelegramAktienBot/webservice/api.py

61 lines
1.7 KiB
Python
Raw Normal View History

2022-03-14 06:32:16 +00:00
import os
from flask import Blueprint, jsonify, request
from db import db
from helper_functions import check_password, hash_password
from models import User
2022-03-14 06:35:26 +00:00
api = Blueprint('api', __name__, url_prefix='/api')
2022-03-14 06:32:16 +00:00
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
2022-03-14 06:35:26 +00:00
@api.route('/users', methods=['GET'])
2022-03-14 06:32:16 +00:00
def users():
res = []
for i in User.query.all():
res.append(i.as_dict())
return jsonify({"status": 200, "data": res})
2022-03-14 06:32:16 +00:00
2022-03-14 06:35:26 +00:00
@api.route('/login', methods=['POST'])
2022-03-14 06:32:16 +00:00
def login():
request_data = request.get_json()
username = request_data['username']
password = request_data['password']
user = User.filter_by(username=username).first()
if check_password(user.password, password):
# TODO Return token
return jsonify({"status": 200, "text": "Successfully logged in"})
2022-03-14 06:32:16 +00:00
else:
return jsonify({"status": 500, "text": "Unable to login"})
2022-03-14 06:32:16 +00:00
2022-03-14 06:35:26 +00:00
@api.route('/logout', methods=['GET'])
2022-03-14 06:32:16 +00:00
def logout():
# TODO
return jsonify({"status": 200, "text": "Successfully logged out"})
2022-03-14 06:32:16 +00:00
2022-03-14 06:35:26 +00:00
@api.route('/register', methods=['POST'])
2022-03-14 06:32:16 +00:00
def register():
request_data = request.get_json()
username = request_data['username']
password = request_data['password']
if User.filter_by(username=username).first() is None:
# Username doesn't exist yet
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()})
else:
return jsonify({"status": 500, "text": "Username already exist"})