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
):
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.
17 def authenticate(self
, username
=None, password
=None):
19 user
= User
.objects
.get(username
=username
)
20 except User
.DoesNotExist
:
21 # password is meaningless
22 user
= User(username
=username
,
23 password
='apache authentication')
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
)
34 def check_afe_user(username
):
35 user
, created
= models
.User
.objects
.get_or_create(login
=username
)
39 def get_user(self
, user_id
):
41 return User
.objects
.get(pk
=user_id
)
42 except User
.DoesNotExist
:
46 class GetApacheUserMiddleware(object):
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.
55 def process_request(self
, request
):
56 # look for a username from Apache
57 user
= request
.META
.get('REMOTE_USER')
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')
63 # no user info - assume we're in development mode
65 thread_local
.set_user(user
)
68 class ApacheAuthMiddleware(GetApacheUserMiddleware
):
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
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
,
82 auth
.login(request
, user_object
)
83 thread_local
.set_user(models
.User
.objects
.get(login
=username
))