def user_home(request, page): """'Homepage' of a User()""" user = User.query.filter_by(username=request.matchdict['user']).first() if not user: return render_404(request) elif not user.has_privilege(u'active'): return render_to_response( request, 'mediagoblin/user_pages/user_nonactive.html', {'user': user}) cursor = MediaEntry.query.\ filter_by(uploader = user.id, state = u'processed').order_by(MediaEntry.created.desc()) pagination = Pagination(page, cursor) media_entries = pagination() #if no data is available, return NotFound if media_entries == None: return render_404(request) user_gallery_url = request.urlgen( 'mediagoblin.user_pages.user_gallery', user=user.username) return render_to_response( request, 'mediagoblin/user_pages/user.html', {'user': user, 'user_gallery_url': user_gallery_url, 'media_entries': media_entries, 'pagination': pagination})
def user_home(request, page): """'Homepage' of a User()""" # TODO: decide if we only want homepages for active users, we can # then use the @get_active_user decorator and also simplify the # template html. user = User.query.filter_by(username=request.matchdict["user"]).first() if not user: return render_404(request) elif user.status != u"active": return render_to_response(request, "mediagoblin/user_pages/user.html", {"user": user}) cursor = MediaEntry.query.filter_by(uploader=user.id, state=u"processed").order_by(MediaEntry.created.desc()) pagination = Pagination(page, cursor) media_entries = pagination() # if no data is available, return NotFound if media_entries == None: return render_404(request) user_gallery_url = request.urlgen("mediagoblin.user_pages.user_gallery", user=user.username) return render_to_response( request, "mediagoblin/user_pages/user.html", {"user": user, "user_gallery_url": user_gallery_url, "media_entries": media_entries, "pagination": pagination}, )
def user_home(request, page): """'Homepage' of a User()""" user = request.db.User.find_one({ 'username': request.matchdict['user']}) if not user: return render_404(request) elif user.status != u'active': return render_to_response( request, 'mediagoblin/user_pages/user.html', {'user': user}) cursor = request.db.MediaEntry.find( {'uploader': user._id, 'state': u'processed'}).sort('created', DESCENDING) pagination = Pagination(page, cursor) media_entries = pagination() #if no data is available, return NotFound if media_entries == None: return render_404(request) user_gallery_url = request.urlgen( 'mediagoblin.user_pages.user_gallery', user=user.username) return render_to_response( request, 'mediagoblin/user_pages/user.html', {'user': user, 'user_gallery_url': user_gallery_url, 'media_entries': media_entries, 'pagination': pagination})
def change_pass(request): form = auth_forms.ChangePassForm(request.form) user = request.user if request.method == 'POST' and form.validate(): if not tools.bcrypt_check_password( form.old_password.data, user.pw_hash): form.old_password.errors.append( _('Wrong password')) return render_to_response( request, 'mediagoblin/plugins/recaptcha/change_pass.html', {'form': form, 'user': user}) # Password matches user.pw_hash = tools.bcrypt_gen_password_hash( form.new_password.data) user.save() messages.add_message( request, messages.SUCCESS, _('Your password was changed successfully')) return redirect(request, 'mediagoblin.edit.account') return render_to_response( request, 'mediagoblin/plugins/recaptcha/change_pass.html', {'form': form, 'user': user})
def processing_panel(request): """ Show to the user what media is still in conversion/processing... and what failed, and why! """ # Get the user user = request.db.User.find_one( {'username': request.matchdict['user'], 'status': u'active'}) # Make sure the user exists and is active if not user: return render_404(request) elif user.status != u'active': return render_to_response( request, 'mediagoblin/user_pages/user.html', {'user': user}) # XXX: Should this be a decorator? # # Make sure we have permission to access this user's panel. Only # admins and this user herself should be able to do so. if not (user._id == request.user._id or request.user.is_admin): # No? Let's simply redirect to this user's homepage then. return redirect( request, 'mediagoblin.user_pages.user_home', user=request.matchdict['user']) # Get media entries which are in-processing processing_entries = request.db.MediaEntry.find( {'uploader': user._id, 'state': u'processing'}).sort('created', DESCENDING) # Get media entries which have failed to process failed_entries = request.db.MediaEntry.find( {'uploader': user._id, 'state': u'failed'}).sort('created', DESCENDING) processed_entries = request.db.MediaEntry.find( {'uploader': user._id, 'state': u'processed'}).sort('created', DESCENDING).limit(10) # Render to response return render_to_response( request, 'mediagoblin/user_pages/processing_panel.html', {'user': user, 'processing_entries': processing_entries, 'failed_entries': failed_entries, 'processed_entries': processed_entries})
def login(request): login_form = forms.LoginForm(request.form) login_failed = False if request.method == 'POST' and login_form.validate(): l = LDAP() username, email = l.login(login_form.username.data, login_form.password.data) if username: user = LocalUser.query.filter( LocalUser.username==username ).first() if user: # set up login in session request.session['user_id'] = six.text_type(user.id) request.session.save() if request.form.get('next'): return redirect(request, location=request.form['next']) else: return redirect(request, "index") else: if not mg_globals.app.auth: messages.add_message( request, messages.WARNING, _('Sorry, authentication is disabled on this ' 'instance.')) return redirect(request, 'index') register_form = forms.RegisterForm(username=username, email=email) return render_to_response( request, 'mediagoblin/auth/register.html', {'register_form': register_form, 'post_url': request.urlgen('mediagoblin.plugins.ldap.register')}) login_failed = True return render_to_response( request, 'mediagoblin/auth/login.html', {'login_form': login_form, 'next': request.GET.get('next') or request.form.get('next'), 'login_failed': login_failed, 'post_url': request.urlgen('mediagoblin.plugins.ldap.login'), 'allow_registration': mg_globals.app_config["allow_registration"]})
def register_client(request): ''' Register an OAuth client ''' form = ClientRegistrationForm(request.form) if request.method == 'POST' and form.validate(): client = OAuthClient() client.name = unicode(request.form['name']) client.description = unicode(request.form['description']) client.type = unicode(request.form['type']) client.owner_id = request.user.id client.redirect_uri = unicode(request.form['redirect_uri']) client.generate_identifier() client.generate_secret() client.save() add_message(request, SUCCESS, _('The client {0} has been registered!')\ .format( client.name)) return redirect(request, 'mediagoblin.plugins.oauth.list_clients') return render_to_response( request, 'oauth/client/register.html', {'form': form})
def user_gallery(request, page, url_user=None): """'Gallery' of a User()""" tag = request.matchdict.get('tag', None) cursor = MediaEntry.query.filter_by( uploader=url_user.id, state=u'processed').order_by(MediaEntry.created.desc()) # Filter potentially by tag too: if tag: cursor = cursor.filter( MediaEntry.tags_helper.any( MediaTag.slug == request.matchdict['tag'])) # Paginate gallery pagination = Pagination(page, cursor) media_entries = pagination() #if no data is available, return NotFound # TODO: Should we really also return 404 for empty galleries? if media_entries == None: return render_404(request) return render_to_response( request, 'mediagoblin/user_pages/gallery.html', {'user': url_user, 'tag': tag, 'media_entries': media_entries, 'pagination': pagination})
def moderation_reports_detail(request): """ This is the page an admin or moderator goes to see the details of a report. The report can be resolved or unresolved. This is also the page that a mod- erator would go to to take an action to resolve a report. """ form = moderation_forms.ReportResolutionForm(request.form) report = Report.query.get(request.matchdict['report_id']) form.take_away_privileges.choices = [ (s.privilege_name,s.privilege_name.title()) \ for s in report.reported_user.all_privileges ] if request.method == "POST" and form.validate() and not ( not request.user.has_privilege(u'admin') and report.reported_user.has_privilege(u'admin')): user = User.query.get(form.targeted_user.data) return take_punitive_actions(request, form, report, user) form.targeted_user.data = report.reported_user_id return render_to_response( request, 'mediagoblin/moderation/report.html', {'report':report, 'form':form})
def forgot_password(request): """ Forgot password view Sends an email with an url to renew forgotten password. Use GET querystring parameter 'username' to pre-populate the input field """ fp_form = auth_forms.ForgotPassForm(request.form, username=request.args.get('username')) if not (request.method == 'POST' and fp_form.validate()): # Either GET request, or invalid form submitted. Display the template return render_to_response(request, 'mediagoblin/plugins/recaptcha/forgot_password.html', {'fp_form': fp_form}) # If we are here: method == POST and form is valid. username casing # has been sanitized. Store if a user was found by email. We should # not reveal if the operation was successful then as we don't want to # leak if an email address exists in the system. found_by_email = '@' in fp_form.username.data if found_by_email: user = User.query.filter_by( email=fp_form.username.data).first() # Don't reveal success in case the lookup happened by email address. success_message = _("If that email address (case sensitive!) is " "registered an email has been sent with " "instructions on how to change your password.") else: # found by username user = User.query.filter_by( username=fp_form.username.data).first() if user is None: messages.add_message(request, messages.WARNING, _("Couldn't find someone with that username.")) return redirect(request, 'mediagoblin.auth.forgot_password') success_message = _("An email has been sent with instructions " "on how to change your password.") if user and user.has_privilege(u'active') is False: # Don't send reminder because user is inactive or has no verified email messages.add_message(request, messages.WARNING, _("Could not send password recovery email as your username is in" "active or your account's email address has not been verified.")) return redirect(request, 'mediagoblin.user_pages.user_home', user=user.username) # SUCCESS. Send reminder and return to login page if user: email_debug_message(request) tools.send_fp_verification_email(user, request) messages.add_message(request, messages.INFO, success_message) return redirect(request, 'mediagoblin.auth.login')
def media_confirm_delete(request, media): form = user_forms.ConfirmDeleteForm(request.form) if request.method == "POST" and form.validate(): if form.confirm.data is True: username = media.get_uploader.username # Delete MediaEntry and all related files, comments etc. media.delete() messages.add_message(request, messages.SUCCESS, _("You deleted the media.")) location = media.url_to_next(request.urlgen) if not location: location = media.url_to_prev(request.urlgen) if not location: location = request.urlgen("mediagoblin.user_pages.user_home", user=username) return redirect(request, location=location) else: messages.add_message( request, messages.ERROR, _("The media was not deleted because you didn't check that you were sure.") ) return redirect_obj(request, media) if request.user.is_admin and request.user.id != media.uploader: messages.add_message( request, messages.WARNING, _("You are about to delete another user's media. " "Proceed with caution.") ) return render_to_response( request, "mediagoblin/user_pages/media_confirm_delete.html", {"media": media, "form": form} )
def register(request): """The registration view. Note that usernames will always be lowercased. Email domains are lowercased while the first part remains case-sensitive. """ if 'pass_auth' not in request.template_env.globals: redirect_name = hook_handle('auth_no_pass_redirect') if redirect_name: return redirect(request, 'mediagoblin.plugins.{0}.register'.format( redirect_name)) else: return redirect(request, 'index') register_form = hook_handle("auth_get_registration_form", request) if request.method == 'POST' and register_form.validate(): # TODO: Make sure the user doesn't exist already user = register_user(request, register_form) if user: # redirect the user to their homepage... there will be a # message waiting for them to verify their email return redirect( request, 'mediagoblin.user_pages.user_home', user=user.username) return render_to_response( request, 'mediagoblin/auth/register.html', {'register_form': register_form, 'post_url': request.urlgen('mediagoblin.auth.register')})
def media_home(request, media, page, **kwargs): """ 'Homepage' of a MediaEntry() """ if request.matchdict.get('comment', None): pagination = Pagination( page, media.get_comments( mg_globals.app_config['comments_ascending']), MEDIA_COMMENTS_PER_PAGE, request.matchdict.get('comment')) else: pagination = Pagination( page, media.get_comments( mg_globals.app_config['comments_ascending']), MEDIA_COMMENTS_PER_PAGE) comments = pagination() comment_form = user_forms.MediaCommentForm(request.form) media_template_name = media.media_manager['display_template'] return render_to_response( request, media_template_name, {'media': media, 'comments': comments, 'pagination': pagination, 'comment_form': comment_form, 'app_config': mg_globals.app_config})
def activity_view(request): """ /<username>/activity/<id> - Display activity This should display a HTML presentation of the activity this is NOT an API endpoint. """ # Get the user object. username = request.matchdict["username"] user = LocalUser.query.filter_by(username=username).first() activity_id = request.matchdict["id"] if request.user is None: return render_404(request) activity = Activity.query.filter_by( id=activity_id, author=user.id ).first() # There isn't many places to check that the public_id is filled so this # will do, it really should be, lets try and fix that if it isn't. activity.get_public_id(request.urlgen) if activity is None: return render_404(request) return render_to_response( request, "mediagoblin/api/activity.html", {"activity": activity} )
def activity_view(request): """ /<username>/activity/<id> - Display activity This should display a HTML presentation of the activity this is NOT an API endpoint. """ # Get the user object. username = request.matchdict["username"] user = User.query.filter_by(username=username).first() activity_id = request.matchdict["id"] if request.user is None: return render_404(request) activity = Activity.query.filter_by( id=activity_id, author=user.id ).first() if activity is None: return render_404(request) return render_to_response( request, "mediagoblin/api/activity.html", {"activity": activity} )
def collection_item_confirm_remove(request, collection_item): form = user_forms.ConfirmCollectionItemRemoveForm(request.form) if request.method == 'POST' and form.validate(): collection = collection_item.in_collection if form.confirm.data is True: remove_collection_item(collection_item) messages.add_message( request, messages.SUCCESS, _('You deleted the item from the collection.')) else: messages.add_message( request, messages.ERROR, _("The item was not removed because you didn't check that you were sure.")) return redirect_obj(request, collection) if ((request.user.has_privilege(u'admin') and request.user.id != collection_item.in_collection.creator)): messages.add_message( request, messages.WARNING, _("You are about to delete an item from another user's collection. " "Proceed with caution.")) return render_to_response( request, 'mediagoblin/user_pages/collection_item_confirm_remove.html', {'collection_item': collection_item, 'form': form})
def deauthorize_applications(request): """ Deauthroize OAuth applications """ if request.method == 'POST' and "application" in request.form: token = request.form["application"] access_token = AccessToken.query.filter_by(token=token).first() if access_token is None: messages.add_message( request, messages.ERROR, _("Unknown application, not able to deauthorize") ) else: access_token.delete() messages.add_message( request, messages.SUCCESS, _("Application has been deauthorized") ) access_tokens = AccessToken.query.filter_by(user=request.user.id) applications = [(a.get_requesttoken, a) for a in access_tokens] return render_to_response( request, 'mediagoblin/edit/deauthorize_applications.html', {'applications': applications} )
def collection_list(request, url_user=None): """A User-defined Collection""" collections = Collection.query.filter_by(get_creator=url_user) return render_to_response( request, "mediagoblin/user_pages/collection_list.html", {"user": url_user, "collections": collections} )
def delete_account(request): """Delete a user completely""" user = request.user if request.method == 'POST': if request.form.get(u'confirmed'): # Form submitted and confirmed. Actually delete the user account # Log out user and delete cookies etc. # TODO: Should we be using MG.auth.views.py:logout for this? request.session.delete() # Delete user account and all related media files etc.... request.user.delete() # We should send a message that the user has been deleted # successfully. But we just deleted the session, so we # can't... return redirect(request, 'index') else: # Did not check the confirmation box... messages.add_message( request, messages.WARNING, _('You need to confirm the deletion of your account.')) # No POST submission or not confirmed, just show page return render_to_response( request, 'mediagoblin/edit/delete_account.html', {'user': user})
def authorize_client(request): form = AuthorizationForm(request.form) client = OAuthClient.query.filter(OAuthClient.id == form.client_id.data).first() if not client: _log.error('No such client id as received from client authorization \ form.') raise BadRequest() if form.validate(): relation = OAuthUserClient() relation.user_id = request.user.id relation.client_id = form.client_id.data if form.allow.data: relation.state = u'approved' elif form.deny.data: relation.state = u'rejected' else: raise BadRequest() relation.save() return redirect(request, location=form.next.data) return render_to_response( request, 'oauth/authorize.html', {'form': form, 'client': client})
def edit_account(request): user = request.user form = forms.EditAccountForm(request.form, wants_comment_notification=user.wants_comment_notification, license_preference=user.license_preference, wants_notifications=user.wants_notifications) if request.method == 'POST' and form.validate(): user.wants_comment_notification = form.wants_comment_notification.data user.wants_notifications = form.wants_notifications.data user.license_preference = form.license_preference.data user.save() messages.add_message(request, messages.SUCCESS, _("Account settings saved")) return redirect(request, 'mediagoblin.user_pages.user_home', user=user.username) return render_to_response( request, 'mediagoblin/edit/edit_account.html', {'user': user, 'form': form})
def authorize_client(request): form = AuthorizationForm(request.form) client = OAuthClient.query.filter(OAuthClient.id == form.client_id.data).first() if not client: _log.error( """No such client id as received from client authorization form.""" ) return BadRequest() if form.validate(): relation = OAuthUserClient() relation.user_id = request.user.id relation.client_id = form.client_id.data if form.allow.data: relation.state = u"approved" elif form.deny.data: relation.state = u"rejected" else: return BadRequest relation.save() return redirect(request, location=form.next.data) return render_to_response(request, "oauth/authorize.html", {"form": form, "client": client})
def register_client(request): ''' Register an OAuth client ''' form = ClientRegistrationForm(request.form) if request.method == 'POST' and form.validate(): client = OAuthClient() client.name = six.text_type(form.name.data) client.description = six.text_type(form.description.data) client.type = six.text_type(form.type.data) client.owner_id = request.user.id client.redirect_uri = six.text_type(form.redirect_uri.data) client.save() add_message(request, SUCCESS, _('The client {0} has been registered!')\ .format( client.name)) return redirect(request, 'mediagoblin.plugins.oauth.list_clients') return render_to_response( request, 'oauth/client/register.html', {'form': form})
def register(request): """OpenID Registration View""" if request.method == 'GET': # Need to connect to openid provider before registering a user to # get the users openid url. If method is 'GET', then this page was # acessed without logging in first. return redirect(request, 'mediagoblin.plugins.openid.login') register_form = auth_forms.RegistrationForm(request.form) if register_form.validate(): user = register_user(request, register_form) if user: # redirect the user to their homepage... there will be a # message waiting for them to verify their email return redirect( request, 'mediagoblin.user_pages.user_home', user=user.username) return render_to_response( request, 'mediagoblin/auth/register.html', {'register_form': register_form, 'post_url': request.urlgen('mediagoblin.plugins.openid.register')})
def start_edit(request): """Starts the process of adding an openid url to a users account""" form = auth_forms.LoginForm(request.form) if request.method == 'POST' and form.validate(): query = OpenIDUserURL.query.filter_by( openid_url=form.openid.data ).first() user = query.user if query else None if not user: return_to = request.urlgen('mediagoblin.plugins.openid.finish_edit') success = _start_verification(request, form, return_to, False) if success: return success else: form.openid.errors.append( _('Sorry, an account is already registered to that OpenID.')) return render_to_response( request, 'mediagoblin/plugins/openid/add.html', {'form': form, 'post_url': request.urlgen('mediagoblin.plugins.openid.edit')})
def simple_template_render(request): """ A view for absolutely simple template rendering. Just make sure 'template' is in the matchdict! """ template_name = request.matchdict["template"] return render_to_response(request, template_name, {})
def login(request): """OpenID Login View""" login_form = auth_forms.LoginForm(request.form) allow_registration = mg_globals.app_config["allow_registration"] # Can't store next in request.GET because of redirects to OpenID provider # Store it in the session next = request.GET.get('next') request.session['next'] = next login_failed = False if request.method == 'POST' and login_form.validate(): return_to = request.urlgen( 'mediagoblin.plugins.openid.finish_login') success = _start_verification(request, login_form, return_to) if success: return success login_failed = True return render_to_response( request, 'mediagoblin/plugins/openid/login.html', {'login_form': login_form, 'next': request.session.get('next'), 'login_failed': login_failed, 'post_url': request.urlgen('mediagoblin.plugins.openid.login'), 'allow_registration': allow_registration})
def edit_account(request): user = request.user form = forms.EditAccountForm( request.form, wants_comment_notification=user.wants_comment_notification, license_preference=user.license_preference, ) if request.method == "POST": form_validated = form.validate() if form_validated and form.wants_comment_notification.validate(form): user.wants_comment_notification = form.wants_comment_notification.data if form_validated and form.new_password.data or form.old_password.data: password_matches = auth_lib.bcrypt_check_password(form.old_password.data, user.pw_hash) if password_matches: # the entire form validates and the password matches user.pw_hash = auth_lib.bcrypt_gen_password_hash(form.new_password.data) else: form.old_password.errors.append(_("Wrong password")) if form_validated and form.license_preference.validate(form): user.license_preference = form.license_preference.data if form_validated and not form.errors: user.save() messages.add_message(request, messages.SUCCESS, _("Account settings saved")) return redirect(request, "mediagoblin.user_pages.user_home", user=user.username) return render_to_response(request, "mediagoblin/edit/edit_account.html", {"user": user, "form": form})
def media_home(request, media, page, **kwargs): """ 'Homepage' of a MediaEntry() """ comment_id = request.matchdict.get("comment", None) if comment_id: if request.user: mark_comment_notification_seen(comment_id, request.user) pagination = Pagination( page, media.get_comments(mg_globals.app_config["comments_ascending"]), MEDIA_COMMENTS_PER_PAGE, comment_id ) else: pagination = Pagination( page, media.get_comments(mg_globals.app_config["comments_ascending"]), MEDIA_COMMENTS_PER_PAGE ) comments = pagination() comment_form = user_forms.MediaCommentForm(request.form) media_template_name = media.media_manager.display_template return render_to_response( request, media_template_name, { "media": media, "comments": comments, "pagination": pagination, "comment_form": comment_form, "app_config": mg_globals.app_config, }, )
def user_collection(request, page, url_user=None): """A User-defined Collection""" collection = Collection.query.filter_by( get_creator=url_user, slug=request.matchdict['collection']).first() if not collection: return render_404(request) cursor = collection.get_collection_items() pagination = Pagination(page, cursor) collection_items = pagination() # if no data is available, return NotFound # TODO: Should an empty collection really also return 404? if collection_items == None: return render_404(request) return render_to_response( request, 'mediagoblin/user_pages/collection.html', {'user': url_user, 'collection': collection, 'collection_items': collection_items, 'pagination': pagination})
def multi_submit_start(request): """ First view for submitting a file. """ submit_form = submit_forms.get_submit_start_form( request.form, license=request.user.license_preference) users_collections = Collection.query.filter_by( actor=request.user.id, type=Collection.USER_DEFINED_TYPE).order_by(Collection.title) if users_collections.count() > 0: submit_form.collection.query = users_collections else: del submit_form.collection # Below is what was used for mediagoblin 0.5.0-dev. Above is the new way. # submit_form = submit_forms.SubmitStartForm(request.form, license=request.user.license_preference) filecount = 0 if request.method == 'POST' and submit_form.validate(): if not check_file_field(request, 'file'): submit_form.file.errors.append( _(u'You must provide at least one file.')) else: for submitted_file in request.files.getlist('file'): try: if not submitted_file.filename: # MOST likely an invalid file continue # Skip the rest of the loop for this file else: filename = submitted_file.filename _log.info("html5-multi-upload: Got filename: %s" % filename) # If the filename contains non ascii generate a unique name if not all(ord(c) < 128 for c in filename): filename = unicode( uuid.uuid4()) + splitext(filename)[-1] # Sniff the submitted media to determine which # media plugin should handle processing media_type, media_manager = sniff_media( submitted_file, filename) # create entry and save in database entry = new_upload_entry(request.user) entry.media_type = unicode(media_type) entry.title = ( unicode(submit_form.title.data) or unicode(splitext(submitted_file.filename)[0])) entry.description = unicode( submit_form.description.data) entry.license = unicode( submit_form.license.data) or None # Process the user's folksonomy "tags" entry.tags = convert_to_tag_list_of_dicts( submit_form.tags.data) # Generate a slug from the title entry.generate_slug() queue_file = prepare_queue_task( request.app, entry, filename) with queue_file: queue_file.write(submitted_file.stream.read()) # Save now so we have this data before kicking off processing entry.save() # Pass off to async processing # # (... don't change entry after this point to avoid race # conditions with changes to the document via processing code) feed_url = request.urlgen( 'mediagoblin.user_pages.atom_feed', qualified=True, user=request.user.username) run_process_media(entry, feed_url) if submit_form.collection and submit_form.collection.data: add_media_to_collection( submit_form.collection.data, entry) create_activity("add", entry, request.user, target=submit_form.collection.data) add_comment_subscription(request.user, entry) filecount = filecount + 1 except Exception as e: ''' This section is intended to catch exceptions raised in mediagoblin.media_types ''' if isinstance(e, TypeNotFound) or isinstance( e, FileTypeNotSupported): submit_form.file.errors.append(e) else: raise add_message(request, SUCCESS, _('Woohoo! Submitted %d Files!' % filecount)) return redirect(request, "mediagoblin.user_pages.user_home", user=request.user.username) return render_to_response(request, 'start.html', {'multi_submit_form': submit_form})
def verify_forgot_password(request): """ Check the forgot-password verification and possibly let the user change their password because of it. """ # get form data variables, and specifically check for presence of token formdata = _process_for_token(request) if not formdata['has_token']: return render_404(request) formdata_vars = formdata['vars'] # Catch error if token is faked or expired try: token = get_timed_signer_url("mail_verification_token") \ .loads(formdata_vars['token'], max_age=10*24*3600) except BadSignature: messages.add_message( request, messages.ERROR, _('The verification key or user id is incorrect.')) return redirect(request, 'index') # check if it's a valid user id user = LocalUser.query.filter_by(id=int(token)).first() # no user in db if not user: messages.add_message(request, messages.ERROR, _('The user id is incorrect.')) return redirect(request, 'index') # check if user active and has email verified if user.has_privilege('active'): cp_form = forms.ChangeForgotPassForm(formdata_vars) if request.method == 'POST' and cp_form.validate(): user.pw_hash = tools.bcrypt_gen_password_hash( cp_form.password.data) user.save() messages.add_message( request, messages.INFO, _("You can now log in using your new password.")) return redirect(request, 'mediagoblin.auth.login') else: return render_to_response( request, 'mediagoblin/plugins/basic_auth/change_fp.html', {'cp_form': cp_form}) ## Commenting this out temporarily because I'm checking into ## what's going on with user.email_verified. ## ## ... if this commit lasts long enough for anyone but me (cwebber) to ## notice it, they should pester me to remove this or remove it ## themselves ;) # # if not user.email_verified: # messages.add_message( # request, # messages.ERROR, # _('You need to verify your email before you can reset your' # ' password.')) if not user.status == 'active': messages.add_message( request, messages.ERROR, _("You are no longer an active user. Please contact the system " "admin to reactivate your account.")) return redirect(request, 'index')
def submit_start(request): """ First view for submitting a file. """ upload_limit, max_file_size = get_upload_file_limits(request.user) submit_form = submit_forms.get_submit_start_form( request.form, license=request.user.license_preference, max_file_size=max_file_size, upload_limit=upload_limit, uploaded=request.user.uploaded) if request.method == 'POST' and submit_form.validate(): if not check_file_field(request, 'file'): submit_form.file.errors.append(_(u'You must provide a file.')) else: try: submit_media( mg_app=request.app, user=request.user, submitted_file=request.files['file'], filename=request.files['file'].filename, title=six.text_type(submit_form.title.data), description=six.text_type(submit_form.description.data), license=six.text_type(submit_form.license.data) or None, tags_string=submit_form.tags.data, upload_limit=upload_limit, max_file_size=max_file_size, urlgen=request.urlgen) add_message(request, SUCCESS, _('Woohoo! Submitted!')) return redirect(request, "mediagoblin.user_pages.user_home", user=request.user.username) # Handle upload limit issues except FileUploadLimit: submit_form.file.errors.append( _(u'Sorry, the file size is too big.')) except UserUploadLimit: submit_form.file.errors.append( _('Sorry, uploading this file will put you over your' ' upload limit.')) except UserPastUploadLimit: messages.add_message( request, messages.WARNING, _('Sorry, you have reached your upload limit.')) return redirect(request, "mediagoblin.user_pages.user_home", user=request.user.username) except FileTypeNotSupported as e: submit_form.file.errors.append(e) except Exception as e: raise return render_to_response(request, 'mediagoblin/submit/start.html', { 'submit_form': submit_form, 'app_config': mg_globals.app_config })
def edit_attachments(request, media): if mg_globals.app_config['allow_attachments']: form = forms.EditAttachmentsForm() # Add any attachements if 'attachment_file' in request.files \ and request.files['attachment_file']: # Security measure to prevent attachments from being served as # text/html, which will be parsed by web clients and pose an XSS # threat. # # TODO # This method isn't flawless as some browsers may perform # content-sniffing. # This method isn't flawless as we do the mimetype lookup on the # machine parsing the upload form, and not necessarily the machine # serving the attachments. if mimetypes.guess_type( request.files['attachment_file'].filename)[0] in \ UNSAFE_MIMETYPES: public_filename = secure_filename('{0}.notsafe'.format( request.files['attachment_file'].filename)) else: public_filename = secure_filename( request.files['attachment_file'].filename) attachment_public_filepath \ = mg_globals.public_store.get_unique_filepath( ['media_entries', unicode(media.id), 'attachment', public_filename]) attachment_public_file = mg_globals.public_store.get_file( attachment_public_filepath, 'wb') try: attachment_public_file.write( request.files['attachment_file'].stream.read()) finally: request.files['attachment_file'].stream.close() media.attachment_files.append(dict( name=form.attachment_name.data \ or request.files['attachment_file'].filename, filepath=attachment_public_filepath, created=datetime.utcnow(), )) media.save() messages.add_message( request, messages.SUCCESS, _("You added the attachment %s!") \ % (form.attachment_name.data or request.files['attachment_file'].filename)) return redirect(request, location=media.url_for_self(request.urlgen)) return render_to_response(request, 'mediagoblin/edit/attachments.html', { 'media': media, 'form': form }) else: raise Forbidden("Attachments are disabled")
def terms_of_service(request): if mg_globals.app_config["show_tos"] is False: return render_404(request) return render_to_response(request, 'mediagoblin/terms_of_service.html', {})
def forgot_password(request): """ Forgot password view Sends an email with an url to renew forgotten password. Use GET querystring parameter 'username' to pre-populate the input field """ fp_form = forms.ForgotPassForm(request.form, username=request.args.get('username')) if not (request.method == 'POST' and fp_form.validate()): # Either GET request, or invalid form submitted. Display the template return render_to_response( request, 'mediagoblin/plugins/basic_auth/forgot_password.html', {'fp_form': fp_form}) # If we are here: method == POST and form is valid. username casing # has been sanitized. Store if a user was found by email. We should # not reveal if the operation was successful then as we don't want to # leak if an email address exists in the system. found_by_email = '@' in fp_form.username.data if found_by_email: user = LocalUser.query.filter_by(email=fp_form.username.data).first() # Don't reveal success in case the lookup happened by email address. success_message = _("If that email address (case sensitive!) is " "registered an email has been sent with " "instructions on how to change your password.") else: # found by username user = LocalUser.query.filter_by( username=fp_form.username.data).first() if user is None: messages.add_message( request, messages.WARNING, _("Couldn't find someone with that username.")) return redirect(request, 'mediagoblin.plugins.basic_auth.forgot_password') success_message = _("An email has been sent with instructions " "on how to change your password.") if user and user.has_privilege('active') is False: # Don't send reminder because user is inactive or has no verified email messages.add_message( request, messages.WARNING, _("Could not send password recovery email as your username is " "inactive or your account's email address has not been verified." )) return redirect(request, 'mediagoblin.user_pages.user_home', user=user.username) # SUCCESS. Send reminder and return to login page if user: email_debug_message(request) tools.send_fp_verification_email(user, request) messages.add_message(request, messages.INFO, success_message) return redirect(request, 'mediagoblin.auth.login')
def media_collect(request, media): """Add media to collection submission""" form = user_forms.MediaCollectForm(request.form) # A user's own collections: form.collection.query = Collection.query.filter_by( creator = request.user.id).order_by(Collection.title) if request.method != 'POST' or not form.validate(): # No POST submission, or invalid form if not form.validate(): messages.add_message(request, messages.ERROR, _('Please check your entries and try again.')) return render_to_response( request, 'mediagoblin/user_pages/media_collect.html', {'media': media, 'form': form}) # If we are here, method=POST and the form is valid, submit things. # If the user is adding a new collection, use that: if form.collection_title.data: # Make sure this user isn't duplicating an existing collection existing_collection = Collection.query.filter_by( creator=request.user.id, title=form.collection_title.data).first() if existing_collection: messages.add_message(request, messages.ERROR, _('You already have a collection called "%s"!') % existing_collection.title) return redirect(request, "mediagoblin.user_pages.media_home", user=media.get_uploader.username, media=media.slug_or_id) collection = Collection() collection.title = form.collection_title.data collection.description = form.collection_description.data collection.creator = request.user.id collection.generate_slug() collection.save() # Otherwise, use the collection selected from the drop-down else: collection = form.collection.data if collection and collection.creator != request.user.id: collection = None # Make sure the user actually selected a collection if not collection: messages.add_message( request, messages.ERROR, _('You have to select or add a collection')) return redirect(request, "mediagoblin.user_pages.media_collect", user=media.get_uploader.username, media_id=media.id) # Check whether media already exists in collection elif CollectionItem.query.filter_by( media_entry=media.id, collection=collection.id).first(): messages.add_message(request, messages.ERROR, _('"%s" already in collection "%s"') % (media.title, collection.title)) else: # Add item to collection add_media_to_collection(collection, media, form.note.data) messages.add_message(request, messages.SUCCESS, _('"%s" added to collection "%s"') % (media.title, collection.title)) return redirect_obj(request, media)
def list_podcast(request): podcast_list = ['s','s','a'] add_podcast_form = forms.add_podcast(request.form) return render_to_response(request, '/podcast/podcastlist.html', {'podcast_list':podcast_list, 'add_podcast':add_podcast_form})
def blog_edit(request): """ View for editing an existing blog or creating a new blog if user have not exceeded maximum allowed acount of blogs. """ url_user = request.matchdict.get('user', None) blog_slug = request.matchdict.get('blog_slug', None) config = pluginapi.get_config('mediagoblin.media_types.blog') max_blog_count = config['max_blog_count'] form = blog_forms.BlogEditForm(request.form) # creating a blog if not blog_slug: if Blog.query.filter_by( author=request.user.id).count() < max_blog_count: if request.method == 'GET': return render_to_response( request, 'mediagoblin/blog/blog_edit_create.html', { 'form': form, 'user': request.user, 'app_config': mg_globals.app_config }) if request.method == 'POST' and form.validate(): _log.info("Here") blog = request.db.Blog() blog.title = six.text_type(form.title.data) blog.description = six.text_type( cleaned_markdown_conversion((form.description.data))) blog.author = request.user.id blog.generate_slug() blog.save() return redirect( request, "mediagoblin.media_types.blog.blog_admin_dashboard", user=request.user.username) else: add_message( request, ERROR, "Welcome! You already have created \ maximum number of blogs." ) return redirect( request, "mediagoblin.media_types.blog.blog_admin_dashboard", user=request.user.username) #Blog already exists. else: blog = get_blog_by_slug(request, blog_slug) if not blog: return render_404(request) if request.method == 'GET': defaults = dict(title=blog.title, description=cleaned_markdown_conversion( blog.description), author=request.user.id) form = blog_forms.BlogEditForm(**defaults) return render_to_response( request, 'mediagoblin/blog/blog_edit_create.html', { 'form': form, 'user': request.user, 'app_config': mg_globals.app_config }) else: if request.method == 'POST' and form.validate(): blog.title = six.text_type(form.title.data) blog.description = six.text_type( cleaned_markdown_conversion((form.description.data))) blog.author = request.user.id blog.generate_slug() blog.save() add_message(request, SUCCESS, "Your blog is updated.") return redirect(request, "mediagoblin.media_types.blog.blog-dashboard", user=request.user.username, blog_slug=blog.slug)