Exemple #1
0
def resend_activation(request):
    """
    The reactivation view

    Resend the activation email.
    """

    if request.user is None:
        messages.add_message(
            request, messages.ERROR,
            _('You must be logged in so we know who to send the email to!'))

        return redirect(request, 'mediagoblin.auth.login')

    if request.user.has_privilege(u'active'):
        messages.add_message(request, messages.ERROR,
                             _("You've already verified your email address!"))

        return redirect(request,
                        "mediagoblin.user_pages.user_home",
                        user=request.user.username)

    email_debug_message(request)
    send_verification_email(request.user, request)

    messages.add_message(request, messages.INFO,
                         _('Resent your verification email.'))
    return redirect(request,
                    'mediagoblin.user_pages.user_home',
                    user=request.user.username)
Exemple #2
0
def add(request):
    if request.method == 'GET':
        return redirect(request, 'mediagoblin.plugins.persona.edit')

    email = _get_response(request)

    if email:
        query = PersonaUserEmails.query.filter_by(
            persona_email=email
        ).first()
    user_exists = query.user if query else None

    if user_exists:
        messages.add_message(
            request,
            messages.WARNING,
            _('Sorry, an account is already registered with that Persona'
              ' email address.'))
        return redirect(request, 'mediagoblin.plugins.persona.edit')

    else:
        # Save the Persona Email to the user
        new_entry = PersonaUserEmails()
        new_entry.persona_email = email
        new_entry.user_id = request.user.id
        new_entry.save()

        messages.add_message(
            request,
            messages.SUCCESS,
            _('Your Persona email address was saved successfully.'))

        return redirect(request, 'mediagoblin.edit.account')
Exemple #3
0
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')
        })
Exemple #4
0
def finish_edit(request):
    """Finishes the process of adding an openid url to a user"""
    response = _finish_verification(request)

    if not response:
        # Verification failed, redirect to add openid page.
        return redirect(request, 'mediagoblin.plugins.openid.edit')

    # Verification was successfull
    query = OpenIDUserURL.query.filter_by(
        openid_url=response.identity_url, ).first()
    user_exists = query.user if query else None

    if user_exists:
        # user exists with that openid url, redirect back to edit page
        messages.add_message(
            request, messages.WARNING,
            _('Sorry, an account is already registered to that OpenID.'))
        return redirect(request, 'mediagoblin.plugins.openid.edit')

    else:
        # Save openid to user
        user = User.query.filter_by(id=request.session['user_id']).first()

        new_entry = OpenIDUserURL()
        new_entry.openid_url = response.identity_url
        new_entry.user_id = user.id
        new_entry.save()

        messages.add_message(request, messages.SUCCESS,
                             _('Your OpenID url was saved successfully.'))

        return redirect(request, 'mediagoblin.edit.account')
Exemple #5
0
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')})
Exemple #6
0
def edit_account(request):
    user = request.user
    form = forms.EditAccountForm(request.form, wants_comment_notification=user.get("wants_comment_notification"))

    if request.method == "POST":
        form_validated = form.validate()

        # if the user has not filled in the new or old password fields
        if not form.new_password.data and not form.old_password.data:
            if form.wants_comment_notification.validate(form):
                user.wants_comment_notification = form.wants_comment_notification.data
                user.save()
                messages.add_message(request, messages.SUCCESS, _("Account settings saved"))
                return redirect(request, "mediagoblin.user_pages.user_home", user=user.username)

        # so the user has filled in one or both of the password fields
        else:
            if form_validated:
                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)
                    user.wants_comment_notification = form.wants_comment_notification.data
                    user.save()
                    messages.add_message(request, messages.SUCCESS, _("Account settings saved"))
                    return redirect(request, "mediagoblin.user_pages.user_home", user=user.username)
                else:
                    form.old_password.errors.append(_("Wrong password"))

    return render_to_response(request, "mediagoblin/edit/edit_account.html", {"user": user, "form": form})
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 all the associated comments
            for comment in media.get_comments():
                comment.delete()

            # Delete all files on the public storage
            try:
                delete_media_files(media)
            except OSError, error:
                _log.error('No such files from the user "{1}"'
                           ' to delete: {0}'.format(str(error), username))
                messages.add_message(request, messages.ERROR,
                                     _('Some of the files with this entry seem'
                                       ' to be missing.  Deleting anyway.'))

            media.delete()
            messages.add_message(
                request, messages.SUCCESS, _('You deleted the media.'))

            return redirect(request, "mediagoblin.user_pages.user_home",
                user=username)
        else:
            messages.add_message(
                request, messages.ERROR,
                _("The media was not deleted because you didn't check that you were sure."))
            return redirect(request,
                            location=media.url_for_self(request.urlgen))
