Update LowerCaseCharField to subclass proper CharField
[ganeti_webmgr.git] / muddle_users / views / user.py
blob47ce5f7c1067883214a70d7f88827c0077c6f734
1 # Copyright (C) 2010 Oregon State University et al.
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
16 # USA.
18 from django import forms
19 from django.contrib import messages
20 from django.contrib.auth.decorators import login_required
21 from django.contrib.auth.forms import UserCreationForm, UserChangeForm, SetPasswordForm
22 from django.contrib.auth.models import User, Group
23 from django.core.urlresolvers import reverse
24 from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden
25 from django.shortcuts import get_object_or_404, render_to_response
26 from django.template import RequestContext,loader
27 from django.utils.translation import ugettext as _
28 from django.utils.translation import ugettext_lazy
31 def render_403(request, message):
32 """
33 Render a 403 response
34 """
35 template = loader.get_template('403.html')
36 context = RequestContext(request, {
37 'message': message,
39 return HttpResponseForbidden(template.render(context))
42 class CustomUserCreationForm(UserCreationForm):
43 email = forms.EmailField(label=_("Email Address"), max_length=100)
46 @login_required
47 def user_list(request, template="user/list.html"):
48 user = request.user
49 if not user.is_superuser:
50 return render_403(request, _('Only a superuser may view all users.'))
52 users = User.objects.all()
54 return render_to_response(template, {
55 'userlist':users
57 context_instance=RequestContext(request),
61 @login_required
62 def user_add(request, template="user/edit.html"):
63 user = request.user
64 if not user.is_superuser:
65 return render_403(request, _('Only a superuser may add a user.'))
67 if request.method == "POST":
68 form = CustomUserCreationForm(request.POST)
69 if form.is_valid():
70 data = form.cleaned_data
71 new_user = User(username=data['username'])
72 new_user.set_password(data['password2'])
73 new_user.email=data['email']
74 new_user.save()
75 return HttpResponseRedirect(new_user.get_absolute_url())
77 else:
78 form = CustomUserCreationForm()
80 return render_to_response(template, {
81 'form':form,
83 context_instance=RequestContext(request),
87 @login_required
88 def user_detail(request, username=None, user_id=None, template="user/detail.html"):
89 user = request.user
90 if not user.is_superuser:
91 return render_403(request, _('Only a superuser may view a user.'))
93 if username:
94 user = get_object_or_404(User, username=username)
95 user_id = user.id
96 elif user_id:
97 user = get_object_or_404(User, id=user_id)
99 groups = Group.objects.filter(user=user_id)
100 return render_to_response(template, {
101 'user_detail':user,
102 'groups':groups,
104 context_instance=RequestContext(request),
108 @login_required
109 def user_edit(request, user_id=None, template="user/edit.html"):
110 user = request.user
111 if not user.is_superuser:
112 return render_403(request, _('Only a superuser may edit a user.'))
114 user_edit = get_object_or_404(User, id=user_id)
116 if request.method == "POST":
117 form = UserEditForm(data=request.POST, instance=user_edit)
118 if form.is_valid():
119 form.save()
120 return HttpResponseRedirect(user_edit.get_absolute_url())
122 elif request.method == "DELETE":
123 user_edit.delete()
124 return HttpResponse('1', mimetype='application/json')
126 else:
127 form = UserEditForm(instance=user_edit)
129 return render_to_response(template, {
130 'form':form,
131 'user_edit':user_edit,
133 context_instance=RequestContext(request),
137 @login_required
138 def user_password(request, user_id=None, template="user/password.html"):
139 user = request.user
140 if not user.is_superuser:
141 return render_403(request, _('Only superusers have access to the change \
142 password form.'))
144 user_edit = get_object_or_404(User, id=user_id)
146 if request.method == "POST":
147 form = SetPasswordForm(user=user_edit, data=request.POST)
148 if form.is_valid():
149 form.save()
150 return HttpResponseRedirect(reverse('user-list'))
151 else:
152 form = SetPasswordForm(user=user_edit)
154 return render_to_response(template, {
155 'form':form,
156 'username':user_edit,
158 context_instance=RequestContext(request),
162 @login_required
163 def user_profile(request, template='user/profile.html'):
165 Form for editing a User's Profile
167 form = None
168 user = request.user
169 if request.method == 'POST':
170 form = UserProfileForm(request.POST)
171 form.user = user
172 if form.is_valid():
173 data = form.cleaned_data
174 user.email = data['email']
175 if data['new_password']:
176 user.set_password(data['new_password'])
177 user.save()
178 user.get_profile().save()
179 form = None
180 messages.add_message(request, messages.SUCCESS,
181 _('Saved successfully'))
183 if not form:
185 form = UserProfileForm(initial={'email':user.email,
186 'old_password':'',
189 return render_to_response(template,
190 {'form':form},
191 context_instance=RequestContext(request))
194 class UserEditForm(UserChangeForm):
196 Form for editing users.
198 This form is here solely to eliminate most of the user fields so that they
199 cannot be edited frivolously.
202 class Meta(UserChangeForm.Meta):
203 fields = (
204 'username',
205 'email',
206 'is_active',
207 'is_superuser',
208 # Don't worry, UserChangeForm blanks out this field, but we must
209 # permit it to be displayed in order to keep UserChangeForm's
210 # clean() happy.
211 "password",
215 class UserProfileForm(forms.Form):
217 Form for editing a User's Profile
219 email = forms.EmailField(label=ugettext_lazy('E-mail'))
220 old_password = forms.CharField(label=ugettext_lazy('Old password'), required=False, widget=forms.PasswordInput)
221 new_password = forms.CharField(label=ugettext_lazy('New password'), required=False, widget=forms.PasswordInput)
222 confirm_password = forms.CharField(label=ugettext_lazy('Confirm password'), required=False, widget=forms.PasswordInput)
224 # needed to verify the user's password
225 user = None
227 def clean(self):
229 Overridden to add password change verification
231 data = self.cleaned_data
232 old = data.get('old_password')
233 new = data.get('new_password')
234 confirm = data.get('confirm_password')
236 if new or confirm:
237 if not self.user.check_password(old):
238 del data['old_password']
239 msg = _('Old Password is incorrect')
240 self._errors['old_password'] = self.error_class([msg])
242 if not new:
243 if 'new_password' in data: del data['new_password']
244 msg = _('Enter a new password')
245 self._errors['new_password'] = self.error_class([msg])
247 if not confirm:
248 if 'confirm_password' in data: del data['confirm_password']
249 msg = _('Confirm new password')
250 self._errors['confirm_password'] = self.error_class([msg])
252 if new and confirm and new != confirm:
253 del data['new_password']
254 del data['confirm_password']
255 msg = _('New passwords do not match')
256 self._errors['new_password'] = self.error_class([msg])
258 return data