cc1  v2.1
CC1 source code docs
 All Classes Namespaces Files Functions Variables Pages
user.py
Go to the documentation of this file.
1 # -*- coding: utf-8 -*-
2 # @COPYRIGHT_begin
3 #
4 # Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18 # @COPYRIGHT_end
19 
20 ##
21 # @package src.wi.views.guest.user
22 #
23 # @author Piotr W√≥jcik
24 # @date 1.10.2010
25 #
26 
27 import re
28 
29 from django.conf import settings
30 from django.contrib.sites.models import RequestSite
31 from django.core.urlresolvers import reverse
32 from django.http import Http404, HttpResponseRedirect
33 from django.shortcuts import render_to_response, redirect
34 from django.template import RequestContext
35 from django.utils.http import base36_to_int
36 from django.utils.translation import ugettext as _
37 from django.views.decorators.cache import never_cache
38 from django.views.decorators.csrf import csrf_protect
39 
40 from common.states import registration_states
41 from wi.forms.user import AuthenticationForm, SetPasswordForm, PasswordResetForm, RegistrationForm
42 from wi.utils import REDIRECT_FIELD_NAME
43 from wi.utils.decorators import django_view
44 from wi.utils.registration import register, activate
45 from wi.utils.views import prep_data
46 
47 
48 @django_view
49 @csrf_protect
50 @never_cache
51 ##
52 #
53 # Login page handling.
54 #
55 def login(request, template_name='auth/login.html', redirect_field_name=REDIRECT_FIELD_NAME,
56  authentication_form=AuthenticationForm):
57 
58  redirect_to = request.REQUEST.get(redirect_field_name, '')
59  if request.method == 'POST':
60  form = authentication_form(data=request.POST)
61  if form.is_valid():
62  from wi.utils.auth import login as auth_login
63 
64  # Light security check -- make sure redirect_to isn't garbage.
65  if not redirect_to or ' ' in redirect_to:
66  redirect_to = settings.LOGIN_REDIRECT_URL
67 
68  # Heavier security check -- redirects to http://example.com should
69  # not be allowed, but things like /view/?param=http://example.com
70  # should be allowed. This regex checks if there is a '//' *before*
71  # a question mark.
72  elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
73  redirect_to = settings.LOGIN_REDIRECT_URL
74 
75  # Okay, security checks complete. Log the user in.
76  user = form.get_user()
77  user.set_password(form.cleaned_data['password'])
78  auth_login(request, user)
79 
80  if request.session.test_cookie_worked():
81  request.session.delete_test_cookie()
82 
83  return HttpResponseRedirect(redirect_to)
84  else:
85  form = authentication_form(request)
86 
87  if ('user' in request.session):
88  return HttpResponseRedirect(reverse('mai_main'))
89 
90  request.session.set_test_cookie()
91  current_site = RequestSite(request)
92  return render_to_response(template_name,
93  {'form': form,
94  redirect_field_name: redirect_to,
95  'site': current_site,
96  'site_name': current_site.name},
97  context_instance=RequestContext(request))
98 
99 
100 @django_view
101 ##
102 #
103 # Logout and redirection to the right next page (\c next_page).
104 #
105 def logout(request, next_page=None, template_name='auth/logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME):
106  from wi.utils.auth import logout as auth_logout
107  auth_logout(request.session)
108  if next_page is None:
109  redirect_to = request.REQUEST.get(redirect_field_name, '')
110  if redirect_to:
111  return HttpResponseRedirect(redirect_to)
112  else:
113  return render_to_response(template_name, {'title': _('Logged out')}, context_instance=RequestContext(request))
114  else:
115  # Redirect to this page until the session has been cleared.
116  return HttpResponseRedirect(next_page or request.path)
117 
118 
119 @django_view
120 @csrf_protect
121 ##
122 #
123 # <b>Password reset</b> form handling (email is sent).
124 #
125 # @parameter{request}
126 # @parameter{template_name} optional
127 # @parameter{password_reset_form} optional
128 #
129 def acc_password_reset(request, template_name='account/password_reset_form.html', password_reset_form=PasswordResetForm):
130  if request.method == "POST":
131  form = password_reset_form(request.POST)
132  if form.is_valid():
133  try:
134  dictionary = {'email': form.cleaned_data['email'], 'wi_data': settings.WI_DATA}
135  prep_data(('guest/user/reset_password_mail/', dictionary), request.session)
136  except Exception:
137  return redirect('acc_password_reset_error')
138 
139  return redirect('acc_password_reset_done')
140  else:
141  form = password_reset_form()
142 
143  rest_data = prep_data('guest/user/is_mailer_active/', request.session)
144 
145  return render_to_response(template_name, dict({'form': form}.items() + rest_data.items()),
146  context_instance=RequestContext(request))
147 
148 
149 # Doesn't need csrf_protect since no-one can guess the URL
150 @django_view
151 ##
152 #
153 # Check whether given address hash is correct. Displayes <b>password edition</b> form.
154 #
155 # @code
156 # acc_password_reset_confirm(request,
157 # uidb36=None,
158 # token=None,
159 # template_name='account/password_reset_confirm.html',
160 # form_class=SetPasswordForm)
161 # @endcode
162 #
163 # @parameter{request}
164 # @parameter{uidb36} optional
165 # @parameter{token} optional
166 # @parameter{template_name} optional
167 # @parameter{form_class} optional
168 #
169 def acc_password_reset_confirm(request, uidb36=None, token=None,
170  template_name='account/password_reset_confirm.html',
171  form_class=SetPasswordForm):
172  assert uidb36 is not None and token is not None # checked by URLconf
173  try:
174  uid_int = base36_to_int(uidb36)
175  except ValueError:
176  raise Http404
177 
178  if request.method == 'POST':
179  form = form_class(request.POST)
180  if form.is_valid():
181  dictionary = {'user_id': uid_int, 'token': token, 'new_password': form.cleaned_data['new_password1']}
182  try:
183  prep_data(('guest/user/set_password_token/', dictionary), request.session)
184  except Exception:
185  return redirect('acc_password_reset_error_token')
186 
187  return redirect('acc_password_reset_complete')
188  else:
189  try:
190  prep_data(('guest/user/check_token/', {'user_id': uid_int, 'token': token}), request.session)
191  except Exception:
192  return redirect('acc_password_reset_error_token')
193  form = form_class()
194 
195  return render_to_response(template_name, {'form': form}, context_instance=RequestContext(request))
196 
197 
198 @django_view
199 ##
200 #
201 # Help main page.
202 #
203 def hlp_help(request, template_name='help/base.html'):
204  rest_data = prep_data('guest/user/is_mailer_active/', request.session)
205  return render_to_response(template_name, rest_data, context_instance=RequestContext(request))
206 
207 
208 @django_view
209 ##
210 #
211 # View changing page language.
212 #
213 def change_language(request, lang, success_url='mai_main'):
214  request.session['django_language'] = lang
215  request.session['_language'] = lang
216  request.session.modified = True
217 
218  return redirect(request.META['HTTP_REFERER'] or success_url)
219 
220 
221 @django_view
222 ##
223 #
224 # Registration form's handling.
225 #
226 def reg_register(request, form_class=RegistrationForm, template_name='registration/registration_form.html'):
227  if request.method == 'POST':
228  form = form_class(data=request.POST)
229  if form.is_valid():
230  response = register(**form.cleaned_data)
231 
232  if response['status'] != 'ok':
233  import logging
234  wi_logger = logging.getLogger('wi_logger')
235  wi_logger.error('Registration error: %s' % response['status'])
236  wi_logger.error(response['data'])
237 
238  return redirect('registration_error')
239 
240  if response['data']['registration_state'] == registration_states['completed']:
241  return redirect('registration_completed')
242 
243  if response['data']['registration_state'] == registration_states['mail_confirmation']:
244  return redirect('registration_mail_confirmation')
245 
246  if response['data']['registration_state'] == registration_states['admin_confirmation']:
247  return redirect('registration_admin_confirmation')
248  else:
249  form = form_class()
250 
251  return render_to_response(template_name, {'form': form}, RequestContext(request))
252 
253 
254 @django_view
255 ##
256 #
257 # User's email address's confirmation (by entering the HTTP address provided in email message).
258 #
259 def reg_activate(request, **kwargs):
260  act_response = activate(**kwargs)
261  if act_response:
262  if act_response['data']['registration_state'] == registration_states['completed']:
263  return redirect('activation_completed')
264 
265  if act_response['data']['registration_state'] == registration_states['admin_confirmation']:
266  return redirect('activation_admin_confirmation')
267 
268  return redirect('activation_error')
269