Email Check
NotesWe can now include an extra check, to make sure new users register with an email address that isn’t already in use. The database would refuse a duplicate anyway (the email column is unique), but that would be an error page rather than a helpful message.
Add a function for finding a user by email address to api/auth_apis.py:
def get_user_by_email_api(email: str, session: Session) -> User | None:
return session.exec(select(User).where(User.email == email)).first().first() returns the first matching user, or None.
Then, in register_post_view, add one more check after the password check, importing get_user_by_email_api:
elif get_user_by_email_api(email, session): # NEW
error_message = "That email address is already registered. Have you forgotten your password?" # NEWNow, if a user tries to register using an existing email address, they will get a message telling them so, with a hint about resetting their password, which is added later in this section.
This does tell anyone who tries that an email address has an account. Most sites accept that for registration forms, since it’s needed to give a useful message. Login and password reset (later in this section) are more sensitive, so they’re careful never to reveal it.