Merge branch 'jordan' of ssh://git.onelab.eu/git/myslice into jordan
[unfold.git] / auth / manifoldbackend.py
1 import time
2
3 from django.contrib.auth.models import User
4
5 from manifold.manifoldapi import ManifoldAPI, ManifoldResult
6 from manifold.core.query        import Query
7
8 # Name my backend 'ManifoldBackend'
9 class ManifoldBackend:
10
11     # Create an authentication method
12     # This is called by the standard Django login procedure
13     def authenticate(self, token=None):
14         if not token:
15             return None
16
17         try:
18             username = token['username']
19             password = token['password']
20             request = token['request']
21
22             auth = {'AuthMethod': 'password', 'Username': username, 'AuthString': password}
23             api = ManifoldAPI(auth)
24             sessions_result = api.forward(Query.create('local:session').to_dict())
25             print "result"
26             sessions = sessions_result.ok_value()
27             print "ok"
28             if not sessions:
29                 print "GetSession failed", sessions_result.error()
30                 return
31             print "first", sessions
32             session = sessions[0]
33             print "SESSION=", session
34
35             # Change to session authentication
36             api.auth = {'AuthMethod': 'session', 'session': session['session']}
37             self.api = api
38
39             # Get account details
40             # the new API would expect Get('local:user') instead
41             persons_result = api.forward(Query.get('local:user').to_dict())
42             persons = persons_result.ok_value()
43             if not persons:
44                 print "GetPersons failed",persons_result.error()
45                 return
46             person = persons[0]
47             print "PERSON=", person
48
49             request.session['manifold'] = {'auth': api.auth, 'person': person, 'expires': session['expires']}
50         except Exception, e:
51             print "E: manifoldbackend", e
52             import traceback
53             traceback.print_exc()
54             return None
55
56         try:
57             # Check if the user exists in Django's local database
58             user = User.objects.get(username=username)
59         except User.DoesNotExist:
60             # Create a user in Django's local database
61             user = User.objects.create_user(username, username, 'passworddoesntmatter')
62             user.first_name = "DUMMY_FIRST_NAME" #person['first_name']
63             user.last_name = "DUMMY LAST NAME" # person['last_name']
64             user.email = person['email']
65         return user
66
67     # Required for your backend to work properly - unchanged in most scenarios
68     def get_user(self, user_id):
69         try:
70             return User.objects.get(pk=user_id)
71         except User.DoesNotExist:
72             return None
73
74