base.py 2.27 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
from zoe_api.auth.requests_oauth2 import EurecomGitLabClient
24 25 26 27 28 29 30
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__)

31 32

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

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

38
    def full_auth(self, username: str, password: str) -> Union[None, User]:  # pylint: disable=too-many-return-statements
39 40
        """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})
41
        if user is None or not user.enabled:
42 43 44 45 46 47 48 49
            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
50 51
        elif user.auth_source == "internal" and user.check_password(password):
            return user
52 53
        elif user.auth_source == "pam" and pam_authenticate(username, password):
            return user
54 55
        else:
            return None
56 57 58


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

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