Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / views.py @ a4075f5a

History | View | Annotate | Download (50.4 kB)

1 aba1e498 Antony Chazapis
# Copyright 2011-2012 GRNET S.A. All rights reserved.
2 176023aa Kostas Papadimitriou
#
3 64cd4730 Antony Chazapis
# Redistribution and use in source and binary forms, with or
4 64cd4730 Antony Chazapis
# without modification, are permitted provided that the following
5 64cd4730 Antony Chazapis
# conditions are met:
6 176023aa Kostas Papadimitriou
#
7 64cd4730 Antony Chazapis
#   1. Redistributions of source code must retain the above
8 64cd4730 Antony Chazapis
#      copyright notice, this list of conditions and the following
9 64cd4730 Antony Chazapis
#      disclaimer.
10 176023aa Kostas Papadimitriou
#
11 64cd4730 Antony Chazapis
#   2. Redistributions in binary form must reproduce the above
12 64cd4730 Antony Chazapis
#      copyright notice, this list of conditions and the following
13 64cd4730 Antony Chazapis
#      disclaimer in the documentation and/or other materials
14 64cd4730 Antony Chazapis
#      provided with the distribution.
15 176023aa Kostas Papadimitriou
#
16 64cd4730 Antony Chazapis
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17 64cd4730 Antony Chazapis
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 64cd4730 Antony Chazapis
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 64cd4730 Antony Chazapis
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20 64cd4730 Antony Chazapis
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 64cd4730 Antony Chazapis
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 64cd4730 Antony Chazapis
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23 64cd4730 Antony Chazapis
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 64cd4730 Antony Chazapis
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 64cd4730 Antony Chazapis
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 64cd4730 Antony Chazapis
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 64cd4730 Antony Chazapis
# POSSIBILITY OF SUCH DAMAGE.
28 176023aa Kostas Papadimitriou
#
29 64cd4730 Antony Chazapis
# The views and conclusions contained in the software and
30 64cd4730 Antony Chazapis
# documentation are those of the authors and should not be
31 64cd4730 Antony Chazapis
# interpreted as representing official policies, either expressed
32 64cd4730 Antony Chazapis
# or implied, of GRNET S.A.
33 64cd4730 Antony Chazapis
34 64cd4730 Antony Chazapis
import logging
35 6e029beb Sofia Papagiannaki
import calendar
36 9a06d96f Olga Brani
import inflect
37 9a06d96f Olga Brani
38 9a06d96f Olga Brani
engine = inflect.engine()
39 64cd4730 Antony Chazapis
40 0905ccd2 Sofia Papagiannaki
from urllib import quote
41 63ecdd20 Sofia Papagiannaki
from functools import wraps
42 aab4d540 Sofia Papagiannaki
from datetime import datetime, timedelta
43 789bcaf9 Sofia Papagiannaki
from collections import defaultdict
44 64cd4730 Antony Chazapis
45 890b0eaf Sofia Papagiannaki
from django.contrib import messages
46 01ac12d5 Sofia Papagiannaki
from django.contrib.auth.decorators import login_required
47 270dd48d Sofia Papagiannaki
from django.contrib.auth.views import password_change
48 01ac12d5 Sofia Papagiannaki
from django.core.urlresolvers import reverse
49 01ac12d5 Sofia Papagiannaki
from django.db import transaction
50 d1757ca7 Sofia Papagiannaki
from django.db.models import Q
51 01ac12d5 Sofia Papagiannaki
from django.db.utils import IntegrityError
52 01ac12d5 Sofia Papagiannaki
from django.forms.fields import URLField
53 9a06d96f Olga Brani
from django.http import (HttpResponse, HttpResponseBadRequest,
54 9a06d96f Olga Brani
                         HttpResponseForbidden, HttpResponseRedirect,
55 9a06d96f Olga Brani
                         HttpResponseBadRequest, Http404)
56 01ac12d5 Sofia Papagiannaki
from django.shortcuts import redirect
57 661c4479 Sofia Papagiannaki
from django.template import RequestContext, loader as template_loader
58 01ac12d5 Sofia Papagiannaki
from django.utils.http import urlencode
59 01ac12d5 Sofia Papagiannaki
from django.utils.translation import ugettext as _
60 aab4d540 Sofia Papagiannaki
from django.views.generic.create_update import (create_object, delete_object,
61 de4ed385 Sofia Papagiannaki
                                                get_model_and_form_class)
62 aab4d540 Sofia Papagiannaki
from django.views.generic.list_detail import object_list, object_detail
63 51c57c9c Sofia Papagiannaki
from django.http import HttpResponseBadRequest
64 661c4479 Sofia Papagiannaki
from django.core.xheaders import populate_xheaders
65 64cd4730 Antony Chazapis
66 9a06d96f Olga Brani
from astakos.im.models import (AstakosUser, ApprovalTerms, AstakosGroup,
67 9a06d96f Olga Brani
                               Resource, EmailChange, GroupKind, Membership,
68 9a06d96f Olga Brani
                               AstakosGroupQuota, RESOURCE_SEPARATOR)
69 9a06d96f Olga Brani
from django.views.decorators.http import require_http_methods
70 f2a4ce70 Sofia Papagiannaki
from django.db.models.query import QuerySet
71 9a06d96f Olga Brani
72 4e30244e Sofia Papagiannaki
from astakos.im.activation_backends import get_backend, SimpleBackend
73 1662ac2d Sofia Papagiannaki
from astakos.im.util import get_context, prepare_response, set_cookie, get_query
74 51c57c9c Sofia Papagiannaki
from astakos.im.forms import (LoginForm, InvitationForm, ProfileForm,
75 51c57c9c Sofia Papagiannaki
                              FeedbackForm, SignApprovalTermsForm,
76 51c57c9c Sofia Papagiannaki
                              ExtendedPasswordChangeForm, EmailChangeForm,
77 51c57c9c Sofia Papagiannaki
                              AstakosGroupCreationForm, AstakosGroupSearchForm,
78 789bcaf9 Sofia Papagiannaki
                              AstakosGroupUpdateForm, AddGroupMembersForm,
79 3bb604eb Sofia Papagiannaki
                              AstakosGroupSortForm, MembersSortForm,
80 29b87e7c Sofia Papagiannaki
                              TimelineForm, PickResourceForm,
81 29b87e7c Sofia Papagiannaki
                              AstakosGroupCreationSummaryForm)
82 aab4d540 Sofia Papagiannaki
from astakos.im.functions import (send_feedback, SendMailError,
83 9a06d96f Olga Brani
                                  logout as auth_logout,
84 51c57c9c Sofia Papagiannaki
                                  activate as activate_func,
85 51c57c9c Sofia Papagiannaki
                                  switch_account_to_shibboleth,
86 9a06d96f Olga Brani
                                  send_group_creation_notification,
87 51c57c9c Sofia Papagiannaki
                                  SendNotificationError)
88 b6852727 Olga Brani
from astakos.im.endpoints.qh import timeline_charge
89 9a06d96f Olga Brani
from astakos.im.settings import (COOKIE_NAME, COOKIE_DOMAIN, LOGOUT_NEXT,
90 3cbd5e47 Olga Brani
                                 LOGGING_LEVEL, PAGINATE_BY, RESOURCES_PRESENTATION_DATA)
91 6e029beb Sofia Papagiannaki
from astakos.im.tasks import request_billing
92 820b18e0 Sofia Papagiannaki
from astakos.im.api.callpoint import AstakosCallpoint
93 64cd4730 Antony Chazapis
94 ae497612 Olga Brani
import astakos.im.messages as astakos_messages
95 ae497612 Olga Brani
96 e015e9e6 Sofia Papagiannaki
logger = logging.getLogger(__name__)
97 e015e9e6 Sofia Papagiannaki
98 5ce3ce4f Sofia Papagiannaki
99 789bcaf9 Sofia Papagiannaki
DB_REPLACE_GROUP_SCHEME = """REPLACE(REPLACE("auth_group".name, 'http://', ''),
100 789bcaf9 Sofia Papagiannaki
                                     'https://', '')"""
101 789bcaf9 Sofia Papagiannaki
102 820b18e0 Sofia Papagiannaki
callpoint = AstakosCallpoint()
103 9a06d96f Olga Brani
104 51c57c9c Sofia Papagiannaki
def render_response(template, tab=None, status=200, reset_cookie=False,
105 51c57c9c Sofia Papagiannaki
                    context_instance=None, **kwargs):
106 890b0eaf Sofia Papagiannaki
    """
107 890b0eaf Sofia Papagiannaki
    Calls ``django.template.loader.render_to_string`` with an additional ``tab``
108 890b0eaf Sofia Papagiannaki
    keyword argument and returns an ``django.http.HttpResponse`` with the
109 890b0eaf Sofia Papagiannaki
    specified ``status``.
110 890b0eaf Sofia Papagiannaki
    """
111 64cd4730 Antony Chazapis
    if tab is None:
112 881c856c Sofia Papagiannaki
        tab = template.partition('_')[0].partition('.html')[0]
113 64cd4730 Antony Chazapis
    kwargs.setdefault('tab', tab)
114 661c4479 Sofia Papagiannaki
    html = template_loader.render_to_string(
115 5ce3ce4f Sofia Papagiannaki
        template, kwargs, context_instance=context_instance)
116 c301698f Sofia Papagiannaki
    response = HttpResponse(html, status=status)
117 c301698f Sofia Papagiannaki
    if reset_cookie:
118 c301698f Sofia Papagiannaki
        set_cookie(response, context_instance['request'].user)
119 c301698f Sofia Papagiannaki
    return response
120 64cd4730 Antony Chazapis
121 63ecdd20 Sofia Papagiannaki
122 63ecdd20 Sofia Papagiannaki
def requires_anonymous(func):
123 63ecdd20 Sofia Papagiannaki
    """
124 270dd48d Sofia Papagiannaki
    Decorator checkes whether the request.user is not Anonymous and in that case
125 7482228b Sofia Papagiannaki
    redirects to `logout`.
126 63ecdd20 Sofia Papagiannaki
    """
127 63ecdd20 Sofia Papagiannaki
    @wraps(func)
128 63ecdd20 Sofia Papagiannaki
    def wrapper(request, *args):
129 63ecdd20 Sofia Papagiannaki
        if not request.user.is_anonymous():
130 63ecdd20 Sofia Papagiannaki
            next = urlencode({'next': request.build_absolute_uri()})
131 270dd48d Sofia Papagiannaki
            logout_uri = reverse(logout) + '?' + next
132 270dd48d Sofia Papagiannaki
            return HttpResponseRedirect(logout_uri)
133 63ecdd20 Sofia Papagiannaki
        return func(request, *args)
134 63ecdd20 Sofia Papagiannaki
    return wrapper
135 63ecdd20 Sofia Papagiannaki
136 5ce3ce4f Sofia Papagiannaki
137 270dd48d Sofia Papagiannaki
def signed_terms_required(func):
138 270dd48d Sofia Papagiannaki
    """
139 270dd48d Sofia Papagiannaki
    Decorator checkes whether the request.user is Anonymous and in that case
140 270dd48d Sofia Papagiannaki
    redirects to `logout`.
141 270dd48d Sofia Papagiannaki
    """
142 270dd48d Sofia Papagiannaki
    @wraps(func)
143 270dd48d Sofia Papagiannaki
    def wrapper(request, *args, **kwargs):
144 fcf90160 Sofia Papagiannaki
        if request.user.is_authenticated() and not request.user.signed_terms:
145 270dd48d Sofia Papagiannaki
            params = urlencode({'next': request.build_absolute_uri(),
146 5ce3ce4f Sofia Papagiannaki
                                'show_form': ''})
147 270dd48d Sofia Papagiannaki
            terms_uri = reverse('latest_terms') + '?' + params
148 270dd48d Sofia Papagiannaki
            return HttpResponseRedirect(terms_uri)
149 270dd48d Sofia Papagiannaki
        return func(request, *args, **kwargs)
150 270dd48d Sofia Papagiannaki
    return wrapper
151 270dd48d Sofia Papagiannaki
152 5ce3ce4f Sofia Papagiannaki
153 9a06d96f Olga Brani
@require_http_methods(["GET", "POST"])
154 270dd48d Sofia Papagiannaki
@signed_terms_required
155 aab4d540 Sofia Papagiannaki
def index(request, login_template_name='im/login.html', extra_context=None):
156 890b0eaf Sofia Papagiannaki
    """
157 dcf55476 Sofia Papagiannaki
    If there is logged on user renders the profile page otherwise renders login page.
158 176023aa Kostas Papadimitriou

159 890b0eaf Sofia Papagiannaki
    **Arguments**
160 176023aa Kostas Papadimitriou

161 dcf55476 Sofia Papagiannaki
    ``login_template_name``
162 dcf55476 Sofia Papagiannaki
        A custom login template to use. This is optional; if not specified,
163 1e685275 Sofia Papagiannaki
        this will default to ``im/login.html``.
164 176023aa Kostas Papadimitriou

165 dcf55476 Sofia Papagiannaki
    ``profile_template_name``
166 dcf55476 Sofia Papagiannaki
        A custom profile template to use. This is optional; if not specified,
167 1e685275 Sofia Papagiannaki
        this will default to ``im/profile.html``.
168 176023aa Kostas Papadimitriou

169 890b0eaf Sofia Papagiannaki
    ``extra_context``
170 890b0eaf Sofia Papagiannaki
        An dictionary of variables to add to the template context.
171 176023aa Kostas Papadimitriou

172 890b0eaf Sofia Papagiannaki
    **Template:**
173 176023aa Kostas Papadimitriou

174 1e685275 Sofia Papagiannaki
    im/profile.html or im/login.html or ``template_name`` keyword argument.
175 176023aa Kostas Papadimitriou

176 890b0eaf Sofia Papagiannaki
    """
