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.auth.views import login |
---|
8 | from django.contrib.auth import REDIRECT_FIELD_NAME |
---|
9 | from django.http import HttpResponseRedirect |
---|
10 | from django.contrib import auth |
---|
11 | from django.core.exceptions import ObjectDoesNotExist |
---|
12 | from django.core.validators import URLValidator, ValidationError |
---|
13 | |
---|
14 | import settings |
---|
15 | |
---|
16 | def zephyr(msg, clas='message', instance='log', rcpt='nobody',): |
---|
17 | proc = subprocess.Popen( |
---|
18 | ['zwrite', '-d', '-n', '-c', clas, '-i', instance, rcpt, ], |
---|
19 | stdin=subprocess.PIPE, stdout=subprocess.PIPE |
---|
20 | ) |
---|
21 | proc.communicate(msg) |
---|
22 | |
---|
23 | def UrlOrAfsValidator(value): |
---|
24 | if value.startswith('/mit/') or value.startswith('/afs/'): |
---|
25 | return |
---|
26 | else: |
---|
27 | try: |
---|
28 | URLValidator()(value) |
---|
29 | except ValidationError: |
---|
30 | raise ValidationError('Provide a valid URL or AFS path') |
---|
31 | |
---|
32 | class ScriptsRemoteUserMiddleware(RemoteUserMiddleware): |
---|
33 | header = 'SSL_CLIENT_S_DN_Email' |
---|
34 | |
---|
35 | class ScriptsRemoteUserBackend(RemoteUserBackend): |
---|
36 | def clean_username(self, username, ): |
---|
37 | if '@' in username: |
---|
38 | name, domain = username.split('@') |
---|
39 | assert domain.upper() == 'MIT.EDU' |
---|
40 | return name |
---|
41 | else: |
---|
42 | return username |
---|
43 | def configure_user(self, user, ): |
---|
44 | username = user.username |
---|
45 | user.password = "ScriptsSSLAuth" |
---|
46 | con = ldap.open('ldap-too.mit.edu') |
---|
47 | con.simple_bind_s("", "") |
---|
48 | dn = "dc=mit,dc=edu" |
---|
49 | fields = ['cn', 'sn', 'givenName', 'mail', ] |
---|
50 | userfilter = ldap.filter.filter_format('uid=%s', [username]) |
---|
51 | result = con.search_s('dc=mit,dc=edu', ldap.SCOPE_SUBTREE, userfilter, fields) |
---|
52 | if len(result) == 1: |
---|
53 | user.first_name = result[0][1]['givenName'][0] |
---|
54 | user.last_name = result[0][1]['sn'][0] |
---|
55 | try: |
---|
56 | user.email = result[0][1]['mail'][0] |
---|
57 | except KeyError: |
---|
58 | user.email = username + '@mit.edu' |
---|
59 | try: |
---|
60 | user.groups.add(auth.models.Group.objects.get(name='mit')) |
---|
61 | except ObjectDoesNotExist: |
---|
62 | print "Failed to retrieve mit group" |
---|
63 | else: |
---|
64 | raise ValueError, ("Could not find user with username '%s' (filter '%s')"%(username, userfilter)) |
---|
65 | try: |
---|
66 | user.groups.add(auth.models.Group.objects.get(name='autocreated')) |
---|
67 | except ObjectDoesNotExist: |
---|
68 | print "Failed to retrieve autocreated group" |
---|
69 | user.save() |
---|
70 | return user |
---|
71 | |
---|
72 | def get_or_create_mit_user(username, ): |
---|
73 | """ |
---|
74 | Given an MIT username, return a Django user object for them. |
---|
75 | If necessary, create (and save) the Django user for them. |
---|
76 | If the MIT user doesn't exist, raises ValueError. |
---|
77 | """ |
---|
78 | user, created = auth.models.User.objects.get_or_create(username=username, ) |
---|
79 | if created: |
---|
80 | backend = ScriptsRemoteUserBackend() |
---|
81 | # Raises ValueError if the user doesn't exist |
---|
82 | try: |
---|
83 | return backend.configure_user(user), created |
---|
84 | except ValueError: |
---|
85 | user.delete() |
---|
86 | raise |
---|
87 | else: |
---|
88 | return user, created |
---|
89 | |
---|
90 | def scripts_login(request, **kwargs): |
---|
91 | host = request.META['HTTP_HOST'].split(':')[0] |
---|
92 | if host == 'localhost': |
---|
93 | return login(request, **kwargs) |
---|
94 | elif request.META['SERVER_PORT'] == '444': |
---|
95 | if request.user.is_authenticated(): |
---|
96 | # They're already authenticated --- go ahead and redirect |
---|
97 | if 'redirect_field_name' in kwargs: |
---|
98 | redirect_field_name = kwargs['redirect_field_names'] |
---|
99 | else: |
---|
100 | from django.contrib.auth import REDIRECT_FIELD_NAME |
---|
101 | redirect_field_name = REDIRECT_FIELD_NAME |
---|
102 | redirect_to = request.REQUEST.get(redirect_field_name, '') |
---|
103 | if not redirect_to or '//' in redirect_to or ' ' in redirect_to: |
---|
104 | redirect_to = settings.LOGIN_REDIRECT_URL |
---|
105 | return HttpResponseRedirect(redirect_to) |
---|
106 | else: |
---|
107 | return login(request, **kwargs) |
---|
108 | else: |
---|
109 | # Move to port 444 |
---|
110 | redirect_to = "https://%s:444%s" % (host, request.META['REQUEST_URI'], ) |
---|
111 | return HttpResponseRedirect(redirect_to) |
---|