aboutsummaryrefslogtreecommitdiffstats
path: root/routes/auth.py
blob: bb3798e33ec32d3a6931f742635aad1dadd43719 (plain)
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
"""
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"
        )