177 dcf55476 Sofia Papagiannaki
    template_name = login_template_name
178 dcf55476 Sofia Papagiannaki
    if request.user.is_authenticated():
179 6ff7a7ca Sofia Papagiannaki
        return HttpResponseRedirect(reverse('edit_profile'))
180 0905ccd2 Sofia Papagiannaki
    return render_response(template_name,
181 5ce3ce4f Sofia Papagiannaki
                           login_form=LoginForm(request=request),
182 5ce3ce4f Sofia Papagiannaki
                           context_instance=get_context(request, extra_context))
183 5ce3ce4f Sofia Papagiannaki
184 64cd4730 Antony Chazapis
185 9a06d96f Olga Brani
@require_http_methods(["GET", "POST"])
186 890b0eaf Sofia Papagiannaki
@login_required
187 270dd48d Sofia Papagiannaki
@signed_terms_required
188 890b0eaf Sofia Papagiannaki
@transaction.commit_manually
189 aab4d540 Sofia Papagiannaki
def invite(request, template_name='im/invitations.html', extra_context=None):
190 890b0eaf Sofia Papagiannaki
    """
191 890b0eaf Sofia Papagiannaki
    Allows a user to invite somebody else.
192 176023aa Kostas Papadimitriou

193 890b0eaf Sofia Papagiannaki
    In case of GET request renders a form for providing the invitee information.
194 890b0eaf Sofia Papagiannaki
    In case of POST checks whether the user has not run out of invitations and then
195 890b0eaf Sofia Papagiannaki
    sends an invitation email to singup to the service.
196 176023aa Kostas Papadimitriou

197 890b0eaf Sofia Papagiannaki
    The view uses commit_manually decorator in order to ensure the number of the
198 890b0eaf Sofia Papagiannaki
    user invitations is going to be updated only if the email has been successfully sent.
199 176023aa Kostas Papadimitriou

200 2cbaacd5 Sofia Papagiannaki
    If the user isn't logged in, redirects to settings.LOGIN_URL.
201 176023aa Kostas Papadimitriou

202 890b0eaf Sofia Papagiannaki
    **Arguments**
203 176023aa Kostas Papadimitriou

204 890b0eaf Sofia Papagiannaki
    ``template_name``
205 890b0eaf Sofia Papagiannaki
        A custom template to use. This is optional; if not specified,
206 1e685275 Sofia Papagiannaki
        this will default to ``im/invitations.html``.
207 176023aa Kostas Papadimitriou

208 890b0eaf Sofia Papagiannaki
    ``extra_context``
209 890b0eaf Sofia Papagiannaki
        An dictionary of variables to add to the template context.
210 176023aa Kostas Papadimitriou

211 890b0eaf Sofia Papagiannaki
    **Template:**
212 176023aa Kostas Papadimitriou

213 1e685275 Sofia Papagiannaki
    im/invitations.html or ``template_name`` keyword argument.
214 176023aa Kostas Papadimitriou

215 890b0eaf Sofia Papagiannaki
    **Settings:**
216 176023aa Kostas Papadimitriou

217 890b0eaf Sofia Papagiannaki
    The view expectes the following settings are defined:
218 176023aa Kostas Papadimitriou

219 890b0eaf Sofia Papagiannaki
    * LOGIN_URL: login uri
220 2cbaacd5 Sofia Papagiannaki
    * ASTAKOS_DEFAULT_CONTACT_EMAIL: service support email
221 890b0eaf Sofia Papagiannaki
    """
222 64cd4730 Antony Chazapis
    status = None
223 64cd4730 Antony Chazapis
    message = None
224 8f5a3a06 Sofia Papagiannaki
    form = InvitationForm()
225 5ce3ce4f Sofia Papagiannaki
226 18ffbee1 Sofia Papagiannaki
    inviter = request.user
227 64cd4730 Antony Chazapis
    if request.method == 'POST':
228 8f5a3a06 Sofia Papagiannaki
        form = InvitationForm(request.POST)
229 64cd4730 Antony Chazapis
        if inviter.invitations > 0:
230 8f5a3a06 Sofia Papagiannaki
            if form.is_valid():
231 8f5a3a06 Sofia Papagiannaki
                try:
232 9a06d96f Olga Brani
                    email = form.cleaned_data.get('username')
233 9a06d96f Olga Brani
                    realname = form.cleaned_data.get('realname')
234 9a06d96f Olga Brani
                    inviter.invite(email, realname)
235 ae497612 Olga Brani
                    message = _(astakos_messages.INVITATION_SENT) % locals()
236 24406ae3 Sofia Papagiannaki
                    messages.success(request, message)
237 8f5a3a06 Sofia Papagiannaki
                except SendMailError, e:
238 8f5a3a06 Sofia Papagiannaki
                    message = e.message
239 24406ae3 Sofia Papagiannaki
                    messages.error(request, message)
240 8f5a3a06 Sofia Papagiannaki
                    transaction.rollback()
241 18ffbee1 Sofia Papagiannaki
                except BaseException, e:
242 ae497612 Olga Brani
                    message = _(astakos_messages.GENERIC_ERROR)
243 24406ae3 Sofia Papagiannaki
                    messages.error(request, message)
244 18ffbee1 Sofia Papagiannaki
                    logger.exception(e)
245 18ffbee1 Sofia Papagiannaki
                    transaction.rollback()
246 18ffbee1 Sofia Papagiannaki
                else:
247 18ffbee1 Sofia Papagiannaki
                    transaction.commit()
248 64cd4730 Antony Chazapis
        else:
249 ae497612 Olga Brani
            message = _(astakos_messages.MAX_INVITATION_NUMBER_REACHED)
250 24406ae3 Sofia Papagiannaki
            messages.error(request, message)
251 176023aa Kostas Papadimitriou
252 a196eb7e Sofia Papagiannaki
    sent = [{'email': inv.username,
253 d6ae71a2 root
             'realname': inv.realname,
254 d6ae71a2 root
             'is_consumed': inv.is_consumed}
255 5ce3ce4f Sofia Papagiannaki
            for inv in request.user.invitations_sent.all()]
256 77e2ad52 root
    kwargs = {'inviter': inviter,
257 5ce3ce4f Sofia Papagiannaki
              'sent': sent}
258 0905ccd2 Sofia Papagiannaki
    context = get_context(request, extra_context, **kwargs)
259 0905ccd2 Sofia Papagiannaki
    return render_response(template_name,
260 5ce3ce4f Sofia Papagiannaki
                           invitation_form=form,
261 5ce3ce4f Sofia Papagiannaki
                           context_instance=context)
262 5ce3ce4f Sofia Papagiannaki
263 64cd4730 Antony Chazapis
264 9a06d96f Olga Brani
@require_http_methods(["GET", "POST"])
265 890b0eaf Sofia Papagiannaki
@login_required
266 270dd48d Sofia Papagiannaki
@signed_terms_required
267 aab4d540 Sofia Papagiannaki
def edit_profile(request, template_name='im/profile.html', extra_context=None):
268 890b0eaf Sofia Papagiannaki
    """
269 890b0eaf Sofia Papagiannaki
    Allows a user to edit his/her profile.
270 176023aa Kostas Papadimitriou

271 890b0eaf Sofia Papagiannaki
    In case of GET request renders a form for displaying the user information.
272 ce86cd44 Sofia Papagiannaki
    In case of POST updates the user informantion and redirects to ``next``
273 ce86cd44 Sofia Papagiannaki
    url parameter if exists.
274 176023aa Kostas Papadimitriou

275 2cbaacd5 Sofia Papagiannaki
    If the user isn't logged in, redirects to settings.LOGIN_URL.
276 176023aa Kostas Papadimitriou

277 890b0eaf Sofia Papagiannaki
    **Arguments**
278 176023aa Kostas Papadimitriou

279 890b0eaf Sofia Papagiannaki
    ``template_name``
280 890b0eaf Sofia Papagiannaki
        A custom template to use. This is optional; if not specified,
281 1e685275 Sofia Papagiannaki
        this will default to ``im/profile.html``.
282 176023aa Kostas Papadimitriou

283 890b0eaf Sofia Papagiannaki
    ``extra_context``
284 890b0eaf Sofia Papagiannaki
        An dictionary of variables to add to the template context.
285 176023aa Kostas Papadimitriou

286 890b0eaf Sofia Papagiannaki
    **Template:**
287 176023aa Kostas Papadimitriou

288 1e685275 Sofia Papagiannaki
    im/profile.html or ``template_name`` keyword argument.
289 176023aa Kostas Papadimitriou

290 92defad4 Sofia Papagiannaki
    **Settings:**
291 176023aa Kostas Papadimitriou

292 92defad4 Sofia Papagiannaki
    The view expectes the following settings are defined:
293 176023aa Kostas Papadimitriou

294 92defad4 Sofia Papagiannaki
    * LOGIN_URL: login uri
295 890b0eaf Sofia Papagiannaki
    """
296 aab4d540 Sofia Papagiannaki
    extra_context = extra_context or {}
297 15efc749 Sofia Papagiannaki
    form = ProfileForm(instance=request.user)
298 15efc749 Sofia Papagiannaki
    extra_context['next'] = request.GET.get('next')
299 c301698f Sofia Papagiannaki
    reset_cookie = False
300 64cd4730 Antony Chazapis
    if request.method == 'POST':
301 15efc749 Sofia Papagiannaki
        form = ProfileForm(request.POST, instance=request.user)
302 890b0eaf Sofia Papagiannaki
        if form.is_valid():
303 64cd4730 Antony Chazapis
            try:
304 c301698f Sofia Papagiannaki
                prev_token = request.user.auth_token
305 c301698f Sofia Papagiannaki
                user = form.save()
306 c301698f Sofia Papagiannaki
                reset_cookie = user.auth_token != prev_token
307 c301698f Sofia Papagiannaki
                form = ProfileForm(instance=user)
308 1a3675a0 Sofia Papagiannaki
                next = request.POST.get('next')
309 1a3675a0 Sofia Papagiannaki
                if next:
310 1a3675a0 Sofia Papagiannaki
                    return redirect(next)
311 ae497612 Olga Brani
                msg = _(astakos_messages.PROFILE_UPDATED)
312 24406ae3 Sofia Papagiannaki
                messages.success(request, msg)
313 890b0eaf Sofia Papagiannaki
            except ValueError, ve:
314 24406ae3 Sofia Papagiannaki
                messages.success(request, ve)
315 23447441 Sofia Papagiannaki
    elif request.method == "GET":
316 fff4343a Sofia Papagiannaki
        if not request.user.is_verified:
317 fff4343a Sofia Papagiannaki
            request.user.is_verified = True
318 fff4343a Sofia Papagiannaki
            request.user.save()
319 0905ccd2 Sofia Papagiannaki
    return render_response(template_name,
320 5ce3ce4f Sofia Papagiannaki
                           reset_cookie=reset_cookie,
321 5ce3ce4f Sofia Papagiannaki
                           profile_form=form,
322 5ce3ce4f Sofia Papagiannaki
                           context_instance=get_context(request,
323 5ce3ce4f Sofia Papagiannaki
                                                        extra_context))
324 5ce3ce4f Sofia Papagiannaki
325 64cd4730 Antony Chazapis
326 10ed0073 Sofia Papagiannaki
@transaction.commit_manually
327 9a06d96f Olga Brani
@require_http_methods(["GET", "POST"])
328 aab4d540 Sofia Papagiannaki
def signup(request, template_name='im/signup.html', on_success='im/signup_complete.html', extra_context=None, backend=None):
329 890b0eaf Sofia Papagiannaki
    """
330 890b0eaf Sofia Papagiannaki
    Allows a user to create a local account.
331 176023aa Kostas Papadimitriou

332 b669d9c0 Sofia Papagiannaki
    In case of GET request renders a form for entering the user information.
333 890b0eaf Sofia Papagiannaki
    In case of POST handles the signup.
334 176023aa Kostas Papadimitriou

335 890b0eaf Sofia Papagiannaki
    The user activation will be delegated to the backend specified by the ``backend`` keyword argument
336 8f5a3a06 Sofia Papagiannaki
    if present, otherwise to the ``astakos.im.activation_backends.InvitationBackend``
337 8f5a3a06 Sofia Papagiannaki
    if settings.ASTAKOS_INVITATIONS_ENABLED is True or ``astakos.im.activation_backends.SimpleBackend`` if not
338 8f5a3a06 Sofia Papagiannaki
    (see activation_backends);
339 5ce3ce4f Sofia Papagiannaki

340 b669d9c0 Sofia Papagiannaki
    Upon successful user creation, if ``next`` url parameter is present the user is redirected there
341 890b0eaf Sofia Papagiannaki
    otherwise renders the same page with a success message.
342 5ce3ce4f Sofia Papagiannaki

343 8f5a3a06 Sofia Papagiannaki
    On unsuccessful creation, renders ``template_name`` with an error message.
344 5ce3ce4f Sofia Papagiannaki

345 890b0eaf Sofia Papagiannaki
    **Arguments**
346 5ce3ce4f Sofia Papagiannaki

347 8f5a3a06 Sofia Papagiannaki
    ``template_name``
348 8f5a3a06 Sofia Papagiannaki
        A custom template to render. This is optional;
349 1e685275 Sofia Papagiannaki
        if not specified, this will default to ``im/signup.html``.
350 176023aa Kostas Papadimitriou

351 f7e8a159 Sofia Papagiannaki
    ``on_success``
352 f7e8a159 Sofia Papagiannaki
        A custom template to render in case of success. This is optional;
353 1e685275 Sofia Papagiannaki
        if not specified, this will default to ``im/signup_complete.html``.
354 176023aa Kostas Papadimitriou

355 890b0eaf Sofia Papagiannaki
    ``extra_context``
356 890b0eaf Sofia Papagiannaki
        An dictionary of variables to add to the template context.
357 176023aa Kostas Papadimitriou

358 890b0eaf Sofia Papagiannaki
    **Template:**
359 5ce3ce4f Sofia Papagiannaki

360 8f5a3a06 Sofia Papagiannaki
    im/signup.html or ``template_name`` keyword argument.
361 5ce3ce4f Sofia Papagiannaki
    im/signup_complete.html or ``on_success`` keyword argument.
362 890b0eaf Sofia Papagiannaki
    """
