aboutsummaryrefslogtreecommitdiffstats
path: root/routes/auth.py
diff options
context:
space:
mode:
authorJesús <heckyel@hyperbola.info>2022-03-22 00:39:40 +0800
committerJesús <heckyel@hyperbola.info>2022-03-22 00:39:40 +0800
commit3fca03988b42adaf8e67cc7137dd1fdba327e197 (patch)
treead39a5bc12a03c82b9a4fd980c1b92ca0a1dac93 /routes/auth.py
downloadheroeapi-3fca03988b42adaf8e67cc7137dd1fdba327e197.tar.lz
heroeapi-3fca03988b42adaf8e67cc7137dd1fdba327e197.tar.xz
heroeapi-3fca03988b42adaf8e67cc7137dd1fdba327e197.zip
initial commit
Diffstat (limited to 'routes/auth.py')
-rw-r--r--routes/auth.py57
1 files changed, 57 insertions, 0 deletions
diff --git a/routes/auth.py b/routes/auth.py
new file mode 100644
index 0000000..bb3798e
--- /dev/null
+++ b/routes/auth.py
@@ -0,0 +1,57 @@
+"""
+Routes - Users
+"""
+import datetime
+import json
+from flask import (
+ Blueprint,
+ Response,
+ request
+)
+from flask_jwt_extended import create_access_token
+from database.models import UserModel
+from mongoengine.errors import (
+ FieldDoesNotExist,
+ NotUniqueError,
+ ValidationError
+)
+from utils.errors import (
+ unauthorized_error,
+ user_already_exists_error,
+ internal_server_error,
+ schema_validation_error
+)
+
+auth = Blueprint("auth", __name__)
+
+
+@auth.route('/auth/token', methods=['POST'])
+def login():
+ """Receive data for login"""
+ try:
+ body = request.get_json()
+ user = UserModel.objects.get(email=body.get('email'))
+ authorized = user.check_password(body.get('password'))
+ if not authorized:
+ raise PermissionError("Check your password or email")
+ expires = datetime.timedelta(days=7)
+ access_token = create_access_token(
+ identity=str(user.id),
+ expires_delta=expires
+ )
+ except PermissionError as e:
+ return unauthorized_error(e)
+ except (FieldDoesNotExist, ValidationError) as e:
+ return schema_validation_error(e)
+ except NotUniqueError as e:
+ return user_already_exists_error(e)
+ except Exception as e:
+ return internal_server_error(e)
+ else:
+ return Response(
+ response=json.dumps({
+ "token": access_token
+ }),
+ status=200,
+ mimetype="applications/json"
+ )