示例#1
0
def manage_user_login(user, user_data, next_url):
    """Manage user login."""
    if user is None:
        # Give a hint for the user
        user = user_repo.get_by(email_addr=user_data.get('email'))
        if user is not None:
            msg, method = get_user_signup_method(user)
            flash(msg, 'info')
            if method == 'local':
                return redirect(url_for_app_type('account.forgot_password',
                                                 _hash_last_flash=True))
            else:
                return redirect(url_for_app_type('account.signin',
                                                 _hash_last_flash=True))
        else:
            return redirect(url_for_app_type('account.signin',
                                             _hash_last_flash=True))
    else:
        login_user(user, remember=True)
        flash("Welcome back %s" % user.fullname, 'success')
        if ((user.email_addr != user.name) and user.newsletter_prompted is False
                and newsletter.is_initialized()):
            return redirect(url_for_app_type('account.newsletter_subscribe',
                                             next=next_url,
                                             _hash_last_flash=True))
        return redirect(next_url)
示例#2
0
def manage_user_login(user, user_data, next_url):
    """Manage user login."""
    if user is None:
        # Give a hint for the user
        user = user_repo.get_by(email_addr=user_data.get('email'))
        if user is not None:
            msg, method = get_user_signup_method(user)
            flash(msg, 'info')
            if method == 'local':
                return redirect(url_for_app_type('account.forgot_password'))
            else:
                return redirect(url_for_app_type('account.signin'))
        else:
            return redirect(url_for_app_type('account.signin'))
    else:
        login_user(user, remember=True)
        flash("Welcome back %s" % user.fullname, 'success')
        request_email = (user.email_addr == user.name)
        if request_email:
            flash("Please update your e-mail address in your profile page")
            return redirect(url_for_app_type('account.update_profile',
                                             name=user.name))
        if (not request_email and user.newsletter_prompted is False
                and newsletter.is_initialized()):
            return redirect(url_for_app_type('account.newsletter_subscribe',
                                             next=next_url))
        return redirect(next_url)
示例#3
0
 def test_url_for_app_type_mvc_with_hashed_flash(self, mock_hash_last_flash, mock_url_for):
     """Test that the hashed flash is not returned with the MVC URL"""
     endpoint = 'bar'
     util.url_for_app_type(endpoint, _hash_last_flash=True)
     mock_url_for.assert_called_with(endpoint)
     err = "Hashed flash should not be called"
     assert not mock_hash_last_flash.called, err
示例#4
0
文件: google.py 项目: fiorda/pybossa
def oauth_authorized():  # pragma: no cover
    """Authorize Oauth."""
    resp = google.oauth.authorized_response()
    next_url = url_for_app_type('home.home')

    if resp is None or request.args.get('error'):
        flash(u'You denied the request to sign in.', 'error')
        flash(u'Reason: ' + request.args['error'], 'error')
        if request.args.get('error'):
            current_app.logger.error(resp)
            return redirect(url_for_app_type('account.signin'))
        return redirect(next_url)
    if isinstance(resp, OAuthException):
        flash('Access denied: %s' % resp.message)
        current_app.logger.error(resp)
        return redirect(next_url)
    headers = {'Authorization': ' '.join(['OAuth', resp['access_token']])}
    url = 'https://www.googleapis.com/oauth2/v1/userinfo'
    try:
        r = requests.get(url, headers=headers)
    except requests.exceptions.http_error:
        # Unauthorized - bad token
        if r.status_code == 401:
            return redirect(url_for_app_type('account.signin'))
        return r.content

    access_token = resp['access_token']
    session['oauth_token'] = access_token
    import json
    user_data = json.loads(r.content)
    user = manage_user(access_token, user_data)
    return manage_user_login(user, user_data, next_url)
