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