forked from rcrowley/django-twitterauth
-
Notifications
You must be signed in to change notification settings - Fork 2
/
__init__.py
53 lines (44 loc) · 1.6 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import datetime
from django.core.exceptions import ImproperlyConfigured
from django.contrib.auth import load_backend, get_backends, authenticate
SESSION_KEY = '_twitterauth_user_id'
BACKEND_SESSION_KEY = '_twitterauth_user_backend'
REDIRECT_FIELD_NAME = 'next'
def login(request, user):
"""
Persist a user id and backend in the request. This way a user doesn't
have to reauthenticate on every request.
"""
if user is None:
user = request.user
if SESSION_KEY in request.session:
if request.session[SESSION_KEY] != user.id:
# To avoid reusing another user's session, create a new, empty
# session if the existing session corresponds to a different
# authenticated user.
request.session.flush()
else:
request.session.cycle_key()
request.session[SESSION_KEY] = user.id
request.session[BACKEND_SESSION_KEY] = user.backend
if hasattr(request, 'user'):
request.user = user
def logout(request):
"""
Removes the authenticated user's ID from the request an flushes their
session data.
"""
request.session.flush()
if hasattr(request, 'user'):
from twitterauth.models import AnonymousUser
request.user = AnonymousUser()
def get_user(request):
from twitterauth.models import AnonymousUser
try:
user_id = request.session[SESSION_KEY]
backend_path = request.session[BACKEND_SESSION_KEY]
backend = load_backend(backend_path)
user = backend.get_user(user_id) or AnonymousUser()
except KeyError:
user = AnonymousUser()
return user