source: main/waeup.cas/trunk/waeup/cas/authenticators.py @ 10476

Last change on this file since 10476 was 10475, checked in by uli, 11 years ago

Check backend values when initializing Kofa authenticator.

File size: 4.6 KB
Line 
1"""Components that do the real authentication stuff.
2"""
3import re
4from pkg_resources import iter_entry_points
5
6
7def get_all_authenticators():
8    """Get all authenticators registered via entry points.
9
10    To create an own authenticator, in the ``setup.py`` of your
11    package add a block like this::
12
13        entry_points='''
14           [waeup.cas.authenticators]
15           myname = my.pkg.my.module:MyAuthenticator
16           '''
17
18    where ``my.pkg.my.module`` must be a module importable at runtime
19    and ``MyAuthenticator`` must be some Authenticator class defined
20    in this module.
21
22    ``myname`` can be chosen as you like, but must not clash with
23    other ``waeup.cas.authenticators``. The name should contain ASCII
24    letters and numbers only, and start with a letter.
25    """
26    return dict(
27        [(x.name, x.load())
28         for x in iter_entry_points(group='waeup.cas.authenticators')])
29
30
31def get_authenticator(local_conf):
32    """Get an `Authenticator` configured by ``local_conf``.
33
34    `local_conf` must be a dictionary of settings.
35
36    An authenticator is identified by its entry-point name which must
37    be given as value of the ``auth`` key.
38
39    It is created passing all keys/values where key starts with
40    ``auth_``.
41
42    Returns a dict of remaining keys/values in `local_conf` with the
43    value of ``auth`` key replaced by an authenticator instance.
44    """
45    gen_opts, auth_opts = filter_auth_opts(local_conf)
46    if 'auth' in local_conf:
47        auth_dict = get_all_authenticators()
48        factory = auth_dict.get(local_conf['auth'])  # get authenticator
49        auth = factory(**auth_opts)
50        gen_opts.update(auth=auth)
51    return gen_opts
52
53
54def filter_auth_opts(local_conf):
55    """Filter out auth-related opts in `local_conf`, a dict.
56
57    Returns two dicts ``(<GENERAL_OPTS>, <AUTHENTICATOR_OPTS>)``
58    containing the general options and authenticator related options.
59
60    This is designed to work with typical paste.deploy config files
61    like this::
62
63      [foo]
64      foo = bar
65      auth = foo
66      auth_opt1 = bar
67
68    All settings not starting with `auth_` are put into the general
69    opts dict, while other are put into the authenticator opts dict.
70    """
71    auth_opts = {}
72    general_opts = {}
73    for name, value in local_conf.items():
74        if name.startswith('auth_'):
75            auth_opts[name] = value
76        else:
77            general_opts[name] = value
78    return general_opts, auth_opts
79
80
81class Authenticator(object):
82
83    #: The name of an authenticator
84    name = 'basic'
85
86    def __init__(self, **kw):
87        pass
88
89
90class DummyAuthenticator(Authenticator):
91    """A dummy authenticator for tests.
92
93    This authenticator does no real authentication. It simply approves
94    credentials ``('bird', 'bebop')`` and denies all other.
95    """
96
97    name = 'dummy'
98
99    def check_credentials(self, username='', password=''):
100        """If username is ``'bird'`` and password ``'bebop'`` check
101        will succeed.
102
103        Returns a tuple ``(<STATUS>, <REASON>)`` with ``<STATUS>``
104        being a boolean and ``<REASON>`` being a string giving the
105        reason why login failed (if so) or an empty string.
106        """
107        reason = ''
108        result = username == 'bird' and password == 'bebop'
109        if not result:
110            reason = 'Invalid username or password.'
111        return result, reason
112
113
114class KofaAuthenticator(Authenticator):
115    """Authenticate against a running Kofa instance.
116    """
117
118    name = 'kofa1'
119
120    def __init__(self, auth_backends="{}"):
121        try:
122            self.backends = eval(auth_backends)
123        except:
124            raise ValueError('auth_backends must be a '
125                             'valid Python expression.')
126        self._check_options()
127
128    def _check_options(self):
129        if not isinstance(self.backends, dict):
130            raise ValueError('Backends must be configured as dicts.')
131        for key, val in self.backends.items():
132            if not isinstance(val, dict):
133                raise ValueError(
134                    'Backend %s: config must be a dict' % key)
135            if not 'url' in val:
136                raise ValueError(
137                    'Backend %s: config must contain an `url` key.' % key)
138            if not 'marker' in val:
139                self.backends[key]['marker'] = '.+'
140            try:
141                re.compile(self.backends[key]['marker'])
142            except:
143                raise ValueError(
144                    'Backend %s: marker must be a valid regular expr.:' % (
145                        key,))
146
147    def check_credentials(self, username='', password=''):
148        """Do the real check.
149        """
150        return False, 'Not implemented.'
Note: See TracBrowser for help on using the repository browser.