Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / api / __init__.py @ 890c2065

History | View | Annotate | Download (8.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
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
from django.utils.translation import ugettext as _
43

    
44
from astakos.im.models import AstakosUser, Service, Resource
45
from astakos.im.api.faults import Fault, ItemNotFound, InternalServerError, BadRequest
46
from astakos.im.settings import (
47
    INVITATIONS_ENABLED, COOKIE_NAME, EMAILCHANGE_ENABLED, QUOTAHOLDER_URL)
48
from astakos.im.forms import FeedbackForm
49
from astakos.im.functions import send_feedback as send_feedback_func
50

    
51
import logging
52
logger = logging.getLogger(__name__)
53

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

    
56
absolute = lambda request, url: request.build_absolute_uri(url)
57

    
58

    
59
def render_fault(request, fault):
60
    if isinstance(fault, InternalServerError) and settings.DEBUG:
61
        fault.details = format_exc(fault)
62

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

    
71

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

    
91

    
92
def get_services_dict():
93
    services = Service.objects.all()
94
    data = tuple({'id': s.pk, 'name': s.name, 'url': s.url, 'icon':
95
                 s.icon} for s in services)
96
    return data
97

    
98
@api_method(http_method=None)
99
def get_services(request):
100
    callback = request.GET.get('callback', None)
101
    mimetype = 'application/json'
102
    data = json.dumps(get_services_dict())
103

    
104
    if callback:
105
        mimetype = 'application/javascript'
106
        data = '%s(%s)' % (callback, data)
107

    
108
    return HttpResponse(content=data, mimetype=mimetype)
109

    
110

    
111
@api_method()
112
def get_menu(request, with_extra_links=False, with_signout=True):
113
    user = request.user
114
    from_location = request.GET.get('location')
115
    index_url = reverse('index')
116
    if from_location:
117
        index_url = "%s?next=%s" % (index_url, from_location)
118

    
119
    l = [{'url': absolute(request, index_url), 'name': _("Sign in")}]
120
    if user.is_authenticated():
121
        l = []
122
        append = l.append
123
        item = MenuItem
124
        item.current_path = absolute(request, request.path)
125
        append(item(
126
               url=absolute(request, reverse('index')),
127
               name=user.email))
128
        if with_extra_links:
129
            append(item(
130
                url=absolute(request, reverse('landing')),
131
                name="Overview")) 
132
        append(item(url=absolute(request, reverse('edit_profile')),
133
               name="Profile"))
134
         
135
        if with_extra_links:
136
            #if EMAILCHANGE_ENABLED:
137
                #append(item(
138
                #      url=absolute(request, reverse('email_change')),
139
                #       name="Change email"))
140
            if INVITATIONS_ENABLED:
141
                append(item(
142
                       url=absolute(request, reverse('invite')),
143
                       name="Invitations"))
144

    
145
            if QUOTAHOLDER_URL:
146
                append(item(
147
                       url=absolute(request, reverse('project_list')),
148
                       name="Projects"))
149
            append(item(
150
                   url=absolute(request, reverse('resource_usage')),
151
                   name="Usage"))
152
            append(item(
153
                url=absolute(request, reverse('api_access')),
154
                name="API Access")) 
155
            
156
            append(item(
157
                   url=absolute(request, reverse('feedback')),
158
                   name="Contact"))
159
        if with_signout:
160
            append(item(
161
                   url=absolute(request, reverse('logout')),
162
                   name="Sign out"))
163

    
164
    callback = request.GET.get('callback', None)
165
    data = json.dumps(tuple(l))
166
    mimetype = 'application/json'
167

    
168
    if callback:
169
        mimetype = 'application/javascript'
170
        data = '%s(%s)' % (callback, data)
171

    
172
    return HttpResponse(content=data, mimetype=mimetype)
173

    
174

    
175
class MenuItem(dict):
176
    current_path = ''
177

    
178
    def __init__(self, *args, **kwargs):
179
        super(MenuItem, self).__init__(*args, **kwargs)
180
        if kwargs.get('url') or kwargs.get('submenu'):
181
            self.__set_is_active__()
182

    
183
    def __setitem__(self, key, value):
184
        super(MenuItem, self).__setitem__(key, value)
185
        if key in ('url', 'submenu'):
186
            self.__set_is_active__()
187

    
188
    def __set_is_active__(self):
189
        if self.get('is_active'):
190
            return
191
        if self.current_path.startswith(self.get('url')):
192
            self.__setitem__('is_active', True)
193
        else:
194
            submenu = self.get('submenu', ())
195
            current = (i for i in submenu if i.get('url') == self.current_path)
196
            try:
197
                current_node = current.next()
198
                if not current_node.get('is_active'):
199
                    current_node.__setitem__('is_active', True)
200
                self.__setitem__('is_active', True)
201
            except StopIteration:
202
                return
203

    
204
    def __setattribute__(self, name, value):
205
        super(MenuItem, self).__setattribute__(name, value)
206
        if name == 'current_path':
207
            self.__set_is_active__()
208

    
209
def __get_uuid_displayname_catalogs(request):
210
    # Normal Response Codes: 200
211
    # Error Response Codes: badRequest (400)
212

    
213
    try:
214
        input_data = json.loads(request.raw_post_data)
215
    except:
216
        raise BadRequest('Request body should be json formatted.')
217
    else:
218
        uuids = input_data.get('uuids', [])
219
        displaynames = input_data.get('displaynames', [])
220
        d  = {'uuid_catalog':AstakosUser.objects.uuid_catalog(uuids),
221
              'displayname_catalog':AstakosUser.objects.displayname_catalog(displaynames)}
222

    
223
        response = HttpResponse()
224
        response.status = 200
225
        response.content = json.dumps(d)
226
        response['Content-Type'] = 'application/json; charset=UTF-8'
227
        response['Content-Length'] = len(response.content)
228
        return response
229

    
230
def __send_feedback(request, email_template_name='im/feedback_mail.txt', user=None):
231
    if not user:
232
        auth_token = request.POST.get('auth', '')
233
        if not auth_token:
234
            raise BadRequest('Missing user authentication')
235

    
236
        try:
237
            user = AstakosUser.objects.get(auth_token=auth_token)
238
        except AstakosUser.DoesNotExist:
239
            raise BadRequest('Invalid user authentication')
240

    
241
    form = FeedbackForm(request.POST)
242
    if not form.is_valid():
243
        raise BadRequest('Invalid data')
244

    
245
    msg = form.cleaned_data['feedback_msg']
246
    data = form.cleaned_data['feedback_data']
247
    try:
248
        send_feedback_func(msg, data, user, email_template_name)
249
    except:
250
        return HttpResponse(status=502)
251
    return HttpResponse(status=200)