363 0d02a287 Sofia Papagiannaki
    if request.user.is_authenticated():
364 6ff7a7ca Sofia Papagiannaki
        return HttpResponseRedirect(reverse('edit_profile'))
365 5ce3ce4f Sofia Papagiannaki
366 0a569195 Sofia Papagiannaki
    provider = get_query(request).get('provider', 'local')
367 890b0eaf Sofia Papagiannaki
    try:
368 18ffbee1 Sofia Papagiannaki
        if not backend:
369 18ffbee1 Sofia Papagiannaki
            backend = get_backend(request)
370 8f5a3a06 Sofia Papagiannaki
        form = backend.get_signup_form(provider)
371 0a569195 Sofia Papagiannaki
    except Exception, e:
372 4e30244e Sofia Papagiannaki
        form = SimpleBackend(request).get_signup_form(provider)
373 24406ae3 Sofia Papagiannaki
        messages.error(request, e)
374 8f5a3a06 Sofia Papagiannaki
    if request.method == 'POST':
375 8f5a3a06 Sofia Papagiannaki
        if form.is_valid():
376 18ffbee1 Sofia Papagiannaki
            user = form.save(commit=False)
377 8f5a3a06 Sofia Papagiannaki
            try:
378 8f5a3a06 Sofia Papagiannaki
                result = backend.handle_activation(user)
379 8f5a3a06 Sofia Papagiannaki
                status = messages.SUCCESS
380 18ffbee1 Sofia Papagiannaki
                message = result.message
381 18ffbee1 Sofia Papagiannaki
                user.save()
382 ca828a10 Sofia Papagiannaki
                if 'additional_email' in form.cleaned_data:
383 ca828a10 Sofia Papagiannaki
                    additional_email = form.cleaned_data['additional_email']
384 ca828a10 Sofia Papagiannaki
                    if additional_email != user.email:
385 ca828a10 Sofia Papagiannaki
                        user.additionalmail_set.create(email=additional_email)
386 5ce3ce4f Sofia Papagiannaki
                        msg = 'Additional email: %s saved for user %s.' % (
387 5ce3ce4f Sofia Papagiannaki
                            additional_email, user.email)
388 aab4d540 Sofia Papagiannaki
                        logger.log(LOGGING_LEVEL, msg)
389 8f5a3a06 Sofia Papagiannaki
                if user and user.is_active:
390 8f5a3a06 Sofia Papagiannaki
                    next = request.POST.get('next', '')
391 40a0cd8b Sofia Papagiannaki
                    response = prepare_response(request, user, next=next)
392 c3f6cdf1 root
                    transaction.commit()
393 40a0cd8b Sofia Papagiannaki
                    return response
394 8f5a3a06 Sofia Papagiannaki
                messages.add_message(request, status, message)
395 c3f6cdf1 root
                transaction.commit()
396 8f5a3a06 Sofia Papagiannaki
                return render_response(on_success,
397 8f5a3a06 Sofia Papagiannaki
                                       context_instance=get_context(request, extra_context))
398 18ffbee1 Sofia Papagiannaki
            except SendMailError, e:
399 18ffbee1 Sofia Papagiannaki
                message = e.message
400 24406ae3 Sofia Papagiannaki
                messages.error(request, message)
401 10ed0073 Sofia Papagiannaki
                transaction.rollback()
402 18ffbee1 Sofia Papagiannaki
            except BaseException, e:
403 ae497612 Olga Brani
                message = _(astakos_messages.GENERIC_ERROR)
404 24406ae3 Sofia Papagiannaki
                messages.error(request, message)
405 0a569195 Sofia Papagiannaki
                logger.exception(e)
406 10ed0073 Sofia Papagiannaki
                transaction.rollback()
407 8f5a3a06 Sofia Papagiannaki
    return render_response(template_name,
408 5ce3ce4f Sofia Papagiannaki
                           signup_form=form,
409 5ce3ce4f Sofia Papagiannaki
                           provider=provider,
410 890b0eaf Sofia Papagiannaki
                           context_instance=get_context(request, extra_context))
411 64cd4730 Antony Chazapis
412 5ce3ce4f Sofia Papagiannaki
413 9a06d96f Olga Brani
@require_http_methods(["GET", "POST"])
414 890b0eaf Sofia Papagiannaki
@login_required
415 270dd48d Sofia Papagiannaki
@signed_terms_required
416 aab4d540 Sofia Papagiannaki
def feedback(request, template_name='im/feedback.html', email_template_name='im/feedback_mail.txt', extra_context=None):
417 890b0eaf Sofia Papagiannaki
    """
418 890b0eaf Sofia Papagiannaki
    Allows a user to send feedback.
419 176023aa Kostas Papadimitriou

420 890b0eaf Sofia Papagiannaki
    In case of GET request renders a form for providing the feedback information.
421 890b0eaf Sofia Papagiannaki
    In case of POST sends an email to support team.
422 176023aa Kostas Papadimitriou

423 2cbaacd5 Sofia Papagiannaki
    If the user isn't logged in, redirects to settings.LOGIN_URL.
424 176023aa Kostas Papadimitriou

425 890b0eaf Sofia Papagiannaki
    **Arguments**
426 176023aa Kostas Papadimitriou

427 890b0eaf Sofia Papagiannaki
    ``template_name``
428 890b0eaf Sofia Papagiannaki
        A custom template to use. This is optional; if not specified,
429 1e685275 Sofia Papagiannaki
        this will default to ``im/feedback.html``.
430 176023aa Kostas Papadimitriou

431 890b0eaf Sofia Papagiannaki
    ``extra_context``
432 890b0eaf Sofia Papagiannaki
        An dictionary of variables to add to the template context.
433 176023aa Kostas Papadimitriou

434 890b0eaf Sofia Papagiannaki
    **Template:**
435 176023aa Kostas Papadimitriou

436 1e685275 Sofia Papagiannaki
    im/signup.html or ``template_name`` keyword argument.
437 176023aa Kostas Papadimitriou

438 890b0eaf Sofia Papagiannaki
    **Settings:**
439 176023aa Kostas Papadimitriou

440 92defad4 Sofia Papagiannaki
    * LOGIN_URL: login uri
441 2cbaacd5 Sofia Papagiannaki
    * ASTAKOS_DEFAULT_CONTACT_EMAIL: List of feedback recipients
442 890b0eaf Sofia Papagiannaki
    """
443 64cd4730 Antony Chazapis
    if request.method == 'GET':
444 890b0eaf Sofia Papagiannaki
        form = FeedbackForm()
445 890b0eaf Sofia Papagiannaki
    if request.method == 'POST':
446 890b0eaf Sofia Papagiannaki
        if not request.user:
447 890b0eaf Sofia Papagiannaki
            return HttpResponse('Unauthorized', status=401)
448 176023aa Kostas Papadimitriou
449 890b0eaf Sofia Papagiannaki
        form = FeedbackForm(request.POST)
450 890b0eaf Sofia Papagiannaki
        if form.is_valid():
451 e9083112 Sofia Papagiannaki
            msg = form.cleaned_data['feedback_msg']
452 8f5a3a06 Sofia Papagiannaki
            data = form.cleaned_data['feedback_data']
453 538ccdd5 Sofia Papagiannaki
            try:
454 8f5a3a06 Sofia Papagiannaki
                send_feedback(msg, data, request.user, email_template_name)
455 8f5a3a06 Sofia Papagiannaki
            except SendMailError, e:
456 24406ae3 Sofia Papagiannaki
                messages.error(request, message)
457 8f5a3a06 Sofia Papagiannaki
            else:
458 ae497612 Olga Brani
                message = _(astakos_messages.FEEDBACK_SENT)
459 aab4d540 Sofia Papagiannaki
                messages.success(request, message)
460 890b0eaf Sofia Papagiannaki
    return render_response(template_name,
461 5ce3ce4f Sofia Papagiannaki
                           feedback_form=form,
462 5ce3ce4f Sofia Papagiannaki
                           context_instance=get_context(request, extra_context))
463 5ce3ce4f Sofia Papagiannaki
464 15efc749 Sofia Papagiannaki
465 9a06d96f Olga Brani
@require_http_methods(["GET", "POST"])
466 8e45d6fd Sofia Papagiannaki
@signed_terms_required
467 aab4d540 Sofia Papagiannaki
def logout(request, template='registration/logged_out.html', extra_context=None):
468 63ecdd20 Sofia Papagiannaki
    """
469 7482228b Sofia Papagiannaki
    Wraps `django.contrib.auth.logout` and delete the cookie.
470 63ecdd20 Sofia Papagiannaki
    """
471 7482228b Sofia Papagiannaki
    response = HttpResponse()
472 8e45d6fd Sofia Papagiannaki
    if request.user.is_authenticated():
473 8e45d6fd Sofia Papagiannaki
        email = request.user.email
474 8e45d6fd Sofia Papagiannaki
        auth_logout(request)
475 8e45d6fd Sofia Papagiannaki
        response.delete_cookie(COOKIE_NAME, path='/', domain=COOKIE_DOMAIN)
476 8e45d6fd Sofia Papagiannaki
        msg = 'Cookie deleted for %s' % email
477 aab4d540 Sofia Papagiannaki
        logger.log(LOGGING_LEVEL, msg)
478 63ecdd20 Sofia Papagiannaki
    next = request.GET.get('next')
479 63ecdd20 Sofia Papagiannaki
    if next:
480 63ecdd20 Sofia Papagiannaki
        response['Location'] = next
481 63ecdd20 Sofia Papagiannaki
        response.status_code = 302
482 63ecdd20 Sofia Papagiannaki
        return response
483 0d02a287 Sofia Papagiannaki
    elif LOGOUT_NEXT:
484 0d02a287 Sofia Papagiannaki
        response['Location'] = LOGOUT_NEXT
485 0d02a287 Sofia Papagiannaki
        response.status_code = 301
486 0d02a287 Sofia Papagiannaki
        return response
487 ae497612 Olga Brani
    messages.success(request, _(astakos_messages.LOGOUT_SUCCESS))
488 49df775e Sofia Papagiannaki
    context = get_context(request, extra_context)
489 9a06d96f Olga Brani
    response.write(
490 9a06d96f Olga Brani
        template_loader.render_to_string(template, context_instance=context))
491 49df775e Sofia Papagiannaki
    return response
492 2126d85d Sofia Papagiannaki
493 5ce3ce4f Sofia Papagiannaki
494 9a06d96f Olga Brani
@require_http_methods(["GET", "POST"])
495 683cf244 Sofia Papagiannaki
@transaction.commit_manually
496 3bb604eb Sofia Papagiannaki
def activate(request, greeting_email_template_name='im/welcome_email.txt',
497 3bb604eb Sofia Papagiannaki
             helpdesk_email_template_name='im/helpdesk_notification.txt'):
498 2126d85d Sofia Papagiannaki
    """
499 683cf244 Sofia Papagiannaki
    Activates the user identified by the ``auth`` request parameter, sends a welcome email
500 683cf244 Sofia Papagiannaki
    and renews the user token.
501 176023aa Kostas Papadimitriou

502 683cf244 Sofia Papagiannaki
    The view uses commit_manually decorator in order to ensure the user state will be updated
503 683cf244 Sofia Papagiannaki
    only if the email will be send successfully.
504 2126d85d Sofia Papagiannaki
    """
505 2126d85d Sofia Papagiannaki
    token = request.GET.get('auth')
506 2126d85d Sofia Papagiannaki
    next = request.GET.get('next')
507 2126d85d Sofia Papagiannaki
    try:
508 2126d85d Sofia Papagiannaki
        user = AstakosUser.objects.get(auth_token=token)
509 2126d85d Sofia Papagiannaki
    except AstakosUser.DoesNotExist:
510 ae497612 Olga Brani
        return HttpResponseBadRequest(_(astakos_messages.ACCOUNT_UNKNOWN))
511 5ce3ce4f Sofia Papagiannaki
512 d1757ca7 Sofia Papagiannaki
    if user.is_active:
513 ae497612 Olga Brani
        message = _(astakos_messages.ACCOUNT_ALREADY_ACTIVE)
514 24406ae3 Sofia Papagiannaki
        messages.error(request, message)
