Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / api / __init__.py @ 5ce3ce4f

History | View | Annotate | Download (10.6 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, BadRequest
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
absolute = lambda request, url: request.build_absolute_uri(url)
53

    
54

    
55
def render_fault(request, fault):
56
    if isinstance(fault, InternalServerError) and settings.DEBUG:
57
        fault.details = format_exc(fault)
58

    
59
    request.serialization = 'text'
60
    data = fault.message + '\n'
61
    if fault.details:
62
        data += '\n' + fault.details
63
    response = HttpResponse(data, status=fault.code)
64
    response['Content-Length'] = len(response.content)
65
    return response
66

    
67

    
68
def api_method(http_method=None):
69
    """Decorator function for views that implement an API method."""
70
    def decorator(func):
71
        @wraps(func)
72
        def wrapper(request, *args, **kwargs):
73
            try:
74
                if http_method and request.method != http_method:
75
                    raise BadRequest('Method not allowed.')
76
                response = func(request, *args, **kwargs)
77
                return response
78
            except Fault, fault:
79
                return render_fault(request, fault)
80
            except BaseException, e:
81
                logger.exception('Unexpected error: %s' % e)
82
                fault = InternalServerError('Unexpected error')
83
                return render_fault(request, fault)
84
        return wrapper
85
    return decorator
86

    
87

    
88
def _get_user_by_username(user_id):
89
    try:
90
        user = AstakosUser.objects.get(username=user_id)
91
    except AstakosUser.DoesNotExist:
92
        raise ItemNotFound('Invalid userid')
93
    else:
94
        response = HttpResponse()
95
        response.status = 200
96
        user_info = {'id': user.id,
97
                     'username': user.username,
98
                     'email': [user.email],
99
                     'name': user.realname,
100
                     'auth_token_created': user.auth_token_created.strftime(format),
101
                     'auth_token_expires': user.auth_token_expires.strftime(format),
102
                     'has_credits': user.has_credits,
103
                     'enabled': user.is_active,
104
                     'groups': [g.name for g in user.groups.all()]}
105
        response.content = json.dumps(user_info)
106
        response['Content-Type'] = 'application/json; charset=UTF-8'
107
        response['Content-Length'] = len(response.content)
108
        return response
109

    
110

    
111
def _get_user_by_email(email):
112
    if not email:
113
        raise BadRequest('Email missing')
114
    try:
115
        user = AstakosUser.objects.get(email=email)
116
    except AstakosUser.DoesNotExist:
117
        raise ItemNotFound('Invalid email')
118

    
119
    if not user.is_active:
120
        raise ItemNotFound('Inactive user')
121
    else:
122
        response = HttpResponse()
123
        response.status = 200
124
        user_info = {'id': user.id,
125
                     'username': user.username,
126
                     'email': [user.email],
127
                     'enabled': user.is_active,
128
                     'name': user.realname,
129
                     'auth_token_created': user.auth_token_created.strftime(format),
130
                     'auth_token_expires': user.auth_token_expires.strftime(format),
131
                     'has_credits': user.has_credits,
132
                     'groups': [g.name for g in user.groups.all()],
133
                     'user_permissions': [p.codename for p in user.user_permissions.all()]}
134
        response.content = json.dumps(user_info)
135
        response['Content-Type'] = 'application/json; charset=UTF-8'
136
        response['Content-Length'] = len(response.content)
137
        return response
138

    
139

    
140
@api_method(http_method='GET')
141
def get_services(request):
142
    callback = request.GET.get('callback', None)
143
    services = Service.objects.all()
144
    data = tuple({'id': s.pk, 'name': s.name, 'url': s.url, 'icon':
145
                 s.icon} for s in services)
146
    data = json.dumps(data)
147
    mimetype = 'application/json'
148

    
149
    if callback:
150
        mimetype = 'application/javascript'
151
        data = '%s(%s)' % (callback, data)
152

    
153
    return HttpResponse(content=data, mimetype=mimetype)
154

    
155

    
156
@api_method()
157
def get_menu(request, with_extra_links=False, with_signout=True):
158
    user = request.user
159
    if not isinstance(user, AstakosUser):
160
        cookie = unquote(request.COOKIES.get(COOKIE_NAME, ''))
161
        email = cookie.partition('|')[0]
162
        try:
163
            if email:
164
                user = AstakosUser.objects.get(email=email, is_active=True)
165
        except AstakosUser.DoesNotExist:
166
            pass
167
    if not isinstance(user, AstakosUser):
168
        index_url = reverse('index')
169
        l = [{'url': absolute(request, index_url), 'name': "Sign in"}]
170
    else:
171
        l = []
172
        append = l.append
173
        item = MenuItem
174
        item.current_path = absolute(request, request.path)
175
        append(
176
            item(
177
                url=absolute(request, reverse('index')),
178
                name=user.email
179
            )
180
        )
181
        append(
182
            item(
183
                url=absolute(request, reverse('edit_profile')),
184
                name="My account"
185
            )
186
        )
187
        if with_extra_links:
188
            if user.has_usable_password() and user.provider in ('local', ''):
189
                append(
190
                    item(
191
                        url=absolute(request, reverse('password_change')),
192
                        name="Change password"
193
                    )
194
                )
195
            if EMAILCHANGE_ENABLED:
196
                append(
197
                    item(
198
                        url=absolute(request, reverse('email_change')),
199
                        name="Change email"
200
                    )
201
                )
202
            if INVITATIONS_ENABLED:
203
                append(
204
                    item(
205
                        url=absolute(request, reverse('invite')),
206
                        name="Invitations"
207
                    )
208
                )
209
            append(
210
                item(
211
                    url=absolute(request, reverse('feedback')),
212
                    name="Feedback"
213
                )
214
            )
215
            append(
216
                item(
217
                    url=absolute(request, reverse('group_list')),
218
                    name="Groups",
219
                    submenu=(
220
                        item(
221
                            url=absolute(request, reverse('group_list')),
222
                            name="Overview"
223
                        ),
224
                        item(
225
                            url=absolute(request,
226
                                         reverse('group_create_list')
227
                                         ),
228
                            name="Create"
229
                        ),
230
                        item(
231
                            url=absolute(request, reverse('group_search')),
232
                            name="Join"
233
                        ),
234
                    )
235
                )
236
            )
237
            append(
238
                item(
239
                    url=absolute(request, reverse('resource_list')),
240
                    name="Resources"
241
                )
242
            )
243
            append(
244
                item(
245
                    url=absolute(request, reverse('billing')),
246
                    name="Billing"
247
                )
248
            )
249
        if with_signout:
250
            append(
251
                item(
252
                    url=absolute(request, reverse('logout')),
253
                    name="Sign out"
254
                )
255
            )
256

    
257
    callback = request.GET.get('callback', None)
258
    data = json.dumps(tuple(l))
259
    mimetype = 'application/json'
260

    
261
    if callback:
262
        mimetype = 'application/javascript'
263
        data = '%s(%s)' % (callback, data)
264

    
265
    return HttpResponse(content=data, mimetype=mimetype)
266

    
267

    
268
class MenuItem(dict):
269
    current_path = ''
270

    
271
    def __init__(self, *args, **kwargs):
272
        super(MenuItem, self).__init__(*args, **kwargs)
273
        if kwargs.get('url') or kwargs.get('submenu'):
274
            self.__set_is_active__()
275

    
276
    def __setitem__(self, key, value):
277
        super(MenuItem, self).__setitem__(key, value)
278
        if key in ('url', 'submenu'):
279
            self.__set_is_active__()
280

    
281
    def __set_is_active__(self):
282
        if self.get('is_active'):
283
            return
284
        if self.current_path == self.get('url'):
285
            self.__setitem__('is_active', True)
286
        else:
287
            submenu = self.get('submenu', ())
288
            current = (i for i in submenu if i.get('url') == self.current_path)
289
            try:
290
                current_node = current.next()
291
                if not current_node.get('is_active'):
292
                    current_node.__setitem__('is_active', True)
293
                self.__setitem__('is_active', True)
294
            except StopIteration:
295
                return
296

    
297
    def __setattribute__(self, name, value):
298
        super(MenuItem, self).__setattribute__(name, value)
299
        if name == 'current_path':
300
            self.__set_is_active__()