Merge remote-tracking branch 'refs/remotes/rodney757/file_limits'
[mediagoblin.git] / mediagoblin / edit / views.py
CommitLineData
9bfe1d8e 1# GNU MediaGoblin -- federated, autonomous media hosting
cf29e8a8 2# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
9bfe1d8e
E
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/>.
aba81c9f 16
3a8c3a38
JW
17from datetime import datetime
18
377db0e7 19from itsdangerous import BadSignature
62d14bf5 20from werkzeug.exceptions import Forbidden
3a8c3a38 21from werkzeug.utils import secure_filename
aba81c9f 22
d9ed098e 23from mediagoblin import messages
10d7496d 24from mediagoblin import mg_globals
152a3bfa 25
d54cf48a 26from mediagoblin import auth
61741697 27from mediagoblin.auth import tools as auth_tools
aba81c9f 28from mediagoblin.edit import forms
b5a64f78 29from mediagoblin.edit.lib import may_edit_media
abc4da29 30from mediagoblin.decorators import (require_active_login, active_user_from_url,
89e1563f
RE
31 get_media_entry_by_id, user_may_alter_collection,
32 get_user_collection)
33from mediagoblin.tools.crypto import get_timed_signer_url
af4414a8 34from mediagoblin.tools.mail import email_debug_message
89e1563f
RE
35from mediagoblin.tools.response import (render_to_response,
36 redirect, redirect_obj, render_404)
5ae0cbaa 37from mediagoblin.tools.translate import pass_to_ugettext as _
89e1563f 38from mediagoblin.tools.template import render_template
152a3bfa 39from mediagoblin.tools.text import (
a855e92a 40 convert_to_tag_list_of_dicts, media_tags_as_string)
9e9d9083 41from mediagoblin.tools.url import slugify
be5be115 42from mediagoblin.db.util import check_media_slug_used, check_collection_slug_used
89e1563f 43from mediagoblin.db.models import User
c849e690 44
825b1362
JW
45import mimetypes
46
97ec97db 47
461dd971 48@get_media_entry_by_id
aba81c9f
E
49@require_active_login
50def edit_media(request, media):
c849e690 51 if not may_edit_media(request, media):
cfa92229 52 raise Forbidden("User may not edit this media")
c849e690 53
2c437493 54 defaults = dict(
ec82fbd8 55 title=media.title,
5da0bf90 56 slug=media.slug,
1d939966 57 description=media.description,
a6c49d49 58 tags=media_tags_as_string(media.tags),
97ec97db 59 license=media.license)
aba81c9f 60
2c437493 61 form = forms.EditForm(
111a609d 62 request.form,
2c437493
JW
63 **defaults)
64
98857207 65 if request.method == 'POST' and form.validate():
d5e90fe4
CAW
66 # Make sure there isn't already a MediaEntry with such a slug
67 # and userid.
dc03850b 68 slug = slugify(form.slug.data)
9e9d9083 69 slug_used = check_media_slug_used(media.uploader, slug, media.id)
3a8c3a38 70
b62b3b98 71 if slug_used:
d5e90fe4 72 form.slug.errors.append(
4b1adc13 73 _(u'An entry with that slug already exists for this user.'))
d5e90fe4 74 else:
dc03850b
HL
75 media.title = form.title.data
76 media.description = form.description.data
de917303 77 media.tags = convert_to_tag_list_of_dicts(
dc03850b 78 form.tags.data)
3a8c3a38 79
dc03850b 80 media.license = unicode(form.license.data) or None
9e9d9083 81 media.slug = slug
747623cc 82 media.save()
d5e90fe4 83
2e6ee596 84 return redirect_obj(request, media)
98857207 85
bec591d8 86 if request.user.is_admin \
5c2b8486 87 and media.uploader != request.user.id \
96a2c366
CAW
88 and request.method != 'POST':
89 messages.add_message(
90 request, messages.WARNING,
4b1adc13 91 _("You are editing another user's media. Proceed with caution."))
96a2c366 92
9038c9f9
CAW
93 return render_to_response(
94 request,
c9c24934
E
95 'mediagoblin/edit/edit.html',
96 {'media': media,
97 'form': form})
46fd661e 98
3a8c3a38 99
825b1362
JW
100# Mimetypes that browsers parse scripts in.
101# Content-sniffing isn't taken into consideration.
102UNSAFE_MIMETYPES = [
103 'text/html',
104 'text/svg+xml']
105
106
954b407c 107@get_media_entry_by_id
630b57a3 108@require_active_login
3a8c3a38
JW
109def edit_attachments(request, media):
110 if mg_globals.app_config['allow_attachments']:
111 form = forms.EditAttachmentsForm()
112
113 # Add any attachements
c43f8c1d
JW
114 if 'attachment_file' in request.files \
115 and request.files['attachment_file']:
3a8c3a38 116
825b1362
JW
117 # Security measure to prevent attachments from being served as
118 # text/html, which will be parsed by web clients and pose an XSS
119 # threat.
120 #
121 # TODO
122 # This method isn't flawless as some browsers may perform
123 # content-sniffing.
124 # This method isn't flawless as we do the mimetype lookup on the
125 # machine parsing the upload form, and not necessarily the machine
126 # serving the attachments.
127 if mimetypes.guess_type(
c43f8c1d 128 request.files['attachment_file'].filename)[0] in \
825b1362
JW
129 UNSAFE_MIMETYPES:
130 public_filename = secure_filename('{0}.notsafe'.format(
c43f8c1d 131 request.files['attachment_file'].filename))
825b1362
JW
132 else:
133 public_filename = secure_filename(
c43f8c1d 134 request.files['attachment_file'].filename)
825b1362 135
3a8c3a38
JW
136 attachment_public_filepath \
137 = mg_globals.public_store.get_unique_filepath(
5c2b8486 138 ['media_entries', unicode(media.id), 'attachment',
825b1362 139 public_filename])
3a8c3a38
JW
140
141 attachment_public_file = mg_globals.public_store.get_file(
142 attachment_public_filepath, 'wb')
143
144 try:
145 attachment_public_file.write(
c43f8c1d 146 request.files['attachment_file'].stream.read())
3a8c3a38 147 finally:
c43f8c1d 148 request.files['attachment_file'].stream.close()
3a8c3a38 149
35029581 150 media.attachment_files.append(dict(
dc03850b 151 name=form.attachment_name.data \
c43f8c1d 152 or request.files['attachment_file'].filename,
3a8c3a38 153 filepath=attachment_public_filepath,
243c3843 154 created=datetime.utcnow(),
3a8c3a38 155 ))
630b57a3 156
3a8c3a38
JW
157 media.save()
158
159 messages.add_message(
160 request, messages.SUCCESS,
32255ec0 161 _("You added the attachment %s!") \
dc03850b 162 % (form.attachment_name.data
c43f8c1d 163 or request.files['attachment_file'].filename))
3a8c3a38 164
950124e6
SS
165 return redirect(request,
166 location=media.url_for_self(request.urlgen))
3a8c3a38
JW
167 return render_to_response(
168 request,
169 'mediagoblin/edit/attachments.html',
170 {'media': media,
171 'form': form})
172 else:
cfa92229 173 raise Forbidden("Attachments are disabled")
3a8c3a38 174
abc4da29
SS
175@require_active_login
176def legacy_edit_profile(request):
177 """redirect the old /edit/profile/?username=USER to /u/USER/edit/"""
178 username = request.GET.get('username') or request.user.username
179 return redirect(request, 'mediagoblin.edit.profile', user=username)
180
3a8c3a38
JW
181
182@require_active_login
abc4da29
SS
183@active_user_from_url
184def edit_profile(request, url_user=None):
185 # admins may edit any user profile
186 if request.user.username != url_user.username:
187 if not request.user.is_admin:
188 raise Forbidden(_("You can only edit your own profile."))
189
a0cf14fe
CFD
190 # No need to warn again if admin just submitted an edited profile
191 if request.method != 'POST':
192 messages.add_message(
193 request, messages.WARNING,
4b1adc13 194 _("You are editing a user's profile. Proceed with caution."))
abc4da29
SS
195
196 user = url_user
a0cf14fe 197
111a609d 198 form = forms.EditProfileForm(request.form,
066d49b2
SS
199 url=user.url,
200 bio=user.bio)
630b57a3 201
202 if request.method == 'POST' and form.validate():
dc03850b
HL
203 user.url = unicode(form.url.data)
204 user.bio = unicode(form.bio.data)
4c465852 205
c8071fa5 206 user.save()
630b57a3 207
c8071fa5
JS
208 messages.add_message(request,
209 messages.SUCCESS,
210 _("Profile changes saved"))
211 return redirect(request,
212 'mediagoblin.user_pages.user_home',
703d09b9 213 user=user.username)
630b57a3 214
215 return render_to_response(
216 request,
217 'mediagoblin/edit/edit_profile.html',
218 {'user': user,
219 'form': form})
c8071fa5 220
89e1563f
RE
221EMAIL_VERIFICATION_TEMPLATE = (
222 u'{uri}?'
223 u'token={verification_key}')
224
c8071fa5
JS
225
226@require_active_login
227def edit_account(request):
c8071fa5 228 user = request.user
111a609d 229 form = forms.EditAccountForm(request.form,
066d49b2 230 wants_comment_notification=user.wants_comment_notification,
93d805ad
RE
231 license_preference=user.license_preference,
232 wants_notifications=user.wants_notifications)
c8071fa5 233
89e1563f 234 if request.method == 'POST' and form.validate():
f670f48d 235 user.wants_comment_notification = form.wants_comment_notification.data
93d805ad 236 user.wants_notifications = form.wants_notifications.data
dc4dfbde 237
f670f48d 238 user.license_preference = form.license_preference.data
dc4dfbde 239
dd57c6c5
RE
240 user.save()
241 messages.add_message(request,
242 messages.SUCCESS,
243 _("Account settings saved"))
244 return redirect(request,
245 'mediagoblin.user_pages.user_home',
246 user=user.username)
630b57a3 247
248 return render_to_response(
249 request,
c8071fa5 250 'mediagoblin/edit/edit_account.html',
630b57a3 251 {'user': user,
252 'form': form})
be5be115
AW
253
254
380f22b8
SS
255@require_active_login
256def delete_account(request):
257 """Delete a user completely"""
258 user = request.user
259 if request.method == 'POST':
260 if request.form.get(u'confirmed'):
261 # Form submitted and confirmed. Actually delete the user account
262 # Log out user and delete cookies etc.
263 # TODO: Should we be using MG.auth.views.py:logout for this?
264 request.session.delete()
265
266 # Delete user account and all related media files etc....
267 request.user.delete()
268
269 # We should send a message that the user has been deleted
270 # successfully. But we just deleted the session, so we
271 # can't...
272 return redirect(request, 'index')
273
274 else: # Did not check the confirmation box...
275 messages.add_message(
276 request, messages.WARNING,
277 _('You need to confirm the deletion of your account.'))
278
279 # No POST submission or not confirmed, just show page
280 return render_to_response(
281 request,
282 'mediagoblin/edit/delete_account.html',
283 {'user': user})
284
285
be5be115
AW
286@require_active_login
287@user_may_alter_collection
288@get_user_collection
289def edit_collection(request, collection):
290 defaults = dict(
291 title=collection.title,
292 slug=collection.slug,
293 description=collection.description)
294
295 form = forms.EditCollectionForm(
111a609d 296 request.form,
be5be115
AW
297 **defaults)
298
299 if request.method == 'POST' and form.validate():
300 # Make sure there isn't already a Collection with such a slug
301 # and userid.
455fd36f 302 slug_used = check_collection_slug_used(collection.creator,
dc03850b 303 form.slug.data, collection.id)
c43f8c1d 304
be5be115 305 # Make sure there isn't already a Collection with this title
44082b12
RE
306 existing_collection = request.db.Collection.query.filter_by(
307 creator=request.user.id,
308 title=form.title.data).first()
c43f8c1d 309
be5be115
AW
310 if existing_collection and existing_collection.id != collection.id:
311 messages.add_message(
a6481028
CAW
312 request, messages.ERROR,
313 _('You already have a collection called "%s"!') % \
dc03850b 314 form.title.data)
be5be115
AW
315 elif slug_used:
316 form.slug.errors.append(
317 _(u'A collection with that slug already exists for this user.'))
318 else:
dc03850b
HL
319 collection.title = unicode(form.title.data)
320 collection.description = unicode(form.description.data)
321 collection.slug = unicode(form.slug.data)
be5be115
AW
322
323 collection.save()
324
2e6ee596 325 return redirect_obj(request, collection)
be5be115
AW
326
327 if request.user.is_admin \
5c2b8486 328 and collection.creator != request.user.id \
be5be115
AW
329 and request.method != 'POST':
330 messages.add_message(
331 request, messages.WARNING,
332 _("You are editing another user's collection. Proceed with caution."))
333
334 return render_to_response(
335 request,
336 'mediagoblin/edit/edit_collection.html',
337 {'collection': collection,
338 'form': form})
39aa1db4
RE
339
340
341@require_active_login
342def change_pass(request):
5adb906a
RE
343 # If no password authentication, no need to change your password
344 if 'pass_auth' not in request.template_env.globals:
345 return redirect(request, 'index')
346
39aa1db4
RE
347 form = forms.ChangePassForm(request.form)
348 user = request.user
349
350 if request.method == 'POST' and form.validate():
351
9008e099 352 if not auth.check_password(
39aa1db4
RE
353 form.old_password.data, user.pw_hash):
354 form.old_password.errors.append(
355 _('Wrong password'))
356
357 return render_to_response(
358 request,
359 'mediagoblin/edit/change_pass.html',
360 {'form': form,
361 'user': user})
362
363 # Password matches
9008e099 364 user.pw_hash = auth.gen_password_hash(
39aa1db4
RE
365 form.new_password.data)
366 user.save()
367
368 messages.add_message(
369 request, messages.SUCCESS,
370 _('Your password was changed successfully'))
371
372 return redirect(request, 'mediagoblin.edit.account')
373
374 return render_to_response(
375 request,
376 'mediagoblin/edit/change_pass.html',
377 {'form': form,
378 'user': user})
89e1563f
RE
379
380
381def verify_email(request):
382 """
383 Email verification view for changing email address
384 """
385 # If no token, we can't do anything
386 if not 'token' in request.GET:
387 return render_404(request)
388
377db0e7
RE
389 # Catch error if token is faked or expired
390 token = None
391 try:
392 token = get_timed_signer_url("mail_verification_token") \
393 .loads(request.GET['token'], max_age=10*24*3600)
394 except BadSignature:
395 messages.add_message(
396 request,
397 messages.ERROR,
398 _('The verification key or user id is incorrect.'))
399
400 return redirect(
401 request,
402 'index')
89e1563f
RE
403
404 user = User.query.filter_by(id=int(token['user'])).first()
405
406 if user:
407 user.email = token['email']
408 user.save()
409
410 messages.add_message(
411 request,
412 messages.SUCCESS,
413 _('Your email address has been verified.'))
414
415 else:
416 messages.add_message(
417 request,
418 messages.ERROR,
419 _('The verification key or user id is incorrect.'))
420
421 return redirect(
422 request, 'mediagoblin.user_pages.user_home',
423 user=user.username)
5adb906a
RE
424
425
402f4360
RE
426def change_email(request):
427 """ View to change the user's email """
428 form = forms.ChangeEmailForm(request.form)
429 user = request.user
430
431 # If no password authentication, no need to enter a password
432 if 'pass_auth' not in request.template_env.globals or not user.pw_hash:
433 form.__delitem__('password')
434
435 if request.method == 'POST' and form.validate():
436 new_email = form.new_email.data
437 users_with_email = User.query.filter_by(
438 email=new_email).count()
439
440 if users_with_email:
441 form.new_email.errors.append(
442 _('Sorry, a user with that email address'
443 ' already exists.'))
444
5a6e4e13 445 if form.password and user.pw_hash and not auth.check_password(
402f4360
RE
446 form.password.data, user.pw_hash):
447 form.password.errors.append(
448 _('Wrong password'))
449
450 if not form.errors:
451 verification_key = get_timed_signer_url(
452 'mail_verification_token').dumps({
453 'user': user.id,
454 'email': new_email})
455
456 rendered_email = render_template(
457 request, 'mediagoblin/edit/verification.txt',
458 {'username': user.username,
459 'verification_url': EMAIL_VERIFICATION_TEMPLATE.format(
460 uri=request.urlgen('mediagoblin.edit.verify_email',
461 qualified=True),
462 verification_key=verification_key)})
463
464 email_debug_message(request)
465 auth_tools.send_verification_email(user, request, new_email,
466 rendered_email)
467
468 return redirect(request, 'mediagoblin.edit.account')
469
470 return render_to_response(
471 request,
472 'mediagoblin/edit/change_email.html',
473 {'form': form,
474 'user': user})