base.py 1.96 KB
Newer Older
1
# Copyright (c) 2018, Daniele Venzano
2 3 4 5 6 7 8 9 10 11 12 13 14 15
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

16 17
"""Base authenticator class."""

18 19 20 21 22 23 24 25 26 27
import logging
from typing import Union

from zoe_api.auth.file import PlainTextAuthenticator
from zoe_api.auth.ldap import LDAPAuthenticator
from zoe_lib.state import SQLManager, User
from zoe_lib.config import get_conf

log = logging.getLogger(__name__)

28 29

class BaseAuthenticator:
30 31
    """Base authenticator class."""

32 33 34 35 36 37
    def __init__(self):
        self.state = SQLManager(get_conf())

    def full_auth(self, username, password) -> Union[None, User]:
        """This method verifies the username and the password against one of the external auth sources."""
        user = self.state.user.select(only_one=True, **{"username": username})
38
        if user is None or not user.enabled:
39 40 41 42 43 44 45 46
            return None

        if user.auth_source == "textfile" and PlainTextAuthenticator(get_conf().auth_file).auth(username, password):
            return user
        elif user.auth_source == "ldap" and LDAPAuthenticator(get_conf(), sasl=False).auth(username, password):
            return user
        elif user.auth_source == "ldap+sasl" and LDAPAuthenticator(get_conf(), sasl=True).auth(username, password):
            return user
47 48
        elif user.auth_source == "internal" and user.check_password(password):
            return user
49 50 51
        else:
            log.error('Unknown auth source {} for user {}, cannot authenticate'.format(user.auth_source, user.username))
            return None