|
1 from django.core.management.base import BaseCommand, CommandError |
|
2 from django.contrib.auth.models import User |
|
3 from django.contrib.sessions.models import Session |
|
4 import re |
|
5 |
|
6 SESSION_RE = re.compile("^[0-9a-f]{20,40}$") |
|
7 |
|
8 class Command(BaseCommand): |
|
9 help = ("print the user information for the provided session key. " |
|
10 "this is very helpful when trying to track down the person who " |
|
11 "experienced a site crash.") |
|
12 args = "session_key" |
|
13 label = 'session key for the user' |
|
14 |
|
15 requires_model_validation = True |
|
16 can_import_settings = True |
|
17 |
|
18 def handle(self, *args, **options): |
|
19 if len(args) > 1: |
|
20 raise CommandError("extra arguments supplied") |
|
21 if len(args) < 1: |
|
22 raise CommandError("session_key argument missing") |
|
23 key = args[0].lower() |
|
24 if not SESSION_RE.match(key): |
|
25 raise CommandError("malformed session key") |
|
26 try: |
|
27 session = Session.objects.get(pk=key) |
|
28 except Session.DoesNotExist: |
|
29 print "Session Key does not exist. Expired?" |
|
30 return |
|
31 |
|
32 data = session.get_decoded() |
|
33 print 'Session to Expire:', session.expire_date |
|
34 print 'Raw Data:', data |
|
35 uid = data.get('_auth_user_id', None) |
|
36 if uid is None: |
|
37 print 'No user associated with session' |
|
38 return |
|
39 print "User id:", uid |
|
40 try: |
|
41 user = User.objects.get(pk=uid) |
|
42 except User.DoesNotExist: |
|
43 print "No user associated with that id." |
|
44 return |
|
45 for key in ['username', 'email', 'first_name', 'last_name']: |
|
46 print key+': ' + getattr(user, key) |
|
47 |
|
48 |
|
49 |