siwe-auth-django


Namesiwe-auth-django JSON
Version 3.0.3 PyPI version JSON
download
home_page
SummaryCustom Django authentication backend using Sign-In with Ethereum (EIP-4361) with a custom wallet user model. Available to use in django rest api or django app.
upload_time2024-02-09 22:07:15
maintainer
docs_urlNone
author
requires_python>=3.8
licenseMIT License Copyright (c) 2024 Giovanni Borgogno Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords authentication authorization django eip-4361 siwe sign-in with ethereum web3
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Siwe Authentication - Django
[![GitHub Stars](https://img.shields.io/github/stars/giovaborgogno/siwe-auth-django.svg?style=flat&label=Stars)](https://github.com/giovaborgogno/siwe-auth-django/stargazers)
[![GitHub Forks](https://img.shields.io/github/forks/giovaborgogno/siwe-auth-django.svg?style=flat&label=Forks)](https://github.com/giovaborgogno/siwe-auth-django/network/members)
[![GitHub Issues](https://img.shields.io/github/issues/giovaborgogno/siwe-auth-django.svg?style=flat&label=Issues)](https://github.com/giovaborgogno/siwe-auth-django/issues)
[![PyPI Version](https://img.shields.io/pypi/v/siwe-auth-django.svg?style=flat&label=PyPI%20Version)](https://pypi.org/project/siwe-auth-django/)
[![GitHub Release Date](https://img.shields.io/github/release-date/giovaborgogno/siwe-auth-django.svg?style=flat&label=Released)](https://github.com/giovaborgogno/siwe-auth-django/releases)

Siwe Authentication is a Django app designed for Ethereum-based authentication using the Sign-In with Ethereum (EIP-4361) standard. It allows users to sign in using their Ethereum wallets, and provides flexible settings for customization.

## Table Of Contents

1. [Get Started](#get-started)
    1. [Installation](#installation)
    2. [Configuration](#configuration)
        - [Configure your settings.py](#add-siwe_auth-to-installed_apps-in-your-settingspy-file)
        - [Configure your urls.py](#include-the-siwe-authentication-urls-in-your-projects-urlspy)
    3. [Run migrations](#run-migrations)
2. [Usage](#usage)
3. [Custom Groups](#custom-groups)
4. [Django User Model](#django-user-model)
5. [Contrubuting](#contributing)
6. [License](#license)

## Get Started

### Installation

Install the package using pip with the following command:

```bash
pip install siwe-auth-django
```

### Configuration


#### Add `'siwe_auth'` to `INSTALLED_APPS` in your settings.py file:

```python
# settings.py

INSTALLED_APPS = [
    # ...
    'siwe_auth',
    # ...
]
```

#### Add authentication configurations in your settings.py file:

```python
# settings.py

AUTH_USER_MODEL = "siwe_auth.Wallet"
AUTHENTICATION_BACKENDS = [
    "siwe_auth.backends.SiweBackend", 
    "django.contrib.auth.backends.ModelBackend" # this is necessary if you want to use superusers in django admin authentication
    ]
SESSION_COOKIE_AGE = 3 * 60 * 60 
```

If you need to create a customized auth user model refer to [Django User Model](#django-user-model) section (Recommended).

#### Add the `SIWE_AUTH` configuration in your settings.py file:

Available settings:

`"CSRF_EXEMPT"`: Flag indicating whether CSRF protection is exempted for Siwe Authentication views (if you are creating an REST API must be `True`).  
`"PROVIDER"`: Ethereum provider URL (it is required).  
`"CREATE_GROUPS_ON_AUTH"`: Flag indicating whether to create groups on user authentication.  
`"CREATE_ENS_PROFILE_ON_AUTH"`: Flag indicating whether to create ENS profiles on user authentication.  
`"CUSTOM_GROUPS"`: List of custom groups to be created on user authentication. If you need to create more group manager refer to [Custom Groups](#custom-groups) section.

```python
# settings.py

from siwe_auth import group # needed if you want to set custom groups

# ...

SIWE_AUTH = {
    "CSRF_EXEMPT": True, # default False
    "PROVIDER": "https://mainnet.infura.io/v3/...", # required
    "CREATE_GROUPS_ON_AUTH": True, # default False
    "CREATE_ENS_PROFILE_ON_AUTH": True, # default True
    "CUSTOM_GROUPS": [
        ("usdt_owners", groups.ERC20OwnerManager(config={'contract': '0x82E...550'})),
        ("nft_owners", groups.ERC721OwnerManager(config={'contract': '0x785...3A5'})),
        # ...
    ], # default []
}
``` 

#### Include the Siwe Authentication URLs in your project's urls.py:

```python
# urls.py

from django.urls import include, path

urlpatterns = [
    # ...
    path('api/auth', include('siwe_auth.urls', namespace='siwe_auth')),
    # ...
]
```

### Run migrations:

```bash
python manage.py migrate
```

## Usage

You need to follow this steps to successful authentication using SIWE protocol (EIP-4361):

1. Get nonce: GET Method `/api/auth/nonce`.
2. Use that nonce to create a SIWE message in frontend and sign the message with your metamask or another wallet.
3. Login: POST Method `/api/auth/login`, using the message and signature. Example request body:
```json
{
    "message": {
        "domain": "your_domain.com",
        "address": "0xA8f1...61905",
        "statement": "This is a test statement.",
        "uri": "https://your_domain.com",
        "version": "1",
        "chainId": 1,
        "nonce": "2483e73dedffbd2616773506",
        "issuedAt": "2024-01-27T18:43:48.011Z"
    },
    "signature": "0xf5b4ea...7bda4e177276dd1c"
}
```
4. Now you have the sessionid in cookies so you can use it for authenticated required views.
5. Refresh the sessionid: POST Method `api/auth/refresh`.
6. Verify if you are authenticated: GET Method `api/auth/verify`.
7. Logout: POST Method `api/auth/logout`.

## [Custom Groups](/src/siwe_auth/groups.py)

Three custom group managers are provided by default:    
`ERC20OwnerManager`  
`ERC721OwnerManager`  
`ERC1155OwnerManager`  

You can create more group managers by extending the `GroupManager` class:
```python
from web3 import HTTPProvider
from siwe_auth.groups import GroupManager

class MyCustomGroup(GroupManager):
    def __init__(self, config: dict):
        # Your custom logic
        pass

    def is_member(self, wallet: object, provider: HTTPProvider) -> bool:
        # Your custom logic to determine membership
        pass
```

You can create custom groups in your settings.py:
```python
# settings.py

from siwe_auth import group # needed if you want to set custom groups

# ...

SIWE_AUTH = {
    # ...
    "CUSTOM_GROUPS": [
        ("usdt_owners", groups.ERC20OwnerManager(config={'contract': '0x82E...550'})),
        ("nft_owners", groups.ERC721OwnerManager(config={'contract': '0x785...3A5'})),
        ("token_owners", groups.ERC1154OwnerManager(config={'contract': '0x872...5F5'})),
        # ...
    ], # default []
}
``` 
Then you can manage these groups with the django GroupManager, example:
```python
from django.contrib.auth.models import Group
# ...

usdt_owners_group = Group.objects.get(name='usdt_owners')
all_usdt_owners = usdt_owners_group.user_set.all()
# ...
```

## [Django User Model](/src/siwe_auth/models.py)

By default, Siwe Authentication uses the `Wallet` model as the user model. If you prefer to use a specific user model, you can either use the provided `AbstractWallet` model or create your own user model. For more details, refer to the [Configuration](#configuration) section.

```python
# Django project your_app/models.py

from siwe_auth.models import AbstractWallet

class MyUserModel(AbstractWallet):
    # Add your custom fields here
```

If you use a customized user model you need to register a customized admin site.
```python
# Django project your_app/admin.py

from django.contrib import admin

from django.contrib.auth import get_user_model
from siwe_auth.admin import WalletBaseAdmin

WalletModel = get_user_model()


# You can inherit from siwe_auth.admin.WalletBaseAdmin or from django.contrib.auth.admin.BaseUserAdmin if you preffer.
class WalletAdmin(WalletBaseAdmin): 
    # Add your custom configuration here
    
admin.site.register(WalletModel, WalletAdmin)
```

## Contributing
Contributions are welcome! Please create issues for bugs or feature requests. Pull requests are encouraged.

## [License](/LICENSE)
This project is licensed under the MIT License - see the LICENSE file for details.
            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "siwe-auth-django",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "Authentication,Authorization,Django,EIP-4361,SIWE,Sign-In with Ethereum,Web3",
    "author": "",
    "author_email": "Giovanni Borgogno <giovaborgogno@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/c0/fb/c16939eef963837b6145ff491536cd702f33c689b21b00088265917cd4ac/siwe_auth_django-3.0.3.tar.gz",
    "platform": null,
    "description": "# Siwe Authentication - Django\n[![GitHub Stars](https://img.shields.io/github/stars/giovaborgogno/siwe-auth-django.svg?style=flat&label=Stars)](https://github.com/giovaborgogno/siwe-auth-django/stargazers)\n[![GitHub Forks](https://img.shields.io/github/forks/giovaborgogno/siwe-auth-django.svg?style=flat&label=Forks)](https://github.com/giovaborgogno/siwe-auth-django/network/members)\n[![GitHub Issues](https://img.shields.io/github/issues/giovaborgogno/siwe-auth-django.svg?style=flat&label=Issues)](https://github.com/giovaborgogno/siwe-auth-django/issues)\n[![PyPI Version](https://img.shields.io/pypi/v/siwe-auth-django.svg?style=flat&label=PyPI%20Version)](https://pypi.org/project/siwe-auth-django/)\n[![GitHub Release Date](https://img.shields.io/github/release-date/giovaborgogno/siwe-auth-django.svg?style=flat&label=Released)](https://github.com/giovaborgogno/siwe-auth-django/releases)\n\nSiwe Authentication is a Django app designed for Ethereum-based authentication using the Sign-In with Ethereum (EIP-4361) standard. It allows users to sign in using their Ethereum wallets, and provides flexible settings for customization.\n\n## Table Of Contents\n\n1. [Get Started](#get-started)\n    1. [Installation](#installation)\n    2. [Configuration](#configuration)\n        - [Configure your settings.py](#add-siwe_auth-to-installed_apps-in-your-settingspy-file)\n        - [Configure your urls.py](#include-the-siwe-authentication-urls-in-your-projects-urlspy)\n    3. [Run migrations](#run-migrations)\n2. [Usage](#usage)\n3. [Custom Groups](#custom-groups)\n4. [Django User Model](#django-user-model)\n5. [Contrubuting](#contributing)\n6. [License](#license)\n\n## Get Started\n\n### Installation\n\nInstall the package using pip with the following command:\n\n```bash\npip install siwe-auth-django\n```\n\n### Configuration\n\n\n#### Add `'siwe_auth'` to `INSTALLED_APPS` in your settings.py file:\n\n```python\n# settings.py\n\nINSTALLED_APPS = [\n    # ...\n    'siwe_auth',\n    # ...\n]\n```\n\n#### Add authentication configurations in your settings.py file:\n\n```python\n# settings.py\n\nAUTH_USER_MODEL = \"siwe_auth.Wallet\"\nAUTHENTICATION_BACKENDS = [\n    \"siwe_auth.backends.SiweBackend\", \n    \"django.contrib.auth.backends.ModelBackend\" # this is necessary if you want to use superusers in django admin authentication\n    ]\nSESSION_COOKIE_AGE = 3 * 60 * 60 \n```\n\nIf you need to create a customized auth user model refer to [Django User Model](#django-user-model) section (Recommended).\n\n#### Add the `SIWE_AUTH` configuration in your settings.py file:\n\nAvailable settings:\n\n`\"CSRF_EXEMPT\"`: Flag indicating whether CSRF protection is exempted for Siwe Authentication views (if you are creating an REST API must be `True`).  \n`\"PROVIDER\"`: Ethereum provider URL (it is required).  \n`\"CREATE_GROUPS_ON_AUTH\"`: Flag indicating whether to create groups on user authentication.  \n`\"CREATE_ENS_PROFILE_ON_AUTH\"`: Flag indicating whether to create ENS profiles on user authentication.  \n`\"CUSTOM_GROUPS\"`: List of custom groups to be created on user authentication. If you need to create more group manager refer to [Custom Groups](#custom-groups) section.\n\n```python\n# settings.py\n\nfrom siwe_auth import group # needed if you want to set custom groups\n\n# ...\n\nSIWE_AUTH = {\n    \"CSRF_EXEMPT\": True, # default False\n    \"PROVIDER\": \"https://mainnet.infura.io/v3/...\", # required\n    \"CREATE_GROUPS_ON_AUTH\": True, # default False\n    \"CREATE_ENS_PROFILE_ON_AUTH\": True, # default True\n    \"CUSTOM_GROUPS\": [\n        (\"usdt_owners\", groups.ERC20OwnerManager(config={'contract': '0x82E...550'})),\n        (\"nft_owners\", groups.ERC721OwnerManager(config={'contract': '0x785...3A5'})),\n        # ...\n    ], # default []\n}\n``` \n\n#### Include the Siwe Authentication URLs in your project's urls.py:\n\n```python\n# urls.py\n\nfrom django.urls import include, path\n\nurlpatterns = [\n    # ...\n    path('api/auth', include('siwe_auth.urls', namespace='siwe_auth')),\n    # ...\n]\n```\n\n### Run migrations:\n\n```bash\npython manage.py migrate\n```\n\n## Usage\n\nYou need to follow this steps to successful authentication using SIWE protocol (EIP-4361):\n\n1. Get nonce: GET Method `/api/auth/nonce`.\n2. Use that nonce to create a SIWE message in frontend and sign the message with your metamask or another wallet.\n3. Login: POST Method `/api/auth/login`, using the message and signature. Example request body:\n```json\n{\n    \"message\": {\n        \"domain\": \"your_domain.com\",\n        \"address\": \"0xA8f1...61905\",\n        \"statement\": \"This is a test statement.\",\n        \"uri\": \"https://your_domain.com\",\n        \"version\": \"1\",\n        \"chainId\": 1,\n        \"nonce\": \"2483e73dedffbd2616773506\",\n        \"issuedAt\": \"2024-01-27T18:43:48.011Z\"\n    },\n    \"signature\": \"0xf5b4ea...7bda4e177276dd1c\"\n}\n```\n4. Now you have the sessionid in cookies so you can use it for authenticated required views.\n5. Refresh the sessionid: POST Method `api/auth/refresh`.\n6. Verify if you are authenticated: GET Method `api/auth/verify`.\n7. Logout: POST Method `api/auth/logout`.\n\n## [Custom Groups](/src/siwe_auth/groups.py)\n\nThree custom group managers are provided by default:    \n`ERC20OwnerManager`  \n`ERC721OwnerManager`  \n`ERC1155OwnerManager`  \n\nYou can create more group managers by extending the `GroupManager` class:\n```python\nfrom web3 import HTTPProvider\nfrom siwe_auth.groups import GroupManager\n\nclass MyCustomGroup(GroupManager):\n    def __init__(self, config: dict):\n        # Your custom logic\n        pass\n\n    def is_member(self, wallet: object, provider: HTTPProvider) -> bool:\n        # Your custom logic to determine membership\n        pass\n```\n\nYou can create custom groups in your settings.py:\n```python\n# settings.py\n\nfrom siwe_auth import group # needed if you want to set custom groups\n\n# ...\n\nSIWE_AUTH = {\n    # ...\n    \"CUSTOM_GROUPS\": [\n        (\"usdt_owners\", groups.ERC20OwnerManager(config={'contract': '0x82E...550'})),\n        (\"nft_owners\", groups.ERC721OwnerManager(config={'contract': '0x785...3A5'})),\n        (\"token_owners\", groups.ERC1154OwnerManager(config={'contract': '0x872...5F5'})),\n        # ...\n    ], # default []\n}\n``` \nThen you can manage these groups with the django GroupManager, example:\n```python\nfrom django.contrib.auth.models import Group\n# ...\n\nusdt_owners_group = Group.objects.get(name='usdt_owners')\nall_usdt_owners = usdt_owners_group.user_set.all()\n# ...\n```\n\n## [Django User Model](/src/siwe_auth/models.py)\n\nBy default, Siwe Authentication uses the `Wallet` model as the user model. If you prefer to use a specific user model, you can either use the provided `AbstractWallet` model or create your own user model. For more details, refer to the [Configuration](#configuration) section.\n\n```python\n# Django project your_app/models.py\n\nfrom siwe_auth.models import AbstractWallet\n\nclass MyUserModel(AbstractWallet):\n    # Add your custom fields here\n```\n\nIf you use a customized user model you need to register a customized admin site.\n```python\n# Django project your_app/admin.py\n\nfrom django.contrib import admin\n\nfrom django.contrib.auth import get_user_model\nfrom siwe_auth.admin import WalletBaseAdmin\n\nWalletModel = get_user_model()\n\n\n# You can inherit from siwe_auth.admin.WalletBaseAdmin or from django.contrib.auth.admin.BaseUserAdmin if you preffer.\nclass WalletAdmin(WalletBaseAdmin): \n    # Add your custom configuration here\n    \nadmin.site.register(WalletModel, WalletAdmin)\n```\n\n## Contributing\nContributions are welcome! Please create issues for bugs or feature requests. Pull requests are encouraged.\n\n## [License](/LICENSE)\nThis project is licensed under the MIT License - see the LICENSE file for details.",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2024 Giovanni Borgogno  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
    "summary": "Custom Django authentication backend using Sign-In with Ethereum (EIP-4361) with a custom wallet user model. Available to use in django rest api or django app.",
    "version": "3.0.3",
    "project_urls": {
        "Homepage": "https://github.com/giovaborgogno/siwe-auth-django",
        "Issues": "https://github.com/giovaborgogno/siwe-auth-django/issues",
        "Repository": "https://github.com/giovaborgogno/siwe-auth-django"
    },
    "split_keywords": [
        "authentication",
        "authorization",
        "django",
        "eip-4361",
        "siwe",
        "sign-in with ethereum",
        "web3"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1e97d4ca5e41017adc7a373f4031d15f04dec7133ebf25c7cc84a31a65e7a398",
                "md5": "7a46899455bfaf89be9f4b4f31300a58",
                "sha256": "11ef039d19542af0a3a90e680a56b9a969992c79939a086a0b96e057a29d270b"
            },
            "downloads": -1,
            "filename": "siwe_auth_django-3.0.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "7a46899455bfaf89be9f4b4f31300a58",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 18461,
            "upload_time": "2024-02-09T22:07:13",
            "upload_time_iso_8601": "2024-02-09T22:07:13.963080Z",
            "url": "https://files.pythonhosted.org/packages/1e/97/d4ca5e41017adc7a373f4031d15f04dec7133ebf25c7cc84a31a65e7a398/siwe_auth_django-3.0.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c0fbc16939eef963837b6145ff491536cd702f33c689b21b00088265917cd4ac",
                "md5": "860ef6ea03cdf5c232bd283dbe8128e9",
                "sha256": "deab8cebd53800a4fc27ea92a56e0a2feb3238f2c85f0eb158a1817f761dde1f"
            },
            "downloads": -1,
            "filename": "siwe_auth_django-3.0.3.tar.gz",
            "has_sig": false,
            "md5_digest": "860ef6ea03cdf5c232bd283dbe8128e9",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 16897,
            "upload_time": "2024-02-09T22:07:15",
            "upload_time_iso_8601": "2024-02-09T22:07:15.617694Z",
            "url": "https://files.pythonhosted.org/packages/c0/fb/c16939eef963837b6145ff491536cd702f33c689b21b00088265917cd4ac/siwe_auth_django-3.0.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-09 22:07:15",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "giovaborgogno",
    "github_project": "siwe-auth-django",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "siwe-auth-django"
}
        
Elapsed time: 0.18314s