Exemple #8
0
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')
        })
Exemple #9
0
def add(request):
    if request.method == 'GET':
        return redirect(request, 'mediagoblin.plugins.persona.edit')

    email = _get_response(request)

    if email:
        query = PersonaUserEmails.query.filter_by(persona_email=email).first()
    user_exists = query.user if query else None

    if user_exists:
        messages.add_message(
            request, messages.WARNING,
            _('Sorry, an account is already registered with that Persona'
              ' email address.'))
        return redirect(request, 'mediagoblin.plugins.persona.edit')

    else:
        # Save the Persona Email to the user
        new_entry = PersonaUserEmails()
        new_entry.persona_email = email
        new_entry.user_id = request.user.id
        new_entry.save()

        request.session['persona_login_email'] = email

        messages.add_message(
            request, messages.SUCCESS,
            _('Your Persona email address was saved successfully.'))

        return redirect(request, 'mediagoblin.edit.account')
Exemple #10
0
def register(request):
    """The registration view.

    Note that usernames will always be lowercased. Email domains are lowercased while
    the first part remains case-sensitive.
    """
    # Redirects to indexpage if registrations are disabled
    if not mg_globals.app_config["allow_registration"]:
        messages.add_message(
            request,
            messages.WARNING,
            _('Sorry, registration is disabled on this instance.'))
        return redirect(request, "index")

    register_form = auth_forms.RegistrationForm(request.form)

    if request.method == 'POST' and register_form.validate():
        # TODO: Make sure the user doesn't exist already
        users_with_username = User.query.filter_by(username=register_form.data['username']).count()
        users_with_email = User.query.filter_by(email=register_form.data['email']).count()

        extra_validation_passes = True

        if users_with_username:
            register_form.username.errors.append(
                _(u'Sorry, a user with that name already exists.'))
            extra_validation_passes = False
        if users_with_email:
            register_form.email.errors.append(
                _(u'Sorry, a user with that email address already exists.'))
            extra_validation_passes = False

        if extra_validation_passes:
            # Create the user
            user = User()
            user.username = register_form.data['username']
            user.email = register_form.data['email']
            user.pw_hash = auth_lib.bcrypt_gen_password_hash(
                register_form.password.data)
            user.verification_key = unicode(uuid.uuid4())
            user.save()

            # log the user in
            request.session['user_id'] = unicode(user.id)
            request.session.save()

            # send verification email
            email_debug_message(request)
            send_verification_email(user, request)

            # 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})
Exemple #11
0
def login(request):
    if request.method == 'GET':
        return redirect(request, 'mediagoblin.auth.login')

    email = _get_response(request)
    if email:
        query = PersonaUserEmails.query.filter_by(persona_email=email).first()
        user = query.user if query else None

        if user:
            request.session['user_id'] = unicode(user.id)
            request.session['persona_login_email'] = email
            request.session.save()

            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.RegistrationForm(email=email,
                                                   persona_email=email)
            return render_to_response(
                request, 'mediagoblin/auth/register.html', {
                    'register_form':
                    register_form,
                    'post_url':
                    request.urlgen('mediagoblin.plugins.persona.register')
                })

    return redirect(request, 'mediagoblin.auth.login')
Exemple #12
0
def change_pass(request):
    # If no password authentication, no need to change your password
    if 'pass_auth' not in request.template_env.globals:
        return redirect(request, 'index')

    form = forms.ChangePassForm(request.form)
    user = request.user

    if request.method == 'POST' and form.validate():

        if not auth.check_password(form.old_password.data, user.pw_hash):
            form.old_password.errors.append(_('Wrong password'))

            return render_to_response(request,
                                      'mediagoblin/edit/change_pass.html', {
                                          'form': form,
                                          'user': user
                                      })

        # Password matches
        user.pw_hash = auth.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/edit/change_pass.html', {
        'form': form,
        'user': user
    })
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')
Exemple #14
0
def resend_activation(request):
    """
    The reactivation view

    Resend the activation email.
    """

    if request.user is None:
        messages.add_message(
            request,
            messages.ERROR,
            _('You must be logged in so we know who to send the email to!'))

        return redirect(request, 'mediagoblin.auth.login')

    if request.user.has_privilege(u'active'):
        messages.add_message(
            request,
            messages.ERROR,
            _("You've already verified your email address!"))

        return redirect(request, "mediagoblin.user_pages.user_home", user=request.user.username)

    email_debug_message(request)
    send_verification_email(request.user, request)

    messages.add_message(
        request,
        messages.INFO,
        _('Resent your verification email.'))
    return redirect(
        request, 'mediagoblin.user_pages.user_home',
        user=request.user.username)