515 23b9b72f Sofia Papagiannaki
        return index(request)
516 5ce3ce4f Sofia Papagiannaki
517 0a569195 Sofia Papagiannaki
    try:
518 3abf6c78 Sofia Papagiannaki
        local_user = AstakosUser.objects.get(
519 5ce3ce4f Sofia Papagiannaki
            ~Q(id=user.id),
520 3abf6c78 Sofia Papagiannaki
            email=user.email,
521 3abf6c78 Sofia Papagiannaki
            is_active=True
522 3abf6c78 Sofia Papagiannaki
        )
523 0a569195 Sofia Papagiannaki
    except AstakosUser.DoesNotExist:
524 27e26a41 Sofia Papagiannaki
        try:
525 3abf6c78 Sofia Papagiannaki
            activate_func(
526 3abf6c78 Sofia Papagiannaki
                user,
527 3abf6c78 Sofia Papagiannaki
                greeting_email_template_name,
528 3abf6c78 Sofia Papagiannaki
                helpdesk_email_template_name,
529 3abf6c78 Sofia Papagiannaki
                verify_email=True
530 3abf6c78 Sofia Papagiannaki
            )
531 23b9b72f Sofia Papagiannaki
            response = prepare_response(request, user, next, renew=True)
532 23b9b72f Sofia Papagiannaki
            transaction.commit()
533 23b9b72f Sofia Papagiannaki
            return response
534 23b9b72f Sofia Papagiannaki
        except SendMailError, e:
535 23b9b72f Sofia Papagiannaki
            message = e.message
536 24406ae3 Sofia Papagiannaki
            messages.error(request, message)
537 23b9b72f Sofia Papagiannaki
            transaction.rollback()
538 23b9b72f Sofia Papagiannaki
            return index(request)
539 23b9b72f Sofia Papagiannaki
        except BaseException, e:
540 ae497612 Olga Brani
            message = _(astakos_messages.GENERIC_ERROR)
541 24406ae3 Sofia Papagiannaki
            messages.error(request, message)
542 23b9b72f Sofia Papagiannaki
            logger.exception(e)
543 23b9b72f Sofia Papagiannaki
            transaction.rollback()
544 23b9b72f Sofia Papagiannaki
            return index(request)
545 0a569195 Sofia Papagiannaki
    else:
546 23b9b72f Sofia Papagiannaki
        try:
547 3abf6c78 Sofia Papagiannaki
            user = switch_account_to_shibboleth(
548 3abf6c78 Sofia Papagiannaki
                user,
549 3abf6c78 Sofia Papagiannaki
                local_user,
550 3abf6c78 Sofia Papagiannaki
                greeting_email_template_name
551 3abf6c78 Sofia Papagiannaki
            )
552 23b9b72f Sofia Papagiannaki
            response = prepare_response(request, user, next, renew=True)
553 23b9b72f Sofia Papagiannaki
            transaction.commit()
554 23b9b72f Sofia Papagiannaki
            return response
555 23b9b72f Sofia Papagiannaki
        except SendMailError, e:
556 23b9b72f Sofia Papagiannaki
            message = e.message
557 24406ae3 Sofia Papagiannaki
            messages.error(request, message)
558 23b9b72f Sofia Papagiannaki
            transaction.rollback()
559 23b9b72f Sofia Papagiannaki
            return index(request)
560 23b9b72f Sofia Papagiannaki
        except BaseException, e:
561 ae497612 Olga Brani
            message = _(astakos_messages.GENERIC_ERROR)
562 24406ae3 Sofia Papagiannaki
            messages.error(request, message)
563 23b9b72f Sofia Papagiannaki
            logger.exception(e)
564 23b9b72f Sofia Papagiannaki
            transaction.rollback()
565 23b9b72f Sofia Papagiannaki
            return index(request)
566 270dd48d Sofia Papagiannaki
567 5ce3ce4f Sofia Papagiannaki
568 9a06d96f Olga Brani
@require_http_methods(["GET", "POST"])
569 aab4d540 Sofia Papagiannaki
def approval_terms(request, term_id=None, template_name='im/approval_terms.html', extra_context=None):
570 270dd48d Sofia Papagiannaki
    term = None
571 270dd48d Sofia Papagiannaki
    terms = None
572 270dd48d Sofia Papagiannaki
    if not term_id:
573 270dd48d Sofia Papagiannaki
        try:
574 270dd48d Sofia Papagiannaki
            term = ApprovalTerms.objects.order_by('-id')[0]
575 270dd48d Sofia Papagiannaki
        except IndexError:
576 270dd48d Sofia Papagiannaki
            pass
577 270dd48d Sofia Papagiannaki
    else:
578 270dd48d Sofia Papagiannaki
        try:
579 aab4d540 Sofia Papagiannaki
            term = ApprovalTerms.objects.get(id=term_id)
580 aab4d540 Sofia Papagiannaki
        except ApprovalTerms.DoesNotExist, e:
581 270dd48d Sofia Papagiannaki
            pass
582 176023aa Kostas Papadimitriou
583 270dd48d Sofia Papagiannaki
    if not term:
584 ae497612 Olga Brani
        messages.error(request, _(astakos_messages.NO_APPROVAL_TERMS))
585 6ff7a7ca Sofia Papagiannaki
        return HttpResponseRedirect(reverse('index'))
586 270dd48d Sofia Papagiannaki
    f = open(term.location, 'r')
587 270dd48d Sofia Papagiannaki
    terms = f.read()
588 176023aa Kostas Papadimitriou
589 270dd48d Sofia Papagiannaki
    if request.method == 'POST':
590 270dd48d Sofia Papagiannaki
        next = request.POST.get('next')
591 270dd48d Sofia Papagiannaki
        if not next:
592 6ff7a7ca Sofia Papagiannaki
            next = reverse('index')
593 270dd48d Sofia Papagiannaki
        form = SignApprovalTermsForm(request.POST, instance=request.user)
594 270dd48d Sofia Papagiannaki
        if not form.is_valid():
595 270dd48d Sofia Papagiannaki
            return render_response(template_name,
596 5ce3ce4f Sofia Papagiannaki
                                   terms=terms,
597 5ce3ce4f Sofia Papagiannaki
                                   approval_terms_form=form,
598 5ce3ce4f Sofia Papagiannaki
                                   context_instance=get_context(request, extra_context))
599 270dd48d Sofia Papagiannaki
        user = form.save()
600 270dd48d Sofia Papagiannaki
        return HttpResponseRedirect(next)
601 270dd48d Sofia Papagiannaki
    else:
602 586967c0 Sofia Papagiannaki
        form = None
603 fcf90160 Sofia Papagiannaki
        if request.user.is_authenticated() and not request.user.signed_terms:
604 586967c0 Sofia Papagiannaki
            form = SignApprovalTermsForm(instance=request.user)
605 270dd48d Sofia Papagiannaki
        return render_response(template_name,
606 5ce3ce4f Sofia Papagiannaki
                               terms=terms,
607 5ce3ce4f Sofia Papagiannaki
                               approval_terms_form=form,
608 5ce3ce4f Sofia Papagiannaki
                               context_instance=get_context(request, extra_context))
609 5ce3ce4f Sofia Papagiannaki
610 270dd48d Sofia Papagiannaki
611 9a06d96f Olga Brani
@require_http_methods(["GET", "POST"])
612 270dd48d Sofia Papagiannaki
@signed_terms_required
613 270dd48d Sofia Papagiannaki
def change_password(request):
614 1039bab1 Sofia Papagiannaki
    return password_change(request,
615 5ce3ce4f Sofia Papagiannaki
                           post_change_redirect=reverse('edit_profile'),
616 5ce3ce4f Sofia Papagiannaki
                           password_change_form=ExtendedPasswordChangeForm)
617 5ce3ce4f Sofia Papagiannaki
618 49790d9d Sofia Papagiannaki
619 9a06d96f Olga Brani
@require_http_methods(["GET", "POST"])
620 8e45d6fd Sofia Papagiannaki
@signed_terms_required
621 8e45d6fd Sofia Papagiannaki
@login_required
622 49790d9d Sofia Papagiannaki
@transaction.commit_manually
623 49790d9d Sofia Papagiannaki
def change_email(request, activation_key=None,
624 49790d9d Sofia Papagiannaki
                 email_template_name='registration/email_change_email.txt',
625 49790d9d Sofia Papagiannaki
                 form_template_name='registration/email_change_form.html',
626 49790d9d Sofia Papagiannaki
                 confirm_template_name='registration/email_change_done.html',
627 aab4d540 Sofia Papagiannaki
                 extra_context=None):
628 49790d9d Sofia Papagiannaki
    if activation_key:
629 49790d9d Sofia Papagiannaki
        try:
630 49790d9d Sofia Papagiannaki
            user = EmailChange.objects.change_email(activation_key)
631 49790d9d Sofia Papagiannaki
            if request.user.is_authenticated() and request.user == user:
632 ae497612 Olga Brani
                msg = _(astakos_messages.EMAIL_CHANGED)
633 24406ae3 Sofia Papagiannaki
                messages.success(request, msg)
634 49790d9d Sofia Papagiannaki
                auth_logout(request)
635 49790d9d Sofia Papagiannaki
                response = prepare_response(request, user)
636 49790d9d Sofia Papagiannaki
                transaction.commit()
637 49790d9d Sofia Papagiannaki
                return response
638 49790d9d Sofia Papagiannaki
        except ValueError, e:
639 24406ae3 Sofia Papagiannaki
            messages.error(request, e)
640 49790d9d Sofia Papagiannaki
        return render_response(confirm_template_name,
641 5ce3ce4f Sofia Papagiannaki
                               modified_user=user if 'user' in locals(
642 5ce3ce4f Sofia Papagiannaki
                               ) else None,
643 5ce3ce4f Sofia Papagiannaki
                               context_instance=get_context(request,
644 5ce3ce4f Sofia Papagiannaki
                                                            extra_context))
645 5ce3ce4f Sofia Papagiannaki
646 49790d9d Sofia Papagiannaki
    if not request.user.is_authenticated():
647 49790d9d Sofia Papagiannaki
        path = quote(request.get_full_path())
648 6ff7a7ca Sofia Papagiannaki
        url = request.build_absolute_uri(reverse('index'))
649 49790d9d Sofia Papagiannaki
        return HttpResponseRedirect(url + '?next=' + path)
650 49790d9d Sofia Papagiannaki
    form = EmailChangeForm(request.POST or None)
651 49790d9d Sofia Papagiannaki
    if request.method == 'POST' and form.is_valid():
652 49790d9d Sofia Papagiannaki
        try:
653 49790d9d Sofia Papagiannaki
            ec = form.save(email_template_name, request)
654 49790d9d Sofia Papagiannaki
        except SendMailError, e:
655 49790d9d Sofia Papagiannaki
            msg = e
656 24406ae3 Sofia Papagiannaki
            messages.error(request, msg)
657 49790d9d Sofia Papagiannaki
            transaction.rollback()
658 49790d9d Sofia Papagiannaki
        except IntegrityError, e:
659 ae497612 Olga Brani
            msg = _(astakos_messages.PENDING_EMAIL_CHANGE_REQUEST)
660 24406ae3 Sofia Papagiannaki
            messages.error(request, msg)
661 49790d9d Sofia Papagiannaki
        else:
662 ae497612 Olga Brani
            msg = _(astakos_messages.EMAIL_CHANGE_REGISTERED)
663 24406ae3 Sofia Papagiannaki
            messages.success(request, msg)
664 49790d9d Sofia Papagiannaki
            transaction.commit()
665 49790d9d Sofia Papagiannaki
    return render_response(form_template_name,
666 5ce3ce4f Sofia Papagiannaki
                           form=form,
667 5ce3ce4f Sofia Papagiannaki
                           context_instance=get_context(request,
668 5ce3ce4f Sofia Papagiannaki
                                                        extra_context))
669 5ce3ce4f Sofia Papagiannaki
670 3cbd5e47 Olga Brani
class ResourcePresentation():
671 3cbd5e47 Olga Brani
    
672 3cbd5e47 Olga Brani
    def __init__(self, data):
673 3cbd5e47 Olga Brani
        self.data = data
674 3cbd5e47 Olga Brani
        
675 3cbd5e47 Olga Brani
    def update_from_result(self, result):
676 3cbd5e47 Olga Brani
        if result.is_success:
677 3cbd5e47 Olga Brani
            for r in result.data:
678 3cbd5e47 Olga Brani
                rname = '%s%s%s' % (r.get('service'), RESOURCE_SEPARATOR, r.get('name'))
679 3cbd5e47 Olga Brani
                if not rname in self.data['resources']:
680 3cbd5e47 Olga Brani
                    self.data['resources'][rname] = {}
681 3cbd5e47 Olga Brani
                    
682 3cbd5e47 Olga Brani
                self.data['resources'][rname].update(r)
683 3cbd5e47 Olga Brani
                self.data['resources'][rname]['id'] = rname
684 3cbd5e47 Olga Brani
                group = r.get('group')
685 3cbd5e47 Olga Brani
                if not group in self.data['groups']:
686 3cbd5e47 Olga Brani
                    self.data['groups'][group] = {}
687 3cbd5e47 Olga Brani
                    
688 3cbd5e47 Olga Brani
                self.data['groups'][r.get('group')].update({'name': r.get('group')})
689 3cbd5e47 Olga Brani
    
690 3cbd5e47 Olga Brani
    def test(self, quota_dict):
