added gen_password_hash and check_password functions to auth/__init__
[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
62d14bf5 19from werkzeug.exceptions import Forbidden
3a8c3a38 20from werkzeug.utils import secure_filename
aba81c9f 21
d9ed098e 22from mediagoblin import messages
10d7496d 23from mediagoblin import mg_globals
152a3bfa 24
d54cf48a 25from mediagoblin import auth
aba81c9f 26from mediagoblin.edit import forms
b5a64f78 27from mediagoblin.edit.lib import may_edit_media
abc4da29 28from mediagoblin.decorators import (require_active_login, active_user_from_url,
dc03850b 29 get_media_entry_by_id,
954b407c 30 user_may_alter_collection, get_user_collection)
2e6ee596
E
31from mediagoblin.tools.response import render_to_response, \
32 redirect, redirect_obj
5ae0cbaa 33from mediagoblin.tools.translate import pass_to_ugettext as _
152a3bfa 34from mediagoblin.tools.text import (
a855e92a 35 convert_to_tag_list_of_dicts, media_tags_as_string)
9e9d9083 36from mediagoblin.tools.url import slugify
be5be115 37from mediagoblin.db.util import check_media_slug_used, check_collection_slug_used
c849e690 38
825b1362
JW
39import mimetypes
40
97ec97db 41
461dd971 42@get_media_entry_by_id
aba81c9f
E
43@require_active_login
44def edit_media(request, media):
c849e690 45 if not may_edit_media(request, media):
cfa92229 46 raise Forbidden("User may not edit this media")
c849e690 47
2c437493 48 defaults = dict(
ec82fbd8 49 title=media.title,
5da0bf90 50 slug=media.slug,
1d939966 51 description=media.description,
a6c49d49 52 tags=media_tags_as_string(media.tags),
97ec97db 53 license=media.license)
aba81c9f 54
2c437493 55 form = forms.EditForm(
111a609d 56 request.form,
2c437493
JW
57 **defaults)
58
98857207 59 if request.method == 'POST' and form.validate():
d5e90fe4
CAW
60 # Make sure there isn't already a MediaEntry with such a slug
61 # and userid.
dc03850b 62 slug = slugify(form.slug.data)
9e9d9083 63 slug_used = check_media_slug_used(media.uploader, slug, media.id)
3a8c3a38 64
b62b3b98 65 if slug_used:
d5e90fe4 66 form.slug.errors.append(
4b1adc13 67 _(u'An entry with that slug already exists for this user.'))
d5e90fe4 68 else:
dc03850b
HL
69 media.title = form.title.data
70 media.description = form.description.data
de917303 71 media.tags = convert_to_tag_list_of_dicts(
dc03850b 72 form.tags.data)
3a8c3a38 73
dc03850b 74 media.license = unicode(form.license.data) or None
9e9d9083 75 media.slug = slug
747623cc 76 media.save()
d5e90fe4 77
2e6ee596 78 return redirect_obj(request, media)
98857207 79
bec591d8 80 if request.user.is_admin \
5c2b8486 81 and media.uploader != request.user.id \
96a2c366
CAW
82 and request.method != 'POST':
83 messages.add_message(
84 request, messages.WARNING,
4b1adc13 85 _("You are editing another user's media. Proceed with caution."))
96a2c366 86
9038c9f9
CAW
87 return render_to_response(
88 request,
c9c24934
E
89 'mediagoblin/edit/edit.html',
90 {'media': media,
91 'form': form})
46fd661e 92
3a8c3a38 93
825b1362
JW
94# Mimetypes that browsers parse scripts in.
95# Content-sniffing isn't taken into consideration.
96UNSAFE_MIMETYPES = [
97 'text/html',
98 'text/svg+xml']
99
100
954b407c 101@get_media_entry_by_id
630b57a3 102@require_active_login
3a8c3a38
JW
103def edit_attachments(request, media):
104 if mg_globals.app_config['allow_attachments']:
105 form = forms.EditAttachmentsForm()
106
107 # Add any attachements
c43f8c1d
JW
108 if 'attachment_file' in request.files \
109 and request.files['attachment_file']:
3a8c3a38 110
825b1362
JW
111 # Security measure to prevent attachments from being served as
112 # text/html, which will be parsed by web clients and pose an XSS
113 # threat.
114 #
115 # TODO
116 # This method isn't flawless as some browsers may perform
117 # content-sniffing.
118 # This method isn't flawless as we do the mimetype lookup on the
119 # machine parsing the upload form, and not necessarily the machine
120 # serving the attachments.
121 if mimetypes.guess_type(
c43f8c1d 122 request.files['attachment_file'].filename)[0] in \
825b1362
JW
123 UNSAFE_MIMETYPES:
124 public_filename = secure_filename('{0}.notsafe'.format(
c43f8c1d 125 request.files['attachment_file'].filename))
825b1362
JW
126 else:
127 public_filename = secure_filename(
c43f8c1d 128 request.files['attachment_file'].filename)
825b1362 129
3a8c3a38
JW
130 attachment_public_filepath \
131 = mg_globals.public_store.get_unique_filepath(
5c2b8486 132 ['media_entries', unicode(media.id), 'attachment',
825b1362 133 public_filename])
3a8c3a38
JW
134
135 attachment_public_file = mg_globals.public_store.get_file(
136 attachment_public_filepath, 'wb')
137
138 try:
139 attachment_public_file.write(
c43f8c1d 140 request.files['attachment_file'].stream.read())
3a8c3a38 141 finally:
c43f8c1d 142 request.files['attachment_file'].stream.close()
3a8c3a38 143
35029581 144 media.attachment_files.append(dict(
dc03850b 145 name=form.attachment_name.data \
c43f8c1d 146 or request.files['attachment_file'].filename,
3a8c3a38 147 filepath=attachment_public_filepath,
243c3843 148 created=datetime.utcnow(),
3a8c3a38 149 ))
630b57a3 150
3a8c3a38
JW
151 media.save()
152
153 messages.add_message(
154 request, messages.SUCCESS,
32255ec0 155 _("You added the attachment %s!") \
dc03850b 156 % (form.attachment_name.data
c43f8c1d 157 or request.files['attachment_file'].filename))
3a8c3a38 158
950124e6
SS
159 return redirect(request,
160 location=media.url_for_self(request.urlgen))
3a8c3a38
JW
161 return render_to_response(
162 request,
163 'mediagoblin/edit/attachments.html',
164 {'media': media,
165 'form': form})
166 else:
cfa92229 167 raise Forbidden("Attachments are disabled")
3a8c3a38 168
abc4da29
SS
169@require_active_login
170def legacy_edit_profile(request):
171 """redirect the old /edit/profile/?username=USER to /u/USER/edit/"""
172 username = request.GET.get('username') or request.user.username
173 return redirect(request, 'mediagoblin.edit.profile', user=username)
174
3a8c3a38
JW
175
176@require_active_login
abc4da29
SS
177@active_user_from_url
178def edit_profile(request, url_user=None):
179 # admins may edit any user profile
180 if request.user.username != url_user.username:
181 if not request.user.is_admin:
182 raise Forbidden(_("You can only edit your own profile."))
183
a0cf14fe
CFD
184 # No need to warn again if admin just submitted an edited profile
185 if request.method != 'POST':
186 messages.add_message(
187 request, messages.WARNING,
4b1adc13 188 _("You are editing a user's profile. Proceed with caution."))
abc4da29
SS
189
190 user = url_user
a0cf14fe 191
111a609d 192 form = forms.EditProfileForm(request.form,
066d49b2
SS
193 url=user.url,
194 bio=user.bio)
630b57a3 195
196 if request.method == 'POST' and form.validate():
dc03850b
HL
197 user.url = unicode(form.url.data)
198 user.bio = unicode(form.bio.data)
4c465852 199
c8071fa5 200 user.save()
630b57a3 201
c8071fa5
JS
202 messages.add_message(request,
203 messages.SUCCESS,
204 _("Profile changes saved"))
205 return redirect(request,
206 'mediagoblin.user_pages.user_home',
703d09b9 207 user=user.username)
630b57a3 208
209 return render_to_response(
210 request,
211 'mediagoblin/edit/edit_profile.html',
212 {'user': user,
213 'form': form})
c8071fa5
JS
214
215
216@require_active_login
217def edit_account(request):
c8071fa5 218 user = request.user
111a609d 219 form = forms.EditAccountForm(request.form,
066d49b2
SS
220 wants_comment_notification=user.wants_comment_notification,
221 license_preference=user.license_preference)
c8071fa5 222
252eaf21 223 if request.method == 'POST':
fa72e516
DM
224 form_validated = form.validate()
225
dc4dfbde
MH
226 if form_validated and \
227 form.wants_comment_notification.validate(form):
228 user.wants_comment_notification = \
229 form.wants_comment_notification.data
230
dc4dfbde
MH
231 if form_validated and \
232 form.license_preference.validate(form):
233 user.license_preference = \
234 form.license_preference.data
235
236 if form_validated and not form.errors:
237 user.save()
238 messages.add_message(request,
239 messages.SUCCESS,
240 _("Account settings saved"))
241 return redirect(request,
242 'mediagoblin.user_pages.user_home',
243 user=user.username)
630b57a3 244
245 return render_to_response(
246 request,
c8071fa5 247 'mediagoblin/edit/edit_account.html',
630b57a3 248 {'user': user,
249 'form': form})
be5be115
AW
250
251
380f22b8
SS
252@require_active_login
253def delete_account(request):
254 """Delete a user completely"""
255 user = request.user
256 if request.method == 'POST':
257 if request.form.get(u'confirmed'):
258 # Form submitted and confirmed. Actually delete the user account
259 # Log out user and delete cookies etc.
260 # TODO: Should we be using MG.auth.views.py:logout for this?
261 request.session.delete()
262
263 # Delete user account and all related media files etc....
264 request.user.delete()
265
266 # We should send a message that the user has been deleted
267 # successfully. But we just deleted the session, so we
268 # can't...
269 return redirect(request, 'index')
270
271 else: # Did not check the confirmation box...
272 messages.add_message(
273 request, messages.WARNING,
274 _('You need to confirm the deletion of your account.'))
275
276 # No POST submission or not confirmed, just show page
277 return render_to_response(
278 request,
279 'mediagoblin/edit/delete_account.html',
280 {'user': user})
281
282
be5be115
AW
283@require_active_login
284@user_may_alter_collection
285@get_user_collection
286def edit_collection(request, collection):
287 defaults = dict(
288 title=collection.title,
289 slug=collection.slug,
290 description=collection.description)
291
292 form = forms.EditCollectionForm(
111a609d 293 request.form,
be5be115
AW
294 **defaults)
295
296 if request.method == 'POST' and form.validate():
297 # Make sure there isn't already a Collection with such a slug
298 # and userid.
455fd36f 299 slug_used = check_collection_slug_used(collection.creator,
dc03850b 300 form.slug.data, collection.id)
c43f8c1d 301
be5be115
AW
302 # Make sure there isn't already a Collection with this title
303 existing_collection = request.db.Collection.find_one({
5c2b8486 304 'creator': request.user.id,
dc03850b 305 'title':form.title.data})
c43f8c1d 306
be5be115
AW
307 if existing_collection and existing_collection.id != collection.id:
308 messages.add_message(
a6481028
CAW
309 request, messages.ERROR,
310 _('You already have a collection called "%s"!') % \
dc03850b 311 form.title.data)
be5be115
AW
312 elif slug_used:
313 form.slug.errors.append(
314 _(u'A collection with that slug already exists for this user.'))
315 else:
dc03850b
HL
316 collection.title = unicode(form.title.data)
317 collection.description = unicode(form.description.data)
318 collection.slug = unicode(form.slug.data)
be5be115
AW
319
320 collection.save()
321
2e6ee596 322 return redirect_obj(request, collection)
be5be115
AW
323
324 if request.user.is_admin \
5c2b8486 325 and collection.creator != request.user.id \
be5be115
AW
326 and request.method != 'POST':
327 messages.add_message(
328 request, messages.WARNING,
329 _("You are editing another user's collection. Proceed with caution."))
330
331 return render_to_response(
332 request,
333 'mediagoblin/edit/edit_collection.html',
334 {'collection': collection,
335 'form': form})
39aa1db4
RE
336
337
338@require_active_login
339def change_pass(request):
340 form = forms.ChangePassForm(request.form)
341 user = request.user
342
343 if request.method == 'POST' and form.validate():
344
345 if not auth_lib.bcrypt_check_password(
346 form.old_password.data, user.pw_hash):
347 form.old_password.errors.append(
348 _('Wrong password'))
349
350 return render_to_response(
351 request,
352 'mediagoblin/edit/change_pass.html',
353 {'form': form,
354 'user': user})
355
356 # Password matches
357 user.pw_hash = auth_lib.bcrypt_gen_password_hash(
358 form.new_password.data)
359 user.save()
360
361 messages.add_message(
362 request, messages.SUCCESS,
363 _('Your password was changed successfully'))
364
365 return redirect(request, 'mediagoblin.edit.account')
366
367 return render_to_response(
368 request,
369 'mediagoblin/edit/change_pass.html',
370 {'form': form,
371 'user': user})