Exemple #15
0
def verify_email(request):
    """
    Email verification view for changing email address
    """
    # If no token, we can't do anything
    if not "token" in request.GET:
        return render_404(request)

    # Catch error if token is faked or expired
    token = None
    try:
        token = get_timed_signer_url("mail_verification_token").loads(request.GET["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")

    user = User.query.filter_by(id=int(token["user"])).first()

    if user:
        user.email = token["email"]
        user.save()

        messages.add_message(request, messages.SUCCESS, _("Your email address has been verified."))

    else:
        messages.add_message(request, messages.ERROR, _("The verification key or user id is incorrect."))

    return redirect(request, "mediagoblin.user_pages.user_home", user=user.username)
Exemple #16
0
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')})
Exemple #17
0
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 = 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')
Exemple #18
0
def forgot_password(request):
    """
    Forgot password view

    Sends an email with an url to renew forgotten password
    """
    fp_form = auth_forms.ForgotPassForm(request.form,
                                        username=request.GET.get('username'))

    if request.method == 'POST' and fp_form.validate():

        # '$or' not available till mongodb 1.5.3
        user = request.db.User.find_one(
            {'username': request.form['username']})
        if not user:
            user = request.db.User.find_one(
                {'email': request.form['username']})

        if user:
            if user.email_verified and user.status == 'active':
                user.fp_verification_key = unicode(uuid.uuid4())
                user.fp_token_expire = datetime.datetime.now() + \
                                          datetime.timedelta(days=10)
                user.save()

                send_fp_verification_email(user, request)

                messages.add_message(
                    request,
                    messages.INFO,
                    _("An email has been sent with instructions on how to "
                      "change your password."))
                email_debug_message(request)

            else:
                # special case... we can't send the email because the
                # username is inactive / hasn't verified their 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)
            return redirect(request, 'mediagoblin.auth.login')
        else:
            messages.add_message(
                request,
                messages.WARNING,
                _("Couldn't find someone with that username or email."))
            return redirect(request, 'mediagoblin.auth.forgot_password')

    return render_to_response(
        request,
        'mediagoblin/auth/forgot_password.html',
        {'fp_form': fp_form})
Exemple #19
0
def edit_subtitles(request, media):
    allowed_extensions = ['aqt','gsub','jss','sub','ttxt','pjs','psb',
                        'rt','smi','stl','ssf','srt','ssa','ass','usf','vtt','lrc']
    form = forms.EditSubtitlesForm(request.form)

    # Add any subtitles
    if 'subtitle_file' in request.files \
        and request.files['subtitle_file']:
        if mimetypes.guess_type(
                request.files['subtitle_file'].filename)[0] in \
                UNSAFE_MIMETYPES:
            public_filename = secure_filename('{0}.notsafe'.format(
                request.files['subtitle_file'].filename))
        else:
            public_filename = secure_filename(
                    request.files['subtitle_file'].filename)
        filepath = request.files['subtitle_file'].filename
        if filepath.split('.')[-1] not in allowed_extensions :
            messages.add_message(
            request,
            messages.ERROR,
            ("Invalid subtitle file"))

            return redirect(request,
                            location=media.url_for_self(request.urlgen))
        subtitle_public_filepath = mg_globals.public_store.get_unique_filepath(
            ['media_entries', six.text_type(media.id), 'subtitle',
             public_filename])

        with mg_globals.public_store.get_file(
            subtitle_public_filepath, 'wb') as subtitle_public_file:
            subtitle_public_file.write(
                request.files['subtitle_file'].stream.read())
        request.files['subtitle_file'].stream.close()

        media.subtitle_files.append(dict(
                name=form.subtitle_language.data \
                    or request.files['subtitle_file'].filename,
                filepath=subtitle_public_filepath,
                created=datetime.utcnow(),
                ))

        media.save()

        messages.add_message(
            request,
            messages.SUCCESS,
            ("You added the subtitle %s!") %
                (form.subtitle_language.data or
                 request.files['subtitle_file'].filename))

        return redirect(request,
                        location=media.url_for_self(request.urlgen))
    return render_to_response(
        request,
        'mediagoblin/plugins/subtitles/subtitles.html',
        {'media': media,
         'form': form})
Exemple #20
0
    def new_controller_func(request, *args, **kwargs):
        if request.user and request.user.status == u"needs_email_verification":
            return redirect(request, "mediagoblin.user_pages.user_home", user=request.user.username)
        elif not request.user or request.user.status != u"active":
            next_url = urljoin(request.urlgen("mediagoblin.auth.login", qualified=True), request.url)

            return redirect(request, "mediagoblin.auth.login", next=next_url)

        return controller(request, *args, **kwargs)
Exemple #21
0
def edit_subtitles(request, media):
    # This was originally quite a long list of allowed extensions, but as far as
    # I understand, Video.js only supports WebVTT format subtitles:
    # https://docs.videojs.com/docs/guides/text-tracks.html
    allowed_extensions = ['vtt']
    form = forms.EditSubtitlesForm(request.form)

    # Add any subtitles
    if 'subtitle_file' in request.files \
        and request.files['subtitle_file']:
        if mimetypes.guess_type(
                request.files['subtitle_file'].filename)[0] in \
                UNSAFE_MIMETYPES:
            public_filename = secure_filename('{}.notsafe'.format(
                request.files['subtitle_file'].filename))
        else:
            public_filename = secure_filename(
                request.files['subtitle_file'].filename)
        filepath = request.files['subtitle_file'].filename
        if filepath.split('.')[-1] not in allowed_extensions:
            messages.add_message(request, messages.ERROR,
                                 ("Invalid subtitle file"))

            return redirect(request,
                            location=media.url_for_self(request.urlgen))
        subtitle_public_filepath = mg_globals.public_store.get_unique_filepath(
            ['media_entries',
             str(media.id), 'subtitle', public_filename])

        with mg_globals.public_store.get_file(subtitle_public_filepath,
                                              'wb') as subtitle_public_file:
            subtitle_public_file.write(
                request.files['subtitle_file'].stream.read())
        request.files['subtitle_file'].stream.close()

        media.subtitle_files.append(dict(
                name=form.subtitle_language.data \
                    or request.files['subtitle_file'].filename,
                filepath=subtitle_public_filepath,
                created=datetime.utcnow(),
                ))

        media.save()

        messages.add_message(request, messages.SUCCESS,
                             ("You added the subtitle %s!") %
                             (form.subtitle_language.data
                              or request.files['subtitle_file'].filename))

        return redirect(request, location=media.url_for_self(request.urlgen))
    return render_to_response(request,
                              'mediagoblin/plugins/subtitles/subtitles.html', {
                                  'media': media,
                                  'form': form
                              })
Exemple #22
0
def mark_all_comment_notifications_seen(request):
    """
    Marks all comment notifications seen.
    """
    for comment in get_notifications(request.user.id):
        mark_comment_notification_seen(comment.subject_id, request.user)

    if request.GET.get("next"):
        return redirect(request, location=request.GET.get("next"))
    else:
        return redirect(request, "index")
Exemple #23
0
def mark_all_comment_notifications_seen(request):
    """
    Marks all comment notifications seen.
    """
    for comment in get_notifications(request.user.id):
        mark_comment_notification_seen(comment.subject_id, request.user)

    if request.GET.get('next'):
        return redirect(request, location=request.GET.get('next'))
    else:
        return redirect(request, 'index')
Exemple #24
0
def blog_delete(request, **kwargs):
    """
    Deletes a blog and media entries, tags associated with it.
    """
    url_user = request.matchdict.get('user')
    owner_user = request.db.LocalUser.query.filter(
        LocalUser.username==url_user
    ).first()

    blog_slug = request.matchdict.get('blog_slug', None)
    blog = get_blog_by_slug(request, blog_slug, author=owner_user.id)
    if not blog:
        return render_404(request)

    form = blog_forms.ConfirmDeleteForm(request.form)
    if request.user.id == blog.author or request.user.has_privilege(u'admin'):
        if request.method == 'POST' and form.validate():
            if form.confirm.data is True:
                blog.delete()
                messages.add_message(
                    request,
                    messages.SUCCESS,
                    _('You deleted the Blog.'))
                return redirect(request, "mediagoblin.media_types.blog.blog_admin_dashboard",
                        user=request.user.username)
            else:
                messages.add_message(
                    request,
                    messages.ERROR,
                    _("The media was not deleted because you didn't check "
                      "that you were sure."))
                return redirect(request, "mediagoblin.media_types.blog.blog_admin_dashboard",
                        user=request.user.username)
        else:
            if request.user.has_privilege(u'admin'):
                messages.add_message(
                    request,
                    messages.WARNING,
                    _("You are about to delete another user's Blog. "
                      "Proceed with caution."))
            return render_to_response(
            request,
            'mediagoblin/blog/blog_confirm_delete.html',
            {'blog':blog,
            'form':form
            })
    else:
        messages.add_message(
            request,
            messages.ERROR,
            _("The blog was not deleted because you have no rights."))
        return redirect(request, "mediagoblin.media_types.blog.blog_admin_dashboard",
        user=request.user.username)
Exemple #25
0
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"]})
Exemple #26
0
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"]
        })
