Exemple #1
0
def openid_add_finish(context, request):
    user = request.user
    # XXX we should put the attempted openid in here
    form = AddOpenIDForm(request)
    remove_form = RemoveOpenIDForm(request)
    remove_form.openids.query = model.session.query(
        model.IdentityURL).with_parent(user)

    ret = dict(
        add_openid_form=form,
        remove_openid_form=remove_form,
    )

    # Process a returning OpenID check
    form.validate()  # Ensure new_openid.errors is an appendable list
    try:
        identity_url, identity_webfinger, auth_time, sreg_res = openid_end(
            request.path_url, request)
    except OpenIDError as exc:
        form.new_openid.errors.append(exc.args[0])
        return ret

    # Allow an OpenID identity to be registered to only one user.
    existing_url = model.session.query(model.IdentityURL) \
        .filter_by(url=identity_url) \
        .first()
    if existing_url:
        if existing_url.user_id == user.id:
            form.new_openid.errors.append(
                u'You can already authenticate with that OpenID identity.')
        else:
            form.new_openid.errors.append(
                u'That OpenID identity is already in use by another account.')
        return ret

    openid = model.IdentityURL(url=identity_url)
    user.identity_urls.append(openid)
    request.session.flash(u"Added a new identity: {0}".format(identity_url),
                          level=u'success',
                          icon=u'user--plus')

    return HTTPSeeOther(location=request.route_url('controls.openid'))
Exemple #2
0
def openid_add_finish(context, request):
    user = request.user
    # XXX we should put the attempted openid in here
    form = AddOpenIDForm(request)
    remove_form = RemoveOpenIDForm(request)
    remove_form.openids.query = model.session.query(model.IdentityURL).with_parent(user)

    ret = dict(
        add_openid_form=form,
        remove_openid_form=remove_form,
    )

    # Process a returning OpenID check
    form.validate()  # Ensure new_openid.errors is an appendable list
    try:
        identity_url, identity_webfinger, auth_time, sreg_res = openid_end(request.path_url, request)
    except OpenIDError as exc:
        form.new_openid.errors.append(exc.args[0])
        return ret

    # Allow an OpenID identity to be registered to only one user.
    existing_url = model.session.query(model.IdentityURL) \
        .filter_by(url=identity_url) \
        .first()
    if existing_url:
        if existing_url.user_id == user.id:
            form.new_openid.errors.append(u'You can already authenticate with that OpenID identity.')
        else:
            form.new_openid.errors.append(u'That OpenID identity is already in use by another account.')
        return ret

    openid = model.IdentityURL(url=identity_url)
    user.identity_urls.append(openid)
    request.session.flash(
        u"Added a new identity: {0}".format(identity_url),
        level=u'success', icon=u'user--plus')

    return HTTPSeeOther(location=request.route_url('controls.openid'))
Exemple #3
0
def login_finish(context, request):
    """Step two of logging in; the OpenID provider redirects back here."""

    def retry():
        """Redirect to the login page, preserving the return key (if any)."""
        location = request.route_url('account.login')
        if return_key:
            location = update_params(location, return_key=return_key)
        return HTTPSeeOther(location=location)

    return_url = request.route_url('account.login_finish')

    return_key = key_from_request(request)
    if return_key is not None:
        return_url = update_params(return_url, return_key=return_key)

    try:
        identity_url, identity_webfinger, auth_time, sreg_res = openid_end(
            return_url=return_url,
            request=request)
    except OpenIDError as exc:
        request.session.flash(exc.message,
            level='error', icon='key--exclamation')
        return retry()

    # Find who owns this URL, if anyone
    identity_owner = model.session.query(User) \
        .filter(User.identity_urls.any(url=identity_url)) \
        .limit(1).first()

    if not identity_owner:
        if return_key:
            request.session.flash('Unknown OpenID URL.',
                level='error', icon='key--exclamation')
            return retry()
        # Someone is either registering a new account, or adding a new OpenID
        # to an existing account
        request.session['pending_identity_url'] = identity_url
        request.session.changed()

        # Try to pull a name and email address out of the SReg response
        username = re.sub(u'[^_a-z0-9]', u'',
            sreg_res.get('nickname', u'').lower())
        form = RegistrationForm(
            username=username,
            email=sreg_res.get('email', u''),
            timezone=sreg_res.get('timezone', u'UTC'),
        )
        return render_to_response(
            'account/register.mako',
            dict(
                form=form,
                identity_url=identity_url,
                identity_webfinger=identity_webfinger,
                identity_email=None),
            request=request)

    elif identity_owner == request.user:
        # Someone is just freshening up their cookie
        auth_headers = safe_openid_login(request, identity_owner, identity_url)
        if auth_headers is None:
            return retry()

        request.session.flash(u'Re-authentication successful', icon='user')

        if return_key:
            # Fetch a stashed request
            old_url = fetch_stash(request, key=return_key)['url']
            if old_url:
                location = update_params(old_url, return_key=return_key)
                log.debug('Following Return Key \'{0}\' to URL: {1}'
                          .format(return_key, location))
                return HTTPSeeOther(location, headers=auth_headers)
        return HTTPSeeOther(request.route_url('root'), headers=auth_headers)

    else:
        # Existing user; new login
        # Log the successful OpenID authentication, mindful of users that may
        # have OpenID logins disabled, for instance.
        # XXX should we deny a logged-in user to authenticate as another user?
        auth_headers = security.forget(request)
        headers = safe_openid_login(request, identity_owner, identity_url)

        if headers is None:
            return retry()

        auth_headers += headers

        # An existing user has logged in successfully.  Bravo!
        log.debug("User {0!r} logged in via OpenID: {1!r}"
                  .format(identity_owner.name, identity_url))

        request.session.flash(
            u"Welcome back, {0}!"
            .format(identity_owner.display_name or identity_owner.name),
            level=u'success', icon='user')

        # XXX this should ALSO probably do the return_key redirect, good grief
        return HTTPSeeOther(
            location=request.route_url('root'),
            headers=auth_headers)
