Added some security checks to attachment upload, it's still not
[mediagoblin.git] / mediagoblin / edit / views.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
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/>.
16
17 from webob import exc
18 from cgi import FieldStorage
19 from datetime import datetime
20
21 from werkzeug.utils import secure_filename
22
23 from mediagoblin import messages
24 from mediagoblin import mg_globals
25
26 from mediagoblin.auth import lib as auth_lib
27 from mediagoblin.edit import forms
28 from mediagoblin.edit.lib import may_edit_media
29 from mediagoblin.decorators import require_active_login, get_user_media_entry
30 from mediagoblin.tools.response import render_to_response, redirect
31 from mediagoblin.tools.translate import pass_to_ugettext as _
32 from mediagoblin.tools.text import (
33 convert_to_tag_list_of_dicts, media_tags_as_string)
34 from mediagoblin.db.util import check_media_slug_used
35
36 import mimetypes
37
38
39 @get_user_media_entry
40 @require_active_login
41 def edit_media(request, media):
42 if not may_edit_media(request, media):
43 return exc.HTTPForbidden()
44
45 defaults = dict(
46 title=media.title,
47 slug=media.slug,
48 description=media.description,
49 tags=media_tags_as_string(media.tags),
50 license=media.license)
51
52 form = forms.EditForm(
53 request.POST,
54 **defaults)
55
56 if request.method == 'POST' and form.validate():
57 # Make sure there isn't already a MediaEntry with such a slug
58 # and userid.
59 slug_used = check_media_slug_used(request.db, media.uploader,
60 request.POST['slug'], media.id)
61
62 if slug_used:
63 form.slug.errors.append(
64 _(u'An entry with that slug already exists for this user.'))
65 else:
66 media.title = unicode(request.POST['title'])
67 media.description = unicode(request.POST.get('description'))
68 media.tags = convert_to_tag_list_of_dicts(
69 request.POST.get('tags'))
70
71 media.license = unicode(request.POST.get('license', '')) or None
72
73 media.slug = unicode(request.POST['slug'])
74
75 media.save()
76
77 return exc.HTTPFound(
78 location=media.url_for_self(request.urlgen))
79
80 if request.user.is_admin \
81 and media.uploader != request.user._id \
82 and request.method != 'POST':
83 messages.add_message(
84 request, messages.WARNING,
85 _("You are editing another user's media. Proceed with caution."))
86
87 return render_to_response(
88 request,
89 'mediagoblin/edit/edit.html',
90 {'media': media,
91 'form': form})
92
93
94 # Mimetypes that browsers parse scripts in.
95 # Content-sniffing isn't taken into consideration.
96 UNSAFE_MIMETYPES = [
97 'text/html',
98 'text/svg+xml']
99
100
101 @get_user_media_entry
102 @require_active_login
103 def edit_attachments(request, media):
104 if mg_globals.app_config['allow_attachments']:
105 form = forms.EditAttachmentsForm()
106
107 # Add any attachements
108 if ('attachment_file' in request.POST
109 and isinstance(request.POST['attachment_file'], FieldStorage)
110 and request.POST['attachment_file'].file):
111
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(
123 request.POST['attachment_file'].filename)[0] in \
124 UNSAFE_MIMETYPES:
125 public_filename = secure_filename('{0}.notsafe'.format(
126 request.POST['attachment_file'].filename))
127 else:
128 public_filename = secure_filename(
129 request.POST['attachment_file'].filename)
130
131 attachment_public_filepath \
132 = mg_globals.public_store.get_unique_filepath(
133 ['media_entries', unicode(media._id), 'attachment',
134 public_filename])
135
136 attachment_public_file = mg_globals.public_store.get_file(
137 attachment_public_filepath, 'wb')
138
139 try:
140 attachment_public_file.write(
141 request.POST['attachment_file'].file.read())
142 finally:
143 request.POST['attachment_file'].file.close()
144
145 media.attachment_files.append(dict(
146 name=request.POST['attachment_name'] \
147 or request.POST['attachment_file'].filename,
148 filepath=attachment_public_filepath,
149 created=datetime.utcnow(),
150 ))
151
152 media.save()
153
154 messages.add_message(
155 request, messages.SUCCESS,
156 "You added the attachment %s!" \
157 % (request.POST['attachment_name']
158 or request.POST['attachment_file'].filename))
159
160 return exc.HTTPFound(
161 location=media.url_for_self(request.urlgen))
162 return render_to_response(
163 request,
164 'mediagoblin/edit/attachments.html',
165 {'media': media,
166 'form': form})
167 else:
168 return exc.HTTPForbidden()
169
170
171 @require_active_login
172 def edit_profile(request):
173 # admins may edit any user profile given a username in the querystring
174 edit_username = request.GET.get('username')
175 if request.user.is_admin and request.user.username != edit_username:
176 user = request.db.User.find_one({'username': edit_username})
177 # No need to warn again if admin just submitted an edited profile
178 if request.method != 'POST':
179 messages.add_message(
180 request, messages.WARNING,
181 _("You are editing a user's profile. Proceed with caution."))
182 else:
183 user = request.user
184
185 form = forms.EditProfileForm(request.POST,
186 url=user.get('url'),
187 bio=user.get('bio'))
188
189 if request.method == 'POST' and form.validate():
190 user.url = unicode(request.POST['url'])
191 user.bio = unicode(request.POST['bio'])
192
193 user.save()
194
195 messages.add_message(request,
196 messages.SUCCESS,
197 _("Profile changes saved"))
198 return redirect(request,
199 'mediagoblin.user_pages.user_home',
200 user=user.username)
201
202 return render_to_response(
203 request,
204 'mediagoblin/edit/edit_profile.html',
205 {'user': user,
206 'form': form})
207
208
209 @require_active_login
210 def edit_account(request):
211 user = request.user
212 form = forms.EditAccountForm(request.POST,
213 wants_comment_notification=user.get('wants_comment_notification'))
214
215 if request.method == 'POST':
216 form_validated = form.validate()
217
218 #if the user has not filled in the new or old password fields
219 if not form.new_password.data and not form.old_password.data:
220 if form.wants_comment_notification.validate(form):
221 user.wants_comment_notification = \
222 form.wants_comment_notification.data
223 user.save()
224 messages.add_message(request,
225 messages.SUCCESS,
226 _("Account settings saved"))
227 return redirect(request,
228 'mediagoblin.user_pages.user_home',
229 user=user.username)
230
231 #so the user has filled in one or both of the password fields
232 else:
233 if form_validated:
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 user.wants_comment_notification = \
242 form.wants_comment_notification.data
243 user.save()
244 messages.add_message(request,
245 messages.SUCCESS,
246 _("Account settings saved"))
247 return redirect(request,
248 'mediagoblin.user_pages.user_home',
249 user=user.username)
250 else:
251 form.old_password.errors.append(_('Wrong password'))
252
253 return render_to_response(
254 request,
255 'mediagoblin/edit/edit_account.html',
256 {'user': user,
257 'form': form})