示例#5
0
 def test_url_for_app_type_mvc_with_hashed_flash(self, mock_hash_last_flash, mock_url_for):
     """Test that the hashed flash is not returned with the MVC URL"""
     endpoint = 'bar'
     util.url_for_app_type(endpoint, _hash_last_flash=True)
     mock_url_for.assert_called_with(endpoint)
     err = "Hashed flash should not be called"
     assert not mock_hash_last_flash.called, err
示例#6
0
def manage_user_login(user, user_data, next_url):
    """Manage user login."""
    if user is None:
        # Give a hint for the user
        user = user_repo.get_by(email_addr=user_data.get('email'))
        if user is not None:
            msg, method = get_user_signup_method(user)
            flash(msg, 'info')
            if method == 'local':
                return redirect(url_for_app_type('account.forgot_password',
                                                 _hash_last_flash=True))
            else:
                return redirect(url_for_app_type('account.signin',
                                                 _hash_last_flash=True))
        else:
            return redirect(url_for_app_type('account.signin',
                                             _hash_last_flash=True))
    else:
        login_user(user, remember=True)
        flash("Welcome back %s" % user.fullname, 'success')
        if ((user.email_addr != user.name) and user.newsletter_prompted is False
                and newsletter.is_initialized()):
            return redirect(url_for_app_type('account.newsletter_subscribe',
                                             next=next_url,
                                             _hash_last_flash=True))
        return redirect(next_url)
示例#7
0
def oauth_authorized():  # pragma: no cover
    """Authorize Oauth."""
    resp = google.oauth.authorized_response()
    next_url = url_for_app_type('home.home')

    if resp is None or request.args.get('error'):
        flash(u'You denied the request to sign in.', 'error')
        flash(u'Reason: ' + request.args['error'], 'error')
        if request.args.get('error'):
            current_app.logger.error(resp)
            return redirect(url_for_app_type('account.signin'))
        return redirect(next_url)
    if isinstance(resp, OAuthException):
        flash('Access denied: %s' % resp.message)
        current_app.logger.error(resp)
        return redirect(next_url)
    headers = {'Authorization': ' '.join(['OAuth', resp['access_token']])}
    url = 'https://www.googleapis.com/oauth2/v1/userinfo'
    try:
        r = requests.get(url, headers=headers)
    except requests.exceptions.http_error:
        # Unauthorized - bad token
        if r.status_code == 401:
            return redirect(url_for_app_type('account.signin'))
        return r.content

    access_token = resp['access_token']
    session['oauth_token'] = access_token
    import json
    user_data = json.loads(r.content)
    user = manage_user(access_token, user_data)
    return manage_user_login(user, user_data, next_url)
示例#8
0
 def test_url_for_app_type_spa_with_hashed_flash(self, mock_hash_last_flash, mock_url_for):
     """Test that the hashed flash is returned with the SPA URL"""
     flash = 'foo'
     endpoint = 'bar'
     mock_hash_last_flash.return_value = flash
     with patch.dict(self.flask_app.config, {'SPA_SERVER_NAME': 'example.com'}):
         util.url_for_app_type(endpoint, _hash_last_flash=True)
         err = "Hashed flash should be included"
         mock_url_for.assert_called_with(endpoint, flash=flash), err
示例#9
0
 def test_url_for_app_type_spa_with_hashed_flash(self, mock_hash_last_flash, mock_url_for):
     """Test that the hashed flash is returned with the SPA URL"""
     flash = 'foo'
     endpoint = 'bar'
     mock_hash_last_flash.return_value = flash
     with patch.dict(self.flask_app.config, {'SPA_SERVER_NAME': 'example.com'}):
         util.url_for_app_type(endpoint, _hash_last_flash=True)
         err = "Hashed flash should be included"
         mock_url_for.assert_called_with(endpoint, flash=flash), err
示例#10
0
def get_email_confirmation_url(account):
    """Return confirmation url for a given user email."""
    key = signer.dumps(account, salt='account-validation')
    scheme = current_app.config.get('PREFERRED_URL_SCHEME')
    if (scheme):
        return url_for_app_type('.confirm_account',
                                key=key,
                                _scheme=scheme,
                                _external=True)
    else:
        return url_for_app_type('.confirm_account', key=key, _external=True)
