This repository has been archived by the owner on May 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
controller.py
66 lines (53 loc) · 2.1 KB
/
controller.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from flask import Blueprint, request, jsonify
from ..models import User
from flask_jwt_extended import jwt_required, create_access_token,\
get_jwt_identity
from mongoengine import ValidationError, NotUniqueError
auth = Blueprint('auth', __name__)
@auth.route('/login', methods=['POST'])
def login():
if not request.is_json:
return jsonify({"message": "Missing JSON in request"}), 400
email = request.json.get('email', None)
password = request.json.get('password', None)
if not email:
return jsonify({"message": "Missing email parameter"}), 400
if not password:
return jsonify({"message": "Missing password parameter"}), 400
user = User.objects(email=email).first()
if user == None:
return jsonify({"message": "User not Found"}), 404
if user.check_password(password):
access_token = create_access_token(identity=user.email)
return jsonify(access_token=access_token), 200
else:
return jsonify({"message": "Incorrect Password"}), 200
@auth.route('/signup', methods=['POST'])
def signup():
if not request.is_json:
return jsonify({"message": "Missing JSON in request"}), 400
if not request.json.get('password'):
return jsonify({"message": "Missing password parameter"}), 400
user = User(**request.json)
user.set_password(request.json.get('password'))
try:
user.validate()
except ValidationError as error:
return jsonify(error.to_dict()), 400
try:
user.save()
access_token = create_access_token(identity=user.email)
return jsonify(access_token=access_token), 200
except NotUniqueError as error:
return jsonify({
'message': 'The email provided is already taken',
'code': 'E_OCUPIED'
}), 400
# Protect a view with jwt_required, which requires a valid access token
# in the request to access.
@auth.route('/protected', methods=['GET'])
@jwt_required
def protected():
# Access the identity of the current user with get_jwt_identity
current_user = get_jwt_identity()
return jsonify(logged_in_as=current_user), 200