Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(recoverable): Add support for username recovery via simple login flows #1041

Merged
merged 7 commits into from
Dec 30, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions docs/configuration.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1159,7 +1159,7 @@ Recoverable

Specifies whether username recovery is enabled.

Default: ``True``.
Default: ``False``.

.. versionadded:: 5.6.0

Expand All @@ -1175,15 +1175,15 @@ Recoverable

Sets subject for the username recovery email.

Default: ``_("Your requested username")``
Default: ``_("Your requested username")``.

.. versionadded:: 5.6.0

.. py:data:: SECURITY_USERNAME_RECOVERY_TEMPLATE

Specifies the path to the template for the username recovery page.

Default: ``"security/recover_username.html"``
Default: ``"security/recover_username.html"``.

.. versionadded:: 5.6.0

Expand Down
2 changes: 1 addition & 1 deletion flask_security/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@
"webauthn": "flask_security.webauthn.WebAuthnTfPlugin",
},
"UNIFIED_SIGNIN": False,
"USERNAME_RECOVERY": True,
"USERNAME_RECOVERY": False,
"USERNAME_RECOVERY_TEMPLATE": "security/recover_username.html",
"USERNAME_RECOVERY_URL": "/recover-username",
"US_SETUP_SALT": "us-setup-salt",
Expand Down
7 changes: 3 additions & 4 deletions flask_security/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
)

from werkzeug.datastructures import MultiDict
from wtforms.validators import Optional, StopValidation, Email
from wtforms.validators import Optional, StopValidation

from .babel import is_lazy_string, make_lazy_string
from .confirmable import requires_confirmation
Expand Down Expand Up @@ -871,11 +871,10 @@ class TwoFactorRescueForm(Form):
submit = SubmitField(get_form_field_label("submit"))


class UsernameRecoveryForm(Form):
class UsernameRecoveryForm(Form, UserEmailFormMixin):
"""The username recovery form"""

email = StringField(get_form_field_label("Email"), validators=[Required(), Email()])
submit = SubmitField(get_form_field_label("recover_password"))
submit = SubmitField(get_form_field_label("recover_username"))
jwag956 marked this conversation as resolved.
Show resolved Hide resolved


class DummyForm(Form):
Expand Down
28 changes: 22 additions & 6 deletions flask_security/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
after_this_request,
current_app,
jsonify,
render_template,
request,
session,
)
Expand Down Expand Up @@ -1161,10 +1160,24 @@ def recover_username():
if user:
send_username_recovery_email(user)

do_flash(*get_message("USERNAME_RECOVERY_REQUEST", email=form.email.data))
if not _security._want_json(request):
do_flash(*get_message("USERNAME_RECOVERY_REQUEST", email=form.email.data))
elif request.method == "POST" and cv("RETURN_GENERIC_RESPONSES"):
rinfo = dict(email=dict())
form_errors_munge(form, rinfo)
if not form.errors:
if not _security._want_json(request):
do_flash(
*get_message("USERNAME_RECOVERY_REQUEST", email=form.email.data)
)

if _security._want_json(request):
return base_render_json(form, include_user=False)

if form.validate_on_submit():
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not comfortable calling validate_on_submit twice .... as with many other views I think that on GET or POST errors - the template should be rendered (as you do). Maybe what I am asking is - rather than this if/redirect here - do the redirect up in the validate_on_submit() part:

if validate_on_submit():
  send_username_recovery_email()
  if _security_want_json(request):
    return base_render_json....
  do_flash(xxx)
    return redirect(get_url(".login")

return redirect(url_for_security("login"))

return render_template(
return _security.render_template(
jwag956 marked this conversation as resolved.
Show resolved Hide resolved
cv("USERNAME_RECOVERY_TEMPLATE"), username_recovery_form=form
)

Expand Down Expand Up @@ -1286,9 +1299,12 @@ def create_blueprint(app, state, import_name):
methods=["GET", "POST"],
endpoint="reset_password",
)(reset_password)
bp.route(
username_recovery_url, methods=["GET", "POST"], endpoint="recover_username"
)(recover_username)
if cv("USERNAME_RECOVERY", app=app):
bp.route(
username_recovery_url,
methods=["GET", "POST"],
endpoint="recover_username",
)(recover_username)

if state.changeable:
bp.route(
Expand Down
2 changes: 2 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ def app(request: pytest.FixtureRequest) -> SecurityFixture:
# Make this hex_md5 for token tests
app.config["SECURITY_HASHING_SCHEMES"] = ["hex_md5"]
app.config["SECURITY_DEPRECATED_HASHING_SCHEMES"] = []
# Enable username recovery for tests
app.config["SECURITY_USERNAME_RECOVERY"] = True
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: do this in for loop below with all the other options


for opt in [
"changeable",
Expand Down
73 changes: 73 additions & 0 deletions tests/test_recoverable.py
Original file line number Diff line number Diff line change
Expand Up @@ -836,6 +836,14 @@ def on_email_sent(app, **kwargs):
email = app.mail.outbox[1]
assert "Your username is: joe" in email.body

# Test JSON responses
response = clients.post(
"/recover-username",
json=dict(email="[email protected]"),
headers={"Content-Type": "application/json"},
)
assert response.status_code == 200


def test_username_recovery_invalid_email(app, clients):
response = clients.post(
Expand All @@ -844,3 +852,68 @@ def test_username_recovery_invalid_email(app, clients):

assert not app.mail.outbox
assert response.status_code == 200

# Test JSON responses
response = clients.post(
"/recover-username",
json=dict(email="[email protected]"),
headers={"Content-Type": "application/json"},
)
assert response.status_code == 400


@pytest.mark.settings(return_generic_responses=True)
def test_username_recovery_generic_responses(app, clients, get_message):
recorded_recovery_sent = []

@username_recovery_email_sent.connect_via(app)
def on_email_sent(app, **kwargs):
recorded_recovery_sent.append(kwargs["user"])

# Test with valid email
with capture_flashes() as flashes:
response = clients.post(
"/recover-username",
data=dict(email="[email protected]"),
follow_redirects=True,
)
assert len(flashes) == 1
assert get_message("USERNAME_RECOVERY_REQUEST") == flashes[0]["message"].encode(
"utf-8"
)
assert len(recorded_recovery_sent) == 1
assert len(app.mail.outbox) == 1
assert response.status_code == 200

# Test with non-existant email (should still return 200)
with capture_flashes() as flashes:
response = clients.post(
"/recover-username",
data=dict(email="[email protected]"),
follow_redirects=True,
)
assert len(flashes) == 1
assert get_message("USERNAME_RECOVERY_REQUEST") == flashes[0]["message"].encode(
"utf-8"
)
# Validate no email was sent (there should only be one from the previous test)
assert len(recorded_recovery_sent) == 1
assert len(app.mail.outbox) == 1
assert response.status_code == 200

# Test JSON responses - valid email
response = clients.post(
"/recover-username",
json=dict(email="[email protected]"),
headers={"Content-Type": "application/json"},
)
assert response.status_code == 200

# Test JSON responses - invalid email
response = clients.post(
"/recover-username",
json=dict(email="[email protected]"),
headers={"Content-Type": "application/json"},
)
assert response.status_code == 200
assert not any(e in response.json["response"].keys() for e in ["error", "errors"])
Loading