示例#11
0
文件: account.py 项目: jinwg/pybossa
def get_email_confirmation_url(account):
    """Return confirmation url for a given user email."""
    key = signer.dumps(account, salt='account-validation')
    scheme = current_app.config.get('PREFERRED_URL_SCHEME')
    if (scheme):
        return url_for_app_type('.confirm_account',
                                key=key,
                                _scheme=scheme,
                                _external=True)
    else:
        return url_for_app_type('.confirm_account', key=key, _external=True)
示例#12
0
文件: account.py 项目: fiorda/pybossa
def forgot_password():
    """
    Request a forgotten password for a user.

    Returns a Jinja2 template.

    """
    form = ForgotPasswordForm(request.body)
    if form.validate_on_submit():
        user = user_repo.get_by(email_addr=form.email_addr.data)
        if user and user.email_addr:
            msg = dict(subject='Account Recovery',
                       recipients=[user.email_addr])
            if user.twitter_user_id:
                msg['body'] = render_template(
                    '/account/email/forgot_password_openid.md',
                    user=user, account_name='Twitter')
                msg['html'] = render_template(
                    '/account/email/forgot_password_openid.html',
                    user=user, account_name='Twitter')
            elif user.facebook_user_id:
                msg['body'] = render_template(
                    '/account/email/forgot_password_openid.md',
                    user=user, account_name='Facebook')
                msg['html'] = render_template(
                    '/account/email/forgot_password_openid.html',
                    user=user, account_name='Facebook')
            elif user.google_user_id:
                msg['body'] = render_template(
                    '/account/email/forgot_password_openid.md',
                    user=user, account_name='Google')
                msg['html'] = render_template(
                    '/account/email/forgot_password_openid.html',
                    user=user, account_name='Google')
            else:
                userdict = {'user': user.name, 'password': user.passwd_hash}
                key = signer.dumps(userdict, salt='password-reset')
                recovery_url = url_for_app_type('.reset_password',
                                                key=key, _external=True)
                msg['body'] = render_template(
                    '/account/email/forgot_password.md',
                    user=user, recovery_url=recovery_url)
                msg['html'] = render_template(
                    '/account/email/forgot_password.html',
                    user=user, recovery_url=recovery_url)
            mail_queue.enqueue(send_mail, msg)
            flash(gettext("We've sent you an email with account "
                          "recovery instructions!"),
                  'success')
        else:
            flash(gettext("We don't have this email in our records. "
                          "You may have signed up with a different "
                          "email or used Twitter, Facebook, or "
                          "Google to sign-in"), 'error')
    if request.method == 'POST' and not form.validate():
        flash(gettext('Something went wrong, please correct the errors on the '
              'form'), 'error')
    data = dict(template='/account/password_forgot.html',
                form=form)
    return handle_content_type(data)