Exemple #27
0
def custom_subtitles(request,media,id=None):
    id = request.matchdict['id']
    path = ""
    for subtitle in media.subtitle_files:
        if subtitle["id"] == id:
            path = subtitle["filepath"]
    text = ""
    value = open_subtitle(path)
    text, status = value[0], value[1]
    if status == True :
        form = forms.CustomizeSubtitlesForm(request.form,
                                             subtitle=text)
        if request.method == 'POST' and form.validate():
            subtitle_data = form.subtitle.data
            status = save_subtitle(path,subtitle_data)
            if status == True:
                messages.add_message(
                    request,
                    messages.SUCCESS,
                    ("Subtitle file changed!!!"))
                return redirect(request,
                                    location=media.url_for_self(request.urlgen))
            else :
                messages.add_message(
                    request,
                    messages.ERROR,
                    ("Couldn't edit the subtitles!!!"))
                return redirect(request,
                                    location=media.url_for_self(request.urlgen))

        return render_to_response(
            request,
            "mediagoblin/plugins/subtitles/custom_subtitles.html",
            {"id": id,
             "media": media,
             "form": form })
    else:
        index = 0
        for subtitle in media.subtitle_files:
            if subtitle["id"] == id:
                delete_container = index
                media.subtitle_files.pop(delete_container)
                media.save()
                break
            index += 1
        messages.add_message(
            request,
            messages.ERROR,
            ("File link broken! Upload the subtitle again"))
        return redirect(request,
                            location=media.url_for_self(request.urlgen))
