Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / api.py @ 0d02a287

History | View | Annotate | Download (6 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
        response.content = json.dumps(user_info)
97
        response['Content-Type'] = 'application/json; charset=UTF-8'
98
        response['Content-Length'] = len(response.content)
99
        return response
100
    except BaseException, e:
101
        logger.exception(e)
102
        fault = InternalServerError('Unexpected error')
103
        return render_fault(request, fault)
104

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

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

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

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

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

    
145
    callback = request.GET.get('callback', None)
146
    data = json.dumps(tuple(l))
147
    mimetype = 'application/json'
148

    
149
    if callback:
150
        mimetype = 'application/javascript'
151
        data = '%s(%s)' % (callback, data)
152

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