Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / api.py @ ef19d181

History | View | Annotate | Download (5.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 traceback import format_exc
35
from time import time, mktime
36
from urllib import quote
37
from urlparse import urlparse
38

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

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

    
48
def render_fault(request, fault):
49
    if isinstance(fault, InternalServerError) and settings.DEBUG:
50
        fault.details = format_exc(fault)
51

    
52
    request.serialization = 'text'
53
    data = fault.message + '\n'
54
    if fault.details:
55
        data += '\n' + fault.details
56
    response = HttpResponse(data, status=fault.code)
57
    response['Content-Length'] = len(response.content)
58
    return response
59

    
60
def authenticate(request):
61
    # Normal Response Codes: 204
62
    # Error Response Codes: internalServerError (500)
63
    #                       badRequest (400)
64
    #                       unauthorised (401)
65
    try:
66
        if request.method != 'GET':
67
            raise BadRequest('Method not allowed.')
68
        x_auth_token = request.META.get('HTTP_X_AUTH_TOKEN')
69
        if not x_auth_token:
70
            return render_fault(request, BadRequest('Missing X-Auth-Token'))
71

    
72
        try:
73
            user = AstakosUser.objects.get(auth_token=x_auth_token)
74
        except AstakosUser.DoesNotExist, e:
75
            return render_fault(request, Unauthorized('Invalid X-Auth-Token'))
76

    
77
        # Check if the is active.
78
        if not user.is_active:
79
            return render_fault(request, Unauthorized('User inactive'))
80

    
81
        # Check if the token has expired.
82
        if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
83
            return render_fault(request, Unauthorized('Authentication expired'))
84

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

    
100
def get_services(request):
101
    if request.method != 'GET':
102
        raise BadRequest('Method not allowed.')
103

    
104
    callback = request.GET.get('callback', None)
105
    data = json.dumps(CLOUD_SERVICES)
106
    mimetype = 'application/json'
107

    
108
    if callback:
109
        mimetype = 'application/javascript'
110
        data = '%s(%s)' % (callback, data)
111

    
112
    return HttpResponse(content=data, mimetype=mimetype)
113

    
114
def get_menu(request):
115
    if request.method != 'GET':
116
        raise BadRequest('Method not allowed.')
117
    location = request.GET.get('location', '')
118
    absolute = lambda (url): request.build_absolute_uri(url)
119
    index_url = absolute(reverse('astakos.im.views.index'))
120
    if urlparse(location).query.rfind('next=') == -1:
121
        index_url = '%s?next=%s' % (index_url, quote(location))
122
    l = [{ 'url': index_url, 'name': "login..."}]
123
    if request.user.is_authenticated():
124
        l = []
125
        l.append({ 'url': absolute(reverse('astakos.im.views.edit_profile')),
126
                  'name': request.user.email})
127
        l.append({ 'url': absolute(reverse('astakos.im.views.edit_profile')),
128
                  'name': "view your profile..." })
129
        if request.user.password:
130
            l.append({ 'url': absolute(reverse('password_change')),
131
                      'name': "change your password..." })
132
        if INVITATIONS_ENABLED:
133
            l.append({ 'url': absolute(reverse('astakos.im.views.invite')),
134
                      'name': "invite some friends..." })
135
        l.append({ 'url': absolute(reverse('astakos.im.views.send_feedback')),
136
                  'name': "feedback..." })
137
        l.append({ 'url': absolute(reverse('astakos.im.views.logout')),
138
                  'name': "logout..."})
139

    
140
    callback = request.GET.get('callback', None)
141
    data = json.dumps(tuple(l))
142
    mimetype = 'application/json'
143

    
144
    if callback:
145
        mimetype = 'application/javascript'
146
        data = '%s(%s)' % (callback, data)
147

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