示例#13
0
def forgot_password():
    """
    Request a forgotten password for a user.

    Returns a Jinja2 template.

    """
    form = ForgotPasswordForm(request.body)
    if form.validate_on_submit():
        user = user_repo.get_by(email_addr=form.email_addr.data)
        if user and user.email_addr:
            msg = dict(subject='Account Recovery',
                       recipients=[user.email_addr])
            if user.twitter_user_id:
                msg['body'] = render_template(
                    '/account/email/forgot_password_openid.md',
                    user=user, account_name='Twitter')
                msg['html'] = render_template(
                    '/account/email/forgot_password_openid.html',
                    user=user, account_name='Twitter')
            elif user.facebook_user_id:
                msg['body'] = render_template(
                    '/account/email/forgot_password_openid.md',
                    user=user, account_name='Facebook')
                msg['html'] = render_template(
                    '/account/email/forgot_password_openid.html',
                    user=user, account_name='Facebook')
            elif user.google_user_id:
                msg['body'] = render_template(
                    '/account/email/forgot_password_openid.md',
                    user=user, account_name='Google')
                msg['html'] = render_template(
                    '/account/email/forgot_password_openid.html',
                    user=user, account_name='Google')
            else:
                userdict = {'user': user.name, 'password': user.passwd_hash}
                key = signer.dumps(userdict, salt='password-reset')
                recovery_url = url_for_app_type('.reset_password',
                                                key=key, _external=True)
                msg['body'] = render_template(
                    '/account/email/forgot_password.md',
                    user=user, recovery_url=recovery_url)
                msg['html'] = render_template(
                    '/account/email/forgot_password.html',
                    user=user, recovery_url=recovery_url)
            mail_queue.enqueue(send_mail, msg)
            flash(gettext("We've sent you an email with account "
                          "recovery instructions!"),
                  'success')
        else:
            flash(gettext("We don't have this email in our records. "
                          "You may have signed up with a different "
                          "email or used Twitter, Facebook, or "
                          "Google to sign-in"), 'error')
    if request.method == 'POST' and not form.validate():
        flash(gettext('Something went wrong, please correct the errors on the '
              'form'), 'error')
    data = dict(template='/account/password_forgot.html',
                form=form)
    return handle_content_type(data)
示例#14
0
 def test_url_for_app_type_spa(self, mock_url_for):
     """Test that the correct SPA URL is returned"""
     spa_name = 'http://local.com'
     fake_endpoint = '/example'
     mock_url_for.return_value = fake_endpoint
     with patch.dict(self.flask_app.config, {'SPA_SERVER_NAME': spa_name}):
         spa_url = util.url_for_app_type('home.home')
         expected = spa_name + fake_endpoint
         assert spa_url == expected, spa_url
示例#15
0
def oauth_authorized():  # pragma: no cover
    """Called after authorization.  """
    resp = weibo.oauth.authorized_response()
    next_url = request.args.get('next') or url_for_app_type('home.home')
    if resp is None:
        flash(u'You denied the request to sign in.', 'error')
        return redirect(next_url)
    if isinstance(resp, OAuthException):
        flash('Access denied: %s' % request.args['error_description'])
        current_app.logger.error(resp)
        return redirect(url_for_app_type('home.home', _hash_last_flash=True))

    access_token = resp['access_token']
    session['oauth_token'] = (access_token, '')
    user_data = weibo.oauth.get('users/show.json?uid=' + resp['uid'] + '&access_token='+access_token).data
    #current_app.logger.info(user_data)
    user = manage_user(access_token, user_data)
    return manage_user_login(user, user_data, next_url)
示例#16
0
def oauth_authorized():  # pragma: no cover
    """Called after authorization.  """
    resp = weibo.oauth.authorized_response()
    next_url = request.args.get('next') or url_for_app_type('home.home')
    if resp is None:
        flash(u'You denied the request to sign in.', 'error')
        return redirect(next_url)
    if isinstance(resp, OAuthException):
        flash('Access denied: %s' % request.args['error_description'])
        current_app.logger.error(resp)
        return redirect(url_for_app_type('home.home', _hash_last_flash=True))

    access_token = resp['access_token']
    session['oauth_token'] = (access_token, '')
    user_data = weibo.oauth.get('users/show.json?uid=' + resp['uid'] + '&access_token='+access_token).data
    #current_app.logger.info(user_data)
    user = manage_user(access_token, user_data)
    return manage_user_login(user, user_data, next_url)
示例#17
0
 def test_url_for_app_type_spa(self, mock_url_for):
     """Test that the correct SPA URL is returned"""
     spa_name = 'http://local.com'
     fake_endpoint = '/example'
     mock_url_for.return_value = fake_endpoint
     with patch.dict(self.flask_app.config, {'SPA_SERVER_NAME': spa_name}):
         spa_url = util.url_for_app_type('home.home')
         expected = spa_name + fake_endpoint
         assert spa_url == expected, spa_url
