[10394] | 1 | """Components that do the real authentication stuff. |
---|
| 2 | """ |
---|
[10475] | 3 | import re |
---|
[10510] | 4 | import sys |
---|
[10394] | 5 | from pkg_resources import iter_entry_points |
---|
[10478] | 6 | try: |
---|
| 7 | import xmlrpclib # Python 2.x |
---|
| 8 | except ImportError: # pragma: no cover |
---|
| 9 | import xmlrpc.client as xmlrpclib # Python 3.x |
---|
[10394] | 10 | |
---|
| 11 | |
---|
| 12 | def get_all_authenticators(): |
---|
| 13 | """Get all authenticators registered via entry points. |
---|
| 14 | |
---|
| 15 | To create an own authenticator, in the ``setup.py`` of your |
---|
| 16 | package add a block like this:: |
---|
| 17 | |
---|
| 18 | entry_points=''' |
---|
| 19 | [waeup.cas.authenticators] |
---|
| 20 | myname = my.pkg.my.module:MyAuthenticator |
---|
| 21 | ''' |
---|
| 22 | |
---|
| 23 | where ``my.pkg.my.module`` must be a module importable at runtime |
---|
| 24 | and ``MyAuthenticator`` must be some Authenticator class defined |
---|
| 25 | in this module. |
---|
| 26 | |
---|
| 27 | ``myname`` can be chosen as you like, but must not clash with |
---|
| 28 | other ``waeup.cas.authenticators``. The name should contain ASCII |
---|
| 29 | letters and numbers only, and start with a letter. |
---|
| 30 | """ |
---|
| 31 | return dict( |
---|
| 32 | [(x.name, x.load()) |
---|
| 33 | for x in iter_entry_points(group='waeup.cas.authenticators')]) |
---|
| 34 | |
---|
| 35 | |
---|
| 36 | def get_authenticator(local_conf): |
---|
| 37 | """Get an `Authenticator` configured by ``local_conf``. |
---|
| 38 | |
---|
| 39 | `local_conf` must be a dictionary of settings. |
---|
| 40 | |
---|
| 41 | An authenticator is identified by its entry-point name which must |
---|
| 42 | be given as value of the ``auth`` key. |
---|
| 43 | |
---|
| 44 | It is created passing all keys/values where key starts with |
---|
| 45 | ``auth_``. |
---|
| 46 | |
---|
| 47 | Returns a dict of remaining keys/values in `local_conf` with the |
---|
| 48 | value of ``auth`` key replaced by an authenticator instance. |
---|
| 49 | """ |
---|
| 50 | gen_opts, auth_opts = filter_auth_opts(local_conf) |
---|
| 51 | if 'auth' in local_conf: |
---|
| 52 | auth_dict = get_all_authenticators() |
---|
| 53 | factory = auth_dict.get(local_conf['auth']) # get authenticator |
---|
| 54 | auth = factory(**auth_opts) |
---|
| 55 | gen_opts.update(auth=auth) |
---|
| 56 | return gen_opts |
---|
| 57 | |
---|
| 58 | |
---|
| 59 | def filter_auth_opts(local_conf): |
---|
| 60 | """Filter out auth-related opts in `local_conf`, a dict. |
---|
| 61 | |
---|
| 62 | Returns two dicts ``(<GENERAL_OPTS>, <AUTHENTICATOR_OPTS>)`` |
---|
| 63 | containing the general options and authenticator related options. |
---|
| 64 | |
---|
| 65 | This is designed to work with typical paste.deploy config files |
---|
| 66 | like this:: |
---|
| 67 | |
---|
| 68 | [foo] |
---|
| 69 | foo = bar |
---|
| 70 | auth = foo |
---|
| 71 | auth_opt1 = bar |
---|
| 72 | |
---|
| 73 | All settings not starting with `auth_` are put into the general |
---|
| 74 | opts dict, while other are put into the authenticator opts dict. |
---|
| 75 | """ |
---|
| 76 | auth_opts = {} |
---|
| 77 | general_opts = {} |
---|
| 78 | for name, value in local_conf.items(): |
---|
| 79 | if name.startswith('auth_'): |
---|
| 80 | auth_opts[name] = value |
---|
| 81 | else: |
---|
| 82 | general_opts[name] = value |
---|
| 83 | return general_opts, auth_opts |
---|
| 84 | |
---|
| 85 | |
---|
| 86 | class Authenticator(object): |
---|
| 87 | |
---|
| 88 | #: The name of an authenticator |
---|
| 89 | name = 'basic' |
---|
| 90 | |
---|
| 91 | def __init__(self, **kw): |
---|
| 92 | pass |
---|
| 93 | |
---|
| 94 | |
---|
| 95 | class DummyAuthenticator(Authenticator): |
---|
| 96 | """A dummy authenticator for tests. |
---|
| 97 | |
---|
| 98 | This authenticator does no real authentication. It simply approves |
---|
| 99 | credentials ``('bird', 'bebop')`` and denies all other. |
---|
| 100 | """ |
---|
| 101 | |
---|
| 102 | name = 'dummy' |
---|
| 103 | |
---|
| 104 | def check_credentials(self, username='', password=''): |
---|
[10396] | 105 | """If username is ``'bird'`` and password ``'bebop'`` check |
---|
| 106 | will succeed. |
---|
| 107 | |
---|
| 108 | Returns a tuple ``(<STATUS>, <REASON>)`` with ``<STATUS>`` |
---|
| 109 | being a boolean and ``<REASON>`` being a string giving the |
---|
| 110 | reason why login failed (if so) or an empty string. |
---|
[10394] | 111 | """ |
---|
[10396] | 112 | reason = '' |
---|
| 113 | result = username == 'bird' and password == 'bebop' |
---|
| 114 | if not result: |
---|
| 115 | reason = 'Invalid username or password.' |
---|
| 116 | return result, reason |
---|
[10462] | 117 | |
---|
| 118 | |
---|
[10478] | 119 | #: Regular expression matching a starting university marker like |
---|
| 120 | #: the string 'MA-' in 'MA-M121212' or 'MA-' in 'MA-APP-13123' |
---|
| 121 | RE_SCHOOL_MARKER = re.compile('^[^\-]+-') |
---|
| 122 | |
---|
| 123 | |
---|
[10462] | 124 | class KofaAuthenticator(Authenticator): |
---|
| 125 | """Authenticate against a running Kofa instance. |
---|
| 126 | """ |
---|
| 127 | |
---|
| 128 | name = 'kofa1' |
---|
| 129 | |
---|
[10475] | 130 | def __init__(self, auth_backends="{}"): |
---|
| 131 | try: |
---|
| 132 | self.backends = eval(auth_backends) |
---|
| 133 | except: |
---|
| 134 | raise ValueError('auth_backends must be a ' |
---|
| 135 | 'valid Python expression.') |
---|
| 136 | self._check_options() |
---|
[10462] | 137 | |
---|
[10475] | 138 | def _check_options(self): |
---|
| 139 | if not isinstance(self.backends, dict): |
---|
| 140 | raise ValueError('Backends must be configured as dicts.') |
---|
| 141 | for key, val in self.backends.items(): |
---|
| 142 | if not isinstance(val, dict): |
---|
| 143 | raise ValueError( |
---|
| 144 | 'Backend %s: config must be a dict' % key) |
---|
| 145 | if not 'url' in val: |
---|
| 146 | raise ValueError( |
---|
| 147 | 'Backend %s: config must contain an `url` key.' % key) |
---|
| 148 | if not 'marker' in val: |
---|
| 149 | self.backends[key]['marker'] = '.+' |
---|
| 150 | try: |
---|
| 151 | re.compile(self.backends[key]['marker']) |
---|
| 152 | except: |
---|
| 153 | raise ValueError( |
---|
| 154 | 'Backend %s: marker must be a valid regular expr.:' % ( |
---|
| 155 | key,)) |
---|
| 156 | |
---|
[10462] | 157 | def check_credentials(self, username='', password=''): |
---|
| 158 | """Do the real check. |
---|
| 159 | """ |
---|
[10478] | 160 | for backend_name, backend in self.backends.items(): |
---|
| 161 | if not re.match(backend['marker'], username): |
---|
| 162 | continue |
---|
| 163 | # remove school marker |
---|
| 164 | username = RE_SCHOOL_MARKER.sub('', username) |
---|
| 165 | proxy = xmlrpclib.ServerProxy( |
---|
| 166 | backend['url'], allow_none=True) |
---|
[10506] | 167 | valid = proxy.check_applicant_credentials(username, password) |
---|
| 168 | if valid is None: |
---|
| 169 | valid = proxy.check_student_credentials(username, password) |
---|
[10478] | 170 | if valid is not None: |
---|
| 171 | return (True, '') |
---|
| 172 | return (False, 'Invalid username or password.') |
---|
[10509] | 173 | |
---|
| 174 | class KofaMoodleAuthenticator(KofaAuthenticator): |
---|
| 175 | """Authenticate against a running Kofa instance and transfer |
---|
| 176 | data to Moodle. |
---|
| 177 | |
---|
| 178 | Configuration of Moodle: |
---|
| 179 | 1. Set 'passwordpolicy' to No |
---|
| 180 | 2. Create external web service 'Kofa' with the following functions: |
---|
| 181 | core_user_create_users, core_user_get_users, |
---|
| 182 | core_user_update_users, enrol_manual_enrol_users |
---|
| 183 | 3. Create token for the admin user (no special web service user needed) |
---|
| 184 | and for service 'Kofa' |
---|
| 185 | 4. Enable and configure CAS server authentication. |
---|
| 186 | CAS protocol version is 1.0. Moodle expects SSL/TLS protocol. |
---|
| 187 | """ |
---|
| 188 | |
---|
| 189 | name = 'kofa_moodle1' |
---|
| 190 | |
---|
| 191 | def check_credentials(self, username='', password=''): |
---|
| 192 | """Do the real check. |
---|
| 193 | """ |
---|
| 194 | for backend_name, backend in self.backends.items(): |
---|
| 195 | if not re.match(backend['marker'], username): |
---|
| 196 | continue |
---|
| 197 | # remove school marker |
---|
| 198 | username = RE_SCHOOL_MARKER.sub('', username) |
---|
| 199 | proxy = xmlrpclib.ServerProxy( |
---|
| 200 | backend['url'], allow_none=True) |
---|
| 201 | moodle = xmlrpclib.ServerProxy( |
---|
| 202 | backend['moodle_url'], allow_none=True) |
---|
| 203 | principal = proxy.check_applicant_credentials(username, password) |
---|
| 204 | if principal is None: |
---|
| 205 | principal = proxy.check_student_credentials(username, password) |
---|
| 206 | if principal is not None: |
---|
| 207 | if principal['type'] == 'student': |
---|
| 208 | student = proxy.get_moodle_data(username) |
---|
| 209 | try: |
---|
| 210 | # Usernames in Moodle must not contain uppercase |
---|
| 211 | # letters even if extendedusernamechars is set True. |
---|
| 212 | result = moodle.core_user_create_users([ |
---|
| 213 | {'username':username.lower(), |
---|
| 214 | 'password':'dummy', |
---|
| 215 | 'firstname':student['firstname'], |
---|
| 216 | 'lastname':student['lastname'], |
---|
| 217 | 'email':student['email']}]) |
---|
| 218 | except xmlrpclib.Fault: |
---|
[10510] | 219 | faultstring = sys.exc_info()[1].faultString |
---|
| 220 | if not 'Username already exists' in faultstring: |
---|
| 221 | return (False, faultstring) |
---|
[10509] | 222 | # user exists |
---|
| 223 | pass |
---|
[10510] | 224 | try: |
---|
| 225 | result = moodle.core_user_get_users([ |
---|
| 226 | {'key':'username', 'value':username}]) |
---|
| 227 | except xmlrpclib.Fault: |
---|
| 228 | faultstring = sys.exc_info()[1].faultString |
---|
| 229 | return (False, faultstring) |
---|
[10509] | 230 | user_id = result['users'][0]['id'] |
---|
| 231 | # Due to a lack of Moodle (Moodle requires an LDAP |
---|
| 232 | # connection) the authentication method can't |
---|
| 233 | # be set when the user is created. It must be updated |
---|
| 234 | # after creation. |
---|
[10510] | 235 | try: |
---|
| 236 | result = moodle.core_user_update_users([ |
---|
| 237 | {'id':user_id,'auth':'cas'}]) |
---|
| 238 | except xmlrpclib.Fault: |
---|
| 239 | faultstring = sys.exc_info()[1].faultString |
---|
| 240 | return (False, faultstring) |
---|
[10509] | 241 | return (True, '') |
---|
| 242 | return (False, 'Invalid username or password.') |
---|