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