added authorization, signup, login with jwt
This commit is contained in:
0
auth/__init__.py
Normal file
0
auth/__init__.py
Normal file
43
auth/auth.py
Normal file
43
auth/auth.py
Normal file
@@ -0,0 +1,43 @@
|
||||
from flask import Blueprint, request
|
||||
from flask_jwt_extended import create_access_token
|
||||
from http import HTTPStatus
|
||||
from werkzeug.security import check_password_hash, generate_password_hash
|
||||
|
||||
from database import db
|
||||
from database.user import User
|
||||
|
||||
auth = Blueprint('auth', __name__)
|
||||
|
||||
|
||||
@auth.route('/login', methods=['POST'])
|
||||
def login():
|
||||
username = request.form.get('username')
|
||||
password = request.form.get('password')
|
||||
|
||||
user = User.query.filter_by(username=username).first()
|
||||
if user and check_password_hash(user.password, password):
|
||||
return {'id': user.id,
|
||||
'username': user.username,
|
||||
'email': user.email,
|
||||
'token': create_access_token(identity=user.username)}
|
||||
return {'description': 'Username or password is invalid'}, HTTPStatus.UNAUTHORIZED
|
||||
|
||||
|
||||
@auth.route('/signup', methods=['POST'])
|
||||
def signup():
|
||||
username = request.form.get('username')
|
||||
email = request.form.get('email')
|
||||
password = request.form.get('password')
|
||||
|
||||
user = User.query.filter_by(username=username).first()
|
||||
if user:
|
||||
return {'description': f'A user called {username} exists already.'}, HTTPStatus.CONFLICT
|
||||
|
||||
# TODO sanity check for password length etc
|
||||
user = User(username=username,
|
||||
email=email,
|
||||
password=generate_password_hash(password))
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
return '', HTTPStatus.NO_CONTENT
|
||||
Reference in New Issue
Block a user