sanic-security


Namesanic-security JSON
Version 1.12.5 PyPI version JSON
download
home_pageNone
SummaryAn async security library for the Sanic framework.
upload_time2024-09-07 02:42:23
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseNone
keywords security authentication authorization verification async sanic
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <!-- PROJECT SHIELDS -->
<!--
*** I'm using markdown "reference style" links for readability.
*** Reference links are enclosed in brackets [ ] instead of parentheses ( ).
*** See the bottom of this document for the declaration of the reference variables
*** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use.
*** https://www.markdownguide.org/basic-syntax/#reference-style-links
-->

[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![Downloads](https://static.pepy.tech/badge/sanic-security)](https://pepy.tech/project/sanic-security)
[![Conda Downloads](https://img.shields.io/conda/dn/conda-forge/sanic-security.svg)](https://anaconda.org/conda-forge/sanic-security)


<!-- PROJECT LOGO -->
<br />
<p align="center">
  <h3 align="center">Sanic Security</h3>
  <p align="center">
   An async security library for the Sanic framework.
  </p>
</p>


<!-- TABLE OF CONTENTS -->
## Table of Contents

* [About the Project](#about-the-project)
* [Getting Started](#getting-started)
  * [Prerequisites](#prerequisites)
  * [Installation](#installation)
  * [Configuration](#configuration)
* [Usage](#usage)
    * [Authentication](#authentication)
    * [Captcha](#captcha)
    * [Two Step Verification](#two-step-verification)
    * [Authorization](#authorization)
    * [Testing](#testing)
    * [Tortoise](#tortoise)
* [Contributing](#contributing)
* [License](#license)
* [Versioning](#versioning)
* [Support](https://discord.gg/JHpZkMfKTJ)

<!-- ABOUT THE PROJECT -->
## About The Project

Sanic Security is an authentication, authorization, and verification library designed for use with [Sanic](https://github.com/huge-success/sanic).

* Login, registration, and authentication with refresh mechanisms
* Two-factor authentication
* Captcha
* Two-step verification
* Role based authorization with wildcard permissions

Visit [security.na-stewart.com](https://security.na-stewart.com) for documentation.

<!-- GETTING STARTED -->
## Getting Started

In order to get started, please install [Pip](https://pypi.org/).

### Installation

* Install the Sanic Security pip package.
```shell
pip3 install sanic-security
````

* Install the Sanic Security pip package with the `cryptography` dependency included.

If you are planning on encoding or decoding JWTs using certain digital signature algorithms (like RSA or ECDSA which use 
the public secret and private secret), you will need to install the `cryptography` library. This can be installed explicitly, or 
as an extra requirement.

```shell
pip3 install sanic-security[crypto]
````

* For developers, fork Sanic Security and install development dependencies.
```shell
pip3 install -e ".[dev]"
````

* Update sanic-security if already installed.
```shell
pip3 install --upgrade sanic-security
```

### Configuration

Sanic Security configuration is merely an object that can be modified either using dot-notation or like a 
dictionary.

For example: 

```python
from sanic_security.configuration import config

config.SECRET = "This is a big secret. Shhhhh"
config["CAPTCHA_FONT"] = "./resources/captcha-font.ttf"
```

You can also use the update() method like on regular dictionaries.

Any environment variables defined with the SANIC_SECURITY_ prefix will be applied to the config. For example, setting 
SANIC_SECURITY_SECRET will be loaded by the application automatically and fed into the SECRET config variable.

You can load environment variables with a different prefix via `config.load_environment_variables("NEW_PREFIX_")` method.

* Default configuration values:

| Key                                   | Value                        | Description                                                                                                                      |
|---------------------------------------|------------------------------|----------------------------------------------------------------------------------------------------------------------------------|
| **SECRET**                            | This is a big secret. Shhhhh | The secret used for generating and signing JWTs. This should be a string unique to your application. Keep it safe.               |
| **PUBLIC_SECRET**                     | None                         | The secret used for verifying and decoding JWTs and can be publicly shared. This should be a string unique to your application.  |
| **SESSION_SAMESITE**                  | strict                       | The SameSite attribute of session cookies.                                                                                       |
| **SESSION_SECURE**                    | True                         | The Secure attribute of session cookies.                                                                                         |
| **SESSION_HTTPONLY**                  | True                         | The HttpOnly attribute of session cookies. HIGHLY recommended that you do not turn this off, unless you know what you are doing. |
| **SESSION_DOMAIN**                    | None                         | The Domain attribute of session cookies.                                                                                         |
| **SESSION_ENCODING_ALGORITHM**        | HS256                        | The algorithm used to encode and decode session JWT's.                                                                           |
| **SESSION_PREFIX**                    | token                        | Prefix attached to the beginning of session cookies.                                                                             |
| **MAX_CHALLENGE_ATTEMPTS**            | 5                            | The maximum amount of session challenge attempts allowed.                                                                        |
| **CAPTCHA_SESSION_EXPIRATION**        | 60                           | The amount of seconds till captcha session expiration on creation. Setting to 0 will disable expiration.                         |
| **CAPTCHA_FONT**                      | captcha-font.ttf             | The file path to the font being used for captcha generation.                                                                     |
| **TWO_STEP_SESSION_EXPIRATION**       | 200                          | The amount of seconds till two-step session expiration on creation. Setting to 0 will disable expiration.                        |
| **AUTHENTICATION_SESSION_EXPIRATION** | 86400                        | The amount of seconds till authentication session expiration on creation. Setting to 0 will disable expiration.                  |
| **AUTHENTICATION_REFRESH_EXPIRATION** | 604800                       | The amount of seconds till authentication refresh expiration. Setting to 0 will disable refresh mechanism.                       |
| **ALLOW_LOGIN_WITH_USERNAME**         | False                        | Allows login via username and email.                                                                                             |
| **INITIAL_ADMIN_EMAIL**               | admin@example.com            | Email used when creating the initial admin account.                                                                              |
| **INITIAL_ADMIN_PASSWORD**            | admin123                     | Password used when creating the initial admin account.                                                                           |

## Usage

Sanic Security's authentication and verification functionality is session based. A new session will be created for the user after the user logs in or requests some form of verification (two-step, captcha). The session data is then encoded into a JWT and stored on a cookie on the user’s browser. The session cookie is then sent
along with every subsequent request. The server can then compare the session stored on the cookie against the session information stored in the database to verify user’s identity and send a response with the corresponding state.

The tables in the below examples represent example [request form-data](https://sanicframework.org/en/guide/basics/request.html#form).

## Authentication

* Initial Administrator Account

Creates initial admin account, you should modify its credentials in config!
  
```python
create_initial_admin_account(app)
if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8000)
```
  
* Registration (With two-step account verification)

Phone can be null or empty.

| Key          | Value               |
|--------------|---------------------|
| **username** | example             |
| **email**    | example@example.com |
| **phone**    | 19811354186         |
| **password** | examplepass         |

```python
@app.post("api/security/register")
async def on_register(request):
    account = await register(request)
    two_step_session = await request_two_step_verification(request, account)
    await email_code(
        account.email, two_step_session.code  # Code = 197251
    )  # Custom method for emailing verification code.
    response = json(
        "Registration successful! Email verification required.",
        two_step_session.json,
    )
    two_step_session.encode(response)
    return response
```

* Verify Account

Verifies the client's account via two-step session code.

| Key      | Value  |
|----------|--------|
| **code** | 197251 |

```python
@app.post("api/security/verify")
async def on_verify(request):
    two_step_session = await verify_account(request)
    return json("You have verified your account and may login!", two_step_session.json)
```

* Login (With two-factor authentication)

Credentials are retrieved via header are constructed by first combining the username and the password with a colon 
(aladdin:opensesame), and then by encoding the resulting string in base64 (YWxhZGRpbjpvcGVuc2VzYW1l). 
Here is an example authorization header: `Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l`. You can use a username 
as well as an email for login if `ALLOW_LOGIN_WITH_USERNAME` is true in the config.

```python
@app.post("api/security/login")
async def on_login(request):
    authentication_session = await login(request, require_second_factor=True)
    two_step_session = await request_two_step_verification(
        request, authentication_session.bearer
    )
    await email_code(
        authentication_session.bearer.email, two_step_session.code  # Code = 197251
    )  # Custom method for emailing verification code.
    response = json(
        "Login successful! Two-factor authentication required.",
        authentication_session.json,
    )
    authentication_session.encode(response)
    two_step_session.encode(response)
    return response
```

If this isn't desired, you can pass an account and password attempt directly into the login method instead.

* Fulfill Second Factor

Fulfills client authentication session's second factor requirement via two-step session code.

| Key      | Value  |
|----------|--------|
| **code** | 197251 |

```python
@app.post("api/security/fulfill-2fa")
async def on_two_factor_authentication(request):
    authentication_session = await fulfill_second_factor(request)
    response = json(
        "Authentication session second-factor fulfilled! You are now authenticated.",
        authentication_session.json,
    )
    authentication_session.encode(response)
    return response
```

* Anonymous Login

Simply create a new session and encode it.

```python
@app.post("api/security/login/anon")
async def on_anonymous_login(request):
    authentication_session = await AuthenticationSession.new(request)
    response = json(
        "Anonymous client now associated with session!", authentication_session.json
    )
    authentication_session.encode(response)
    return response
```

* Logout

```python
@app.post("api/security/logout")
async def on_logout(request):
    authentication_session = await logout(request)
    return json("Logout successful!", authentication_session.json)
```

* Authenticate

```python
@app.post("api/security/auth")
async def on_authenticate(request):
    authentication_session = await authenticate(request)
    response = json(
        "You have been authenticated.",
        authentication_session.json,
    )
    return response
```

* Requires Authentication (This method is not called directly and instead used as a decorator)

```python
@app.post("api/security/auth")
@requires_authentication
async def on_authenticate(request):
    authentication_session = request.ctx.authentication_session
    response = json(
        "You have been authenticated.",
        authentication_session.json,
    )
    return response
```

* Refresh Encoder

A new/refreshed session is returned during authentication if the client's session expired during authentication and
requires encoding. Rather than doing so manually, it can be done automatically via middleware.

```python
attach_refresh_encoder(app)
if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8000)
```

## Captcha

A pre-existing font for captcha challenges is included in the Sanic Security repository. You may set your own font by 
downloading a .ttf font and defining the file's path in the configuration.

[1001 Free Fonts](https://www.1001fonts.com/)

[Recommended Font](https://www.1001fonts.com/source-sans-pro-font.html)

* Request Captcha

```python
@app.get("api/security/captcha")
async def on_captcha_img_request(request):
    captcha_session = await request_captcha(request)
    response = captcha_session.get_image()  # Captcha: 192731
    captcha_session.encode(response)
    return response
```

* Captcha

| Key         | Value  |
|-------------|--------|
| **captcha** | 192731 |

```python
@app.post("api/security/captcha")
async def on_captcha(request):
    captcha_session = await captcha(request)
    return json("Captcha attempt successful!", captcha_session.json)
```

* Requires Captcha (This method is not called directly and instead used as a decorator)

| Key         | Value  |
|-------------|--------|
| **captcha** | 192731 |

```python
@app.post("api/security/captcha")
@requires_captcha
async def on_captcha(request):
    return json("Captcha attempt successful!", request.ctx.captcha_session.json)
```

## Two-step Verification

Two-step verification should be integrated with other custom functionality. For example, account verification during registration.

* Request Two-step Verification

| Key         | Value               |
|-------------|---------------------|
| **email**   | example@example.com |

```python
@app.post("api/security/two-step/request")
async def on_two_step_request(request):
    two_step_session = await request_two_step_verification(request)  # Code = 197251
    await email_code(
        two_step_session.bearer.email, two_step_session.code
    )  # Custom method for emailing verification code.
    response = json("Verification request successful!", two_step_session.json)
    two_step_session.encode(response)
    return response
``` 

* Resend Two-step Verification Code

```python
@app.post("api/security/two-step/resend")
async def on_two_step_resend(request):
    two_step_session = await TwoStepSession.decode(request)  # Code = 197251
    await email_code(
        two_step_session.bearer.email, two_step_session.code
    )  # Custom method for emailing verification code.
    return json("Verification code resend successful!", two_step_session.json)
```

* Two-step Verification

| Key      | Value  |
|----------|--------|
| **code** | 197251 |

```python
@app.post("api/security/two-step")
async def on_two_step_verification(request):
    two_step_session = await two_step_verification(request)
    response = json("Two-step verification attempt successful!", two_step_session.json)
    return response
```

* Requires Two-step Verification (This method is not called directly and instead used as a decorator)

| Key      | Value  |
|----------|--------|
| **code** | 197251 |

```python
@app.post("api/security/two-step")
@requires_two_step_verification
async def on_two_step_verification(request):
    response = json(
        "Two-step verification attempt successful!",
        request.ctx.two_step_session.json,
    )
    return response
```

## Authorization

Sanic Security uses role based authorization with wildcard permissions.

Roles are created for various job functions. The permissions to perform certain operations are assigned to specific roles. 
Users are assigned particular roles, and through those role assignments acquire the permissions needed to perform 
particular system functions. Since users are not assigned permissions directly, but only acquire them through their 
role (or roles), management of individual user rights becomes a matter of simply assigning appropriate roles to the 
user's account; this simplifies common operations, such as adding a user, or changing a user's department. 

Wildcard permissions support the concept of multiple levels or parts. For example, you could grant a user the permission
`printer:query`, `printer:query,delete`, or `printer:*`.
* Assign Role

```python
await assign_role(
    "Chat Room Moderator",
    account,
    "channels:view,delete, account:suspend,mute, voice:*",
    "Can read and delete messages in all chat rooms, suspend and mute accounts, and control voice chat.",
)
```

* Check Permissions

```python
@app.post("api/security/perms")
async def on_check_perms(request):
    authentication_session = await check_permissions(
        request, "channels:view", "voice:*"
    )
    return text("Account is authorized.")
```

* Require Permissions (This method is not called directly and instead used as a decorator.)

```python
@app.post("api/security/perms")
@require_permissions("channels:view", "voice:*")
async def on_check_perms(request):
    return text("Account is authorized.")
```

* Check Roles

```python
@app.post("api/security/roles")
async def on_check_roles(request):
    authentication_session = await check_roles(request, "Chat Room Moderator")
    return text("Account is authorized.")
```

* Require Roles (This method is not called directly and instead used as a decorator)

```python
@app.post("api/security/roles")
@require_roles("Chat Room Moderator")
async def on_check_roles(request):
    return text("Account is authorized.")
```

## Testing

* Set the `TEST_DATABASE_URL` configuration value.

* Make sure the test Sanic instance (`test/server.py`) is running on your machine.

* Run the unit test client (`test/tests.py`) for results.

## Tortoise

Sanic Security uses [Tortoise ORM](https://tortoise-orm.readthedocs.io/en/latest/index.html) for database operations.

Tortoise ORM is an easy-to-use asyncio ORM (Object Relational Mapper).

* Initialise your models and database like so: 

```python
async def init():
    await Tortoise.init(
        db_url="sqlite://db.sqlite3",
        modules={"models": ["sanic_security.models", "app.models"]},
    )
    await Tortoise.generate_schemas()
```

or

```python
register_tortoise(
    app,
    db_url="sqlite://db.sqlite3",
    modules={"models": ["sanic_security.models", "app.models"]},
    generate_schemas=True,
)
```

* Define your models like so:

```python
from tortoise.models import Model
from tortoise import fields


class Tournament(Model):
    id = fields.IntField(pk=True)
    name = fields.TextField()
```

* Use it like so:

```python
# Create instance by save
tournament = Tournament(name="New Tournament")
await tournament.save()

# Or by .create()
await Tournament.create(name="Another Tournament")

# Now search for a record
tour = await Tournament.filter(name__contains="Another").first()
print(tour.name)
```

<!-- CONTRIBUTING -->
## Contributing

Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**.

1. Fork the Project
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the Branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request


<!-- LICENSE -->
## License

Distributed under the MIT License. See `LICENSE` for more information.

<!-- Versioning -->
## Versioning

**0.0.0**

* MAJOR version when you make incompatible API changes.

* MINOR version when you add functionality in a backwards compatible manner.

* PATCH version when you make backwards compatible bug fixes.

[https://semver.org/](https://semver.org/)

<!-- MARKDOWN LINKS & IMAGES -->
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
[contributors-shield]: https://img.shields.io/github/contributors/sunset-developer/sanic-security.svg?style=flat-square
[contributors-url]: https://github.com/sunset-developer/sanic-security/graphs/contributors
[forks-shield]: https://img.shields.io/github/forks/sunset-developer/sanic-security.svg?style=flat-square
[forks-url]: https://github.com/sunset-developer/sanic-security/network/members
[stars-shield]: https://img.shields.io/github/stars/sunset-developer/sanic-security.svg?style=flat-square
[stars-url]: https://github.com/sunset-developer/sanic-security/stargazers
[issues-shield]: https://img.shields.io/github/issues/sunset-developer/sanic-security.svg?style=flat-square
[issues-url]: https://github.com/sunset-developer/sanic-security/issues
[license-shield]: https://img.shields.io/github/license/sunset-developer/sanic-security.svg?style=flat-square
[license-url]: https://github.com/sunset-developer/sanic-security/blob/master/LICENSE

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "sanic-security",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "security, authentication, authorization, verification, async, sanic",
    "author": null,
    "author_email": "Aidan Stewart <na.stewart365@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/68/d5/88bca775c2a2492cf7792183ff8cdf381a30c85e732bd5b93b278247b010/sanic_security-1.12.5.tar.gz",
    "platform": null,
    "description": "<!-- PROJECT SHIELDS -->\r\n<!--\r\n*** I'm using markdown \"reference style\" links for readability.\r\n*** Reference links are enclosed in brackets [ ] instead of parentheses ( ).\r\n*** See the bottom of this document for the declaration of the reference variables\r\n*** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use.\r\n*** https://www.markdownguide.org/basic-syntax/#reference-style-links\r\n-->\r\n\r\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\r\n[![Downloads](https://static.pepy.tech/badge/sanic-security)](https://pepy.tech/project/sanic-security)\r\n[![Conda Downloads](https://img.shields.io/conda/dn/conda-forge/sanic-security.svg)](https://anaconda.org/conda-forge/sanic-security)\r\n\r\n\r\n<!-- PROJECT LOGO -->\r\n<br />\r\n<p align=\"center\">\r\n  <h3 align=\"center\">Sanic Security</h3>\r\n  <p align=\"center\">\r\n   An async security library for the Sanic framework.\r\n  </p>\r\n</p>\r\n\r\n\r\n<!-- TABLE OF CONTENTS -->\r\n## Table of Contents\r\n\r\n* [About the Project](#about-the-project)\r\n* [Getting Started](#getting-started)\r\n  * [Prerequisites](#prerequisites)\r\n  * [Installation](#installation)\r\n  * [Configuration](#configuration)\r\n* [Usage](#usage)\r\n    * [Authentication](#authentication)\r\n    * [Captcha](#captcha)\r\n    * [Two Step Verification](#two-step-verification)\r\n    * [Authorization](#authorization)\r\n    * [Testing](#testing)\r\n    * [Tortoise](#tortoise)\r\n* [Contributing](#contributing)\r\n* [License](#license)\r\n* [Versioning](#versioning)\r\n* [Support](https://discord.gg/JHpZkMfKTJ)\r\n\r\n<!-- ABOUT THE PROJECT -->\r\n## About The Project\r\n\r\nSanic Security is an authentication, authorization, and verification library designed for use with [Sanic](https://github.com/huge-success/sanic).\r\n\r\n* Login, registration, and authentication with refresh mechanisms\r\n* Two-factor authentication\r\n* Captcha\r\n* Two-step verification\r\n* Role based authorization with wildcard permissions\r\n\r\nVisit [security.na-stewart.com](https://security.na-stewart.com) for documentation.\r\n\r\n<!-- GETTING STARTED -->\r\n## Getting Started\r\n\r\nIn order to get started, please install [Pip](https://pypi.org/).\r\n\r\n### Installation\r\n\r\n* Install the Sanic Security pip package.\r\n```shell\r\npip3 install sanic-security\r\n````\r\n\r\n* Install the Sanic Security pip package with the `cryptography` dependency included.\r\n\r\nIf you are planning on encoding or decoding JWTs using certain digital signature algorithms (like RSA or ECDSA which use \r\nthe public secret and private secret), you will need to install the `cryptography` library. This can be installed explicitly, or \r\nas an extra requirement.\r\n\r\n```shell\r\npip3 install sanic-security[crypto]\r\n````\r\n\r\n* For developers, fork Sanic Security and install development dependencies.\r\n```shell\r\npip3 install -e \".[dev]\"\r\n````\r\n\r\n* Update sanic-security if already installed.\r\n```shell\r\npip3 install --upgrade sanic-security\r\n```\r\n\r\n### Configuration\r\n\r\nSanic Security configuration is merely an object that can be modified either using dot-notation or like a \r\ndictionary.\r\n\r\nFor example: \r\n\r\n```python\r\nfrom sanic_security.configuration import config\r\n\r\nconfig.SECRET = \"This is a big secret. Shhhhh\"\r\nconfig[\"CAPTCHA_FONT\"] = \"./resources/captcha-font.ttf\"\r\n```\r\n\r\nYou can also use the update() method like on regular dictionaries.\r\n\r\nAny environment variables defined with the SANIC_SECURITY_ prefix will be applied to the config. For example, setting \r\nSANIC_SECURITY_SECRET will be loaded by the application automatically and fed into the SECRET config variable.\r\n\r\nYou can load environment variables with a different prefix via `config.load_environment_variables(\"NEW_PREFIX_\")` method.\r\n\r\n* Default configuration values:\r\n\r\n| Key                                   | Value                        | Description                                                                                                                      |\r\n|---------------------------------------|------------------------------|----------------------------------------------------------------------------------------------------------------------------------|\r\n| **SECRET**                            | This is a big secret. Shhhhh | The secret used for generating and signing JWTs. This should be a string unique to your application. Keep it safe.               |\r\n| **PUBLIC_SECRET**                     | None                         | The secret used for verifying and decoding JWTs and can be publicly shared. This should be a string unique to your application.  |\r\n| **SESSION_SAMESITE**                  | strict                       | The SameSite attribute of session cookies.                                                                                       |\r\n| **SESSION_SECURE**                    | True                         | The Secure attribute of session cookies.                                                                                         |\r\n| **SESSION_HTTPONLY**                  | True                         | The HttpOnly attribute of session cookies. HIGHLY recommended that you do not turn this off, unless you know what you are doing. |\r\n| **SESSION_DOMAIN**                    | None                         | The Domain attribute of session cookies.                                                                                         |\r\n| **SESSION_ENCODING_ALGORITHM**        | HS256                        | The algorithm used to encode and decode session JWT's.                                                                           |\r\n| **SESSION_PREFIX**                    | token                        | Prefix attached to the beginning of session cookies.                                                                             |\r\n| **MAX_CHALLENGE_ATTEMPTS**            | 5                            | The maximum amount of session challenge attempts allowed.                                                                        |\r\n| **CAPTCHA_SESSION_EXPIRATION**        | 60                           | The amount of seconds till captcha session expiration on creation. Setting to 0 will disable expiration.                         |\r\n| **CAPTCHA_FONT**                      | captcha-font.ttf             | The file path to the font being used for captcha generation.                                                                     |\r\n| **TWO_STEP_SESSION_EXPIRATION**       | 200                          | The amount of seconds till two-step session expiration on creation. Setting to 0 will disable expiration.                        |\r\n| **AUTHENTICATION_SESSION_EXPIRATION** | 86400                        | The amount of seconds till authentication session expiration on creation. Setting to 0 will disable expiration.                  |\r\n| **AUTHENTICATION_REFRESH_EXPIRATION** | 604800                       | The amount of seconds till authentication refresh expiration. Setting to 0 will disable refresh mechanism.                       |\r\n| **ALLOW_LOGIN_WITH_USERNAME**         | False                        | Allows login via username and email.                                                                                             |\r\n| **INITIAL_ADMIN_EMAIL**               | admin@example.com            | Email used when creating the initial admin account.                                                                              |\r\n| **INITIAL_ADMIN_PASSWORD**            | admin123                     | Password used when creating the initial admin account.                                                                           |\r\n\r\n## Usage\r\n\r\nSanic Security's authentication and verification functionality is session based. A new session will be created for the user after the user logs in or requests some form of verification (two-step, captcha). The session data is then encoded into a JWT and stored on a cookie on the user\u2019s browser. The session cookie is then sent\r\nalong with every subsequent request. The server can then compare the session stored on the cookie against the session information stored in the database to verify user\u2019s identity and send a response with the corresponding state.\r\n\r\nThe tables in the below examples represent example [request form-data](https://sanicframework.org/en/guide/basics/request.html#form).\r\n\r\n## Authentication\r\n\r\n* Initial Administrator Account\r\n\r\nCreates initial admin account, you should modify its credentials in config!\r\n  \r\n```python\r\ncreate_initial_admin_account(app)\r\nif __name__ == \"__main__\":\r\n    app.run(host=\"127.0.0.1\", port=8000)\r\n```\r\n  \r\n* Registration (With two-step account verification)\r\n\r\nPhone can be null or empty.\r\n\r\n| Key          | Value               |\r\n|--------------|---------------------|\r\n| **username** | example             |\r\n| **email**    | example@example.com |\r\n| **phone**    | 19811354186         |\r\n| **password** | examplepass         |\r\n\r\n```python\r\n@app.post(\"api/security/register\")\r\nasync def on_register(request):\r\n    account = await register(request)\r\n    two_step_session = await request_two_step_verification(request, account)\r\n    await email_code(\r\n        account.email, two_step_session.code  # Code = 197251\r\n    )  # Custom method for emailing verification code.\r\n    response = json(\r\n        \"Registration successful! Email verification required.\",\r\n        two_step_session.json,\r\n    )\r\n    two_step_session.encode(response)\r\n    return response\r\n```\r\n\r\n* Verify Account\r\n\r\nVerifies the client's account via two-step session code.\r\n\r\n| Key      | Value  |\r\n|----------|--------|\r\n| **code** | 197251 |\r\n\r\n```python\r\n@app.post(\"api/security/verify\")\r\nasync def on_verify(request):\r\n    two_step_session = await verify_account(request)\r\n    return json(\"You have verified your account and may login!\", two_step_session.json)\r\n```\r\n\r\n* Login (With two-factor authentication)\r\n\r\nCredentials are retrieved via header are constructed by first combining the username and the password with a colon \r\n(aladdin:opensesame), and then by encoding the resulting string in base64 (YWxhZGRpbjpvcGVuc2VzYW1l). \r\nHere is an example authorization header: `Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l`. You can use a username \r\nas well as an email for login if `ALLOW_LOGIN_WITH_USERNAME` is true in the config.\r\n\r\n```python\r\n@app.post(\"api/security/login\")\r\nasync def on_login(request):\r\n    authentication_session = await login(request, require_second_factor=True)\r\n    two_step_session = await request_two_step_verification(\r\n        request, authentication_session.bearer\r\n    )\r\n    await email_code(\r\n        authentication_session.bearer.email, two_step_session.code  # Code = 197251\r\n    )  # Custom method for emailing verification code.\r\n    response = json(\r\n        \"Login successful! Two-factor authentication required.\",\r\n        authentication_session.json,\r\n    )\r\n    authentication_session.encode(response)\r\n    two_step_session.encode(response)\r\n    return response\r\n```\r\n\r\nIf this isn't desired, you can pass an account and password attempt directly into the login method instead.\r\n\r\n* Fulfill Second Factor\r\n\r\nFulfills client authentication session's second factor requirement via two-step session code.\r\n\r\n| Key      | Value  |\r\n|----------|--------|\r\n| **code** | 197251 |\r\n\r\n```python\r\n@app.post(\"api/security/fulfill-2fa\")\r\nasync def on_two_factor_authentication(request):\r\n    authentication_session = await fulfill_second_factor(request)\r\n    response = json(\r\n        \"Authentication session second-factor fulfilled! You are now authenticated.\",\r\n        authentication_session.json,\r\n    )\r\n    authentication_session.encode(response)\r\n    return response\r\n```\r\n\r\n* Anonymous Login\r\n\r\nSimply create a new session and encode it.\r\n\r\n```python\r\n@app.post(\"api/security/login/anon\")\r\nasync def on_anonymous_login(request):\r\n    authentication_session = await AuthenticationSession.new(request)\r\n    response = json(\r\n        \"Anonymous client now associated with session!\", authentication_session.json\r\n    )\r\n    authentication_session.encode(response)\r\n    return response\r\n```\r\n\r\n* Logout\r\n\r\n```python\r\n@app.post(\"api/security/logout\")\r\nasync def on_logout(request):\r\n    authentication_session = await logout(request)\r\n    return json(\"Logout successful!\", authentication_session.json)\r\n```\r\n\r\n* Authenticate\r\n\r\n```python\r\n@app.post(\"api/security/auth\")\r\nasync def on_authenticate(request):\r\n    authentication_session = await authenticate(request)\r\n    response = json(\r\n        \"You have been authenticated.\",\r\n        authentication_session.json,\r\n    )\r\n    return response\r\n```\r\n\r\n* Requires Authentication (This method is not called directly and instead used as a decorator)\r\n\r\n```python\r\n@app.post(\"api/security/auth\")\r\n@requires_authentication\r\nasync def on_authenticate(request):\r\n    authentication_session = request.ctx.authentication_session\r\n    response = json(\r\n        \"You have been authenticated.\",\r\n        authentication_session.json,\r\n    )\r\n    return response\r\n```\r\n\r\n* Refresh Encoder\r\n\r\nA new/refreshed session is returned during authentication if the client's session expired during authentication and\r\nrequires encoding. Rather than doing so manually, it can be done automatically via middleware.\r\n\r\n```python\r\nattach_refresh_encoder(app)\r\nif __name__ == \"__main__\":\r\n    app.run(host=\"127.0.0.1\", port=8000)\r\n```\r\n\r\n## Captcha\r\n\r\nA pre-existing font for captcha challenges is included in the Sanic Security repository. You may set your own font by \r\ndownloading a .ttf font and defining the file's path in the configuration.\r\n\r\n[1001 Free Fonts](https://www.1001fonts.com/)\r\n\r\n[Recommended Font](https://www.1001fonts.com/source-sans-pro-font.html)\r\n\r\n* Request Captcha\r\n\r\n```python\r\n@app.get(\"api/security/captcha\")\r\nasync def on_captcha_img_request(request):\r\n    captcha_session = await request_captcha(request)\r\n    response = captcha_session.get_image()  # Captcha: 192731\r\n    captcha_session.encode(response)\r\n    return response\r\n```\r\n\r\n* Captcha\r\n\r\n| Key         | Value  |\r\n|-------------|--------|\r\n| **captcha** | 192731 |\r\n\r\n```python\r\n@app.post(\"api/security/captcha\")\r\nasync def on_captcha(request):\r\n    captcha_session = await captcha(request)\r\n    return json(\"Captcha attempt successful!\", captcha_session.json)\r\n```\r\n\r\n* Requires Captcha (This method is not called directly and instead used as a decorator)\r\n\r\n| Key         | Value  |\r\n|-------------|--------|\r\n| **captcha** | 192731 |\r\n\r\n```python\r\n@app.post(\"api/security/captcha\")\r\n@requires_captcha\r\nasync def on_captcha(request):\r\n    return json(\"Captcha attempt successful!\", request.ctx.captcha_session.json)\r\n```\r\n\r\n## Two-step Verification\r\n\r\nTwo-step verification should be integrated with other custom functionality. For example, account verification during registration.\r\n\r\n* Request Two-step Verification\r\n\r\n| Key         | Value               |\r\n|-------------|---------------------|\r\n| **email**   | example@example.com |\r\n\r\n```python\r\n@app.post(\"api/security/two-step/request\")\r\nasync def on_two_step_request(request):\r\n    two_step_session = await request_two_step_verification(request)  # Code = 197251\r\n    await email_code(\r\n        two_step_session.bearer.email, two_step_session.code\r\n    )  # Custom method for emailing verification code.\r\n    response = json(\"Verification request successful!\", two_step_session.json)\r\n    two_step_session.encode(response)\r\n    return response\r\n``` \r\n\r\n* Resend Two-step Verification Code\r\n\r\n```python\r\n@app.post(\"api/security/two-step/resend\")\r\nasync def on_two_step_resend(request):\r\n    two_step_session = await TwoStepSession.decode(request)  # Code = 197251\r\n    await email_code(\r\n        two_step_session.bearer.email, two_step_session.code\r\n    )  # Custom method for emailing verification code.\r\n    return json(\"Verification code resend successful!\", two_step_session.json)\r\n```\r\n\r\n* Two-step Verification\r\n\r\n| Key      | Value  |\r\n|----------|--------|\r\n| **code** | 197251 |\r\n\r\n```python\r\n@app.post(\"api/security/two-step\")\r\nasync def on_two_step_verification(request):\r\n    two_step_session = await two_step_verification(request)\r\n    response = json(\"Two-step verification attempt successful!\", two_step_session.json)\r\n    return response\r\n```\r\n\r\n* Requires Two-step Verification (This method is not called directly and instead used as a decorator)\r\n\r\n| Key      | Value  |\r\n|----------|--------|\r\n| **code** | 197251 |\r\n\r\n```python\r\n@app.post(\"api/security/two-step\")\r\n@requires_two_step_verification\r\nasync def on_two_step_verification(request):\r\n    response = json(\r\n        \"Two-step verification attempt successful!\",\r\n        request.ctx.two_step_session.json,\r\n    )\r\n    return response\r\n```\r\n\r\n## Authorization\r\n\r\nSanic Security uses role based authorization with wildcard permissions.\r\n\r\nRoles are created for various job functions. The permissions to perform certain operations are assigned to specific roles. \r\nUsers are assigned particular roles, and through those role assignments acquire the permissions needed to perform \r\nparticular system functions. Since users are not assigned permissions directly, but only acquire them through their \r\nrole (or roles), management of individual user rights becomes a matter of simply assigning appropriate roles to the \r\nuser's account; this simplifies common operations, such as adding a user, or changing a user's department. \r\n\r\nWildcard permissions support the concept of multiple levels or parts. For example, you could grant a user the permission\r\n`printer:query`, `printer:query,delete`, or `printer:*`.\r\n* Assign Role\r\n\r\n```python\r\nawait assign_role(\r\n    \"Chat Room Moderator\",\r\n    account,\r\n    \"channels:view,delete, account:suspend,mute, voice:*\",\r\n    \"Can read and delete messages in all chat rooms, suspend and mute accounts, and control voice chat.\",\r\n)\r\n```\r\n\r\n* Check Permissions\r\n\r\n```python\r\n@app.post(\"api/security/perms\")\r\nasync def on_check_perms(request):\r\n    authentication_session = await check_permissions(\r\n        request, \"channels:view\", \"voice:*\"\r\n    )\r\n    return text(\"Account is authorized.\")\r\n```\r\n\r\n* Require Permissions (This method is not called directly and instead used as a decorator.)\r\n\r\n```python\r\n@app.post(\"api/security/perms\")\r\n@require_permissions(\"channels:view\", \"voice:*\")\r\nasync def on_check_perms(request):\r\n    return text(\"Account is authorized.\")\r\n```\r\n\r\n* Check Roles\r\n\r\n```python\r\n@app.post(\"api/security/roles\")\r\nasync def on_check_roles(request):\r\n    authentication_session = await check_roles(request, \"Chat Room Moderator\")\r\n    return text(\"Account is authorized.\")\r\n```\r\n\r\n* Require Roles (This method is not called directly and instead used as a decorator)\r\n\r\n```python\r\n@app.post(\"api/security/roles\")\r\n@require_roles(\"Chat Room Moderator\")\r\nasync def on_check_roles(request):\r\n    return text(\"Account is authorized.\")\r\n```\r\n\r\n## Testing\r\n\r\n* Set the `TEST_DATABASE_URL` configuration value.\r\n\r\n* Make sure the test Sanic instance (`test/server.py`) is running on your machine.\r\n\r\n* Run the unit test client (`test/tests.py`) for results.\r\n\r\n## Tortoise\r\n\r\nSanic Security uses [Tortoise ORM](https://tortoise-orm.readthedocs.io/en/latest/index.html) for database operations.\r\n\r\nTortoise ORM is an easy-to-use asyncio ORM (Object Relational Mapper).\r\n\r\n* Initialise your models and database like so: \r\n\r\n```python\r\nasync def init():\r\n    await Tortoise.init(\r\n        db_url=\"sqlite://db.sqlite3\",\r\n        modules={\"models\": [\"sanic_security.models\", \"app.models\"]},\r\n    )\r\n    await Tortoise.generate_schemas()\r\n```\r\n\r\nor\r\n\r\n```python\r\nregister_tortoise(\r\n    app,\r\n    db_url=\"sqlite://db.sqlite3\",\r\n    modules={\"models\": [\"sanic_security.models\", \"app.models\"]},\r\n    generate_schemas=True,\r\n)\r\n```\r\n\r\n* Define your models like so:\r\n\r\n```python\r\nfrom tortoise.models import Model\r\nfrom tortoise import fields\r\n\r\n\r\nclass Tournament(Model):\r\n    id = fields.IntField(pk=True)\r\n    name = fields.TextField()\r\n```\r\n\r\n* Use it like so:\r\n\r\n```python\r\n# Create instance by save\r\ntournament = Tournament(name=\"New Tournament\")\r\nawait tournament.save()\r\n\r\n# Or by .create()\r\nawait Tournament.create(name=\"Another Tournament\")\r\n\r\n# Now search for a record\r\ntour = await Tournament.filter(name__contains=\"Another\").first()\r\nprint(tour.name)\r\n```\r\n\r\n<!-- CONTRIBUTING -->\r\n## Contributing\r\n\r\nContributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**.\r\n\r\n1. Fork the Project\r\n2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)\r\n3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)\r\n4. Push to the Branch (`git push origin feature/AmazingFeature`)\r\n5. Open a Pull Request\r\n\r\n\r\n<!-- LICENSE -->\r\n## License\r\n\r\nDistributed under the MIT License. See `LICENSE` for more information.\r\n\r\n<!-- Versioning -->\r\n## Versioning\r\n\r\n**0.0.0**\r\n\r\n* MAJOR version when you make incompatible API changes.\r\n\r\n* MINOR version when you add functionality in a backwards compatible manner.\r\n\r\n* PATCH version when you make backwards compatible bug fixes.\r\n\r\n[https://semver.org/](https://semver.org/)\r\n\r\n<!-- MARKDOWN LINKS & IMAGES -->\r\n<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->\r\n[contributors-shield]: https://img.shields.io/github/contributors/sunset-developer/sanic-security.svg?style=flat-square\r\n[contributors-url]: https://github.com/sunset-developer/sanic-security/graphs/contributors\r\n[forks-shield]: https://img.shields.io/github/forks/sunset-developer/sanic-security.svg?style=flat-square\r\n[forks-url]: https://github.com/sunset-developer/sanic-security/network/members\r\n[stars-shield]: https://img.shields.io/github/stars/sunset-developer/sanic-security.svg?style=flat-square\r\n[stars-url]: https://github.com/sunset-developer/sanic-security/stargazers\r\n[issues-shield]: https://img.shields.io/github/issues/sunset-developer/sanic-security.svg?style=flat-square\r\n[issues-url]: https://github.com/sunset-developer/sanic-security/issues\r\n[license-shield]: https://img.shields.io/github/license/sunset-developer/sanic-security.svg?style=flat-square\r\n[license-url]: https://github.com/sunset-developer/sanic-security/blob/master/LICENSE\r\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "An async security library for the Sanic framework.",
    "version": "1.12.5",
    "project_urls": {
        "Documentation": "https://security.na-stewart.com/",
        "Repository": "https://github.com/na-stewart/sanic-security"
    },
    "split_keywords": [
        "security",
        " authentication",
        " authorization",
        " verification",
        " async",
        " sanic"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1df023346be023735e240d144f4db9dd39008dee1f3f85f77620d7c586e5ff66",
                "md5": "bba3a08a84cc1d1081131dfc64b67c02",
                "sha256": "99f88ea8be7798cc1cc87cb25b8c0bcd28e6732455e923b9b4913136ef4108fd"
            },
            "downloads": -1,
            "filename": "sanic_security-1.12.5-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "bba3a08a84cc1d1081131dfc64b67c02",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 35135,
            "upload_time": "2024-09-07T02:42:21",
            "upload_time_iso_8601": "2024-09-07T02:42:21.794575Z",
            "url": "https://files.pythonhosted.org/packages/1d/f0/23346be023735e240d144f4db9dd39008dee1f3f85f77620d7c586e5ff66/sanic_security-1.12.5-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "68d588bca775c2a2492cf7792183ff8cdf381a30c85e732bd5b93b278247b010",
                "md5": "f5bba315199a63f3b49795208c40788b",
                "sha256": "ad353e09655e92c9b3685674c6f47e3d9d02c63d50f4df5f4eb0aa87a149e526"
            },
            "downloads": -1,
            "filename": "sanic_security-1.12.5.tar.gz",
            "has_sig": false,
            "md5_digest": "f5bba315199a63f3b49795208c40788b",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 32769,
            "upload_time": "2024-09-07T02:42:23",
            "upload_time_iso_8601": "2024-09-07T02:42:23.452013Z",
            "url": "https://files.pythonhosted.org/packages/68/d5/88bca775c2a2492cf7792183ff8cdf381a30c85e732bd5b93b278247b010/sanic_security-1.12.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-09-07 02:42:23",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "na-stewart",
    "github_project": "sanic-security",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "sanic-security"
}
        
Elapsed time: 0.56254s