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/>.
19 from datetime
import datetime
21 from itsdangerous
import BadSignature
22 from pyld
import jsonld
23 from werkzeug
.exceptions
import Forbidden
24 from werkzeug
.utils
import secure_filename
25 from jsonschema
import ValidationError
, Draft4Validator
27 from mediagoblin
import messages
28 from mediagoblin
import mg_globals
30 from mediagoblin
.auth
import (check_password
,
32 from mediagoblin
.edit
import forms
33 from mediagoblin
.edit
.lib
import may_edit_media
34 from mediagoblin
.decorators
import (require_active_login
, active_user_from_url
,
35 get_media_entry_by_id
, user_may_alter_collection
,
36 get_user_collection
, user_has_privilege
,
38 from mediagoblin
.tools
.crypto
import get_timed_signer_url
39 from mediagoblin
.tools
.metadata
import (compact_and_validate
, DEFAULT_CHECKER
,
41 from mediagoblin
.tools
.mail
import email_debug_message
42 from mediagoblin
.tools
.response
import (render_to_response
,
43 redirect
, redirect_obj
, render_404
)
44 from mediagoblin
.tools
.translate
import pass_to_ugettext
as _
45 from mediagoblin
.tools
.template
import render_template
46 from mediagoblin
.tools
.text
import (
47 convert_to_tag_list_of_dicts
, media_tags_as_string
)
48 from mediagoblin
.tools
.url
import slugify
49 from mediagoblin
.db
.util
import check_media_slug_used
, check_collection_slug_used
50 from mediagoblin
.db
.models
import User
, Client
, AccessToken
55 @get_media_entry_by_id
57 def edit_media(request
, media
):
58 if not may_edit_media(request
, media
):
59 raise Forbidden("User may not edit this media")
64 description
=media
.description
,
65 tags
=media_tags_as_string(media
.tags
),
66 license
=media
.license
)
68 form
= forms
.EditForm(
72 if request
.method
== 'POST' and form
.validate():
73 # Make sure there isn't already a MediaEntry with such a slug
75 slug
= slugify(form
.slug
.data
)
76 slug_used
= check_media_slug_used(media
.uploader
, slug
, media
.id)
79 form
.slug
.errors
.append(
80 _(u
'An entry with that slug already exists for this user.'))
82 media
.title
= form
.title
.data
83 media
.description
= form
.description
.data
84 media
.tags
= convert_to_tag_list_of_dicts(
87 media
.license
= six
.text_type(form
.license
.data
) or None
91 return redirect_obj(request
, media
)
93 if request
.user
.has_privilege(u
'admin') \
94 and media
.uploader
!= request
.user
.id \
95 and request
.method
!= 'POST':
97 request
, messages
.WARNING
,
98 _("You are editing another user's media. Proceed with caution."))
100 return render_to_response(
102 'mediagoblin/edit/edit.html',
107 # Mimetypes that browsers parse scripts in.
108 # Content-sniffing isn't taken into consideration.
114 @get_media_entry_by_id
115 @require_active_login
116 def edit_attachments(request
, media
):
117 if mg_globals
.app_config
['allow_attachments']:
118 form
= forms
.EditAttachmentsForm()
120 # Add any attachements
121 if 'attachment_file' in request
.files \
122 and request
.files
['attachment_file']:
124 # Security measure to prevent attachments from being served as
125 # text/html, which will be parsed by web clients and pose an XSS
129 # This method isn't flawless as some browsers may perform
131 # This method isn't flawless as we do the mimetype lookup on the
132 # machine parsing the upload form, and not necessarily the machine
133 # serving the attachments.
134 if mimetypes
.guess_type(
135 request
.files
['attachment_file'].filename
)[0] in \
137 public_filename
= secure_filename('{0}.notsafe'.format(
138 request
.files
['attachment_file'].filename
))
140 public_filename
= secure_filename(
141 request
.files
['attachment_file'].filename
)
143 attachment_public_filepath \
144 = mg_globals
.public_store
.get_unique_filepath(
145 ['media_entries', six
.text_type(media
.id), 'attachment',
148 attachment_public_file
= mg_globals
.public_store
.get_file(
149 attachment_public_filepath
, 'wb')
152 attachment_public_file
.write(
153 request
.files
['attachment_file'].stream
.read())
155 request
.files
['attachment_file'].stream
.close()
157 media
.attachment_files
.append(dict(
158 name
=form
.attachment_name
.data \
159 or request
.files
['attachment_file'].filename
,
160 filepath
=attachment_public_filepath
,
161 created
=datetime
.utcnow(),
166 messages
.add_message(
167 request
, messages
.SUCCESS
,
168 _("You added the attachment %s!") \
169 % (form
.attachment_name
.data
170 or request
.files
['attachment_file'].filename
))
172 return redirect(request
,
173 location
=media
.url_for_self(request
.urlgen
))
174 return render_to_response(
176 'mediagoblin/edit/attachments.html',
180 raise Forbidden("Attachments are disabled")
182 @require_active_login
183 def legacy_edit_profile(request
):
184 """redirect the old /edit/profile/?username=USER to /u/USER/edit/"""
185 username
= request
.GET
.get('username') or request
.user
.username
186 return redirect(request
, 'mediagoblin.edit.profile', user
=username
)
189 @require_active_login
190 @active_user_from_url
191 def edit_profile(request
, url_user
=None):
192 # admins may edit any user profile
193 if request
.user
.username
!= url_user
.username
:
194 if not request
.user
.has_privilege(u
'admin'):
195 raise Forbidden(_("You can only edit your own profile."))
197 # No need to warn again if admin just submitted an edited profile
198 if request
.method
!= 'POST':
199 messages
.add_message(
200 request
, messages
.WARNING
,
201 _("You are editing a user's profile. Proceed with caution."))
205 form
= forms
.EditProfileForm(request
.form
,
209 if request
.method
== 'POST' and form
.validate():
210 user
.url
= six
.text_type(form
.url
.data
)
211 user
.bio
= six
.text_type(form
.bio
.data
)
215 messages
.add_message(request
,
217 _("Profile changes saved"))
218 return redirect(request
,
219 'mediagoblin.user_pages.user_home',
222 return render_to_response(
224 'mediagoblin/edit/edit_profile.html',
228 EMAIL_VERIFICATION_TEMPLATE
= (
230 u
'token={verification_key}')
233 @require_active_login
234 def edit_account(request
):
236 form
= forms
.EditAccountForm(request
.form
,
237 wants_comment_notification
=user
.wants_comment_notification
,
238 license_preference
=user
.license_preference
,
239 wants_notifications
=user
.wants_notifications
)
241 if request
.method
== 'POST' and form
.validate():
242 user
.wants_comment_notification
= form
.wants_comment_notification
.data
243 user
.wants_notifications
= form
.wants_notifications
.data
245 user
.license_preference
= form
.license_preference
.data
248 messages
.add_message(request
,
250 _("Account settings saved"))
251 return redirect(request
,
252 'mediagoblin.user_pages.user_home',
255 return render_to_response(
257 'mediagoblin/edit/edit_account.html',
261 @require_active_login
262 def deauthorize_applications(request
):
263 """ Deauthroize OAuth applications """
264 if request
.method
== 'POST' and "application" in request
.form
:
265 token
= request
.form
["application"]
266 access_token
= AccessToken
.query
.filter_by(token
=token
).first()
267 if access_token
is None:
268 messages
.add_message(
271 _("Unknown application, not able to deauthorize")
274 access_token
.delete()
275 messages
.add_message(
278 _("Application has been deauthorized")
281 access_tokens
= AccessToken
.query
.filter_by(user
=request
.user
.id)
282 applications
= [(a
.get_requesttoken
, a
) for a
in access_tokens
]
284 return render_to_response(
286 'mediagoblin/edit/deauthorize_applications.html',
287 {'applications': applications
}
290 @require_active_login
291 def delete_account(request
):
292 """Delete a user completely"""
294 if request
.method
== 'POST':
295 if request
.form
.get(u
'confirmed'):
296 # Form submitted and confirmed. Actually delete the user account
297 # Log out user and delete cookies etc.
298 # TODO: Should we be using MG.auth.views.py:logout for this?
299 request
.session
.delete()
301 # Delete user account and all related media files etc....
302 request
.user
.delete()
304 # We should send a message that the user has been deleted
305 # successfully. But we just deleted the session, so we
307 return redirect(request
, 'index')
309 else: # Did not check the confirmation box...
310 messages
.add_message(
311 request
, messages
.WARNING
,
312 _('You need to confirm the deletion of your account.'))
314 # No POST submission or not confirmed, just show page
315 return render_to_response(
317 'mediagoblin/edit/delete_account.html',
321 @require_active_login
322 @user_may_alter_collection
324 def edit_collection(request
, collection
):
326 title
=collection
.title
,
327 slug
=collection
.slug
,
328 description
=collection
.description
)
330 form
= forms
.EditCollectionForm(
334 if request
.method
== 'POST' and form
.validate():
335 # Make sure there isn't already a Collection with such a slug
337 slug_used
= check_collection_slug_used(collection
.creator
,
338 form
.slug
.data
, collection
.id)
340 # Make sure there isn't already a Collection with this title
341 existing_collection
= request
.db
.Collection
.query
.filter_by(
342 creator
=request
.user
.id,
343 title
=form
.title
.data
).first()
345 if existing_collection
and existing_collection
.id != collection
.id:
346 messages
.add_message(
347 request
, messages
.ERROR
,
348 _('You already have a collection called "%s"!') % \
351 form
.slug
.errors
.append(
352 _(u
'A collection with that slug already exists for this user.'))
354 collection
.title
= six
.text_type(form
.title
.data
)
355 collection
.description
= six
.text_type(form
.description
.data
)
356 collection
.slug
= six
.text_type(form
.slug
.data
)
360 return redirect_obj(request
, collection
)
362 if request
.user
.has_privilege(u
'admin') \
363 and collection
.creator
!= request
.user
.id \
364 and request
.method
!= 'POST':
365 messages
.add_message(
366 request
, messages
.WARNING
,
367 _("You are editing another user's collection. Proceed with caution."))
369 return render_to_response(
371 'mediagoblin/edit/edit_collection.html',
372 {'collection': collection
,
376 def verify_email(request
):
378 Email verification view for changing email address
380 # If no token, we can't do anything
381 if not 'token' in request
.GET
:
382 return render_404(request
)
384 # Catch error if token is faked or expired
387 token
= get_timed_signer_url("mail_verification_token") \
388 .loads(request
.GET
['token'], max_age
=10*24*3600)
390 messages
.add_message(
393 _('The verification key or user id is incorrect.'))
399 user
= User
.query
.filter_by(id=int(token
['user'])).first()
402 user
.email
= token
['email']
405 messages
.add_message(
408 _('Your email address has been verified.'))
411 messages
.add_message(
414 _('The verification key or user id is incorrect.'))
417 request
, 'mediagoblin.user_pages.user_home',
421 def change_email(request
):
422 """ View to change the user's email """
423 form
= forms
.ChangeEmailForm(request
.form
)
426 # If no password authentication, no need to enter a password
427 if 'pass_auth' not in request
.template_env
.globals or not user
.pw_hash
:
428 form
.__delitem
__('password')
430 if request
.method
== 'POST' and form
.validate():
431 new_email
= form
.new_email
.data
432 users_with_email
= User
.query
.filter_by(
433 email
=new_email
).count()
436 form
.new_email
.errors
.append(
437 _('Sorry, a user with that email address'
440 if form
.password
and user
.pw_hash
and not check_password(
441 form
.password
.data
, user
.pw_hash
):
442 form
.password
.errors
.append(
446 verification_key
= get_timed_signer_url(
447 'mail_verification_token').dumps({
451 rendered_email
= render_template(
452 request
, 'mediagoblin/edit/verification.txt',
453 {'username': user
.username
,
454 'verification_url': EMAIL_VERIFICATION_TEMPLATE
.format(
455 uri
=request
.urlgen('mediagoblin.edit.verify_email',
457 verification_key
=verification_key
)})
459 email_debug_message(request
)
460 auth_tools
.send_verification_email(user
, request
, new_email
,
463 return redirect(request
, 'mediagoblin.edit.account')
465 return render_to_response(
467 'mediagoblin/edit/change_email.html',
471 @user_has_privilege(u
'admin')
472 @require_active_login
473 @get_media_entry_by_id
474 def edit_metadata(request
, media
):
475 form
= forms
.EditMetaDataForm(request
.form
)
476 if request
.method
== "POST" and form
.validate():
477 metadata_dict
= dict([(row
['identifier'],row
['value'])
478 for row
in form
.media_metadata
.data
])
479 json_ld_metadata
= None
480 json_ld_metadata
= compact_and_validate(metadata_dict
)
481 media
.media_metadata
= json_ld_metadata
483 return redirect_obj(request
, media
)
485 if len(form
.media_metadata
) == 0:
486 for identifier
, value
in six
.iteritems(media
.media_metadata
):
487 if identifier
== "@context": continue
488 form
.media_metadata
.append_entry({
489 'identifier':identifier
,
492 return render_to_response(
494 'mediagoblin/edit/metadata.html',