Merge changes from master branch. Fix quota updates. Clean up util. Create token...
[pithos] / pithos / im / views.py
1 # Copyright 2011 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 datetime import datetime
35 from functools import wraps
36 from math import ceil
37
38 from django.conf import settings
39 from django.http import HttpResponse, HttpResponseRedirect
40 from django.utils.http import urlencode
41 from django.shortcuts import redirect
42 from django.template.loader import render_to_string
43
44 from models import User
45 from util import isoformat
46
47
48 def render_response(template, tab=None, status=200, **kwargs):
49     if tab is None:
50         tab = template.partition('_')[0]
51     kwargs.setdefault('tab', tab)
52     html = render_to_string(template, kwargs)
53     return HttpResponse(html, status=status)
54
55
56 def requires_admin(func):
57     @wraps(func)
58     def wrapper(request, *args):
59         if not settings.BYPASS_ADMIN_AUTH:
60             if not request.user:
61                 next = urlencode({'next': request.build_absolute_uri()})
62                 login_uri = settings.LOGIN_URL + '?' + next
63                 return HttpResponseRedirect(login_uri)
64             if not request.user_obj.is_admin:
65                 return HttpResponse('Forbidden', status=403)
66         return func(request, *args)
67     return wrapper
68
69
70 def index(request):
71     stats = {}
72     stats['users'] = User.objects.count()
73     return render_response('index.html', tab='home', stats=stats)
74
75
76 @requires_admin
77 def admin(request):
78     stats = {}
79     stats['users'] = User.objects.count()
80     return render_response('admin.html', tab='home', stats=stats)
81
82
83 @requires_admin
84 def users_list(request):
85     users = User.objects.order_by('id')
86     
87     filter = request.GET.get('filter', '')
88     if filter:
89         if filter.startswith('-'):
90             users = users.exclude(uniq__icontains=filter[1:])
91         else:
92             users = users.filter(uniq__icontains=filter)
93     
94     try:
95         page = int(request.GET.get('page', 1))
96     except ValueError:
97         page = 1
98     offset = max(0, page - 1) * settings.ADMIN_PAGE_LIMIT
99     limit = offset + settings.ADMIN_PAGE_LIMIT
100     
101     npages = int(ceil(1.0 * users.count() / settings.ADMIN_PAGE_LIMIT))
102     prev = page - 1 if page > 1 else None
103     next = page + 1 if page < npages else None
104     return render_response('users_list.html',
105                             users=users[offset:limit],
106                             filter=filter,
107                             pages=range(1, npages + 1),
108                             page=page,
109                             prev=prev,
110                             next=next)
111
112
113 @requires_admin
114 def users_create(request):
115     if request.method == 'GET':
116         return render_response('users_create.html')
117     if request.method == 'POST':
118         user = User()
119         user.uniq = request.POST.get('uniq')
120         user.realname = request.POST.get('realname')
121         user.is_admin = True if request.POST.get('admin') else False
122         user.affiliation = request.POST.get('affiliation')
123         user.quota = int(request.POST.get('quota') or 0) * (1024 ** 3)  # In GiB
124         user.renew_token()
125         user.save()
126         return redirect(users_info, user.id)
127
128
129 @requires_admin
130 def users_info(request, user_id):
131     user = User.objects.get(id=user_id)
132     return render_response('users_info.html', user=user)
133
134
135 @requires_admin
136 def users_modify(request, user_id):
137     user = User.objects.get(id=user_id)
138     user.uniq = request.POST.get('uniq')
139     user.realname = request.POST.get('realname')
140     user.is_admin = True if request.POST.get('admin') else False
141     user.affiliation = request.POST.get('affiliation')
142     user.quota = int(request.POST.get('quota') or 0) * (1024 ** 3)  # In GiB
143     user.auth_token = request.POST.get('auth_token')
144     try:
145         auth_token_expires = request.POST.get('auth_token_expires')
146         d = datetime.strptime(auth_token_expires, '%Y-%m-%dT%H:%MZ')
147         user.auth_token_expires = d
148     except ValueError:
149         pass
150     user.save()
151     return redirect(users_info, user.id)
152
153
154 @requires_admin
155 def users_delete(request, user_id):
156     user = User.objects.get(id=user_id)
157     user.delete()
158     return redirect(users_list)