Newer
Older
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
# -*- coding: utf-8 -*-
"""
app.api.users
~~~~~~~~~~~~~
This module implements the users API.
:copyright: (c) 2017 European Spallation Source ERIC
:license: BSD 2-Clause, see LICENSE for more details.
"""
from flask import current_app, Blueprint, jsonify, request
from flask_ldap3_login import AuthenticationResponseStatus
from ..extensions import ldap_manager
from .. import utils, tokens
bp = Blueprint('users_api', __name__)
@bp.route('/login', methods=['POST'])
def login():
data = request.get_json()
if data is None:
raise utils.CSEntryError('Body should be a JSON object')
try:
username = data['username']
password = data['password']
except KeyError:
raise utils.CSEntryError('Missing mandatory field (username or password)', status_code=422)
response = ldap_manager.authenticate(username, password)
if response.status == AuthenticationResponseStatus.success:
current_app.logger.debug(f'{username} successfully logged in')
user = ldap_manager._save_user(
response.user_dn,
response.user_id,
response.user_info,
response.user_groups)
payload = {'access_token': tokens.generate_access_token(identity=user.id)}
return jsonify(payload), 200
raise utils.CSEntryError('Invalid credentials', status_code=401)