1 | import subprocess |
---|
2 | import ldap |
---|
3 | import ldap.filter |
---|
4 | |
---|
5 | from django.contrib.auth.middleware import RemoteUserMiddleware |
---|
6 | from django.contrib.auth.backends import RemoteUserBackend |
---|
7 | from django.contrib import auth |
---|
8 | from django.core.exceptions import ObjectDoesNotExist |
---|
9 | |
---|
10 | def zephyr(msg, clas='remit', instance='log', rcpt='adehnert',): |
---|
11 | proc = subprocess.Popen( |
---|
12 | ['zwrite', '-d', '-n', '-c', clas, '-i', instance, rcpt, ], |
---|
13 | stdin=subprocess.PIPE, stdout=subprocess.PIPE |
---|
14 | ) |
---|
15 | proc.communicate(msg) |
---|
16 | |
---|
17 | class ScriptsRemoteUserMiddleware(RemoteUserMiddleware): |
---|
18 | header = 'SSL_CLIENT_S_DN_Email' |
---|
19 | |
---|
20 | class ScriptsRemoteUserBackend(RemoteUserBackend): |
---|
21 | def clean_username(self, username, ): |
---|
22 | if '@' in username: |
---|
23 | name, domain = username.split('@') |
---|
24 | assert domain.upper() == 'MIT.EDU' |
---|
25 | return name |
---|
26 | else: |
---|
27 | return username |
---|
28 | def configure_user(self, user, ): |
---|
29 | username = user.username |
---|
30 | user.password = "ScriptsSSLAuth" |
---|
31 | con = ldap.open('ldap.mit.edu') |
---|
32 | con.simple_bind_s("", "") |
---|
33 | dn = "dc=mit,dc=edu" |
---|
34 | fields = ['cn', 'sn', 'givenName', 'mail', ] |
---|
35 | userfilter = ldap.filter.filter_format('uid=%s', [username]) |
---|
36 | result = con.search_s('dc=mit,dc=edu', ldap.SCOPE_SUBTREE, userfilter, fields) |
---|
37 | if len(result) == 1: |
---|
38 | user.first_name = result[0][1]['givenName'][0] |
---|
39 | user.last_name = result[0][1]['sn'][0] |
---|
40 | user.email = result[0][1]['mail'][0] |
---|
41 | try: |
---|
42 | user.groups.add(auth.models.Group.objects.get(name='mit')) |
---|
43 | except ObjectDoesNotExist: |
---|
44 | print "Failed to retrieve mit group" |
---|
45 | else: |
---|
46 | raise ValueError, ("Could not find user with username '%s' (filter '%s')"%(username, userfilter)) |
---|
47 | try: |
---|
48 | user.groups.add(auth.models.Group.objects.get(name='autocreated')) |
---|
49 | except ObjectDoesNotExist: |
---|
50 | print "Failed to retrieve autocreated group" |
---|
51 | user.save() |
---|
52 | return user |
---|