Merge remote branch 'remotes/elrond/dev/storage_config'
[mediagoblin.git] / mediagoblin / auth / views.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011 Free Software Foundation, Inc
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it 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
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 import uuid
18
19 from webob import exc
20
21 from mediagoblin import messages
22 from mediagoblin import mg_globals
23 from mediagoblin.util import render_to_response, redirect, render_404
24 from mediagoblin.util import pass_to_ugettext as _
25 from mediagoblin.db.util import ObjectId
26 from mediagoblin.auth import lib as auth_lib
27 from mediagoblin.auth import forms as auth_forms
28 from mediagoblin.auth.lib import send_verification_email
29
30
31 def register(request):
32 """
33 Your classic registration view!
34 """
35 # Redirects to indexpage if registrations are disabled
36 if not mg_globals.app_config["allow_registration"]:
37 messages.add_message(
38 request,
39 messages.WARNING,
40 _('Sorry, registration is disabled on this instance.'))
41 return redirect(request, "index")
42
43 register_form = auth_forms.RegistrationForm(request.POST)
44
45 if request.method == 'POST' and register_form.validate():
46 # TODO: Make sure the user doesn't exist already
47
48 users_with_username = request.db.User.find(
49 {'username': request.POST['username'].lower()}).count()
50 users_with_email = request.db.User.find(
51 {'email': request.POST['email'].lower()}).count()
52
53 extra_validation_passes = True
54
55 if users_with_username:
56 register_form.username.errors.append(
57 _(u'Sorry, a user with that name already exists.'))
58 extra_validation_passes = False
59 if users_with_email:
60 register_form.email.errors.append(
61 _(u'Sorry, that email address has already been taken.'))
62 extra_validation_passes = False
63
64 if extra_validation_passes:
65 # Create the user
66 user = request.db.User()
67 user['username'] = request.POST['username'].lower()
68 user['email'] = request.POST['email'].lower()
69 user['pw_hash'] = auth_lib.bcrypt_gen_password_hash(
70 request.POST['password'])
71 user.save(validate=True)
72
73 # log the user in
74 request.session['user_id'] = unicode(user['_id'])
75 request.session.save()
76
77 # send verification email
78 send_verification_email(user, request)
79
80 # redirect the user to their homepage... there will be a
81 # message waiting for them to verify their email
82 return redirect(
83 request, 'mediagoblin.user_pages.user_home',
84 user=user['username'])
85
86 return render_to_response(
87 request,
88 'mediagoblin/auth/register.html',
89 {'register_form': register_form})
90
91
92 def login(request):
93 """
94 MediaGoblin login view.
95
96 If you provide the POST with 'next', it'll redirect to that view.
97 """
98 login_form = auth_forms.LoginForm(request.POST)
99
100 login_failed = False
101
102 if request.method == 'POST' and login_form.validate():
103 user = request.db.User.one(
104 {'username': request.POST['username'].lower()})
105
106 if user and user.check_login(request.POST['password']):
107 # set up login in session
108 request.session['user_id'] = unicode(user['_id'])
109 request.session.save()
110
111 if request.POST.get('next'):
112 return exc.HTTPFound(location=request.POST['next'])
113 else:
114 return redirect(request, "index")
115
116 else:
117 # Prevent detecting who's on this system by testing login
118 # attempt timings
119 auth_lib.fake_login_attempt()
120 login_failed = True
121
122 return render_to_response(
123 request,
124 'mediagoblin/auth/login.html',
125 {'login_form': login_form,
126 'next': request.GET.get('next') or request.POST.get('next'),
127 'login_failed': login_failed,
128 'allow_registration': mg_globals.app_config["allow_registration"]})
129
130
131 def logout(request):
132 # Maybe deleting the user_id parameter would be enough?
133 request.session.delete()
134
135 return redirect(request, "index")
136
137
138 def verify_email(request):
139 """
140 Email verification view
141
142 validates GET parameters against database and unlocks the user account, if
143 you are lucky :)
144 """
145 # If we don't have userid and token parameters, we can't do anything; 404
146 if not request.GET.has_key('userid') or not request.GET.has_key('token'):
147 return render_404(request)
148
149 user = request.db.User.find_one(
150 {'_id': ObjectId(unicode(request.GET['userid']))})
151
152 if user and user['verification_key'] == unicode(request.GET['token']):
153 user['status'] = u'active'
154 user['email_verified'] = True
155 user.save()
156 messages.add_message(
157 request,
158 messages.SUCCESS,
159 _("Your email address has been verified. "
160 "You may now login, edit your profile, and submit images!"))
161 else:
162 messages.add_message(
163 request,
164 messages.ERROR,
165 _('The verification key or user id is incorrect'))
166
167 return redirect(
168 request, 'mediagoblin.user_pages.user_home',
169 user=user['username'])
170
171
172 def resend_activation(request):
173 """
174 The reactivation view
175
176 Resend the activation email.
177 """
178 request.user['verification_key'] = unicode(uuid.uuid4())
179 request.user.save()
180
181 send_verification_email(request.user, request)
182
183 messages.add_message(
184 request,
185 messages.INFO,
186 _('Resent your verification email.'))
187 return redirect(
188 request, 'mediagoblin.user_pages.user_home',
189 user=request.user['username'])