remove unnecessary imports
[mygpo.git] / mygpo / web / views / users.py
blob2215e958468840d69420d1a28bdec99a8caa6cc0
2 # This file is part of my.gpodder.org.
4 # my.gpodder.org is free software: you can redistribute it and/or modify it
5 # under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or (at your
7 # option) any later version.
9 # my.gpodder.org is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
12 # License for more details.
14 # You should have received a copy of the GNU Affero General Public License
15 # along with my.gpodder.org. If not, see <http://www.gnu.org/licenses/>.
18 from django.shortcuts import render_to_response
19 from django.http import HttpResponseRedirect
20 from django.contrib.auth import authenticate, login
21 from django.contrib.auth.decorators import login_required
22 from django.template.defaultfilters import slugify
23 from django.template import RequestContext
24 from mygpo.api.models import UserProfile
25 from mygpo.web.forms import RestorePasswordForm
26 from django.contrib.sites.models import Site
27 from django.conf import settings
28 from mygpo.decorators import manual_gc, allowed_methods
29 from django.utils.translation import ugettext as _
30 import string
31 import random
33 from mygpo.constants import DEFAULT_LOGIN_REDIRECT
35 def login_user(request):
36 # Do not show login page for already-logged-in users
37 if request.user.is_authenticated():
38 return HttpResponseRedirect(DEFAULT_LOGIN_REDIRECT)
40 if 'user' not in request.POST or 'pwd' not in request.POST:
41 if request.GET.get('restore_password', False):
42 form = RestorePasswordForm()
43 else:
44 form = None
46 return render_to_response('login.html', {
47 'url': Site.objects.get_current(),
48 'next': request.GET.get('next', ''),
49 'restore_password_form': form,
50 }, context_instance=RequestContext(request))
52 username = request.POST['user']
53 password = request.POST['pwd']
54 user = authenticate(username=username, password=password)
56 if user is None:
57 return render_to_response('login.html', {
58 'error_message': _('Wrong username or password.'),
59 'next': request.POST.get('next', ''),
60 }, context_instance=RequestContext(request))
62 if not user.is_active:
64 p, c = UserProfile.objects.get_or_create(user=user)
66 if p.deleted:
67 return render_to_response('login.html', {
68 'error_message': _('You have deleted your account, but you can register again')
69 }, context_instance=RequestContext(request))
71 else:
72 return render_to_response('login.html', {
73 'error_message': _('Please activate your account first.'),
74 'activation_needed': True,
75 }, context_instance=RequestContext(request))
77 login(request, user)
79 try:
80 if user.get_profile().generated_id:
81 site = Site.objects.get_current()
82 return render_to_response('migrate.html', {
83 'url': site,
84 'username': user
85 }, context_instance=RequestContext(request))
87 except UserProfile.DoesNotExist:
88 profile, c = UserProfile.objects.get_or_create(user=user)
90 if 'next' in request.POST and request.POST['next'] and request.POST['next'] != '/login/':
91 return HttpResponseRedirect(request.POST['next'])
93 return HttpResponseRedirect(DEFAULT_LOGIN_REDIRECT)
95 @login_required
96 def migrate_user(request):
97 user = request.user
98 username = request.POST.get('username', user.username)
100 if username == '':
101 username = user.username
103 if user.username != username:
104 current_site = Site.objects.get_current()
105 if User.objects.filter(username__exact=username).count() > 0:
106 return render_to_response('migrate.html', {
107 'error_message': '%s is already taken' % username,
108 'url': current_site,
109 'username': user.username
110 }, context_instance=RequestContext(request))
112 if slugify(username) != username.lower():
113 return render_to_response('migrate.html', {
114 'error_message': '%s is not a valid username. Please use characters, numbers, underscore and dash only.' % username,
115 'url': current_site,
116 'username': user.username
117 }, context_instance=RequestContext(request))
119 else:
120 user.username = username
121 user.save()
123 user.get_profile().generated_id = 0
124 user.get_profile().save()
126 return HttpResponseRedirect('/')
128 def get_user(username, email):
129 if username:
130 return User.objects.get(username=username)
131 elif email:
132 return User.objects.get(email=email)
133 else:
134 raise User.DoesNotExist('neither username nor email provided')
137 @allowed_methods(['POST'])
138 def restore_password(request):
139 form = RestorePasswordForm(request.POST)
140 if not form.is_valid():
141 return HttpResponseRedirect('/login/')
143 try:
144 user = get_user(form.cleaned_data['username'], form.cleaned_data['email'])
146 except User.DoesNotExist:
147 error_message = _('User does not exist.')
148 return render_to_response('password_reset_failed.html', {
149 'error_message': error_message
150 }, context_instance=RequestContext(request))
152 site = Site.objects.get_current()
153 pwd = "".join(random.sample(string.letters+string.digits, 8))
154 subject = _('Reset password for your account on %s') % site
155 message = _('Here is your new password for your account %(username)s on %(site)s: %(password)s') % {'username': user.username, 'site': site, 'password': pwd}
156 user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
157 user.set_password(pwd)
158 user.save()
159 return render_to_response('password_reset.html', context_instance=RequestContext(request))
162 @manual_gc
163 @allowed_methods(['GET', 'POST'])
164 def resend_activation(request):
165 error_message = ''
167 if request.method == 'GET':
168 form = ResendActivationForm()
169 return render_to_response('registration/resend_activation.html', {
170 'form': form,
171 }, context_instance=RequestContext(request))
173 site = Site.objects.get_current()
174 form = ResendActivationForm(request.POST)
176 try:
177 if not form.is_valid():
178 raise ValueError(_('Invalid Username entered'))
180 try:
181 user = get_user(form.cleaned_data['username'], form.cleaned_data['email'])
182 except User.DoesNotExist:
183 raise ValueError(_('User does not exist.'))
185 p, c = UserProfile.objects.get_or_create(user=user)
186 if p.deleted:
187 raise ValueError(_('You have deleted your account, but you can regster again.'))
189 try:
190 profile = RegistrationProfile.objects.get(user=user)
191 except RegistrationProfile.DoesNotExist:
192 profile = RegistrationProfile.objects.create_profile(user)
194 if profile.activation_key == RegistrationProfile.ACTIVATED:
195 user.is_active = True
196 user.save()
197 raise ValueError(_('Your account already has been activated. Go ahead and log in.'))
199 elif profile.activation_key_expired():
200 raise ValueError(_('Your activation key has expired. Please try another username, or retry with the same one tomorrow.'))
202 except ValueError, e:
203 return render_to_response('registration/resend_activation.html', {
204 'form': form,
205 'error_message' : e
206 }, context_instance=RequestContext(request))
209 try:
210 profile.send_activation_email(site)
212 except AttributeError:
213 #old versions of django-registration send registration mails from RegistrationManager
214 RegistrationProfile.objects.send_activation_email(profile, site)
216 return render_to_response('registration/resent_activation.html', context_instance=RequestContext(request))