Exemple #28
0
def blog_delete(request, **kwargs):
    """
    Deletes a blog and media entries, tags associated with it.
    """
    url_user = request.matchdict.get('user')
    owner_user = request.db.LocalUser.query.filter(
        LocalUser.username == url_user).first()

    blog_slug = request.matchdict.get('blog_slug', None)
    blog = get_blog_by_slug(request, blog_slug, author=owner_user.id)
    if not blog:
        return render_404(request)

    form = blog_forms.ConfirmDeleteForm(request.form)
    if request.user.id == blog.author or request.user.has_privilege(u'admin'):
        if request.method == 'POST' and form.validate():
            if form.confirm.data is True:
                blog.delete()
                messages.add_message(request, messages.SUCCESS,
                                     _('You deleted the Blog.'))
                return redirect(
                    request,
                    "mediagoblin.media_types.blog.blog_admin_dashboard",
                    user=request.user.username)
            else:
                messages.add_message(
                    request, messages.ERROR,
                    _("The media was not deleted because you didn't check "
                      "that you were sure."))
                return redirect(
                    request,
                    "mediagoblin.media_types.blog.blog_admin_dashboard",
                    user=request.user.username)
        else:
            if request.user.has_privilege(u'admin'):
                messages.add_message(
                    request, messages.WARNING,
                    _("You are about to delete another user's Blog. "
                      "Proceed with caution."))
            return render_to_response(
                request, 'mediagoblin/blog/blog_confirm_delete.html', {
                    'blog': blog,
                    'form': form
                })
    else:
        messages.add_message(
            request, messages.ERROR,
            _("The blog was not deleted because you have no rights."))
        return redirect(request,
                        "mediagoblin.media_types.blog.blog_admin_dashboard",
                        user=request.user.username)
Exemple #29
0
def mark_all_comment_notifications_seen(request):
    """
    Marks all comment notifications seen.
    """
    for comment in get_notifications(request.user.id):
        mark_comment_notification_seen(
            comment.obj().get_comment_link().id,
            request.user
        )

    if request.GET.get('next'):
        return redirect(request, location=request.GET.get('next'))
    else:
        return redirect(request, 'index')
Exemple #30
0
    def new_controller_func(request, *args, **kwargs):
        if request.user and \
                request.user.status == u'needs_email_verification':
            return redirect(request,
                            'mediagoblin.user_pages.user_home',
                            user=request.user.username)
        elif not request.user or request.user.status != u'active':
            next_url = urljoin(
                request.urlgen('mediagoblin.auth.login', qualified=True),
                request.url)

            return redirect(request, 'mediagoblin.auth.login', next=next_url)

        return controller(request, *args, **kwargs)
