__init__.py 10.2 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
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

67

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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

87

88
89
def _get_user_by_username(user_id):
    try:
90
        user = AstakosUser.objects.get(username=user_id)
91
    except AstakosUser.DoesNotExist:
92
93
94
        raise ItemNotFound('Invalid userid')
    else:
        response = HttpResponse()
95
96
97
98
99
100
101
102
103
104
        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()]}
105
106
107
108
109
        response.content = json.dumps(user_info)
        response['Content-Type'] = 'application/json; charset=UTF-8'
        response['Content-Length'] = len(response.content)
        return response

110

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

119
120
121
122
    if not user.is_active:
        raise ItemNotFound('Inactive user')
    else:
        response = HttpResponse()
123
124
125
126
127
128
129
130
131
132
133
        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()]}
134
135
136
        response.content = json.dumps(user_info)
        response['Content-Type'] = 'application/json; charset=UTF-8'
        response['Content-Length'] = len(response.content)
137
138
        return response

139

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

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

    return HttpResponse(content=data, mimetype=mimetype)

155

156
@api_method()
Olga Brani's avatar
Bug fix    
Olga Brani committed
157
def get_menu(request, with_extra_links=False, with_signout=True):
Olga Brani's avatar
Olga Brani committed
158
159
160
161
162
163
164
165
166
167
168
    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')
169
        l = [{'url': absolute(request, index_url), 'name': "Sign in"}]
170
171
    else:
        l = []
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
172
173
174
        append = l.append
        item = MenuItem
        item.current_path = absolute(request, request.path)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
175
        append(item(
Olga Brani's avatar
Olga Brani committed
176
177
               url=absolute(request, reverse('index')),
               name=user.email))
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
178
179
        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
                append(item(
Olga Brani's avatar
Olga Brani committed
183
184
                       url=absolute(request, reverse('password_change')),
                       name="Change password"))
185
            if EMAILCHANGE_ENABLED:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
186
                append(item(
Olga Brani's avatar
Olga Brani committed
187
188
                       url=absolute(request, reverse('email_change')),
                       name="Change email"))
189
            if INVITATIONS_ENABLED:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
190
                append(item(
Olga Brani's avatar
Olga Brani committed
191
192
                       url=absolute(request, reverse('invite')),
                       name="Invitations"))
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
193
            append(item(
Olga Brani's avatar
Olga Brani committed
194
195
                   url=absolute(request, reverse('feedback')),
                   name="Feedback"))
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
196
            append(item(
Olga Brani's avatar
Olga Brani committed
197
198
199
200
201
202
                   url=absolute(request, reverse('group_list')),
                   name="Groups",
                   submenu=(item(
                            url=absolute(request,
                                         reverse('group_list')),
                            name="Overview"),
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
203
204
205
206
207
208
209
210
211
                            item(
                                url=absolute(request,
                                             reverse('group_create_list')),
                                name="Create"),
                            item(
                                url=absolute(request,
                                             reverse('group_search')),
                                name="Join"),)))
            append(item(
Olga Brani's avatar
Olga Brani committed
212
213
                   url=absolute(request, reverse('resource_list')),
                   name="Resources"))
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
214
            append(item(
Olga Brani's avatar
Olga Brani committed
215
216
                   url=absolute(request, reverse('billing')),
                   name="Billing"))
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
217
            append(item(
Olga Brani's avatar
Olga Brani committed
218
219
                   url=absolute(request, reverse('timeline')),
                   name="Timeline"))
220
        if with_signout:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
221
            append(item(
Olga Brani's avatar
Olga Brani committed
222
223
                   url=absolute(request, reverse('logout')),
                   name="Sign out"))
224

225
226
227
228
229
230
231
232
    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
233
234
    return HttpResponse(content=data, mimetype=mimetype)

235

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
236
237
class MenuItem(dict):
    current_path = ''
238

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
239
240
241
242
    def __init__(self, *args, **kwargs):
        super(MenuItem, self).__init__(*args, **kwargs)
        if kwargs.get('url') or kwargs.get('submenu'):
            self.__set_is_active__()
243

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
244
245
246
247
    def __setitem__(self, key, value):
        super(MenuItem, self).__setitem__(key, value)
        if key in ('url', 'submenu'):
            self.__set_is_active__()
248

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
249
    def __set_is_active__(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
250
251
        if self.get('is_active'):
            return
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
252
253
254
        if self.current_path == self.get('url'):
            self.__setitem__('is_active', True)
        else:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
255
256
257
258
259
260
261
262
263
            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
264

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
265
266
267
    def __setattribute__(self, name, value):
        super(MenuItem, self).__setattribute__(name, value)
        if name == 'current_path':
268
            self.__set_is_active__()