File size: 1,942 Bytes
8d2a91d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import streamlit as st
import streamlit_authenticator as stauth

# Example credential dictionary for demonstration.
# In practice, store hashed passwords in a safe location (e.g., environment variables, secrets manager).
# You can generate hashed passwords using stauth.Hasher.
CREDENTIALS = {
    "usernames": {
        "alice": {
            "name": "Alice Doe",
            "password": "$2b$12$abc123exampleHashALICEXXXXXXXXXXXXXXX",
            "role": "premium"
        },
        "bob": {
            "name": "Bob Smith",
            "password": "$2b$12$abc123exampleHashBOBXXXXXXXXXXXXXXXXXX",
            "role": "free"
        }
    }
}


def login():
    """
    Creates a login widget for the Streamlit app using streamlit_authenticator.

    Returns:
        (username, authentication_status, authenticator_obj)
        - username: str or None
        - authentication_status: bool (True if authenticated)
        - authenticator_obj: an instance of the Authenticate class, so you can call logout, etc.
    """
    authenticator = stauth.Authenticate(
        credentials=CREDENTIALS,
        cookie_name="smart_edit_cookie",
        key="abcdef",
        cookie_expiry_days=1
    )

    # This call draws the login form in the Streamlit UI.
    name, authentication_status, username = authenticator.login("Login", "main")

    return username, authentication_status, authenticator


def show_logout_button(authenticator):
    """
    Renders a logout button in the Streamlit UI for authenticated users.
    """
    authenticator.logout("Logout", "main")


def is_premium_user(username):
    """
    Checks if the logged-in user has the "premium" role.

    Returns:
        True if the user's role is premium, False otherwise.
    """
    # Retrieve the stored role from the credentials dict
    if username in CREDENTIALS["usernames"]:
        return CREDENTIALS["usernames"][username].get("role") == "premium"
    return False