示例#18
0
def oauth_authorized():  # pragma: no cover
    """Called after authorization.  """
    resp = wechat.oauth.authorized_response()
    next_url = request.args.get('next') or url_for_app_type('home.home')
    if resp is None:
        flash(u'You denied the request to sign in.', 'error')
        return redirect(next_url)
    if isinstance(resp, OAuthException):
        flash('Access denied: %s' % resp.message)
        current_app.logger.error(resp)
        return redirect(url_for_app_type('home.home', _hash_last_flash=True))

    access_token = dict(oauth_token=resp['oauth_token'],
                        oauth_token_secret=resp['oauth_token_secret'])

    no_login = int(request.args.get(NO_LOGIN, 0))
    if no_login == 1:
        return manage_user_no_login(access_token, next_url)

    user_data = dict(user_id=resp['openid'])
    user = manage_user(access_token, user_data)
    return manage_user_login(user, user_data, next_url)
示例#19
0
def oauth_authorized():  # pragma: no cover
    """Authorize facebook login."""
    resp = facebook.oauth.authorized_response()
    next_url = request.args.get('next') or url_for_app_type('home.home')
    if resp is None:
        flash(u'You denied the request to sign in.', 'error')
        flash(u'Reason: ' + request.args['error_reason'] +
              ' ' + request.args['error_description'], 'error')
        next_url = (request.args.get('next') or
                    url_for_app_type('home.home', _hash_last_flash=True))
        return redirect(next_url)
    if isinstance(resp, OAuthException):
        flash('Access denied: %s' % resp.message)
        current_app.logger.error(resp)
        return redirect(url_for_app_type('home.home', _hash_last_flash=True))
    # We have to store the oauth_token in the session to get the USER fields
    access_token = resp['access_token']
    session['oauth_token'] = (resp['access_token'], '')
    user_data = facebook.oauth.get('/me?fields=id,email,name').data

    user = manage_user(access_token, user_data)
    return manage_user_login(user, user_data, next_url)
示例#20
0
def oauth_authorized():  # pragma: no cover
    """Authorize facebook login."""
    resp = facebook.oauth.authorized_response()
    next_url = request.args.get('next') or url_for_app_type('home.home')
    if resp is None:
        flash('You denied the request to sign in.', 'error')
        flash('Reason: ' + request.args['error_reason'] +
              ' ' + request.args['error_description'], 'error')
        next_url = (request.args.get('next') or
                    url_for_app_type('home.home', _hash_last_flash=True))
        return redirect(next_url)
    if isinstance(resp, OAuthException):
        flash('Access denied: %s' % resp.message)
        current_app.logger.error(resp)
        return redirect(url_for_app_type('home.home', _hash_last_flash=True))
    # We have to store the oauth_token in the session to get the USER fields
    access_token = resp['access_token']
    session['oauth_token'] = (resp['access_token'], '')
    user_data = facebook.oauth.get('/me?fields=id,email,name').data

    user = manage_user(access_token, user_data)
    return manage_user_login(user, user_data, next_url)
示例#21
0
def manage_user_login(user, user_data, next_url):
    """Manage user login."""
    if user is None:
        user = user_repo.get_by_name(user_data['screen_name'])
        msg, method = get_user_signup_method(user)
        flash(msg, 'info')
        if method == 'local':
            return redirect(url_for_app_type('account.forgot_password'))
        else:
            return redirect(url_for_app_type('account.signin'))

    login_user(user, remember=True)
    flash("Welcome back %s" % user.fullname, 'success')
    if ((user.email_addr != user.name) and user.newsletter_prompted is False
            and newsletter.is_initialized()):
        return redirect(
            url_for_app_type('account.newsletter_subscribe', next=next_url))
    if user.email_addr != user.name:
        return redirect(next_url)
    else:
        flash("Please update your e-mail address in your profile page")
        return redirect(
            url_for_app_type('account.update_profile', name=user.name))