Exemple #31
0
    def new_controller_func(request, *args, **kwargs):
        if request.user and \
                not request.user.has_privilege(u'active'):
            return redirect(request,
                            'mediagoblin.user_pages.user_home',
                            user=request.user.username)
        elif not request.user or not request.user.has_privilege(u'active'):
            next_url = urljoin(
                request.urlgen('mediagoblin.auth.login', qualified=True),
                request.url)

            return redirect(request, 'mediagoblin.auth.login', next=next_url)

        return controller(request, *args, **kwargs)
Exemple #32
0
def login(request):
    """
    MediaGoblin login view.

    If you provide the POST with 'next', it'll redirect to that view.
    """
    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}.login'.format(redirect_name))
        else:
            return redirect(request, 'index')

    login_form = hook_handle("auth_get_login_form", request)

    login_failed = False

    if request.method == 'POST':

        if login_form.validate():
            user = check_login_simple(login_form.username.data,
                                      login_form.password.data)

            if user:
                # set up login in session
                if login_form.stay_logged_in.data:
                    request.session['stay_logged_in'] = True
                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")

            login_failed = True
            remote_addr = (request.access_route and request.access_route[-1]
                           or request.remote_addr)
            _log.warn("Failed login attempt from %r", remote_addr)

    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.auth.login'),
            'allow_registration': mg_globals.app_config["allow_registration"]
        })
Exemple #33
0
def verify_email(request):
    """
    Email verification view

    validates GET parameters against database and unlocks the user account, if
    you are lucky :)
    """
    # If we don't have userid and token parameters, we can't do anything; 404
    if not 'token' in request.GET:
        return render_404(request)

    # Catch error if token is faked or expired
    try:
        token = get_timed_signer_url("mail_verification_token") \
                .loads(request.GET['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')

    user = User.query.filter_by(id=int(token)).first()

    if user and user.has_privilege(u'active') is False:
        user.verification_key = None
        user.all_privileges.append(
            Privilege.query.filter(
            Privilege.privilege_name==u'active').first())

        user.save()

        messages.add_message(
            request,
            messages.SUCCESS,
            _("Your email address has been verified. "
              "You may now login, edit your profile, and submit images!"))
    else:
        messages.add_message(
            request,
            messages.ERROR,
            _('The verification key or user id is incorrect'))

    return redirect(
        request, 'mediagoblin.user_pages.user_home',
        user=user.username)
def login(request):
    """
    MediaGoblin login view.

    If you provide the POST with 'next', it'll redirect to that view.
    """
    #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}.login'.format(
    #            redirect_name))
    #    else:
    #        return redirect(request, 'index')

    login_form = auth_forms.LoginForm(request.form)

    login_failed = False

    #if request.method == 'POST' and login_form.validate():
    if request.method == 'POST':

        if login_form.validate():
            user = check_login_simple(
                login_form.username.data,
                login_form.password.data)

            if user:
                # set up login in session
                if login_form.stay_logged_in.data:
                    request.session['stay_logged_in'] = True
                request.session['user_id'] = unicode(user.id)
                request.session.save()

                if request.form.get('next'):
                    return redirect(request, location=request.form['next'])
                else:
                    return redirect(request, "index")

            login_failed = True

    return render_to_response(
        request,
        'mediagoblin/plugins/recaptcha/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.recaptcha.login'),
         'allow_registration': mg_globals.app_config["allow_registration"]})
Exemple #35
0
    def new_controller_func(request, *args, **kwargs):
        if request.user and \
                request.user.get('status') == u'needs_email_verification':
            return redirect(
                request, 'mediagoblin.user_pages.user_home',
                user=request.user.username)
        elif not request.user or request.user.get('status') != u'active':
            next_url = urljoin(
                    request.urlgen('mediagoblin.auth.login',
                        qualified=True),
                    request.url)

            return redirect(request, 'mediagoblin.auth.login',
                            next=url_quote(next_url))

        return controller(request, *args, **kwargs)
Exemple #36
0
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})
Exemple #37
0
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
    })
