Skip to content
Snippets Groups Projects
users.py 1.32 KiB
Newer Older
Benjamin Bertrand's avatar
Benjamin Bertrand committed
# -*- 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)