Move authentication logic to lib.
[pithos] / pithos / lib / user.py
1 # Copyright 2011-2012 GRNET S.A. All rights reserved.
2
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
5 # conditions are met:
6
7 #   1. Redistributions of source code must retain the above
8 #      copyright notice, this list of conditions and the following
9 #      disclaimer.
10
11 #   2. Redistributions in binary form must reproduce the above
12 #      copyright notice, this list of conditions and the following
13 #      disclaimer in the documentation and/or other materials
14 #      provided with the distribution.
15
16 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 # POSSIBILITY OF SUCH DAMAGE.
28
29 # The views and conclusions contained in the software and
30 # documentation are those of the authors and should not be
31 # interpreted as representing official policies, either expressed
32 # or implied, of GRNET S.A.
33
34 from time import time, mktime
35 from urlparse import urlparse
36 from httplib import HTTPConnection, HTTPSConnection
37 from urllib import quote, unquote
38
39 from django.conf import settings
40 from django.utils import simplejson as json
41
42
43 def authenticate(token, authentication_url='http://127.0.0.1:8000/im/authenticate'):
44     p = urlparse(authentication_url)
45     if p.scheme == 'http':
46         conn = HTTPConnection(p.netloc)
47     elif p.scheme == 'https':
48         conn = HTTPSConnection(p.netloc)
49     else:
50         raise Exception('Unknown URL scheme')
51     
52     kwargs = {}
53     kwargs['headers'] = {}
54     kwargs['headers']['X-Auth-Token'] = token
55     kwargs['headers']['Content-Length'] = 0
56     
57     conn.request('GET', p.path, **kwargs)
58     response = conn.getresponse()
59     
60     headers = response.getheaders()
61     headers = dict((unquote(h), unquote(v)) for h,v in headers)
62     length = response.getheader('content-length', None)
63     data = response.read(length)
64     status = int(response.status)
65     
66     if status < 200 or status >= 300:
67         raise Exception(data, int(response.status))
68     
69     return json.loads(data)
70
71 def user_for_token(token, authentication_url, override_users):
72     if not token:
73         return None
74     
75     if override_users:
76         try:
77             return {'uniq': override_users[token].decode('utf8')}
78         except:
79             return None
80     
81     try:
82         return authenticate(token, authentication_url)
83     except:
84         return None
85
86 def get_user(request, authentication_url='http://127.0.0.1:8000/im/authenticate', override_users={}):
87     request.user = None
88     request.user_uniq = None
89     
90     # Try to find token in a parameter or in a request header.
91     user = user_for_token(request.GET.get('X-Auth-Token'), authentication_url, override_users)
92     if not user:
93         user = user_for_token(request.META.get('HTTP_X_AUTH_TOKEN'), authentication_url, override_users)
94     if not user:
95         return
96     
97     request.user = user
98     request.user_uniq = user['uniq']