Exemple #38
0
def edit_profile(request, url_user=None):
    # admins may edit any user profile
    if request.user.username != url_user.username:
        if not request.user.has_privilege(u'admin'):
            raise Forbidden(_("You can only edit your own profile."))

        # No need to warn again if admin just submitted an edited profile
        if request.method != 'POST':
            messages.add_message(
                request, messages.WARNING,
                _("You are editing a user's profile. Proceed with caution."))

    user = url_user

    form = forms.EditProfileForm(request.form, url=user.url, bio=user.bio)

    if request.method == 'POST' and form.validate():
        user.url = unicode(form.url.data)
        user.bio = unicode(form.bio.data)

        user.save()

        messages.add_message(request, messages.SUCCESS,
                             _("Profile changes saved"))
        return redirect(request,
                        'mediagoblin.user_pages.user_home',
                        user=user.username)

    return render_to_response(request, 'mediagoblin/edit/edit_profile.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.')
        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
    })
Exemple #40
0
def change_pass(request):
    form = 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/basic_auth/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/basic_auth/change_pass.html', {
            'form': form,
            'user': user
        })
Exemple #41
0
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})
Exemple #42
0
def authorize_finish(request):
    """ Finishes the authorize """
    _ = pass_to_ugettext
    token = request.form["oauth_token"]
    verifier = request.form["oauth_verifier"]
    oauth_request = RequestToken.query.filter_by(token=token,
                                                 verifier=verifier)
    oauth_request = oauth_request.first()

    if oauth_request is None:
        # invalid token or verifier
        err_msg = _("No request token found.")
        return render_400(request, err_msg)

    oauth_request.used = True
    oauth_request.updated = datetime.datetime.now()
    oauth_request.save()

    if oauth_request.callback == "oob":
        # out of bounds
        context = {"oauth_request": oauth_request}
        return render_to_response(request, "mediagoblin/api/oob.html", context)

    # okay we need to redirect them then!
    querystring = "?oauth_token={0}&oauth_verifier={1}".format(
        oauth_request.token, oauth_request.verifier)

    # It's come from the OAuth headers so it'll be encoded.
    redirect_url = urllib.unquote(oauth_request.callback)

    return redirect(request, querystring=querystring, location=redirect_url)
def media_post_comment(request, media):
    """
    recieves POST from a MediaEntry() comment form, saves the comment.
    """
    assert request.method == 'POST'

    comment = request.db.MediaComment()
    comment.media_entry = media.id
    comment.author = request.user.id
    comment.content = unicode(request.form['comment_content'])

    if not comment.content.strip():
        messages.add_message(
            request,
            messages.ERROR,
            _("Oops, your comment was empty."))
    else:
        comment.save()

        messages.add_message(
            request, messages.SUCCESS,
            _('Your comment has been posted!'))

        media_uploader = media.get_uploader
        #don't send email if you comment on your own post
        if (comment.author != media_uploader and
            media_uploader.wants_comment_notification):
            send_comment_email(media_uploader, comment, media, request)

    return redirect(request, location=media.url_for_self(request.urlgen))
Exemple #44
0
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 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})
Exemple #46
0
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 authorize(request, client):
    # TODO: Get rid of the JSON responses in this view, it's called by the
    # user-agent, not the client.
    user_client_relation = OAuthUserClient.query.filter(
        (OAuthUserClient.user == request.user)
        & (OAuthUserClient.client == client))

    if user_client_relation.filter(
            OAuthUserClient.state == u'approved').count():
        redirect_uri = None

        if client.type == u'public':
            if not client.redirect_uri:
                return json_response(
                    {
                        'status':
                        400,
                        'errors': [
                            u'Public clients should have a redirect_uri pre-set.'
                        ]
                    },
                    _disable_cors=True)

            redirect_uri = client.redirect_uri

        if client.type == u'confidential':
            redirect_uri = request.GET.get('redirect_uri', client.redirect_uri)
            if not redirect_uri:
                return json_response(
                    {
                        'status': 400,
                        'errors': [u'No redirect_uri supplied!']
                    },
                    _disable_cors=True)

        code = OAuthCode()
        code.user = request.user
        code.client = client
        code.save()

        redirect_uri = ''.join(
            [redirect_uri, '?',
             urlencode({'code': code.code})])

        _log.debug('Redirecting to {0}'.format(redirect_uri))

        return redirect(request, location=redirect_uri)
    else:
        # Show prompt to allow client to access data
        # - on accept: send the user agent back to the redirect_uri with the
        # code parameter
        # - on deny: send the user agent back to the redirect uri with error
        # information
        form = AuthorizationForm(request.form)
        form.client_id.data = client.id
        form.next.data = request.url
        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})
