Fixed imports
This commit is contained in:
64
webservice/api_blueprint_user.py
Normal file
64
webservice/api_blueprint_user.py
Normal file
@@ -0,0 +1,64 @@
|
||||
import datetime
|
||||
import os
|
||||
|
||||
import jwt
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from db import db
|
||||
from helper_functions import check_password, hash_password, get_token, extract_token_data
|
||||
from models import User
|
||||
|
||||
users_blueprint = Blueprint('users', __name__, url_prefix='/api')
|
||||
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
|
||||
|
||||
|
||||
@users_blueprint.route('/users', methods=['GET'])
|
||||
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'])
|
||||
def login():
|
||||
request_data = request.get_json()
|
||||
username = request_data['username']
|
||||
password = request_data['password']
|
||||
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if check_password(user.password, password):
|
||||
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})
|
||||
else:
|
||||
return jsonify({"status": 500, "text": "Unable to login"})
|
||||
|
||||
|
||||
@users_blueprint.route('/logout', methods=['GET'])
|
||||
def logout():
|
||||
# TODO
|
||||
return jsonify({"status": 200, "text": "Successfully logged out"})
|
||||
|
||||
|
||||
@users_blueprint.route('/register', methods=['POST'])
|
||||
def register():
|
||||
request_data = request.get_json()
|
||||
username = request_data['username']
|
||||
password = request_data['password']
|
||||
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if user 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"})
|
||||
Reference in New Issue
Block a user