[dbb39a2] | 1 | from django.contrib.auth.models import User |
---|
| 2 | import socket |
---|
| 3 | import settings |
---|
| 4 | |
---|
| 5 | class SocketAuthBackend(): |
---|
| 6 | def authenticate(self, username, password, ): |
---|
| 7 | (result,) = query("AUTHENTICATE", username, password, ) |
---|
| 8 | print result |
---|
| 9 | if result == 'true': |
---|
| 10 | try: |
---|
| 11 | user = User.objects.get(username=username) |
---|
| 12 | if len(user.groups.filter(name='local-auth-only')) > 0: |
---|
| 13 | if user.check_password(password): |
---|
| 14 | return user |
---|
| 15 | else: |
---|
| 16 | return None |
---|
| 17 | else: |
---|
| 18 | return user |
---|
| 19 | except User.DoesNotExist: |
---|
| 20 | user = User(username=username, password='SocketAuth') |
---|
| 21 | user.is_staff = False |
---|
| 22 | user.is_superuser = False |
---|
| 23 | # Is there a race condition here? Yes. |
---|
| 24 | # Should I do more error-checking? Yes. |
---|
| 25 | # Do I care? No. |
---|
| 26 | (first, last, email,) = query('FINGER', username) |
---|
| 27 | user.first_name = first |
---|
| 28 | user.last_name = last |
---|
| 29 | user.email = email |
---|
| 30 | user.save() |
---|
| 31 | return user |
---|
| 32 | return None |
---|
| 33 | |
---|
| 34 | def get_user(self, user_id): |
---|
| 35 | try: |
---|
| 36 | return User.objects.get(pk=user_id) |
---|
| 37 | except User.DoesNotExist: |
---|
| 38 | return None |
---|
| 39 | |
---|
| 40 | |
---|
| 41 | def query(*args): |
---|
| 42 | conn = socket.socket(socket.AF_UNIX) |
---|
| 43 | conn.connect(settings.AUTH_SOCK) |
---|
| 44 | conn.send('\n'.join(args)) |
---|
| 45 | conn.shutdown(socket.SHUT_WR) |
---|
| 46 | result = conn.makefile().read().strip().split('\n') |
---|
| 47 | conn.close() |
---|
| 48 | return result |
---|