Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / api.py @ 59f598f1

History | View | Annotate | Download (6.2 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
import logging
35

    
36
from traceback import format_exc
37
from time import time, mktime
38
from urllib import quote
39
from urlparse import urlparse
40

    
41
from django.conf import settings
42
from django.http import HttpResponse
43
from django.utils import simplejson as json
44
from django.core.urlresolvers import reverse
45

    
46
from astakos.im.faults import BadRequest, Unauthorized, InternalServerError
47
from astakos.im.models import AstakosUser
48
from astakos.im.settings import CLOUD_SERVICES, INVITATIONS_ENABLED
49

    
50
logger = logging.getLogger(__name__)
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 authenticate(request):
65
    # Normal Response Codes: 204
66
    # Error Response Codes: internalServerError (500)
67
    #                       badRequest (400)
68
    #                       unauthorised (401)
69
    try:
70
        if request.method != 'GET':
71
            raise BadRequest('Method not allowed.')
72
        x_auth_token = request.META.get('HTTP_X_AUTH_TOKEN')
73
        if not x_auth_token:
74
            return render_fault(request, BadRequest('Missing X-Auth-Token'))
75

    
76
        try:
77
            user = AstakosUser.objects.get(auth_token=x_auth_token)
78
        except AstakosUser.DoesNotExist, e:
79
            return render_fault(request, Unauthorized('Invalid X-Auth-Token'))
80

    
81
        # Check if the is active.
82
        if not user.is_active:
83
            return render_fault(request, Unauthorized('User inactive'))
84

    
85
        # Check if the token has expired.
86
        if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
87
            return render_fault(request, Unauthorized('Authentication expired'))
88

    
89
        response = HttpResponse()
90
        response.status=204
91
        user_info = {'username':user.username,
92
                     'uniq':user.email,
93
                     'auth_token':user.auth_token,
94
                     'auth_token_created':user.auth_token_created.isoformat(),
95
                     'auth_token_expires':user.auth_token_expires.isoformat(),
96
                     'has_credits':user.has_credits}
97
        response.content = json.dumps(user_info)
98
        response['Content-Type'] = 'application/json; charset=UTF-8'
99
        response['Content-Length'] = len(response.content)
100
        return response
101
    except BaseException, e:
102
        logger.exception(e)
103
        fault = InternalServerError('Unexpected error')
104
        return render_fault(request, fault)
105

    
106
def get_services(request):
107
    if request.method != 'GET':
108
        raise BadRequest('Method not allowed.')
109

    
110
    callback = request.GET.get('callback', None)
111
    data = json.dumps(CLOUD_SERVICES)
112
    mimetype = 'application/json'
113

    
114
    if callback:
115
        mimetype = 'application/javascript'
116
        data = '%s(%s)' % (callback, data)
117

    
118
    return HttpResponse(content=data, mimetype=mimetype)
119

    
120
def get_menu(request):
121
    location = request.GET.get('location', '')
122
    exclude = []
123
    index_url = reverse('index')
124
    login_url = reverse('login')
125
    logout_url = reverse('astakos.im.views.logout')
126
    absolute = lambda (url): request.build_absolute_uri(url)
127
    l = index_url, login_url, logout_url
128
    forbidden = []
129
    for url in l:
130
        url = url.rstrip('/')
131
        forbidden.extend([url, url + '/', absolute(url), absolute(url + '/')])
132
    if location not in forbidden:
133
        index_url = '%s?next=%s' % (index_url, quote(location))
134
    l = [{ 'url': absolute(index_url), 'name': "Sign in"}]
135
    if request.user.is_authenticated():
136
        l = []
137
        l.append({ 'url': absolute(reverse('astakos.im.views.index')),
138
                  'name': request.user.email})
139
        l.append({ 'url': absolute(reverse('astakos.im.views.edit_profile')),
140
                  'name': "View your profile" })
141
        if request.user.password:
142
            l.append({ 'url': absolute(reverse('password_change')),
143
                      'name': "Change your password" })
144
        if INVITATIONS_ENABLED:
145
            l.append({ 'url': absolute(reverse('astakos.im.views.invite')),
146
                      'name': "Invite some friends" })
147
        l.append({ 'url': absolute(reverse('astakos.im.views.send_feedback')),
148
                  'name': "Send feedback" })
149
        l.append({ 'url': absolute(reverse('astakos.im.views.logout')),
150
                  'name': "Sign out"})
151

    
152
    callback = request.GET.get('callback', None)
153
    data = json.dumps(tuple(l))
154
    mimetype = 'application/json'
155

    
156
    if callback:
157
        mimetype = 'application/javascript'
158
        data = '%s(%s)' % (callback, data)
159

    
160
    return HttpResponse(content=data, mimetype=mimetype)