691 3cbd5e47 Olga Brani
        for k, v in quota_dict.iteritems():
692 3cbd5e47 Olga Brani
            rname = k
693 3cbd5e47 Olga Brani
            value = v
694 3cbd5e47 Olga Brani
            if not rname in self.data['resources']:
695 3cbd5e47 Olga Brani
                    self.data['resources'][rname] = {}
696 3cbd5e47 Olga Brani
                    
697 3cbd5e47 Olga Brani
 
698 3cbd5e47 Olga Brani
            self.data['resources'][rname]['value'] = value
699 3cbd5e47 Olga Brani
            
700 3cbd5e47 Olga Brani
    
701 3cbd5e47 Olga Brani
    def update_from_result_report(self, result):
702 3cbd5e47 Olga Brani
        if result.is_success:
703 3cbd5e47 Olga Brani
            for r in result.data:
704 3cbd5e47 Olga Brani
                rname = r.get('name')
705 3cbd5e47 Olga Brani
                if not rname in self.data['resources']:
706 3cbd5e47 Olga Brani
                    self.data['resources'][rname] = {}
707 3cbd5e47 Olga Brani
                    
708 3cbd5e47 Olga Brani
                self.data['resources'][rname].update(r)
709 3cbd5e47 Olga Brani
                self.data['resources'][rname]['id'] = rname
710 3cbd5e47 Olga Brani
                group = r.get('group')
711 3cbd5e47 Olga Brani
                if not group in self.data['groups']:
712 3cbd5e47 Olga Brani
                    self.data['groups'][group] = {}
713 3cbd5e47 Olga Brani
                    
714 3cbd5e47 Olga Brani
                self.data['groups'][r.get('group')].update({'name': r.get('group')})
715 3cbd5e47 Olga Brani
                
716 3cbd5e47 Olga Brani
    def get_group_resources(self, group):
717 3cbd5e47 Olga Brani
        return dict(filter(lambda t: t[1].get('group') == group, self.data['resources'].iteritems()))
718 3cbd5e47 Olga Brani
    
719 3cbd5e47 Olga Brani
    def get_groups_resources(self):
720 3cbd5e47 Olga Brani
        for g in self.data['groups']:
721 3cbd5e47 Olga Brani
            yield g, self.get_group_resources(g)
722 3cbd5e47 Olga Brani
    
723 3cbd5e47 Olga Brani
    def get_quota(self, group_quotas):
724 3cbd5e47 Olga Brani
        print '!!!!!', group_quotas
725 3cbd5e47 Olga Brani
        for r, v in group_quotas.iteritems():
726 3cbd5e47 Olga Brani
            rname = str(r)
727 3cbd5e47 Olga Brani
            quota = self.data['resources'].get(rname)
728 3cbd5e47 Olga Brani
            quota['value'] = v
729 3cbd5e47 Olga Brani
            yield quota
730 3cbd5e47 Olga Brani
    
731 3cbd5e47 Olga Brani
    
732 3cbd5e47 Olga Brani
    def get_policies(self, policies_data):
733 3cbd5e47 Olga Brani
        for policy in policies_data:
734 3cbd5e47 Olga Brani
            rname = '%s%s%s' % (policy.get('service'), RESOURCE_SEPARATOR, policy.get('resource'))
735 3cbd5e47 Olga Brani
            policy.update(self.data['resources'].get(rname))
736 3cbd5e47 Olga Brani
            yield policy
737 3cbd5e47 Olga Brani
        
738 3cbd5e47 Olga Brani
    def __repr__(self):
739 3cbd5e47 Olga Brani
        return self.data.__repr__()
740 3cbd5e47 Olga Brani
                
741 3cbd5e47 Olga Brani
    def __iter__(self, *args, **kwargs):
742 3cbd5e47 Olga Brani
        return self.data.__iter__(*args, **kwargs)
743 3cbd5e47 Olga Brani
    
744 3cbd5e47 Olga Brani
    def __getitem__(self, *args, **kwargs):
745 3cbd5e47 Olga Brani
        return self.data.__getitem__(*args, **kwargs)
746 3cbd5e47 Olga Brani
    
747 3cbd5e47 Olga Brani
    def get(self, *args, **kwargs):
748 3cbd5e47 Olga Brani
        return self.data.get(*args, **kwargs)
749 3cbd5e47 Olga Brani
        
750 3cbd5e47 Olga Brani
        
751 12269b45 Olga Brani
752 8c804c12 Sofia Papagiannaki
@require_http_methods(["GET", "POST"])
753 8e45d6fd Sofia Papagiannaki
@signed_terms_required
754 01ac12d5 Sofia Papagiannaki
@login_required
755 0f4fa26d Sofia Papagiannaki
def group_add(request, kind_name='default'):
756 3cbd5e47 Olga Brani
    
757 820b18e0 Sofia Papagiannaki
    result = callpoint.list_resources()
758 3cbd5e47 Olga Brani
    resource_catalog = ResourcePresentation(RESOURCES_PRESENTATION_DATA)
759 3cbd5e47 Olga Brani
    resource_catalog.update_from_result(result)
760 3cbd5e47 Olga Brani
    
761 3cbd5e47 Olga Brani
    if not result.is_success:
762 820b18e0 Sofia Papagiannaki
        messages.error(
763 820b18e0 Sofia Papagiannaki
            request,
764 820b18e0 Sofia Papagiannaki
            'Unable to retrieve system resources: %s' % result.reason
765 820b18e0 Sofia Papagiannaki
    )
766 820b18e0 Sofia Papagiannaki
    
767 0f4fa26d Sofia Papagiannaki
    try:
768 5ce3ce4f Sofia Papagiannaki
        kind = GroupKind.objects.get(name=kind_name)
769 0f4fa26d Sofia Papagiannaki
    except:
770 ae497612 Olga Brani
        return HttpResponseBadRequest(_(astakos_messages.GROUPKIND_UNKNOWN))
771 820b18e0 Sofia Papagiannaki
    
772 12269b45 Olga Brani
    
773 5ce3ce4f Sofia Papagiannaki
774 5ce3ce4f Sofia Papagiannaki
    post_save_redirect = '/im/group/%(id)s/'
775 5ce3ce4f Sofia Papagiannaki
    context_processors = None
776 0f4fa26d Sofia Papagiannaki
    model, form_class = get_model_and_form_class(
777 0f4fa26d Sofia Papagiannaki
        model=None,
778 0f4fa26d Sofia Papagiannaki
        form_class=AstakosGroupCreationForm
779 0f4fa26d Sofia Papagiannaki
    )
780 820b18e0 Sofia Papagiannaki
    
781 0f4fa26d Sofia Papagiannaki
    if request.method == 'POST':
782 820b18e0 Sofia Papagiannaki
        form = form_class(request.POST, request.FILES)
783 0f4fa26d Sofia Papagiannaki
        if form.is_valid():
784 8c804c12 Sofia Papagiannaki
            return render_response(
785 8c804c12 Sofia Papagiannaki
                template='im/astakosgroup_form_summary.html',
786 8c804c12 Sofia Papagiannaki
                context_instance=get_context(request),
787 29b87e7c Sofia Papagiannaki
                form = AstakosGroupCreationSummaryForm(form.cleaned_data),
788 3cbd5e47 Olga Brani
                policies = resource_catalog.get_policies(form.policies()),
789 5841646f Olga Brani
                resource_catalog= resource_catalog,
790 8c804c12 Sofia Papagiannaki
            )
791 3cbd5e47 Olga Brani
         
792 0f4fa26d Sofia Papagiannaki
    else:
793 0f4fa26d Sofia Papagiannaki
        now = datetime.now()
794 0f4fa26d Sofia Papagiannaki
        data = {
795 6abd262c Olga Brani
            'kind': kind,
796 0f4fa26d Sofia Papagiannaki
        }
797 3cbd5e47 Olga Brani
        for group, resources in resource_catalog.get_groups_resources():
798 6abd262c Olga Brani
            data['is_selected_%s' % group] = False
799 6abd262c Olga Brani
            for resource in resources:
800 6abd262c Olga Brani
                data['%s_uplimit' % resource] = ''
801 6abd262c Olga Brani
        
802 820b18e0 Sofia Papagiannaki
        form = form_class(data)
803 0f4fa26d Sofia Papagiannaki
804 0f4fa26d Sofia Papagiannaki
    # Create the template, context, response
805 ae497612 Olga Brani
    template_name = "%s/%s_form.html" % (
806 0f4fa26d Sofia Papagiannaki
        model._meta.app_label,
807 0f4fa26d Sofia Papagiannaki
        model._meta.object_name.lower()
808 0f4fa26d Sofia Papagiannaki
    )
809 0f4fa26d Sofia Papagiannaki
    t = template_loader.get_template(template_name)
810 0f4fa26d Sofia Papagiannaki
    c = RequestContext(request, {
811 c8977d75 Olga Brani
        'form': form,
812 c8977d75 Olga Brani
        'kind': kind,
813 820b18e0 Sofia Papagiannaki
        'resource_catalog':resource_catalog,
814 0f4fa26d Sofia Papagiannaki
    }, context_processors)
815 0f4fa26d Sofia Papagiannaki
    return HttpResponse(t.render(c))
816 8e45d6fd Sofia Papagiannaki
817 8c804c12 Sofia Papagiannaki
818 ae497612 Olga Brani
#@require_http_methods(["POST"])
819 ae497612 Olga Brani
@require_http_methods(["GET", "POST"])
820 29b87e7c Sofia Papagiannaki
@signed_terms_required
821 29b87e7c Sofia Papagiannaki
@login_required
822 8c804c12 Sofia Papagiannaki
def group_add_complete(request):
823 29b87e7c Sofia Papagiannaki
    model = AstakosGroup
824 29b87e7c Sofia Papagiannaki
    form = AstakosGroupCreationSummaryForm(request.POST)
825 29b87e7c Sofia Papagiannaki
    if form.is_valid():
826 29b87e7c Sofia Papagiannaki
        d = form.cleaned_data
827 29b87e7c Sofia Papagiannaki
        d['owners'] = [request.user]
828 29b87e7c Sofia Papagiannaki
        result = callpoint.create_groups((d,)).next()
829 29b87e7c Sofia Papagiannaki
        if result.is_success:
830 29b87e7c Sofia Papagiannaki
            new_object = result.data[0]
831 ae497612 Olga Brani
            msg = _(astakos_messages.OBJECT_CREATED) %\
832 29b87e7c Sofia Papagiannaki
                {"verbose_name": model._meta.verbose_name}
833 29b87e7c Sofia Papagiannaki
            messages.success(request, msg, fail_silently=True)
834 29b87e7c Sofia Papagiannaki
            
835 29b87e7c Sofia Papagiannaki
            # send notification
836 29b87e7c Sofia Papagiannaki
            try:
837 29b87e7c Sofia Papagiannaki
                send_group_creation_notification(
838 29b87e7c Sofia Papagiannaki
                    template_name='im/group_creation_notification.txt',
839 29b87e7c Sofia Papagiannaki
                    dictionary={
840 29b87e7c Sofia Papagiannaki
                        'group': new_object,
841 29b87e7c Sofia Papagiannaki
                        'owner': request.user,
842 29b87e7c Sofia Papagiannaki
                        'policies': d.get('policies', [])
843 29b87e7c Sofia Papagiannaki
                    }
844 29b87e7c Sofia Papagiannaki
                )
845 29b87e7c Sofia Papagiannaki
            except SendNotificationError, e:
846 29b87e7c Sofia Papagiannaki
                messages.error(request, e, fail_silently=True)
847 29b87e7c Sofia Papagiannaki
            post_save_redirect = '/im/group/%(id)s/'
848 29b87e7c Sofia Papagiannaki
            return HttpResponseRedirect(post_save_redirect % new_object)
849 29b87e7c Sofia Papagiannaki
        else:
850 3cbd5e47 Olga Brani
            d = {"verbose_name": model._meta.verbose_name,
851 29b87e7c Sofia Papagiannaki
                 "reason":result.reason}
852 3cbd5e47 Olga Brani
            msg = _(astakos_messages.OBJECT_CREATED_FAILED) % d 
853 29b87e7c Sofia Papagiannaki
            messages.error(request, msg, fail_silently=True)
854 8c804c12 Sofia Papagiannaki
    return render_response(
855 29b87e7c Sofia Papagiannaki
        template='im/astakosgroup_form_summary.html',
856 29b87e7c Sofia Papagiannaki
        context_instance=get_context(request),
857 29b87e7c Sofia Papagiannaki
        form=form)
858 8c804c12 Sofia Papagiannaki
859 8c804c12 Sofia Papagiannaki
860 ae497612 Olga Brani
#@require_http_methods(["GET"])
861 ae497612 Olga Brani
@require_http_methods(["GET", "POST"])
862 8e45d6fd Sofia Papagiannaki
@signed_terms_required
863 8e45d6fd Sofia Papagiannaki
@login_required
864 ade90760 Sofia Papagiannaki
def group_list(request):
865 789bcaf9 Sofia Papagiannaki
    none = request.user.astakos_groups.none()
866 5841646f Olga Brani
    sorting = request.GET.get('sorting')
