1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
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.
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.
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/>.
17 from datetime
import datetime
19 from itsdangerous
import BadSignature
20 from pyld
import jsonld
21 from werkzeug
.exceptions
import Forbidden
22 from werkzeug
.utils
import secure_filename
24 from mediagoblin
import messages
25 from mediagoblin
import mg_globals
27 from mediagoblin
.auth
import (check_password
,
29 from mediagoblin
.edit
import forms
30 from mediagoblin
.edit
.lib
import may_edit_media
31 from mediagoblin
.decorators
import (require_active_login
, active_user_from_url
,
32 get_media_entry_by_id
, user_may_alter_collection
,
33 get_user_collection
, user_has_privilege
,
35 from mediagoblin
.tools
.crypto
import get_timed_signer_url
36 from mediagoblin
.tools
.mail
import email_debug_message
37 from mediagoblin
.tools
.response
import (render_to_response
,
38 redirect
, redirect_obj
, render_404
)
39 from mediagoblin
.tools
.translate
import pass_to_ugettext
as _
40 from mediagoblin
.tools
.template
import render_template
41 from mediagoblin
.tools
.text
import (
42 convert_to_tag_list_of_dicts
, media_tags_as_string
)
43 from mediagoblin
.tools
.url
import slugify
44 from mediagoblin
.db
.util
import check_media_slug_used
, check_collection_slug_used
45 from mediagoblin
.db
.models
import User
50 @get_media_entry_by_id
52 def edit_media(request
, media
):
53 if not may_edit_media(request
, media
):
54 raise Forbidden("User may not edit this media")
59 description
=media
.description
,
60 tags
=media_tags_as_string(media
.tags
),
61 license
=media
.license
)
63 form
= forms
.EditForm(
67 if request
.method
== 'POST' and form
.validate():
68 # Make sure there isn't already a MediaEntry with such a slug
70 slug
= slugify(form
.slug
.data
)
71 slug_used
= check_media_slug_used(media
.uploader
, slug
, media
.id)
74 form
.slug
.errors
.append(
75 _(u
'An entry with that slug already exists for this user.'))
77 media
.title
= form
.title
.data
78 media
.description
= form
.description
.data
79 media
.tags
= convert_to_tag_list_of_dicts(
82 media
.license
= unicode(form
.license
.data
) or None
86 return redirect_obj(request
, media
)
88 if request
.user
.has_privilege(u
'admin') \
89 and media
.uploader
!= request
.user
.id \
90 and request
.method
!= 'POST':
92 request
, messages
.WARNING
,
93 _("You are editing another user's media. Proceed with caution."))
95 return render_to_response(
97 'mediagoblin/edit/edit.html',
102 # Mimetypes that browsers parse scripts in.
103 # Content-sniffing isn't taken into consideration.
109 @get_media_entry_by_id
110 @require_active_login
111 def edit_attachments(request
, media
):
112 if mg_globals
.app_config
['allow_attachments']:
113 form
= forms
.EditAttachmentsForm()
115 # Add any attachements
116 if 'attachment_file' in request
.files \
117 and request
.files
['attachment_file']:
119 # Security measure to prevent attachments from being served as
120 # text/html, which will be parsed by web clients and pose an XSS
124 # This method isn't flawless as some browsers may perform
126 # This method isn't flawless as we do the mimetype lookup on the
127 # machine parsing the upload form, and not necessarily the machine
128 # serving the attachments.
129 if mimetypes
.guess_type(
130 request
.files
['attachment_file'].filename
)[0] in \
132 public_filename
= secure_filename('{0}.notsafe'.format(
133 request
.files
['attachment_file'].filename
))
135 public_filename
= secure_filename(
136 request
.files
['attachment_file'].filename
)
138 attachment_public_filepath \
139 = mg_globals
.public_store
.get_unique_filepath(
140 ['media_entries', unicode(media
.id), 'attachment',
143 attachment_public_file
= mg_globals
.public_store
.get_file(
144 attachment_public_filepath
, 'wb')
147 attachment_public_file
.write(
148 request
.files
['attachment_file'].stream
.read())
150 request
.files
['attachment_file'].stream
.close()
152 media
.attachment_files
.append(dict(
153 name
=form
.attachment_name
.data \
154 or request
.files
['attachment_file'].filename
,
155 filepath
=attachment_public_filepath
,
156 created
=datetime
.utcnow(),
161 messages
.add_message(
162 request
, messages
.SUCCESS
,
163 _("You added the attachment %s!") \
164 % (form
.attachment_name
.data
165 or request
.files
['attachment_file'].filename
))
167 return redirect(request
,
168 location
=media
.url_for_self(request
.urlgen
))
169 return render_to_response(
171 'mediagoblin/edit/attachments.html',
175 raise Forbidden("Attachments are disabled")
177 @require_active_login
178 def legacy_edit_profile(request
):
179 """redirect the old /edit/profile/?username=USER to /u/USER/edit/"""
180 username
= request
.GET
.get('username') or request
.user
.username
181 return redirect(request
, 'mediagoblin.edit.profile', user
=username
)
184 @require_active_login
185 @active_user_from_url
186 def edit_profile(request
, url_user
=None):
187 # admins may edit any user profile
188 if request
.user
.username
!= url_user
.username
:
189 if not request
.user
.has_privilege(u
'admin'):
190 raise Forbidden(_("You can only edit your own profile."))
192 # No need to warn again if admin just submitted an edited profile
193 if request
.method
!= 'POST':
194 messages
.add_message(
195 request
, messages
.WARNING
,
196 _("You are editing a user's profile. Proceed with caution."))
200 form
= forms
.EditProfileForm(request
.form
,
204 if request
.method
== 'POST' and form
.validate():
205 user
.url
= unicode(form
.url
.data
)
206 user
.bio
= unicode(form
.bio
.data
)
210 messages
.add_message(request
,
212 _("Profile changes saved"))
213 return redirect(request
,
214 'mediagoblin.user_pages.user_home',
217 return render_to_response(
219 'mediagoblin/edit/edit_profile.html',
223 EMAIL_VERIFICATION_TEMPLATE
= (
225 u
'token={verification_key}')
228 @require_active_login
229 def edit_account(request
):
231 form
= forms
.EditAccountForm(request
.form
,
232 wants_comment_notification
=user
.wants_comment_notification
,
233 license_preference
=user
.license_preference
,
234 wants_notifications
=user
.wants_notifications
)
236 if request
.method
== 'POST' and form
.validate():
237 user
.wants_comment_notification
= form
.wants_comment_notification
.data
238 user
.wants_notifications
= form
.wants_notifications
.data
240 user
.license_preference
= form
.license_preference
.data
243 messages
.add_message(request
,
245 _("Account settings saved"))
246 return redirect(request
,
247 'mediagoblin.user_pages.user_home',
250 return render_to_response(
252 'mediagoblin/edit/edit_account.html',
257 @require_active_login
258 def delete_account(request
):
259 """Delete a user completely"""
261 if request
.method
== 'POST':
262 if request
.form
.get(u
'confirmed'):
263 # Form submitted and confirmed. Actually delete the user account
264 # Log out user and delete cookies etc.
265 # TODO: Should we be using MG.auth.views.py:logout for this?
266 request
.session
.delete()
268 # Delete user account and all related media files etc....
269 request
.user
.delete()
271 # We should send a message that the user has been deleted
272 # successfully. But we just deleted the session, so we
274 return redirect(request
, 'index')
276 else: # Did not check the confirmation box...
277 messages
.add_message(
278 request
, messages
.WARNING
,
279 _('You need to confirm the deletion of your account.'))
281 # No POST submission or not confirmed, just show page
282 return render_to_response(
284 'mediagoblin/edit/delete_account.html',
288 @require_active_login
289 @user_may_alter_collection
291 def edit_collection(request
, collection
):
293 title
=collection
.title
,
294 slug
=collection
.slug
,
295 description
=collection
.description
)
297 form
= forms
.EditCollectionForm(
301 if request
.method
== 'POST' and form
.validate():
302 # Make sure there isn't already a Collection with such a slug
304 slug_used
= check_collection_slug_used(collection
.creator
,
305 form
.slug
.data
, collection
.id)
307 # Make sure there isn't already a Collection with this title
308 existing_collection
= request
.db
.Collection
.query
.filter_by(
309 creator
=request
.user
.id,
310 title
=form
.title
.data
).first()
312 if existing_collection
and existing_collection
.id != collection
.id:
313 messages
.add_message(
314 request
, messages
.ERROR
,
315 _('You already have a collection called "%s"!') % \
318 form
.slug
.errors
.append(
319 _(u
'A collection with that slug already exists for this user.'))
321 collection
.title
= unicode(form
.title
.data
)
322 collection
.description
= unicode(form
.description
.data
)
323 collection
.slug
= unicode(form
.slug
.data
)
327 return redirect_obj(request
, collection
)
329 if request
.user
.has_privilege(u
'admin') \
330 and collection
.creator
!= request
.user
.id \
331 and request
.method
!= 'POST':
332 messages
.add_message(
333 request
, messages
.WARNING
,
334 _("You are editing another user's collection. Proceed with caution."))
336 return render_to_response(
338 'mediagoblin/edit/edit_collection.html',
339 {'collection': collection
,
343 def verify_email(request
):
345 Email verification view for changing email address
347 # If no token, we can't do anything
348 if not 'token' in request
.GET
:
349 return render_404(request
)
351 # Catch error if token is faked or expired
354 token
= get_timed_signer_url("mail_verification_token") \
355 .loads(request
.GET
['token'], max_age
=10*24*3600)
357 messages
.add_message(
360 _('The verification key or user id is incorrect.'))
366 user
= User
.query
.filter_by(id=int(token
['user'])).first()
369 user
.email
= token
['email']
372 messages
.add_message(
375 _('Your email address has been verified.'))
378 messages
.add_message(
381 _('The verification key or user id is incorrect.'))
384 request
, 'mediagoblin.user_pages.user_home',
388 def change_email(request
):
389 """ View to change the user's email """
390 form
= forms
.ChangeEmailForm(request
.form
)
393 # If no password authentication, no need to enter a password
394 if 'pass_auth' not in request
.template_env
.globals or not user
.pw_hash
:
395 form
.__delitem
__('password')
397 if request
.method
== 'POST' and form
.validate():
398 new_email
= form
.new_email
.data
399 users_with_email
= User
.query
.filter_by(
400 email
=new_email
).count()
403 form
.new_email
.errors
.append(
404 _('Sorry, a user with that email address'
407 if form
.password
and user
.pw_hash
and not check_password(
408 form
.password
.data
, user
.pw_hash
):
409 form
.password
.errors
.append(
413 verification_key
= get_timed_signer_url(
414 'mail_verification_token').dumps({
418 rendered_email
= render_template(
419 request
, 'mediagoblin/edit/verification.txt',
420 {'username': user
.username
,
421 'verification_url': EMAIL_VERIFICATION_TEMPLATE
.format(
422 uri
=request
.urlgen('mediagoblin.edit.verify_email',
424 verification_key
=verification_key
)})
426 email_debug_message(request
)
427 auth_tools
.send_verification_email(user
, request
, new_email
,
430 return redirect(request
, 'mediagoblin.edit.account')
432 return render_to_response(
434 'mediagoblin/edit/change_email.html',
438 @user_has_privilege(u
'admin')
439 @require_active_login
440 @get_media_entry_by_id
441 def edit_metadata(request
, media
):
442 form
= forms
.EditMetaDataForm(request
.form
)
443 if request
.method
== "POST" and form
.validate():
444 context
= dict([(row
['identifier'],row
['value'])
445 for row
in form
.context
.data
])
446 metadata_dict
= dict([(row
['identifier'],row
['value'])
447 for row
in form
.media_metadata
.data
])
448 # TODO VALIDATE THIS BEFORE WE ENTER IT
449 # validate(metadata_dict)
451 json_ld_metadata
= jsonld
.compact(metadata_dict
, context
)
452 # media.media_metadata = json_ld_metadata
454 return redirect_obj(request
, media
)
456 if media
.media_metadata
:
457 for row
in media
.media_metadata
.iteritems():
458 if row
[0] == "@context": continue
460 # TODO Will change when we revert the metadata branch
461 value
= row
[1]['@value']
462 form
.media_metadata
.append_entry({
463 'identifier':identifier
,
465 for row
in media
.media_metadata
['@context'].iteritems():
466 identifier
, value
= row
[0:2]
467 form
.context
.append_entry({
468 'identifier':identifier
,
471 form
.media_metadata
.append_entry({
474 form
.media_metadata
.append_entry({
477 form
.context
.append_entry({
480 return render_to_response(
482 'mediagoblin/edit/metadata.html',