__init__.py 10.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Copyright 2011-2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

34
35
36
37
from functools import wraps
from traceback import format_exc
from urllib import quote, unquote

38
39
from django.http import HttpResponse
from django.utils import simplejson as json
40
41
42
43
from django.conf import settings
from django.core.urlresolvers import reverse

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
48
import logging
logger = logging.getLogger(__name__)
49
50
51

format = ('%a, %d %b %Y %H:%M:%S GMT')

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
52
53
absolute = lambda request, url: request.build_absolute_uri(url)

54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def render_fault(request, fault):
    if isinstance(fault, InternalServerError) and settings.DEBUG:
        fault.details = format_exc(fault)

    request.serialization = 'text'
    data = fault.message + '\n'
    if fault.details:
        data += '\n' + fault.details
    response = HttpResponse(data, status=fault.code)
    response['Content-Length'] = len(response.content)
    return response

def api_method(http_method=None):
    """Decorator function for views that implement an API method."""
    def decorator(func):
        @wraps(func)
        def wrapper(request, *args, **kwargs):
            try:
                if http_method and request.method != http_method:
                    raise BadRequest('Method not allowed.')
                response = func(request, *args, **kwargs)
                return response
            except Fault, fault:
                return render_fault(request, fault)
            except BaseException, e:
                logger.exception('Unexpected error: %s' % e)
                fault = InternalServerError('Unexpected error')
                return render_fault(request, fault)
        return wrapper
    return decorator

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

def _get_user_by_email(email):
    if not email:
        raise BadRequest('Email missing')
    try:
        user = AstakosUser.objects.get(email = email)
112
    except AstakosUser.DoesNotExist:
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
        raise ItemNotFound('Invalid email')
    
    if not user.is_active:
        raise ItemNotFound('Inactive user')
    else:
        response = HttpResponse()
        response.status=200
        user_info = {'id':user.id,
                     'username':user.username,
                     'email':[user.email],
                     'enabled':user.is_active,
                     'name':user.realname,
                     'auth_token_created':user.auth_token_created.strftime(format),
                     'auth_token_expires':user.auth_token_expires.strftime(format),
                     'has_credits':user.has_credits,
                     'groups':[g.name for g in user.groups.all()],
                     'user_permissions':[p.codename for p in user.user_permissions.all()]}
        response.content = json.dumps(user_info)
        response['Content-Type'] = 'application/json; charset=UTF-8'
        response['Content-Length'] = len(response.content)
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
        return response

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

    if callback:
        mimetype = 'application/javascript'
        data = '%s(%s)' % (callback, data)

    return HttpResponse(content=data, mimetype=mimetype)

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

    if callback:
        mimetype = 'application/javascript'
        data = '%s(%s)' % (callback, data)

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
    return HttpResponse(content=data, mimetype=mimetype)

class MenuItem(dict):
    current_path = ''
    
    def __init__(self, *args, **kwargs):
        super(MenuItem, self).__init__(*args, **kwargs)
        if kwargs.get('url') or kwargs.get('submenu'):
            self.__set_is_active__()
    
    def __setitem__(self, key, value):
        super(MenuItem, self).__setitem__(key, value)
        if key in ('url', 'submenu'):
            self.__set_is_active__()
    
    def __set_is_active__(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
274
275
        if self.get('is_active'):
            return
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
276
277
278
        if self.current_path == self.get('url'):
            self.__setitem__('is_active', True)
        else:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
279
280
281
282
283
284
285
286
287
288
289
290
291
292
            submenu = self.get('submenu', ())
            current = (i for i in submenu if i.get('url') == self.current_path)
            try:
                current_node = current.next()
                if not current_node.get('is_active'):
                    current_node.__setitem__('is_active', True)
                self.__setitem__('is_active', True)
            except StopIteration:
                return
        
    def __setattribute__(self, name, value):
        super(MenuItem, self).__setattribute__(name, value)
        if name == 'current_path':
            self.__set_is_active__()