root / snf-astakos-app / astakos / im / api / __init__.py @ 7376ef80
History | View | Annotate | Download (7.9 kB)
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 |
import logging |
35 |
import urllib |
36 |
|
37 |
from traceback import format_exc |
38 |
|
39 |
from django.http import HttpResponse |
40 |
from django.utils import simplejson as json |
41 |
from django.conf import settings |
42 |
from django.core.urlresolvers import reverse |
43 |
|
44 |
from astakos.im.models import AstakosUser, Service |
45 |
from astakos.im.api.faults import Fault, ItemNotFound, InternalServerError, Unauthorized, BadRequest |
46 |
from astakos.im.settings import INVITATIONS_ENABLED, COOKIE_NAME, EMAILCHANGE_ENABLED |
47 |
|
48 |
logger = logging.getLogger(__name__) |
49 |
format = ('%a, %d %b %Y %H:%M:%S GMT')
|
50 |
|
51 |
class apiMethod(object): |
52 |
def __init__(self, http_method=None, token_required=False, perms=None): |
53 |
self.http_method = http_method
|
54 |
self.token_required = token_required
|
55 |
self.perms = perms if perms else () |
56 |
|
57 |
def __call__(self, func): |
58 |
def wrapped_f(request, *args, **kwargs): |
59 |
try:
|
60 |
if self.http_method and request.method != self.http_method: |
61 |
raise BadRequest('Method not allowed.') |
62 |
x_auth_token = request.META.get('HTTP_X_AUTH_TOKEN')
|
63 |
if self.token_required: |
64 |
if not x_auth_token: |
65 |
raise Unauthorized('Access denied') |
66 |
kwargs['user'] = self._get_token_owner(x_auth_token) |
67 |
response = func(request, *args, **kwargs) |
68 |
return response
|
69 |
except Fault, fault:
|
70 |
return render_fault(request, fault)
|
71 |
except BaseException, e: |
72 |
logger.exception('Unexpected error: %s' % e)
|
73 |
fault = InternalServerError('Unexpected error')
|
74 |
return render_fault(request, fault)
|
75 |
return wrapped_f
|
76 |
|
77 |
def _get_token_owner(self, x_auth_token): |
78 |
return
|
79 |
|
80 |
def render_fault(request, fault): |
81 |
if isinstance(fault, InternalServerError) and settings.DEBUG: |
82 |
fault.details = format_exc(fault) |
83 |
|
84 |
request.serialization = 'text'
|
85 |
data = fault.message + '\n'
|
86 |
if fault.details:
|
87 |
data += '\n' + fault.details
|
88 |
response = HttpResponse(data, status=fault.code) |
89 |
response['Content-Length'] = len(response.content) |
90 |
return response
|
91 |
|
92 |
def _get_user_by_username(user_id): |
93 |
try:
|
94 |
user = AstakosUser.objects.get(username = user_id) |
95 |
except AstakosUser.DoesNotExist, e:
|
96 |
raise ItemNotFound('Invalid userid') |
97 |
else:
|
98 |
response = HttpResponse() |
99 |
response.status=200
|
100 |
user_info = {'id':user.id,
|
101 |
'username':user.username,
|
102 |
'email':[user.email],
|
103 |
'name':user.realname,
|
104 |
'auth_token_created':user.auth_token_created.strftime(format),
|
105 |
'auth_token_expires':user.auth_token_expires.strftime(format),
|
106 |
'has_credits':user.has_credits,
|
107 |
'enabled':user.is_active,
|
108 |
'groups':[g.name for g in user.groups.all()]} |
109 |
response.content = json.dumps(user_info) |
110 |
response['Content-Type'] = 'application/json; charset=UTF-8' |
111 |
response['Content-Length'] = len(response.content) |
112 |
return response
|
113 |
|
114 |
def _get_user_by_email(email): |
115 |
if not email: |
116 |
raise BadRequest('Email missing') |
117 |
try:
|
118 |
user = AstakosUser.objects.get(email = email) |
119 |
except AstakosUser.DoesNotExist, e:
|
120 |
raise ItemNotFound('Invalid email') |
121 |
|
122 |
if not user.is_active: |
123 |
raise ItemNotFound('Inactive user') |
124 |
else:
|
125 |
response = HttpResponse() |
126 |
response.status=200
|
127 |
user_info = {'id':user.id,
|
128 |
'username':user.username,
|
129 |
'email':[user.email],
|
130 |
'enabled':user.is_active,
|
131 |
'name':user.realname,
|
132 |
'auth_token_created':user.auth_token_created.strftime(format),
|
133 |
'auth_token_expires':user.auth_token_expires.strftime(format),
|
134 |
'has_credits':user.has_credits,
|
135 |
'groups':[g.name for g in user.groups.all()], |
136 |
'user_permissions':[p.codename for p in user.user_permissions.all()]} |
137 |
response.content = json.dumps(user_info) |
138 |
response['Content-Type'] = 'application/json; charset=UTF-8' |
139 |
response['Content-Length'] = len(response.content) |
140 |
return response
|
141 |
|
142 |
@apiMethod(http_method='GET') |
143 |
def get_services(request): |
144 |
callback = request.GET.get('callback', None) |
145 |
services = Service.objects.all() |
146 |
data = tuple({'name':s.name, 'url':s.url, 'icon':s.icon} for s in services) |
147 |
data = json.dumps(data) |
148 |
mimetype = 'application/json'
|
149 |
|
150 |
if callback:
|
151 |
mimetype = 'application/javascript'
|
152 |
data = '%s(%s)' % (callback, data)
|
153 |
|
154 |
return HttpResponse(content=data, mimetype=mimetype)
|
155 |
|
156 |
@apiMethod()
|
157 |
def get_menu(request, with_extra_links=False, with_signout=True): |
158 |
index_url = reverse('index')
|
159 |
absolute = lambda (url): request.build_absolute_uri(url)
|
160 |
l = [{ 'url': absolute(index_url), 'name': "Sign in"}] |
161 |
cookie = urllib.unquote(request.COOKIES.get(COOKIE_NAME, ''))
|
162 |
email = cookie.partition('|')[0] |
163 |
try:
|
164 |
user = AstakosUser.objects.get(email=email, is_active=True)
|
165 |
except AstakosUser.DoesNotExist:
|
166 |
pass
|
167 |
else:
|
168 |
l = [] |
169 |
l.append({ 'url': absolute(reverse('astakos.im.views.index')), |
170 |
'name': user.email})
|
171 |
l.append({ 'url': absolute(reverse('astakos.im.views.edit_profile')), |
172 |
'name': "My account" }) |
173 |
if with_extra_links:
|
174 |
if user.has_usable_password():
|
175 |
l.append({ 'url': absolute(reverse('password_change')), |
176 |
'name': "Change password" }) |
177 |
if EMAILCHANGE_ENABLED:
|
178 |
l.append({'url':absolute(reverse('email_change')), |
179 |
'name': "Change email"}) |
180 |
if INVITATIONS_ENABLED:
|
181 |
l.append({ 'url': absolute(reverse('astakos.im.views.invite')), |
182 |
'name': "Invitations" }) |
183 |
l.append({ 'url': absolute(reverse('astakos.im.views.feedback')), |
184 |
'name': "Feedback" }) |
185 |
if with_signout:
|
186 |
l.append({ 'url': absolute(reverse('astakos.im.views.logout')), |
187 |
'name': "Sign out"}) |
188 |
|
189 |
callback = request.GET.get('callback', None) |
190 |
data = json.dumps(tuple(l))
|
191 |
mimetype = 'application/json'
|
192 |
|
193 |
if callback:
|
194 |
mimetype = 'application/javascript'
|
195 |
data = '%s(%s)' % (callback, data)
|
196 |
|
197 |
return HttpResponse(content=data, mimetype=mimetype)
|