streamlit-authenticator-mongo


Namestreamlit-authenticator-mongo JSON
Version 0.1.5 PyPI version JSON
download
home_pagehttps://github.com/RobotForge/Streamlit-Authenticator-mongo
SummaryA secure authentication module to validate user credentials and insert user credentails in Mongodb with streamlit.
upload_time2024-01-06 19:35:14
maintainer
docs_urlNone
authorKegbokokim Ibok
requires_python>=3.6
license
keywords python streamlit authentication components mongodb
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ## Streamlit Authenticator Mongo

**A secure authentication module to validate user credentials stored in a Mongo database in a Streamlit application.**


## Installation

Streamlit-Authenticator-Mongo is distributed via [PyPI](https://pypi.org/project/streamlit-authenticator-mongo/):

```python
pip install streamlit-authenticator-mongo
```

## Example

Using Streamlit-Authenticator-Mongo is as simple as importing the module and calling it to verify your predefined users' credentials.

```python
import streamlit as st
import streamlit_authenticator_mongo as stauth
```

### 1. Hashing passwords

* Initially create a YAML configuration file and enter the number of days to expiry for a JWT cookie that will be stored on the client's browser to enable passwordless reauthentication. If you do not require reauthentication, you may set the number of days to expiry to 0. 

```python
cookie:
  expiry_days: 30
  key: some_signature_key # Must be string
  name: some_cookie_name

```

* Then Initalize a mongodb client and get the collection using the Mongo Client API.


```python
    client = MongoClient(uri)
    db = client["database"]
    collection = db["collection"]
```

* Create a Mongodb document and insert to the database as follow. Ensure the password is hashed with the hashing module


```python

    doc = {
        'username':'Johnny',
        'password': stauth.Hasher(['dog']).generate()[0]
        'email': 'johnwick@wicked.com',
        'name': 'John Wick'
    }
    collection.insert_one(doc)
```





### 2. Creating a login widget

* Subsequently import the configuration file and the collection object into your script and create an authentication object.

```python
import yaml
from yaml.loader import SafeLoader
from dbscript import collection

with open('../config.yaml') as file:
    config = yaml.load(file, Loader=SafeLoader)

authenticator = stauth.Authenticate(
    collection,
    config['cookie']['name'],
    config['cookie']['key'],
    config['cookie']['expiry_days'],

)
```


* Then finally render the login module as follows. Here you will need to provide a name for the login form, and specify where the form should be located i.e. main body or sidebar (will default to main body).

```python
authenticator.login('Login', 'main')
```
![](https://github.com/mkhorasani/Streamlit-Authenticator/blob/main/graphics/login_form.PNG)

### 3. Authenticating users

* You can then retrieve the name, authentication status, and username from Streamlit's session state using **st.session_state["name"]**, **st.session_state["authentication_status"]**, and **st.session_state["username"]** to allow a verified user to proceed to any restricted content.
* In addition, you may include an optional logout button at any location on your main body or sidebar (will default to main body). The optional **key** parameter for the logout widget should be used with multipage applications to prevent Streamlit from throwing duplicate key errors.

```python
if st.session_state["authentication_status"]:
    authenticator.logout('Logout', 'main', key='unique_key')
    st.write(f'Welcome *{st.session_state["name"]}*')
    st.title('Some content')
elif st.session_state["authentication_status"] is False:
    st.error('Username/password is incorrect')
elif st.session_state["authentication_status"] is None:
    st.warning('Please enter your username and password')
```

![](https://github.com/mkhorasani/Streamlit-Authenticator/blob/main/graphics/logged_in.PNG)

* Or prompt an unverified user to enter a correct username and password.

![](https://github.com/mkhorasani/Streamlit-Authenticator/blob/main/graphics/incorrect_login.PNG)

* Please note that logging out will revert the authentication status to **None** and will delete the associated reauthentication cookie as well.

### 4. Creating a password reset widget

* You may use the **reset_password** widget to allow a logged in user to modify their password as shown below.

```python
if st.session_state["authentication_status"]:
    try:
        if authenticator.reset_password(st.session_state["username"], 'Reset password'):
            st.success('Password modified successfully')
    except Exception as e:
        st.error(e)
```

![](https://github.com/mkhorasani/Streamlit-Authenticator/blob/main/graphics/reset_password.PNG)



### 5. Creating a new user registration widget

* You may use the **register_user** widget to allow to allow anyone to sign up. After a successful validation, the new user entry is added to the database. The user can then go an login with the new account

```python
try:
    if authenticator.register_user('Register user'):
        st.success('User registered successfully')
except Exception as e:
    st.error(e)
```

![](https://github.com/mkhorasani/Streamlit-Authenticato-mongor/blob/main/graphics/register_user.PNG)


### 6. Creating a forgot password widget

* You may use the **forgot_password** widget to allow a user to generate a new random password. This password will be automatically hashed and saved in the database. The widget will return the username, email, and new random password of the user which should then be transferred to them securely.

```python
try:
    username_of_forgotten_password, email_of_forgotten_password, new_random_password = authenticator.forgot_password('Forgot password')
    if username_of_forgotten_password:
        st.success('New password to be sent securely')
        # Random password should be transferred to user securely
    else:
        st.error('Username not found')
except Exception as e:
    st.error(e)
```

![](https://github.com/mkhorasani/Streamlit-Authenticator/blob/main/graphics/forgot_password.PNG)



### 7. Creating a forgot username widget

* You may use the **forgot_username** widget to allow a user to retrieve their forgotten username. The widget will return the username and email of the user which should then be transferred to them securely.

```python
try:
    username_of_forgotten_username, email_of_forgotten_username = authenticator.forgot_username('Forgot username')
    if username_of_forgotten_username:
        st.success('Username to be sent securely')
        # Username should be transferred to user securely
    else:
        st.error('Email not found')
except Exception as e:
    st.error(e)
```

![](https://github.com/mkhorasani/Streamlit-Authenticator/blob/main/graphics/forgot_username.PNG)


## Credits
- Mohamed Abdou for the highly versatile cookie manager in [Extra-Streamlit-Components](https://github.com/Mohamed-512/Extra-Streamlit-Components).
- Mohammad Khorasani for providing the springboard and inspiration in [Streamlit-Authenticator] https://github.com/mkhorasani/Streamlit-Authenticator

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/RobotForge/Streamlit-Authenticator-mongo",
    "name": "streamlit-authenticator-mongo",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": "",
    "keywords": "Python,Streamlit,Authentication,Components,MongoDB",
    "author": "Kegbokokim Ibok",
    "author_email": "ibokkegbo@robotforge.co",
    "download_url": "https://files.pythonhosted.org/packages/b4/30/2ec5ffb557e4b01aabc7d7ad2bca6395800d488c3faa96f1b76ab3727cf8/streamlit-authenticator-mongo-0.1.5.tar.gz",
    "platform": null,
    "description": "## Streamlit Authenticator Mongo\r\n\r\n**A secure authentication module to validate user credentials stored in a Mongo database in a Streamlit application.**\r\n\r\n\r\n## Installation\r\n\r\nStreamlit-Authenticator-Mongo is distributed via [PyPI](https://pypi.org/project/streamlit-authenticator-mongo/):\r\n\r\n```python\r\npip install streamlit-authenticator-mongo\r\n```\r\n\r\n## Example\r\n\r\nUsing Streamlit-Authenticator-Mongo is as simple as importing the module and calling it to verify your predefined users' credentials.\r\n\r\n```python\r\nimport streamlit as st\r\nimport streamlit_authenticator_mongo as stauth\r\n```\r\n\r\n### 1. Hashing passwords\r\n\r\n* Initially create a YAML configuration file and enter the number of days to expiry for a JWT cookie that will be stored on the client's browser to enable passwordless reauthentication. If you do not require reauthentication, you may set the number of days to expiry to 0. \r\n\r\n```python\r\ncookie:\r\n  expiry_days: 30\r\n  key: some_signature_key # Must be string\r\n  name: some_cookie_name\r\n\r\n```\r\n\r\n* Then Initalize a mongodb client and get the collection using the Mongo Client API.\r\n\r\n\r\n```python\r\n    client = MongoClient(uri)\r\n    db = client[\"database\"]\r\n    collection = db[\"collection\"]\r\n```\r\n\r\n* Create a Mongodb document and insert to the database as follow. Ensure the password is hashed with the hashing module\r\n\r\n\r\n```python\r\n\r\n    doc = {\r\n        'username':'Johnny',\r\n        'password': stauth.Hasher(['dog']).generate()[0]\r\n        'email': 'johnwick@wicked.com',\r\n        'name': 'John Wick'\r\n    }\r\n    collection.insert_one(doc)\r\n```\r\n\r\n\r\n\r\n\r\n\r\n### 2. Creating a login widget\r\n\r\n* Subsequently import the configuration file and the collection object into your script and create an authentication object.\r\n\r\n```python\r\nimport yaml\r\nfrom yaml.loader import SafeLoader\r\nfrom dbscript import collection\r\n\r\nwith open('../config.yaml') as file:\r\n    config = yaml.load(file, Loader=SafeLoader)\r\n\r\nauthenticator = stauth.Authenticate(\r\n    collection,\r\n    config['cookie']['name'],\r\n    config['cookie']['key'],\r\n    config['cookie']['expiry_days'],\r\n\r\n)\r\n```\r\n\r\n\r\n* Then finally render the login module as follows. Here you will need to provide a name for the login form, and specify where the form should be located i.e. main body or sidebar (will default to main body).\r\n\r\n```python\r\nauthenticator.login('Login', 'main')\r\n```\r\n![](https://github.com/mkhorasani/Streamlit-Authenticator/blob/main/graphics/login_form.PNG)\r\n\r\n### 3. Authenticating users\r\n\r\n* You can then retrieve the name, authentication status, and username from Streamlit's session state using **st.session_state[\"name\"]**, **st.session_state[\"authentication_status\"]**, and **st.session_state[\"username\"]** to allow a verified user to proceed to any restricted content.\r\n* In addition, you may include an optional logout button at any location on your main body or sidebar (will default to main body). The optional **key** parameter for the logout widget should be used with multipage applications to prevent Streamlit from throwing duplicate key errors.\r\n\r\n```python\r\nif st.session_state[\"authentication_status\"]:\r\n    authenticator.logout('Logout', 'main', key='unique_key')\r\n    st.write(f'Welcome *{st.session_state[\"name\"]}*')\r\n    st.title('Some content')\r\nelif st.session_state[\"authentication_status\"] is False:\r\n    st.error('Username/password is incorrect')\r\nelif st.session_state[\"authentication_status\"] is None:\r\n    st.warning('Please enter your username and password')\r\n```\r\n\r\n![](https://github.com/mkhorasani/Streamlit-Authenticator/blob/main/graphics/logged_in.PNG)\r\n\r\n* Or prompt an unverified user to enter a correct username and password.\r\n\r\n![](https://github.com/mkhorasani/Streamlit-Authenticator/blob/main/graphics/incorrect_login.PNG)\r\n\r\n* Please note that logging out will revert the authentication status to **None** and will delete the associated reauthentication cookie as well.\r\n\r\n### 4. Creating a password reset widget\r\n\r\n* You may use the **reset_password** widget to allow a logged in user to modify their password as shown below.\r\n\r\n```python\r\nif st.session_state[\"authentication_status\"]:\r\n    try:\r\n        if authenticator.reset_password(st.session_state[\"username\"], 'Reset password'):\r\n            st.success('Password modified successfully')\r\n    except Exception as e:\r\n        st.error(e)\r\n```\r\n\r\n![](https://github.com/mkhorasani/Streamlit-Authenticator/blob/main/graphics/reset_password.PNG)\r\n\r\n\r\n\r\n### 5. Creating a new user registration widget\r\n\r\n* You may use the **register_user** widget to allow to allow anyone to sign up. After a successful validation, the new user entry is added to the database. The user can then go an login with the new account\r\n\r\n```python\r\ntry:\r\n    if authenticator.register_user('Register user'):\r\n        st.success('User registered successfully')\r\nexcept Exception as e:\r\n    st.error(e)\r\n```\r\n\r\n![](https://github.com/mkhorasani/Streamlit-Authenticato-mongor/blob/main/graphics/register_user.PNG)\r\n\r\n\r\n### 6. Creating a forgot password widget\r\n\r\n* You may use the **forgot_password** widget to allow a user to generate a new random password. This password will be automatically hashed and saved in the database. The widget will return the username, email, and new random password of the user which should then be transferred to them securely.\r\n\r\n```python\r\ntry:\r\n    username_of_forgotten_password, email_of_forgotten_password, new_random_password = authenticator.forgot_password('Forgot password')\r\n    if username_of_forgotten_password:\r\n        st.success('New password to be sent securely')\r\n        # Random password should be transferred to user securely\r\n    else:\r\n        st.error('Username not found')\r\nexcept Exception as e:\r\n    st.error(e)\r\n```\r\n\r\n![](https://github.com/mkhorasani/Streamlit-Authenticator/blob/main/graphics/forgot_password.PNG)\r\n\r\n\r\n\r\n### 7. Creating a forgot username widget\r\n\r\n* You may use the **forgot_username** widget to allow a user to retrieve their forgotten username. The widget will return the username and email of the user which should then be transferred to them securely.\r\n\r\n```python\r\ntry:\r\n    username_of_forgotten_username, email_of_forgotten_username = authenticator.forgot_username('Forgot username')\r\n    if username_of_forgotten_username:\r\n        st.success('Username to be sent securely')\r\n        # Username should be transferred to user securely\r\n    else:\r\n        st.error('Email not found')\r\nexcept Exception as e:\r\n    st.error(e)\r\n```\r\n\r\n![](https://github.com/mkhorasani/Streamlit-Authenticator/blob/main/graphics/forgot_username.PNG)\r\n\r\n\r\n## Credits\r\n- Mohamed Abdou for the highly versatile cookie manager in [Extra-Streamlit-Components](https://github.com/Mohamed-512/Extra-Streamlit-Components).\r\n- Mohammad Khorasani for providing the springboard and inspiration in [Streamlit-Authenticator] https://github.com/mkhorasani/Streamlit-Authenticator\r\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "A secure authentication module to validate user credentials and insert user credentails in Mongodb with streamlit.",
    "version": "0.1.5",
    "project_urls": {
        "Homepage": "https://github.com/RobotForge/Streamlit-Authenticator-mongo"
    },
    "split_keywords": [
        "python",
        "streamlit",
        "authentication",
        "components",
        "mongodb"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "7ce05eb8ea3b5adc6d4a8415a038371408a9fc899ad2a5dbd250d4212b30dddd",
                "md5": "c3e5cdd87fabc0b0f62a723d712b5c8b",
                "sha256": "ea0df0ccd02af5c148f523e2a8cc9493e429eb9adb97052d0f8fc5a997f77fa7"
            },
            "downloads": -1,
            "filename": "streamlit_authenticator_mongo-0.1.5-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c3e5cdd87fabc0b0f62a723d712b5c8b",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 15263,
            "upload_time": "2024-01-06T19:35:11",
            "upload_time_iso_8601": "2024-01-06T19:35:11.717078Z",
            "url": "https://files.pythonhosted.org/packages/7c/e0/5eb8ea3b5adc6d4a8415a038371408a9fc899ad2a5dbd250d4212b30dddd/streamlit_authenticator_mongo-0.1.5-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b4302ec5ffb557e4b01aabc7d7ad2bca6395800d488c3faa96f1b76ab3727cf8",
                "md5": "401d66d9bc6bca8d954face069b4073c",
                "sha256": "c6c602e86a2bddd4afa702d988afa4071252f19b823945dfc437659e29405663"
            },
            "downloads": -1,
            "filename": "streamlit-authenticator-mongo-0.1.5.tar.gz",
            "has_sig": false,
            "md5_digest": "401d66d9bc6bca8d954face069b4073c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 14969,
            "upload_time": "2024-01-06T19:35:14",
            "upload_time_iso_8601": "2024-01-06T19:35:14.454978Z",
            "url": "https://files.pythonhosted.org/packages/b4/30/2ec5ffb557e4b01aabc7d7ad2bca6395800d488c3faa96f1b76ab3727cf8/streamlit-authenticator-mongo-0.1.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-01-06 19:35:14",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "RobotForge",
    "github_project": "Streamlit-Authenticator-mongo",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "streamlit-authenticator-mongo"
}
        
Elapsed time: 2.79608s