Exemple #49
0
def file_a_report(request, media, comment):
    """
    This view handles the filing of a Report.
    """
    if comment is not None:
        if not comment.target().id == media.id:
            return render_404(request)

        form = user_forms.CommentReportForm(request.form)
        context = {'media': comment.target(), 'comment': comment, 'form': form}
    else:
        form = user_forms.MediaReportForm(request.form)
        context = {'media': media, 'form': form}
    form.reporter_id.data = request.user.id

    if request.method == "POST":
        report_object = build_report_object(form,
                                            media_entry=media,
                                            comment=comment)

        # if the object was built successfully, report_table will not be None
        if report_object:
            report_object.save()
            return redirect(request, 'index')

    return render_to_response(request, 'mediagoblin/user_pages/report.html',
                              context)
Exemple #50
0
def verify_email(request):
    """
    Email verification view

    validates GET parameters against database and unlocks the user account, if
    you are lucky :)
    """
    # If we don't have userid and token parameters, we can't do anything; 404
    if not 'userid' in request.GET or not 'token' in request.GET:
        return render_404(request)

    user = request.db.User.find_one(
        {'_id': ObjectId(unicode(request.GET['userid']))})

    if user and user.verification_key == unicode(request.GET['token']):
        user.status = u'active'
        user.email_verified = True
        user.verification_key = None

        user.save()

        messages.add_message(
            request,
            messages.SUCCESS,
            _("Your email address has been verified. "
              "You may now login, edit your profile, and submit images!"))
    else:
        messages.add_message(
            request,
            messages.ERROR,
            _('The verification key or user id is incorrect'))

    return redirect(
        request, 'mediagoblin.user_pages.user_home',
        user=user.username)
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})
Exemple #52
0
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}
    )
Exemple #53
0
    def new_controller_func(request, *args, **kwargs):
        if request.user and \
                not request.user.has_privilege(u'active'):
            return redirect(
                request, 'mediagoblin.user_pages.user_home',
                user=request.user.username)
        elif not request.user or not request.user.has_privilege(u'active'):
            next_url = urljoin(
                    request.urlgen('mediagoblin.auth.login',
                        qualified=True),
                    request.url)

            return redirect(request, 'mediagoblin.auth.login',
                            next=next_url)

        return controller(request, *args, **kwargs)
Exemple #54
0
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})
Exemple #55
0
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})
Exemple #56
0
def subscribe_comments(request, media):

    add_comment_subscription(request.user, media)

    messages.add_message(request, messages.SUCCESS,
                         _('Subscribed to comments on %s!') % media.title)

    return redirect(request, location=media.url_for_self(request.urlgen))
Exemple #57
0
    def wrapper(request, *args, **kwargs):
        if not mgg.app_config["allow_registration"]:
            messages.add_message(
                request, messages.WARNING,
                _('Sorry, registration is disabled on this instance.'))
            return redirect(request, "index")

        return controller(request, *args, **kwargs)
Exemple #58
0
    def wrapper(request, *args, **kwargs):
        if not mgg.app.auth:
            messages.add_message(
                request, messages.WARNING,
                _('Sorry, authentication is disabled on this instance.'))
            return redirect(request, 'index')

        return controller(request, *args, **kwargs)
Exemple #59
0
def finish_login(request):
    """Complete OpenID Login Process"""
    response = _finish_verification(request)

    if not response:
        # Verification failed, redirect to login page.
        return redirect(request, 'mediagoblin.plugins.openid.login')

    # Verification was successfull
    query = OpenIDUserURL.query.filter_by(
        openid_url=response.identity_url, ).first()
    user = query.user if query else None

    if user:
        # Set up login in session
        request.session['user_id'] = str(user.id)
        request.session.save()

        if request.session.get('next'):
            return redirect(request, location=request.session.pop('next'))
        else:
            return redirect(request, "index")
    else:
        # No user, need to register
        if not mg_globals.app_config['allow_registration']:
            messages.add_message(
                request, messages.WARNING,
                _('Sorry, registration is disabled on this instance.'))
            return redirect(request, 'index')

        # Get email and nickname from response
        email = _response_email(response)
        username = _response_nickname(response)

        register_form = auth_forms.RegistrationForm(
            request.form,
            openid=response.identity_url,
            email=email,
            username=username)
        return render_to_response(
            request, 'mediagoblin/auth/register.html', {
                'register_form': register_form,
                'post_url':
                request.urlgen('mediagoblin.plugins.openid.register')
            })
Exemple #60
0
def silence_comments(request, media):
    silence_comment_subscription(request.user, media)

    messages.add_message(request,
                         messages.SUCCESS,
                         _('You will not receive notifications for comments on'
                           ' %s.') % media.title)

    return redirect(request, location=media.url_for_self(request.urlgen))