mkhorasani / Streamlit-Authenticator

A secure authentication module to validate user credentials in a Streamlit application.
Apache License 2.0
1.38k stars 229 forks source link

Adding custom form field validation for "register_user" #96

Closed sohomhm closed 7 months ago

sohomhm commented 7 months ago

Hi @mkhorasani ,

First of all, thanks a ton for this essential package -- saves us a lot of time and effort!

Coming to my query, I have a very specific use case for my new user registration form -- I would like to restrict registration of those users who basically have an email id from a very specific domain (For ex: Just allowing user emails with @gmail.com domain)

I can see as per line#52, the email validation just checks whether it contains an @; I would like to add the specific domain as the validation to it along with the @ check!

Is there any way we can achieve this?

P.S. The custom form field validation should not be just on the email but may also extend for other fields as well!

velicanu commented 7 months ago

Yea you can definitely bring your own validation logic. Just redefine (or subclass) the Validator class and re-implement the name, username, or email validation logic as you see fit. Here's a minimal code example that changes email validation to allow only users from gmail domain:

import streamlit_authenticator as stauth
import yaml

class CustomValidator(stauth.validator.Validator):
    def validate_email(self, email: str) -> bool:
        return email.endswith("@gmail.com")

config = yaml.load("path/to/auth.yaml", Loader=yaml.SafeLoader)

authenticator = stauth.Authenticate(
    credentials=config["credentials"],
    cookie_name=config["cookie"]["name"],
    key=config["cookie"]["key"],
    cookie_expiry_days=config["cookie"]["expiry_days"],
    preauthorized=config["preauthorized"],
    validator=CustomValidator(),
)
sohomhm commented 7 months ago

Thanks a ton for the help! :100: