api.py 5.39 KB
Newer Older
Antony Chazapis's avatar
Antony Chazapis committed
1
# Copyright 2011-2012 GRNET S.A. All rights reserved.
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
34
35
# 
# 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.

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

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

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
44
from astakos.im.faults import BadRequest, Unauthorized, InternalServerError
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
45
from astakos.im.models import AstakosUser
46
from astakos.im.settings import CLOUD_SERVICES, INVITATIONS_ENABLED
47
48

def render_fault(request, fault):
Antony Chazapis's avatar
Antony Chazapis committed
49
    if isinstance(fault, InternalServerError) and settings.DEBUG:
50
51
52
        fault.details = format_exc(fault)
    
    request.serialization = 'text'
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
53
54
55
    data = fault.message + '\n'
    if fault.details:
        data += '\n' + fault.details
56
57
    response = HttpResponse(data, status=fault.code)
    response['Content-Length'] = len(response.content)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
58
    return response
59
60
61

def authenticate(request):
    # Normal Response Codes: 204
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
62
    # Error Response Codes: internalServerError (500)
63
64
65
66
67
68
69
70
71
72
    #                       badRequest (400)
    #                       unauthorised (401)
    try:
        if request.method != 'GET':
            raise BadRequest('Method not allowed.')
        x_auth_token = request.META.get('HTTP_X_AUTH_TOKEN')
        if not x_auth_token:
            return render_fault(request, BadRequest('Missing X-Auth-Token'))
        
        try:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
73
74
            user = AstakosUser.objects.get(auth_token=x_auth_token)
        except AstakosUser.DoesNotExist, e:
75
76
77
            return render_fault(request, Unauthorized('Invalid X-Auth-Token')) 
        
        # Check if the is active.
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
78
        if not user.is_active:
79
80
81
82
83
84
85
86
            return render_fault(request, Unauthorized('User inactive'))
        
        # Check if the token has expired.
        if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
            return render_fault(request, Unauthorized('Authentication expired'))
        
        response = HttpResponse()
        response.status=204
87
88
        user_info = {'username':user.username,
                     'uniq':user.email,
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
89
                     'auth_token':user.auth_token,
root's avatar
root committed
90
91
                     'auth_token_created':user.auth_token_created.isoformat(),
                     'auth_token_expires':user.auth_token_expires.isoformat()}
92
        response.content = json.dumps(user_info)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
93
94
        response['Content-Type'] = 'application/json; charset=UTF-8'
        response['Content-Length'] = len(response.content)
95
96
        return response
    except BaseException, e:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
97
        fault = InternalServerError('Unexpected error')
98
        return render_fault(request, fault)
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125

def get_services(request):
    if request.method != 'GET':
        raise BadRequest('Method not allowed.')
    data = json.dumps(CLOUD_SERVICES)
    return HttpResponse(content=data, mimetype="application/json")

def get_menu(request):
    if request.method != 'GET':
        raise BadRequest('Method not allowed.')
    location = request.GET.get('location', '')
    index_url = reverse('astakos.im.views.index')
    if urlparse(location).query.rfind('next=') == -1:
        index_url = '%s?next=%s' % (index_url, quote(location))
    l = [{ 'url': index_url, 'name': "login..."}]
    if request.user.is_authenticated():
        l = []
        l.append({ 'url': reverse('astakos.im.views.edit_profile'), 'name': request.user.email})
        l.append({ 'url': reverse('astakos.im.views.edit_profile'), 'name': "view your profile..." })
        if request.user.password:
            l.append({ 'url': reverse('password_change'), 'name': "change your password..." })
        if INVITATIONS_ENABLED:
            l.append({ 'url': reverse('astakos.im.views.invite'), 'name': "invite some friends..." })
        l.append({ 'url': reverse('astakos.im.views.send_feedback'), 'name': "feedback..." })
        l.append({ 'url': reverse('astakos.im.views.logout'), 'name': "logout..."})
    data = json.dumps(tuple(l))
    return HttpResponse(content=data, mimetype="application/json")