示例#22
0
def oauth_authorized():  # pragma: no cover
    """Called after authorization.

    After this function finished handling,
    the OAuth information is removed from the session again. When this
    happened, the tokengetter from above is used to retrieve the oauth
    token and secret.

    Because the remote application could have re-authorized the application
    it is necessary to update the values in the database.

    If the application redirected back after denying, the response passed
    to the function will be `None`. Otherwise a dictionary with the values
    the application submitted. Note that Twitter itself does not really
    redirect back unless the user clicks on the application name.
    """
    resp = twitter.oauth.authorized_response()
    next_url = request.args.get('next') or url_for_app_type('home.home')
    if resp is None:
        flash(u'You denied the request to sign in.', 'error')
        return redirect(next_url)
    if isinstance(resp, OAuthException):
        flash('Access denied: %s' % resp.message)
        current_app.logger.error(resp)
        return redirect(url_for_app_type('home.home', _hash_last_flash=True))

    access_token = dict(oauth_token=resp['oauth_token'],
                        oauth_token_secret=resp['oauth_token_secret'])

    no_login = int(request.args.get(NO_LOGIN, 0))
    if no_login == 1:
        return manage_user_no_login(access_token, next_url)

    user_data = dict(screen_name=resp['screen_name'],
                     user_id=resp['user_id'])
    user = manage_user(access_token, user_data)
    return manage_user_login(user, user_data, next_url)
示例#23
0
def oauth_authorized():  # pragma: no cover
    """Called after authorization.

    After this function finished handling,
    the OAuth information is removed from the session again. When this
    happened, the tokengetter from above is used to retrieve the oauth
    token and secret.

    Because the remote application could have re-authorized the application
    it is necessary to update the values in the database.

    If the application redirected back after denying, the response passed
    to the function will be `None`. Otherwise a dictionary with the values
    the application submitted. Note that Twitter itself does not really
    redirect back unless the user clicks on the application name.
    """
    resp = twitter.oauth.authorized_response()
    next_url = request.args.get('next') or url_for_app_type('home.home')
    if resp is None:
        flash(u'You denied the request to sign in.', 'error')
        return redirect(next_url)
    if isinstance(resp, OAuthException):
        flash('Access denied: %s' % resp.message)
        current_app.logger.error(resp)
        return redirect(url_for_app_type('home.home', _hash_last_flash=True))

    access_token = dict(oauth_token=resp['oauth_token'],
                        oauth_token_secret=resp['oauth_token_secret'])

    no_login = int(request.args.get(NO_LOGIN, 0))
    if no_login == 1:
        return manage_user_no_login(access_token, next_url)

    user_data = dict(screen_name=resp['screen_name'],
                     user_id=resp['user_id'])
    user = manage_user(access_token, user_data)
    return manage_user_login(user, user_data, next_url)
示例#24
0
def login():  # pragma: no cover
    """Login with myKaarma."""
    if not current_app.config.get('LDAP_HOST', False):
        if sp.is_user_logged_in():
            auth_data = sp.get_auth_data_in_session()
            """Add received data from idp to a user data dictionary"""
            user_data = {}
            user_data['id'] = auth_data.attributes["UserUUID"]
            user_data['name'] = auth_data.attributes["name"]
            user_data['email'] = auth_data.attributes["email"]
            """Find user details or create user with details"""
            user = manage_user(user_data)
            next_url = request.args.get('next') or url_for_app_type(
                'home.home')
            return manage_user_login(user, user_data, next_url)
        else:
            return redirect(url_for('mykaarma.login_mykaarma',
                                    _scheme='https',
                                    _external=True),
                            code=302)
    else:
        return abort(404)
示例#25
0
def get_email_confirmation_url(account):
    """Return confirmation url for a given user email."""
    key = signer.dumps(account, salt='account-validation')
    return url_for_app_type('.confirm_account', key=key, _external=True)