Exemple #4
0
def login_finish(context, request):
    """Step two of logging in; the OpenID provider redirects back here."""

    def retry():
        """Redirect to the login page, preserving the return key (if any)."""
        location = request.route_url('account.login')
        if return_key:
            location = update_params(location, return_key=return_key)
        return HTTPSeeOther(location=location)

    return_url = request.route_url('account.login_finish')

    return_key = key_from_request(request)
    if return_key is not None:
        return_url = update_params(return_url, return_key=return_key)

    try:
        identity_url, identity_webfinger, auth_time, sreg_res = openid_end(
            return_url=return_url,
            request=request)
    except OpenIDError as exc:
        request.session.flash(exc.message,
            level='error', icon='key--exclamation')
        return retry()

    # Find who owns this URL, if anyone
    identity_owner = model.session.query(User) \
        .filter(User.identity_urls.any(url=identity_url)) \
        .limit(1).first()

    if not identity_owner:
        if return_key:
            request.session.flash('Unknown OpenID URL.',
                level='error', icon='key--exclamation')
            return retry()
        # Someone is either registering a new account, or adding a new OpenID
        # to an existing account
        request.session['pending_identity_url'] = identity_url
        request.session.changed()

        # Try to pull a name and email address out of the SReg response
        username = re.sub(u'[^_a-z0-9]', u'',
            sreg_res.get('nickname', u'').lower())
        form = RegistrationForm(
            username=username,
            email=sreg_res.get('email', u''),
            timezone=sreg_res.get('timezone', u'UTC'),
        )
        return render_to_response(
            'account/register.mako',
            dict(
                form=form,
                identity_url=identity_url,
                identity_webfinger=identity_webfinger,
                identity_email=None),
            request=request)

    elif identity_owner == request.user:
        # Someone is just freshening up their cookie
        auth_headers = safe_openid_login(request, identity_owner, identity_url)
        if auth_headers is None:
            return retry()

        request.session.flash(u'Re-authentication successful', icon='user')

        if return_key:
            # Fetch a stashed request
            old_url = fetch_stash(request, key=return_key)['url']
            if old_url:
                location = update_params(old_url, return_key=return_key)
                log.debug('Following Return Key \'{0}\' to URL: {1}'
                          .format(return_key, location))
                return HTTPSeeOther(location, headers=auth_headers)
        return HTTPSeeOther(request.route_url('root'), headers=auth_headers)

    else:
        # Existing user; new login
        # Log the successful OpenID authentication, mindful of users that may
        # have OpenID logins disabled, for instance.
        # XXX should we deny a logged-in user to authenticate as another user?
        auth_headers = security.forget(request)
        headers = safe_openid_login(request, identity_owner, identity_url)

        if headers is None:
            return retry()

        auth_headers += headers

        # An existing user has logged in successfully.  Bravo!
        log.debug("User {0!r} logged in via OpenID: {1!r}"
                  .format(identity_owner.name, identity_url))

        request.session.flash(
            u"Welcome back, {0}!"
            .format(identity_owner.display_name or identity_owner.name),
            level=u'success', icon='user')

        # XXX this should ALSO probably do the return_key redirect, good grief
        return HTTPSeeOther(
            location=request.route_url('root'),
            headers=auth_headers)