Code

Ticket #14350: login_user.txt

File login_user.txt, 1.0 KB (added by James Westby <jw+debian@…>, 4 years ago)

Suggested approach

Line 
1def login_user(self, user):
2    if not 'django.contrib.sessions' in settings.INSTALLED_APPS:
3        raise AssertionError("Unable to login without django.contrib.sessions in INSTALLED_APPS")
4    user.backend = "%s.%s" % ("django.contrib.auth.backends",
5                              "ModelBackend")
6    engine = import_module(settings.SESSION_ENGINE)
7 
8    # Create a fake request to store login details.
9    request = HttpRequest()
10    if self.session:
11        request.session = self.session
12    else:
13        request.session = engine.SessionStore()
14    login(request, user)
15 
16    # Set the cookie to represent the session.
17    session_cookie = settings.SESSION_COOKIE_NAME
18    self.cookies[session_cookie] = request.session.session_key
19    cookie_data = {
20        'max-age': None,
21        'path': '/',
22        'domain': settings.SESSION_COOKIE_DOMAIN,
23        'secure': settings.SESSION_COOKIE_SECURE or None,
24        'expires': None,
25    }
26    self.cookies[session_cookie].update(cookie_data)
27 
28    # Save the session values.
29    request.session.save()