867 3cbd5e47 Olga Brani
    query = """
868 789bcaf9 Sofia Papagiannaki
        SELECT auth_group.id,
869 789bcaf9 Sofia Papagiannaki
        %s AS groupname,
870 789bcaf9 Sofia Papagiannaki
        im_groupkind.name AS kindname,
871 789bcaf9 Sofia Papagiannaki
        im_astakosgroup.*,
872 789bcaf9 Sofia Papagiannaki
        owner.email AS groupowner,
873 789bcaf9 Sofia Papagiannaki
        (SELECT COUNT(*) FROM im_membership
874 789bcaf9 Sofia Papagiannaki
            WHERE group_id = im_astakosgroup.group_ptr_id
875 789bcaf9 Sofia Papagiannaki
            AND date_joined IS NOT NULL) AS approved_members_num,
876 04febd09 Olga Brani
        (SELECT CASE WHEN(
877 04febd09 Olga Brani
                    SELECT date_joined FROM im_membership
878 04febd09 Olga Brani
                    WHERE group_id = im_astakosgroup.group_ptr_id
879 04febd09 Olga Brani
                    AND person_id = %s) IS NULL
880 0f225db4 Sofia Papagiannaki
                    THEN 0 ELSE 1 END) AS membership_status
881 789bcaf9 Sofia Papagiannaki
        FROM im_astakosgroup
882 789bcaf9 Sofia Papagiannaki
        INNER JOIN im_membership ON (
883 789bcaf9 Sofia Papagiannaki
            im_astakosgroup.group_ptr_id = im_membership.group_id)
884 789bcaf9 Sofia Papagiannaki
        INNER JOIN auth_group ON(im_astakosgroup.group_ptr_id = auth_group.id)
885 789bcaf9 Sofia Papagiannaki
        INNER JOIN im_groupkind ON (im_astakosgroup.kind_id = im_groupkind.id)
886 789bcaf9 Sofia Papagiannaki
        LEFT JOIN im_astakosuser_owner ON (
887 789bcaf9 Sofia Papagiannaki
            im_astakosuser_owner.astakosgroup_id = im_astakosgroup.group_ptr_id)
888 789bcaf9 Sofia Papagiannaki
        LEFT JOIN auth_user as owner ON (
889 789bcaf9 Sofia Papagiannaki
            im_astakosuser_owner.astakosuser_id = owner.id)
890 3cbd5e47 Olga Brani
        WHERE im_membership.person_id = %s 
891 3cbd5e47 Olga Brani
        """ % (DB_REPLACE_GROUP_SCHEME, request.user.id, request.user.id)
892 3cbd5e47 Olga Brani
       
893 3cbd5e47 Olga Brani
    if sorting:
894 3cbd5e47 Olga Brani
        query = query+" ORDER BY %s ASC" %sorting    
895 3cbd5e47 Olga Brani
    else:
896 84a7cd69 Olga Brani
        query = query+" ORDER BY groupname ASC"     
897 3cbd5e47 Olga Brani
    q = AstakosGroup.objects.raw(query)
898 5841646f Olga Brani
899 3cbd5e47 Olga Brani
       
900 3cbd5e47 Olga Brani
       
901 f2a4ce70 Sofia Papagiannaki
    # Create the template, context, response
902 f2a4ce70 Sofia Papagiannaki
    template_name = "%s/%s_list.html" % (
903 f2a4ce70 Sofia Papagiannaki
        q.model._meta.app_label,
904 f2a4ce70 Sofia Papagiannaki
        q.model._meta.object_name.lower()
905 f2a4ce70 Sofia Papagiannaki
    )
906 f2a4ce70 Sofia Papagiannaki
    extra_context = dict(
907 f2a4ce70 Sofia Papagiannaki
        is_search=False,
908 f2a4ce70 Sofia Papagiannaki
        q=q,
909 f2a4ce70 Sofia Papagiannaki
        sorting=request.GET.get('sorting'),
910 f2a4ce70 Sofia Papagiannaki
        page=request.GET.get('page', 1)
911 f2a4ce70 Sofia Papagiannaki
    )
912 f2a4ce70 Sofia Papagiannaki
    return render_response(template_name,
913 f2a4ce70 Sofia Papagiannaki
                           context_instance=get_context(request, extra_context)
914 f2a4ce70 Sofia Papagiannaki
    )
915 5ce3ce4f Sofia Papagiannaki
916 8e45d6fd Sofia Papagiannaki
917 8c804c12 Sofia Papagiannaki
@require_http_methods(["GET", "POST"])
918 8e45d6fd Sofia Papagiannaki
@signed_terms_required
919 8e45d6fd Sofia Papagiannaki
@login_required
920 8e45d6fd Sofia Papagiannaki
def group_detail(request, group_id):
921 032ade79 Sofia Papagiannaki
    q = AstakosGroup.objects.select_related().filter(pk=group_id)
922 661c4479 Sofia Papagiannaki
    q = q.extra(select={
923 661c4479 Sofia Papagiannaki
        'is_member': """SELECT CASE WHEN EXISTS(
924 661c4479 Sofia Papagiannaki
                            SELECT id FROM im_membership
925 661c4479 Sofia Papagiannaki
                            WHERE group_id = im_astakosgroup.group_ptr_id
926 661c4479 Sofia Papagiannaki
                            AND person_id = %s)
927 661c4479 Sofia Papagiannaki
                        THEN 1 ELSE 0 END""" % request.user.id,
928 661c4479 Sofia Papagiannaki
        'is_owner': """SELECT CASE WHEN EXISTS(
929 032ade79 Sofia Papagiannaki
                        SELECT id FROM im_astakosuser_owner
930 032ade79 Sofia Papagiannaki
                        WHERE astakosgroup_id = im_astakosgroup.group_ptr_id
931 032ade79 Sofia Papagiannaki
                        AND astakosuser_id = %s)
932 661c4479 Sofia Papagiannaki
                        THEN 1 ELSE 0 END""" % request.user.id,
933 661c4479 Sofia Papagiannaki
        'kindname': """SELECT name FROM im_groupkind
934 661c4479 Sofia Papagiannaki
                       WHERE id = im_astakosgroup.kind_id"""})
935 9a06d96f Olga Brani
936 661c4479 Sofia Papagiannaki
    model = q.model
937 661c4479 Sofia Papagiannaki
    context_processors = None
938 661c4479 Sofia Papagiannaki
    mimetype = None
939 8e45d6fd Sofia Papagiannaki
    try:
940 661c4479 Sofia Papagiannaki
        obj = q.get()
941 032ade79 Sofia Papagiannaki
    except AstakosGroup.DoesNotExist:
942 032ade79 Sofia Papagiannaki
        raise Http404("No %s found matching the query" % (
943 032ade79 Sofia Papagiannaki
            model._meta.verbose_name))
944 9a06d96f Olga Brani
945 661c4479 Sofia Papagiannaki
    update_form = AstakosGroupUpdateForm(instance=obj)
946 661c4479 Sofia Papagiannaki
    addmembers_form = AddGroupMembersForm()
947 661c4479 Sofia Papagiannaki
    if request.method == 'POST':
948 661c4479 Sofia Papagiannaki
        update_data = {}
949 661c4479 Sofia Papagiannaki
        addmembers_data = {}
950 9a06d96f Olga Brani
        for k, v in request.POST.iteritems():
951 661c4479 Sofia Papagiannaki
            if k in update_form.fields:
952 661c4479 Sofia Papagiannaki
                update_data[k] = v
953 661c4479 Sofia Papagiannaki
            if k in addmembers_form.fields:
954 661c4479 Sofia Papagiannaki
                addmembers_data[k] = v
955 661c4479 Sofia Papagiannaki
        update_data = update_data or None
956 661c4479 Sofia Papagiannaki
        addmembers_data = addmembers_data or None
957 661c4479 Sofia Papagiannaki
        update_form = AstakosGroupUpdateForm(update_data, instance=obj)
958 661c4479 Sofia Papagiannaki
        addmembers_form = AddGroupMembersForm(addmembers_data)
959 661c4479 Sofia Papagiannaki
        if update_form.is_valid():
960 661c4479 Sofia Papagiannaki
            update_form.save()
961 661c4479 Sofia Papagiannaki
        if addmembers_form.is_valid():
962 ae497612 Olga Brani
            try:
963 ae497612 Olga Brani
                map(obj.approve_member, addmembers_form.valid_users)
964 ae497612 Olga Brani
            except AssertionError:
965 ae497612 Olga Brani
                msg = _(astakos_messages.GROUP_MAX_PARTICIPANT_NUMBER_REACHED)
966 ae497612 Olga Brani
                messages.error(request, msg)
967 661c4479 Sofia Papagiannaki
            addmembers_form = AddGroupMembersForm()
968 9a06d96f Olga Brani
969 9a06d96f Olga Brani
    template_name = "%s/%s_detail.html" % (
970 9a06d96f Olga Brani
        model._meta.app_label, model._meta.object_name.lower())
971 661c4479 Sofia Papagiannaki
    t = template_loader.get_template(template_name)
972 661c4479 Sofia Papagiannaki
    c = RequestContext(request, {
973 661c4479 Sofia Papagiannaki
        'object': obj,
974 661c4479 Sofia Papagiannaki
    }, context_processors)
975 9a06d96f Olga Brani
976 801be7a3 Sofia Papagiannaki
    # validate sorting
977 9a06d96f Olga Brani
    sorting = request.GET.get('sorting')
978 801be7a3 Sofia Papagiannaki
    if sorting:
979 801be7a3 Sofia Papagiannaki
        form = MembersSortForm({'sort_by': sorting})
980 801be7a3 Sofia Papagiannaki
        if form.is_valid():
981 801be7a3 Sofia Papagiannaki
            sorting = form.cleaned_data.get('sort_by')
982 3cbd5e47 Olga Brani
    
983 3cbd5e47 Olga Brani
 
984 3cbd5e47 Olga Brani
    
985 bdc1c103 Olga Brani
    result = callpoint.list_resources()
986 3cbd5e47 Olga Brani
    resource_catalog = ResourcePresentation(RESOURCES_PRESENTATION_DATA)
987 3cbd5e47 Olga Brani
    resource_catalog.update_from_result(result)
988 3cbd5e47 Olga Brani
989 bdc1c103 Olga Brani
    
990 3cbd5e47 Olga Brani
    if not result.is_success:
991 3cbd5e47 Olga Brani
        messages.error(
992 3cbd5e47 Olga Brani
            request,
993 3cbd5e47 Olga Brani
            'Unable to retrieve system resources: %s' % result.reason
994 3cbd5e47 Olga Brani
    )
995 3cbd5e47 Olga Brani
    
996 3cbd5e47 Olga Brani
    print '######', obj.quota
997 3cbd5e47 Olga Brani
   
998 661c4479 Sofia Papagiannaki
    extra_context = {'update_form': update_form,
999 661c4479 Sofia Papagiannaki
                     'addmembers_form': addmembers_form,
1000 661c4479 Sofia Papagiannaki
                     'page': request.GET.get('page', 1),
1001 bdc1c103 Olga Brani
                     'sorting': sorting,
1002 bdc1c103 Olga Brani
                     'resource_catalog':resource_catalog,
1003 3cbd5e47 Olga Brani
                     'quota':resource_catalog.get_quota(obj.quota)}
1004 661c4479 Sofia Papagiannaki
    for key, value in extra_context.items():
1005 661c4479 Sofia Papagiannaki
        if callable(value):
1006 661c4479 Sofia Papagiannaki
            c[key] = value()
1007 04febd09 Olga Brani
        else:
1008 661c4479 Sofia Papagiannaki
            c[key] = value
1009 661c4479 Sofia Papagiannaki
    response = HttpResponse(t.render(c), mimetype=mimetype)
1010 9a06d96f Olga Brani
    populate_xheaders(
1011 9a06d96f Olga Brani
        request, response, model, getattr(obj, obj._meta.pk.name))
1012 661c4479 Sofia Papagiannaki
    return response
1013 8e45d6fd Sofia Papagiannaki
1014 5ce3ce4f Sofia Papagiannaki
1015 8c804c12 Sofia Papagiannaki
@require_http_methods(["GET", "POST"])
1016 01ac12d5 Sofia Papagiannaki
@signed_terms_required
1017 01ac12d5 Sofia Papagiannaki
@login_required
1018 95a51cdc Sofia Papagiannaki
def group_search(request, extra_context=None, **kwargs):
1019 d220292f Sofia Papagiannaki
    q = request.GET.get('q')
1020 04febd09 Olga Brani
    sorting = request.GET.get('sorting')
1021 01ac12d5 Sofia Papagiannaki
    if request.method == 'GET':
1022 d220292f Sofia Papagiannaki
        form = AstakosGroupSearchForm({'q': q} if q else None)
1023 01ac12d5 Sofia Papagiannaki
    else:
1024 01ac12d5 Sofia Papagiannaki
        form = AstakosGroupSearchForm(get_query(request))
1025 01ac12d5 Sofia Papagiannaki
        if form.is_valid():
1026 01ac12d5 Sofia Papagiannaki
            q = form.cleaned_data['q'].strip()
1027 d220292f Sofia Papagiannaki
    if q:
1028 789bcaf9 Sofia Papagiannaki
        queryset = AstakosGroup.objects.select_related()
1029 789bcaf9 Sofia Papagiannaki
        queryset = queryset.filter(name__contains=q)
1030 789bcaf9 Sofia Papagiannaki
        queryset = queryset.filter(approval_date__isnull=False)