示例#26
0
文件: flickr.py 项目: PyBossa/pybossa
def logout():
    """Log out."""
    next_url = request.args.get('next') or url_for_app_type('home.home')
    _remove_credentials(session)
    return redirect(next_url)
示例#27
0
def get_email_confirmation_url(account):
    """Return confirmation url for a given user email."""
    key = signer.dumps(account, salt='account-validation')
    return url_for_app_type('.confirm_account', key=key, _external=True)
示例#28
0
 def test_url_for_app_type_mvc(self, mock_url_for):
     """Test that the correct MVC URL is returned"""
     fake_endpoint = '/example'
     mock_url_for.return_value = fake_endpoint
     spa_url = util.url_for_app_type('home.home')
     assert spa_url == fake_endpoint, spa_url
示例#29
0
def logout():
    """Log out."""
    next_url = request.args.get('next') or url_for_app_type('home.home')
    _remove_credentials(session)
    return redirect(next_url)
示例#30
0
 def test_url_for_app_type_mvc(self, mock_url_for):
     """Test that the correct MVC URL is returned"""
     fake_endpoint = '/example'
     mock_url_for.return_value = fake_endpoint
     spa_url = util.url_for_app_type('home.home')
     assert spa_url == fake_endpoint, spa_url
示例#31
0
def forgot_password():
    """
    Request a forgotten password for a user.

    Returns a Jinja2 template.

    """
    form = ForgotPasswordForm(request.body)
    data = dict(template='/account/password_forgot.html',
                form=form)

    if form.validate_on_submit():
        email_addr = form.email_addr.data.lower()
        user = user_repo.get_by(email_addr=email_addr)
        if user and not user.enabled:
            brand = current_app.config['BRAND']
            flash(gettext('Your account is disabled. '
                          'Please contact your {} administrator.'.format(brand)),
                  'error')
            return handle_content_type(data)
        if user and user.email_addr:
            msg = dict(subject='Account Recovery',
                       recipients=[user.email_addr])
            if user.twitter_user_id:
                msg['body'] = render_template(
                    '/account/email/forgot_password_openid.md',
                    user=user, account_name='Twitter')
                msg['html'] = render_template(
                    '/account/email/forgot_password_openid.html',
                    user=user, account_name='Twitter')
            elif user.facebook_user_id:
                msg['body'] = render_template(
                    '/account/email/forgot_password_openid.md',
                    user=user, account_name='Facebook')
                msg['html'] = render_template(
                    '/account/email/forgot_password_openid.html',
                    user=user, account_name='Facebook')
            elif user.google_user_id:
                msg['body'] = render_template(
                    '/account/email/forgot_password_openid.md',
                    user=user, account_name='Google')
                msg['html'] = render_template(
                    '/account/email/forgot_password_openid.html',
                    user=user, account_name='Google')
            else:
                userdict = {'user': user.name, 'password': user.passwd_hash}
                key = signer.dumps(userdict, salt='password-reset')
                recovery_url = url_for_app_type('.reset_password',
                                                key=key, _external=True)
                msg['body'] = render_template(
                    '/account/email/forgot_password.md',
                    user=user, recovery_url=recovery_url, key=key)
                msg['html'] = render_template(
                    '/account/email/forgot_password.html',
                    user=user, recovery_url=recovery_url, key=key)
            mail_queue.enqueue(send_mail, msg)
            flash(gettext("We've sent you an email with account "
                          "recovery instructions!"),
                  'success')
        else:
            flash(gettext("We don't have this email in our records. "
                          "You may have signed up with a different "
                          "email"), 'error')
    if request.method == 'POST':
        if not form.validate():
            flash(gettext('Something went wrong, please correct the errors on the '
                'form'), 'error')
        else:
            return redirect_content_type(url_for('account.password_reset_key'))
    return handle_content_type(data)