base.py 2.6 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
import logging
from typing import Union

21
import pam
Daniele Venzano's avatar
Daniele Venzano committed
22

23 24 25 26 27 28 29
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__)

30 31

class BaseAuthenticator:
32 33
    """Base authenticator class."""

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

37
    def full_auth(self, username: str, password: str) -> Union[None, User]:  # pylint: disable=too-many-return-statements
38 39
        """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})
40
        if user is None or not user.enabled:
41 42 43
            return None

        if user.auth_source == "textfile" and PlainTextAuthenticator(get_conf().auth_file).auth(username, password):
44
            log.info('User {} authenticated via textfile'.format(user.username))
45 46
            return user
        elif user.auth_source == "ldap" and LDAPAuthenticator(get_conf(), sasl=False).auth(username, password):
47
            log.info('User {} authenticated via ldap'.format(user.username))
48 49
            return user
        elif user.auth_source == "ldap+sasl" and LDAPAuthenticator(get_conf(), sasl=True).auth(username, password):
50
            log.info('User {} authenticated via ldap+sasl'.format(user.username))
51
            return user
52
        elif user.auth_source == "internal" and user.check_password(password):
53
            log.info('User {} authenticated via internal db'.format(user.username))
54
            return user
55
        elif user.auth_source == "pam" and pam_authenticate(username, password):
56
            log.info('User {} authenticated via PAM'.format(user.username))
57
            return user
58 59
        else:
            return None
60 61 62


def pam_authenticate(username, password):
63
    """Use the PAM module to authenticate. Zoe needs access to /etc/shadow."""
64

Daniele Venzano's avatar
Daniele Venzano committed
65 66
    pam_obj = pam.pam()
    return pam_obj.authenticate(username, password)