root / api / middleware.py @ bc923fb7
History | View | Annotate | Download (2.6 kB)
1 |
from django.conf import settings |
---|---|
2 |
from django.http import HttpResponse, HttpResponseRedirect |
3 |
from synnefo.db.models import SynnefoUser |
4 |
from synnefo.aai.shibboleth import Tokens, register_shibboleth_user |
5 |
import time |
6 |
import datetime |
7 |
|
8 |
class ApiAuthMiddleware(object): |
9 |
|
10 |
auth_token = "X-Auth-Token"
|
11 |
auth_user = "X-Auth-User"
|
12 |
auth_key = "X-Auth-Key"
|
13 |
|
14 |
def process_request(self, request): |
15 |
if not request.path.startswith('/api/') : |
16 |
return
|
17 |
|
18 |
token = None
|
19 |
|
20 |
#Try to find token in a cookie
|
21 |
try:
|
22 |
token = request.COOKIES['X-Auth-Token']
|
23 |
except Exception: |
24 |
pass
|
25 |
|
26 |
#Try to find token in request header
|
27 |
if not token: |
28 |
token = request.META.get('HTTP_X_AUTH_TOKEN', None) |
29 |
|
30 |
if token:
|
31 |
user = None
|
32 |
#Retrieve user from DB or other caching mechanism
|
33 |
try:
|
34 |
user = SynnefoUser.objects.get(auth_token=token) |
35 |
except SynnefoUser.DoesNotExist:
|
36 |
user = None
|
37 |
|
38 |
#Check user's auth token
|
39 |
if (time.time() -
|
40 |
time.mktime(user.auth_token_expires.timetuple())) > 0:
|
41 |
#The user's token has expired, re-login
|
42 |
user = None
|
43 |
|
44 |
request.user = user |
45 |
return
|
46 |
|
47 |
#A Rackspace API authentication request
|
48 |
if self.auth_user in request.META and self.auth_key in request.META and 'GET' == request.method: |
49 |
# This is here merely for compatibility with the Openstack API.
|
50 |
# All normal users should authenticate through Sibbolleth. Admin
|
51 |
# users or other selected users could use this as a bypass
|
52 |
# mechanism
|
53 |
user = SynnefoUser.objects\ |
54 |
.filter(name = request.META[self.auth_user]) \
|
55 |
.filter(uniq = request.META[self.auth_key])
|
56 |
|
57 |
response = HttpResponse() |
58 |
if user.count() <= 0: |
59 |
response.status_code = 401
|
60 |
else:
|
61 |
response.status_code = 204
|
62 |
response['X-Auth-Token'] = user[0].auth_token |
63 |
#TODO: set the following fields when we do have this info
|
64 |
response['X-Server-Management-Url'] = "" |
65 |
response['X-Storage-Url'] = "" |
66 |
response['X-CDN-Management-Url'] = "" |
67 |
return response
|
68 |
|
69 |
request.user = None
|
70 |
|
71 |
def process_response(self, request, response): |
72 |
#Tell proxies and other interested parties that the
|
73 |
#request varies based on the auth token, to avoid
|
74 |
#caching of results
|
75 |
response['Vary'] = self.auth_token |
76 |
return response
|
77 |
|