Patch unixbench 4.1.0 to support parallel make
[autotest-zwu.git] / frontend / apache_auth.py
blob4ed1471615862712ea07054f0a184a625063fe82
1 from django.contrib.auth.models import User, Group, check_password
2 from django.contrib.auth import backends
3 from django.contrib import auth
4 from django import http
6 from autotest_lib.frontend import thread_local
7 from autotest_lib.frontend.afe import models, management
9 DEBUG_USER = 'debug_user'
11 class SimpleAuthBackend(backends.ModelBackend):
12 """
13 Automatically allows any login. This backend is for use when Apache is
14 doing the real authentication. Also ensures logged-in user exists in
15 frontend.afe.models.User database.
16 """
17 def authenticate(self, username=None, password=None):
18 try:
19 user = User.objects.get(username=username)
20 except User.DoesNotExist:
21 # password is meaningless
22 user = User(username=username,
23 password='apache authentication')
24 user.is_staff = True
25 user.save() # need to save before adding groups
26 user.groups.add(Group.objects.get(
27 name=management.BASIC_ADMIN))
29 SimpleAuthBackend.check_afe_user(username)
30 return user
33 @staticmethod
34 def check_afe_user(username):
35 user, created = models.User.objects.get_or_create(login=username)
36 if created:
37 user.save()
39 def get_user(self, user_id):
40 try:
41 return User.objects.get(pk=user_id)
42 except User.DoesNotExist:
43 return None
46 class GetApacheUserMiddleware(object):
47 """
48 Middleware for use when Apache is doing authentication. Looks for
49 REMOTE_USER in headers and passed the username found to
50 thread_local.set_user(). If no such header is found, looks for
51 HTTP_AUTHORIZATION header with username (this allows CLI to authenticate).
52 If neither of those are found, DEBUG_USER is used.
53 """
55 def process_request(self, request):
56 # look for a username from Apache
57 user = request.META.get('REMOTE_USER')
58 if user is None:
59 # look for a user in headers. This is insecure but
60 # it's our temporarily solution for CLI auth.
61 user = request.META.get('HTTP_AUTHORIZATION')
62 if user is None:
63 # no user info - assume we're in development mode
64 user = DEBUG_USER
65 thread_local.set_user(user)
68 class ApacheAuthMiddleware(GetApacheUserMiddleware):
69 """
70 Like GetApacheUserMiddleware, but also logs the user into Django's auth
71 system, and replaces the username in thread_local with the actual User model
72 object.
73 """
76 def process_request(self, request):
77 super(ApacheAuthMiddleware, self).process_request(request)
78 username = thread_local.get_user()
79 thread_local.set_user(None)
80 user_object = auth.authenticate(username=username,
81 password='')
82 auth.login(request, user_object)
83 thread_local.set_user(models.User.objects.get(login=username))