1031 789bcaf9 Sofia Papagiannaki
        queryset = queryset.extra(select={
1032 9a06d96f Olga Brani
                                  'groupname': DB_REPLACE_GROUP_SCHEME,
1033 9a06d96f Olga Brani
                                  'kindname': "im_groupkind.name",
1034 9a06d96f Olga Brani
                                  'approved_members_num': """
1035 789bcaf9 Sofia Papagiannaki
                    SELECT COUNT(*) FROM im_membership
1036 789bcaf9 Sofia Papagiannaki
                    WHERE group_id = im_astakosgroup.group_ptr_id
1037 789bcaf9 Sofia Papagiannaki
                    AND date_joined IS NOT NULL""",
1038 9a06d96f Olga Brani
                                  'membership_approval_date': """
1039 789bcaf9 Sofia Papagiannaki
                    SELECT date_joined FROM im_membership
1040 789bcaf9 Sofia Papagiannaki
                    WHERE group_id = im_astakosgroup.group_ptr_id
1041 789bcaf9 Sofia Papagiannaki
                    AND person_id = %s""" % request.user.id,
1042 9a06d96f Olga Brani
                                  'is_member': """
1043 789bcaf9 Sofia Papagiannaki
                    SELECT CASE WHEN EXISTS(
1044 789bcaf9 Sofia Papagiannaki
                    SELECT date_joined FROM im_membership
1045 789bcaf9 Sofia Papagiannaki
                    WHERE group_id = im_astakosgroup.group_ptr_id
1046 789bcaf9 Sofia Papagiannaki
                    AND person_id = %s)
1047 701118f4 Sofia Papagiannaki
                    THEN 1 ELSE 0 END""" % request.user.id,
1048 9a06d96f Olga Brani
                                  'is_owner': """
1049 701118f4 Sofia Papagiannaki
                    SELECT CASE WHEN EXISTS(
1050 701118f4 Sofia Papagiannaki
                    SELECT id FROM im_astakosuser_owner
1051 701118f4 Sofia Papagiannaki
                    WHERE astakosgroup_id = im_astakosgroup.group_ptr_id
1052 701118f4 Sofia Papagiannaki
                    AND astakosuser_id = %s)
1053 bdc1c103 Olga Brani
                    THEN 1 ELSE 0 END""" % request.user.id,
1054 bdc1c103 Olga Brani
                    'is_owner': """SELECT CASE WHEN EXISTS(
1055 bdc1c103 Olga Brani
                        SELECT id FROM im_astakosuser_owner
1056 bdc1c103 Olga Brani
                        WHERE astakosgroup_id = im_astakosgroup.group_ptr_id
1057 bdc1c103 Olga Brani
                        AND astakosuser_id = %s)
1058 bdc1c103 Olga Brani
                        THEN 1 ELSE 0 END""" % request.user.id, 
1059 bdc1c103 Olga Brani
                    })
1060 04febd09 Olga Brani
        if sorting:
1061 04febd09 Olga Brani
            # TODO check sorting value
1062 04febd09 Olga Brani
            queryset = queryset.order_by(sorting)
1063 84a7cd69 Olga Brani
        else:
1064 84a7cd69 Olga Brani
            queryset = queryset.order_by("groupname")
1065 3cbd5e47 Olga Brani
1066 d220292f Sofia Papagiannaki
    else:
1067 d220292f Sofia Papagiannaki
        queryset = AstakosGroup.objects.none()
1068 d220292f Sofia Papagiannaki
    return object_list(
1069 d220292f Sofia Papagiannaki
        request,
1070 d220292f Sofia Papagiannaki
        queryset,
1071 d220292f Sofia Papagiannaki
        paginate_by=PAGINATE_BY,
1072 d220292f Sofia Papagiannaki
        page=request.GET.get('page') or 1,
1073 d220292f Sofia Papagiannaki
        template_name='im/astakosgroup_list.html',
1074 d220292f Sofia Papagiannaki
        extra_context=dict(form=form,
1075 d220292f Sofia Papagiannaki
                           is_search=True,
1076 04febd09 Olga Brani
                           q=q,
1077 04febd09 Olga Brani
                           sorting=sorting))
1078 5ce3ce4f Sofia Papagiannaki
1079 9a06d96f Olga Brani
1080 ae497612 Olga Brani
@require_http_methods(["GET", "POST"])
1081 df67421c Sofia Papagiannaki
@signed_terms_required
1082 df67421c Sofia Papagiannaki
@login_required
1083 df67421c Sofia Papagiannaki
def group_all(request, extra_context=None, **kwargs):
1084 789bcaf9 Sofia Papagiannaki
    q = AstakosGroup.objects.select_related()
1085 789bcaf9 Sofia Papagiannaki
    q = q.filter(approval_date__isnull=False)
1086 789bcaf9 Sofia Papagiannaki
    q = q.extra(select={
1087 789bcaf9 Sofia Papagiannaki
                'groupname': DB_REPLACE_GROUP_SCHEME,
1088 789bcaf9 Sofia Papagiannaki
                'kindname': "im_groupkind.name",
1089 789bcaf9 Sofia Papagiannaki
                'approved_members_num': """
1090 789bcaf9 Sofia Papagiannaki
                    SELECT COUNT(*) FROM im_membership
1091 789bcaf9 Sofia Papagiannaki
                    WHERE group_id = im_astakosgroup.group_ptr_id
1092 789bcaf9 Sofia Papagiannaki
                    AND date_joined IS NOT NULL""",
1093 789bcaf9 Sofia Papagiannaki
                'membership_approval_date': """
1094 789bcaf9 Sofia Papagiannaki
                    SELECT date_joined FROM im_membership
1095 789bcaf9 Sofia Papagiannaki
                    WHERE group_id = im_astakosgroup.group_ptr_id
1096 789bcaf9 Sofia Papagiannaki
                    AND person_id = %s""" % request.user.id,
1097 789bcaf9 Sofia Papagiannaki
                'is_member': """
1098 789bcaf9 Sofia Papagiannaki
                    SELECT CASE WHEN EXISTS(
1099 789bcaf9 Sofia Papagiannaki
                    SELECT date_joined FROM im_membership
1100 789bcaf9 Sofia Papagiannaki
                    WHERE group_id = im_astakosgroup.group_ptr_id
1101 789bcaf9 Sofia Papagiannaki
                    AND person_id = %s)
1102 bdc1c103 Olga Brani
                    THEN 1 ELSE 0 END""" % request.user.id,
1103 bdc1c103 Olga Brani
                 'is_owner': """SELECT CASE WHEN EXISTS(
1104 bdc1c103 Olga Brani
                        SELECT id FROM im_astakosuser_owner
1105 bdc1c103 Olga Brani
                        WHERE astakosgroup_id = im_astakosgroup.group_ptr_id
1106 bdc1c103 Olga Brani
                        AND astakosuser_id = %s)
1107 bdc1c103 Olga Brani
                        THEN 1 ELSE 0 END""" % request.user.id,   })
1108 04febd09 Olga Brani
    sorting = request.GET.get('sorting')
1109 04febd09 Olga Brani
    if sorting:
1110 04febd09 Olga Brani
        # TODO check sorting value
1111 04febd09 Olga Brani
        q = q.order_by(sorting)
1112 84a7cd69 Olga Brani
    else:
1113 84a7cd69 Olga Brani
        q = q.order_by("groupname")
1114 84a7cd69 Olga Brani
        
1115 df67421c Sofia Papagiannaki
    return object_list(
1116 9a06d96f Olga Brani
        request,
1117 9a06d96f Olga Brani
        q,
1118 9a06d96f Olga Brani
        paginate_by=PAGINATE_BY,
1119 9a06d96f Olga Brani
        page=request.GET.get('page') or 1,
1120 9a06d96f Olga Brani
        template_name='im/astakosgroup_list.html',
1121 9a06d96f Olga Brani
        extra_context=dict(form=AstakosGroupSearchForm(),
1122 9a06d96f Olga Brani
                           is_search=True,
1123 9a06d96f Olga Brani
                           sorting=sorting))
1124 df67421c Sofia Papagiannaki
1125 01ac12d5 Sofia Papagiannaki
1126 ae497612 Olga Brani
#@require_http_methods(["POST"])
1127 ae497612 Olga Brani
@require_http_methods(["POST", "GET"])
1128 01ac12d5 Sofia Papagiannaki
@signed_terms_required
1129 01ac12d5 Sofia Papagiannaki
@login_required
1130 01ac12d5 Sofia Papagiannaki
def group_join(request, group_id):
1131 95a51cdc Sofia Papagiannaki
    m = Membership(group_id=group_id,
1132 5ce3ce4f Sofia Papagiannaki
                   person=request.user,
1133 789bcaf9 Sofia Papagiannaki
                   date_requested=datetime.now())
1134 95a51cdc Sofia Papagiannaki
    try:
1135 95a51cdc Sofia Papagiannaki
        m.save()
1136 0f4fa26d Sofia Papagiannaki
        post_save_redirect = reverse(
1137 0f4fa26d Sofia Papagiannaki
            'group_detail',
1138 789bcaf9 Sofia Papagiannaki
            kwargs=dict(group_id=group_id))
1139 95a51cdc Sofia Papagiannaki
        return HttpResponseRedirect(post_save_redirect)
1140 95a51cdc Sofia Papagiannaki
    except IntegrityError, e:
1141 95a51cdc Sofia Papagiannaki
        logger.exception(e)
1142 ae497612 Olga Brani
        msg = _(astakos_messages.GROUP_JOIN_FAILURE)
1143 95a51cdc Sofia Papagiannaki
        messages.error(request, msg)
1144 95a51cdc Sofia Papagiannaki
        return group_search(request)
1145 01ac12d5 Sofia Papagiannaki
1146 5ce3ce4f Sofia Papagiannaki
1147 8c804c12 Sofia Papagiannaki
@require_http_methods(["POST"])
1148 01ac12d5 Sofia Papagiannaki
@signed_terms_required
1149 01ac12d5 Sofia Papagiannaki
@login_required
1150 01ac12d5 Sofia Papagiannaki
def group_leave(request, group_id):
1151 01ac12d5 Sofia Papagiannaki
    try:
1152 0f4fa26d Sofia Papagiannaki
        m = Membership.objects.select_related().get(
1153 0f4fa26d Sofia Papagiannaki
            group__id=group_id,
1154 032ade79 Sofia Papagiannaki
            person=request.user)
1155 01ac12d5 Sofia Papagiannaki
    except Membership.DoesNotExist:
1156 ae497612 Olga Brani
        return HttpResponseBadRequest(_(astakos_messages.NOT_A_MEMBER))
1157 01ac12d5 Sofia Papagiannaki
    if request.user in m.group.owner.all():
1158 ae497612 Olga Brani
        return HttpResponseForbidden(_(astakos_messages.OWNER_CANNOT_LEAVE_GROUP))
1159 0f4fa26d Sofia Papagiannaki
    return delete_object(
1160 0f4fa26d Sofia Papagiannaki
        request,
1161 0f4fa26d Sofia Papagiannaki
        model=Membership,
1162 5ce3ce4f Sofia Papagiannaki
        object_id=m.id,
1163 0f4fa26d Sofia Papagiannaki
        template_name='im/astakosgroup_list.html',
1164 5ce3ce4f Sofia Papagiannaki
        post_delete_redirect=reverse(
1165 0f4fa26d Sofia Papagiannaki
            'group_detail',
1166 032ade79 Sofia Papagiannaki
            kwargs=dict(group_id=group_id)))
1167 01ac12d5 Sofia Papagiannaki
1168 5ce3ce4f Sofia Papagiannaki
1169 1eaeb5b6 Sofia Papagiannaki
def handle_membership(func):
1170 1eaeb5b6 Sofia Papagiannaki
    @wraps(func)
1171 1eaeb5b6 Sofia Papagiannaki
    def wrapper(request, group_id, user_id):
1172 1eaeb5b6 Sofia Papagiannaki
        try:
1173 1eaeb5b6 Sofia Papagiannaki
            m = Membership.objects.select_related().get(
1174 1eaeb5b6 Sofia Papagiannaki
                group__id=group_id,
1175 032ade79 Sofia Papagiannaki
                person__id=user_id)
1176 1eaeb5b6 Sofia Papagiannaki
        except Membership.DoesNotExist:
1177 ae497612 Olga Brani
            return HttpResponseBadRequest(_(astakos_messages.NOT_MEMBER))
1178 1eaeb5b6 Sofia Papagiannaki
        else:
1179 1eaeb5b6 Sofia Papagiannaki
            if request.user not in m.group.owner.all():
1180 ae497612 Olga Brani
                return HttpResponseForbidden(_(astakos_messages.NOT_OWNER))
1181 1eaeb5b6 Sofia Papagiannaki
            func(request, m)
1182 56b1281c Sofia Papagiannaki
            return group_detail(request, group_id)
1183 1eaeb5b6 Sofia Papagiannaki
    return wrapper
1184 01ac12d5 Sofia Papagiannaki
1185 5ce3ce4f Sofia Papagiannaki
1186 ae497612 Olga Brani
#@require_http_methods(["POST"])
1187 ae497612 Olga Brani
@require_http_methods(["POST", "GET"])
1188 01ac12d5 Sofia Papagiannaki
@signed_terms_required
1189 01ac12d5 Sofia Papagiannaki
@login_required
1190 1eaeb5b6 Sofia Papagiannaki
@handle_membership
1191 01ac12d5 Sofia Papagiannaki
def approve_member(request, membership):
1192 01ac12d5 Sofia Papagiannaki
    try:
1193 01ac12d5 Sofia Papagiannaki
        membership.approve()
1194 01ac12d5 Sofia Papagiannaki
        realname = membership.person.realname
1195 ae497612 Olga Brani
        msg = _(astakos_messages.MEMBER_JOINED_GROUP) % locals()
1196 01ac12d5 Sofia Papagiannaki
        messages.success(request, msg)
1197 ae497612 Olga Brani
    except AssertionError:
1198 ae497612 Olga Brani
        msg = _(astakos_messages.GROUP_MAX_PARTICIPANT_NUMBER_REACHED)
1199 ae497612 Olga Brani
        messages.error(request, msg)
1200 01ac12d5 Sofia Papagiannaki
    except BaseException, e:
1201 01ac12d5 Sofia Papagiannaki
        logger.exception(e)
1202 56b1281c Sofia Papagiannaki
        realname = membership.person.realname
1203 ae497612 Olga Brani
        msg = _(astakos_messages.GENERIC_ERROR)
1204 01ac12d5 Sofia Papagiannaki
        messages.error(request, msg)
1205 5ce3ce4f Sofia Papagiannaki
1206 5ce3ce4f Sofia Papagiannaki
1207 01ac12d5 Sofia Papagiannaki
@signed_terms_required
1208 01ac12d5 Sofia Papagiannaki
@login_required
1209 1eaeb5b6 Sofia Papagiannaki
@handle_membership
1210 01ac12d5 Sofia Papagiannaki
def disapprove_member(request, membership):
1211 01ac12d5 Sofia Papagiannaki
    try:
1212 01ac12d5 Sofia Papagiannaki
        membership.disapprove()
1213 01ac12d5 Sofia Papagiannaki
        realname = membership.person.realname
1214 ae497612 Olga Brani
        msg = MEMBER_REMOVED % realname
1215 01ac12d5 Sofia Papagiannaki
        messages.success(request, msg)
1216 01ac12d5 Sofia Papagiannaki
    except BaseException, e:
1217 01ac12d5 Sofia Papagiannaki
        logger.exception(e)
1218 ae497612 Olga Brani
        msg = _(astakos_messages.GENERIC_ERROR)
1219 01ac12d5 Sofia Papagiannaki
        messages.error(request, msg)
1220 ffb1e7a8 Sofia Papagiannaki
1221 5ce3ce4f Sofia Papagiannaki
1222 ae497612 Olga Brani
#@require_http_methods(["GET"])
1223 ae497612 Olga Brani
@require_http_methods(["POST", "GET"])
1224 ffb1e7a8 Sofia Papagiannaki
@signed_terms_required
1225 ffb1e7a8 Sofia Papagiannaki
@login_required
1226 ffb1e7a8 Sofia Papagiannaki
def resource_list(request):
1227 9a06d96f Olga Brani
#     if request.method == 'POST':
1228 9a06d96f Olga Brani
#         form = PickResourceForm(request.POST)
1229 9a06d96f Olga Brani
#         if form.is_valid():
1230 9a06d96f Olga Brani
#             r = form.cleaned_data.get('resource')
1231 9a06d96f Olga Brani
#             if r:
1232 9a06d96f Olga Brani
#                 groups = request.user.membership_set.only('group').filter(
1233 9a06d96f Olga Brani
#                     date_joined__isnull=False)
1234 9a06d96f Olga Brani
#                 groups = [g.group_id for g in groups]
1235 9a06d96f Olga Brani
#                 q = AstakosGroupQuota.objects.select_related().filter(
1236 9a06d96f Olga Brani
#                     resource=r, group__in=groups)
1237 9a06d96f Olga Brani
#     else:
1238 9a06d96f Olga Brani
#         form = PickResourceForm()
1239 9a06d96f Olga Brani
#         q = AstakosGroupQuota.objects.none()
1240 9a06d96f Olga Brani
#
1241 9a06d96f Olga Brani
#     return object_list(request, q,
1242 9a06d96f Olga Brani
#                        template_name='im/astakosuserquota_list.html',
1243 9a06d96f Olga Brani
#                        extra_context={'form': form, 'data':data})
1244 9a06d96f Olga Brani
1245 52343ac8 Olga Brani
    def with_class(entry):
1246 52343ac8 Olga Brani
        entry['load_class'] = 'red'
1247 52343ac8 Olga Brani
        max_value = float(entry['maxValue'])
1248 52343ac8 Olga Brani
        curr_value = float(entry['currValue'])
1249 639e0352 Olga Brani
        if max_value > 0 :
1250 639e0352 Olga Brani
           entry['ratio'] = (curr_value / max_value) * 100
1251 639e0352 Olga Brani
        else: 
1252 639e0352 Olga Brani
           entry['ratio'] = 0 
1253 52343ac8 Olga Brani
        if entry['ratio'] < 66:
1254 9a06d96f Olga Brani
            entry['load_class'] = 'yellow'
1255 52343ac8 Olga Brani
        if entry['ratio'] < 33:
1256 9a06d96f Olga Brani
            entry['load_class'] = 'green'
1257 9a06d96f Olga Brani
        return entry
1258 9a06d96f Olga Brani
1259 52343ac8 Olga Brani
    def pluralize(entry):
1260 9a06d96f Olga Brani
        entry['plural'] = engine.plural(entry.get('name'))
1261 9a06d96f Olga Brani
        return entry
1262 52343ac8 Olga Brani
1263 820b18e0 Sofia Papagiannaki
    result = callpoint.get_user_status(request.user.id)
1264 820b18e0 Sofia Papagiannaki
    if result.is_success:
1265 820b18e0 Sofia Papagiannaki
        backenddata = map(with_class, result.data)
1266 820b18e0 Sofia Papagiannaki
        data = map(pluralize, result.data)
1267 9a06d96f Olga Brani
    else:
1268 820b18e0 Sofia Papagiannaki
        data = None
1269 820b18e0 Sofia Papagiannaki
        messages.error(request, result.reason)
1270 3cbd5e47 Olga Brani
    resource_catalog = ResourcePresentation(RESOURCES_PRESENTATION_DATA)
1271 3cbd5e47 Olga Brani
    resource_catalog.update_from_result_report(result)
1272 3cbd5e47 Olga Brani
    
1273 3cbd5e47 Olga Brani
1274 3cbd5e47 Olga Brani
    
1275 9a06d96f Olga Brani
    return render_response('im/resource_list.html',
1276 9a06d96f Olga Brani
                           data=data,
1277 3cbd5e47 Olga Brani
                           context_instance=get_context(request),
1278 3cbd5e47 Olga Brani
                                       resource_catalog=resource_catalog,
1279 3cbd5e47 Olga Brani
                           result=result)
1280 9a06d96f Olga Brani
1281 1b866d9e Olga Brani
1282 4b7d68f0 Olga Brani
def group_create_list(request):
1283 9eafaa32 Sofia Papagiannaki
    form = PickResourceForm()
1284 4b7d68f0 Olga Brani
    return render_response(
1285 4b7d68f0 Olga Brani
        template='im/astakosgroup_create_list.html',
1286 032ade79 Sofia Papagiannaki
        context_instance=get_context(request),)
1287 6e029beb Sofia Papagiannaki
1288 5ce3ce4f Sofia Papagiannaki
1289 ae497612 Olga Brani
#@require_http_methods(["GET"])
1290 ae497612 Olga Brani
@require_http_methods(["POST", "GET"])
1291 6e029beb Sofia Papagiannaki
@signed_terms_required
1292 6e029beb Sofia Papagiannaki
@login_required
1293 6e029beb Sofia Papagiannaki
def billing(request):
1294 9a06d96f Olga Brani
1295 6e029beb Sofia Papagiannaki
    today = datetime.today()
1296 9a06d96f Olga Brani
    month_last_day = calendar.monthrange(today.year, today.month)[1]
1297 9a06d96f Olga Brani
    data['resources'] = map(with_class, data['resources'])
1298 5056da3d Olga Brani
    start = request.POST.get('datefrom', None)
1299 5056da3d Olga Brani
    if start:
1300 5056da3d Olga Brani
        today = datetime.fromtimestamp(int(start))
1301 9a06d96f Olga Brani
        month_last_day = calendar.monthrange(today.year, today.month)[1]
1302 9a06d96f Olga Brani
1303 6e029beb Sofia Papagiannaki
    start = datetime(today.year, today.month, 1).strftime("%s")
1304 6e029beb Sofia Papagiannaki
    end = datetime(today.year, today.month, month_last_day).strftime("%s")
1305 4de59eac Olga Brani
    r = request_billing.apply(args=('pgerakios@grnet.gr',
1306 5ce3ce4f Sofia Papagiannaki
                                    int(start) * 1000,
1307 5056da3d Olga Brani
                                    int(end) * 1000))
1308 5056da3d Olga Brani
    data = {}
1309 9a06d96f Olga Brani
1310 6e029beb Sofia Papagiannaki
    try:
1311 6e029beb Sofia Papagiannaki
        status, data = r.result
1312 9a06d96f Olga Brani
        data = _clear_billing_data(data)
1313 6e029beb Sofia Papagiannaki
        if status != 200:
1314 ae497612 Olga Brani
            messages.error(request, _(astakos_messages.BILLING_ERROR) % status)
1315 6e029beb Sofia Papagiannaki
    except:
1316 6e029beb Sofia Papagiannaki
        messages.error(request, r.result)
1317 9a06d96f Olga Brani
1318 5056da3d Olga Brani
    print type(start)
1319 9a06d96f Olga Brani
1320 6e029beb Sofia Papagiannaki
    return render_response(
1321 6e029beb Sofia Papagiannaki
        template='im/billing.html',
1322 6e029beb Sofia Papagiannaki
        context_instance=get_context(request),
1323 5056da3d Olga Brani
        data=data,
1324 9a06d96f Olga Brani
        zerodate=datetime(month=1, year=1970, day=1),
1325 5056da3d Olga Brani
        today=today,
1326 5056da3d Olga Brani
        start=int(start),
1327 9a06d96f Olga Brani
        month_last_day=month_last_day)
1328 9a06d96f Olga Brani
1329 9a06d96f Olga Brani
1330 0f225db4 Sofia Papagiannaki
def _clear_billing_data(data):
1331 9a06d96f Olga Brani
1332 5056da3d Olga Brani
    # remove addcredits entries
1333 5056da3d Olga Brani
    def isnotcredit(e):
1334 5056da3d Olga Brani
        return e['serviceName'] != "addcredits"
1335 9a06d96f Olga Brani
1336 9a06d96f Olga Brani
    # separate services
1337 5056da3d Olga Brani
    def servicefilter(service_name):
1338 5056da3d Olga Brani
        service = service_name
1339 9a06d96f Olga Brani
1340 5056da3d Olga Brani
        def fltr(e):
1341 5056da3d Olga Brani
            return e['serviceName'] == service
1342 5056da3d Olga Brani
        return fltr
1343 9a06d96f Olga Brani
1344 5056da3d Olga Brani
    data['bill_nocredits'] = filter(isnotcredit, data['bill'])
1345 5056da3d Olga Brani
    data['bill_vmtime'] = filter(servicefilter('vmtime'), data['bill'])
1346 5056da3d Olga Brani
    data['bill_diskspace'] = filter(servicefilter('diskspace'), data['bill'])
1347 4de59eac Olga Brani
    data['bill_addcredits'] = filter(servicefilter('addcredits'), data['bill'])
1348 54213d7a Sofia Papagiannaki
1349 9a06d96f Olga Brani
    return data
1350 1b866d9e Olga Brani
     
1351 1b866d9e Olga Brani
     
1352 ae497612 Olga Brani
#@require_http_methods(["GET"])
1353 ae497612 Olga Brani
@require_http_methods(["POST", "GET"])
1354 3bcad004 Sofia Papagiannaki
@signed_terms_required
1355 3bcad004 Sofia Papagiannaki
@login_required
1356 54213d7a Sofia Papagiannaki
def timeline(request):
1357 88305cf0 root
#    data = {'entity':request.user.email}
1358 2925e285 root
    timeline_body = ()
1359 2925e285 root
    timeline_header = ()
1360 88305cf0 root
#    form = TimelineForm(data)
1361 88305cf0 root
    form = TimelineForm()
1362 54213d7a Sofia Papagiannaki
    if request.method == 'POST':
1363 54213d7a Sofia Papagiannaki
        data = request.POST
1364 2925e285 root
        form = TimelineForm(data)
1365 2925e285 root
        if form.is_valid():
1366 2925e285 root
            data = form.cleaned_data
1367 2925e285 root
            timeline_header = ('entity', 'resource',
1368 2925e285 root
                               'event name', 'event date',
1369 2925e285 root
                               'incremental cost', 'total cost')
1370 2925e285 root
            timeline_body = timeline_charge(
1371 9a06d96f Olga Brani
                data['entity'], data['resource'],
1372 9a06d96f Olga Brani
                data['start_date'], data['end_date'],
1373 9a06d96f Olga Brani
                data['details'], data['operation'])
1374 9a06d96f Olga Brani
1375 54213d7a Sofia Papagiannaki
    return render_response(template='im/timeline.html',
1376 54213d7a Sofia Papagiannaki
                           context_instance=get_context(request),
1377 54213d7a Sofia Papagiannaki
                           form=form,
1378 c3f6cdf1 root
                           timeline_header=timeline_header,
1379 c3f6cdf1 root
                           timeline_body=timeline_body)
1380 7c76af95 Olga Brani
    return data