ConnectKit-FastAPIAuthentication


NameConnectKit-FastAPIAuthentication JSON
Version 1.4.0 PyPI version JSON
download
home_pageNone
SummaryUser JWT Authentication for FastAPI services
upload_time2024-06-14 12:19:38
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseThe MIT License (MIT) Copyright © 2024 MTUCI Open Source 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 connectkit authentication jwt cookie otp totp fastapi
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # ConnectKit FastAPIAuthentication [*en*|[ru](./README_RU.md)]

___

ConnectKit FastAPIAuthentication adds accounts, user sessions, and
a user authentication mechanism using JWT for FastAPI applications.

Logging in via oauth2 or OpenID connect is not supported at the moment.

## Installation

___

```shell
pip install ConnectKit-FastAPIAuthentication
```

## Usage

___

Configuration parameters are loaded from environment variables, and can be redefined later.

    SECURE_SECRET=str                 # Key for signing JWT
    SECURE_ACCESS_EXPIRE=5            # Access token validity period in minutes
    SECURE_REFRESH_EXPIRE=24          # Refresh token validity time in hours for a short session
    SECURE_REFRESH_LONG_EXPIRE=720    # Refresh token validity time in hours for a long session
    SECURE_PATH=/api                  # Prefix of the path to which the cookie with the token will be bound
    SECURE_COOKIE_NAME=access         # The name of the cookie in which the token will be
    SECURE_ONLY=True                  # Instructing the browser to accept the token only if https
    SECURE_BLOCK_TRIES=5              # Number of attempts to enter the wrong password before the account is blocked
    SECURE_OTP_ENABLED=True           # Use 2FA via one-time passwords
    SECURE_OTP_BLOCK_TRIES=3          # Number of attempts to transfer OTP before logout
    SECURE_OTP_ISSUER=Localhost inc.  # The OTP ISSUER transmitted to user when 2FA is enabled
    SECURE_STRICT_VERIFICATION=True   # Strict verification for re-entering the password

To redefine:

```python
from authentication.settings import settings

settings.SECURE_COOKIE_NAME = "new_name"
```

[To set up a database connection](https://github.com/mtuciru/ConnectKit-Database/blob/master/README.md).

To enable authorization endpoints:

```python
from fastapi import FastAPI
from authentication import router as auth_router

app = FastAPI()
app.include_router(auth_router, prefix="/api/auth")

```

To get the current account or session:

```python
from fastapi import APIRouter, Depends
from authentication import get_account, get_session
from authentication.models import Account, AccountSession
from authentication.errors import auth_errors, with_errors

router = APIRouter()


@router.get("/test", responses=with_errors(*auth_errors))
async def test(account: Account = Depends(get_account)):
    print(account)


@router.get("/test2", responses=with_errors(*auth_errors))
async def test2(account_session: AccountSession = Depends(get_session)):
    print(account_session)

```

The `get_session` function checks for the presence of a session and the passage of 2FA.

The `get_account` function checks the same as `get_session`, as well as the account activation status.

If the login is not completed or outdated, HttpException will be raised from the list of `auth_errors` exceptions.

To implement the registration form, manually add users and administrative work:

```python
from authentication import (NewAccount, login_rules, password_rules,
                            login_type, password_type,
                            create_new_account, delete_account,
                            block_account, unblock_account, get_block_status,
                            get_status_otp, disable_otp)
from pydantic import BaseModel, EmailStr

# Creating a new user

try:
    new_acc = NewAccount(
        login="root",  # The user's unique login is set by the login_rules rule
        password="password",  # The user's password is set by the password_rules rule
        properties={  # User properties required in a specific task, Dict[str, Any]
            "name": "name"
        },
        active=True  # Is the account activated, False by default
    )
    account = await create_new_account(new_acc)
except ValueError as e:
    # The user already exists, or there is a validation error in the New Account
    pass


# Example of a registration scheme

class UserRegistration(BaseModel):
    login: login_type
    nickname: str
    email: EmailStr
    password: password_type


# Deleting an account
await delete_account(account)

# Getting the blocking status (bool, Optional[str])
block, reason = await get_block_status(account)

# Getting 2FA status
otp_enabled = await get_status_otp(account)

# Account blocking (a blocked account cannot log in)
await block_account(account, "reason")

# Unblocking account
await unblock_account(account)

# Forced disable of 2FA
await disable_otp(account)


```

Authentication diagram:

![Authentication diagram](./login.jpg)

Token update diagram:

![Token update diagram](./refresh.jpg)

## License

___

ConnectKit FastAPIAuthentication is [MIT License](./LICENSE).
            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "ConnectKit-FastAPIAuthentication",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "connectkit, authentication, jwt, cookie, otp, totp, fastapi",
    "author": null,
    "author_email": "RealMetamorph <andr.timchuk@yandex.ru>",
    "download_url": "https://files.pythonhosted.org/packages/59/88/16b07d358bedf33a250bc30b364ae4cfc127c2c64fe371ad444c185cdf1c/connectkit_fastapiauthentication-1.4.0.tar.gz",
    "platform": null,
    "description": "# ConnectKit FastAPIAuthentication [*en*|[ru](./README_RU.md)]\n\n___\n\nConnectKit FastAPIAuthentication adds accounts, user sessions, and\na user authentication mechanism using JWT for FastAPI applications.\n\nLogging in via oauth2 or OpenID connect is not supported at the moment.\n\n## Installation\n\n___\n\n```shell\npip install ConnectKit-FastAPIAuthentication\n```\n\n## Usage\n\n___\n\nConfiguration parameters are loaded from environment variables, and can be redefined later.\n\n    SECURE_SECRET=str                 # Key for signing JWT\n    SECURE_ACCESS_EXPIRE=5            # Access token validity period in minutes\n    SECURE_REFRESH_EXPIRE=24          # Refresh token validity time in hours for a short session\n    SECURE_REFRESH_LONG_EXPIRE=720    # Refresh token validity time in hours for a long session\n    SECURE_PATH=/api                  # Prefix of the path to which the cookie with the token will be bound\n    SECURE_COOKIE_NAME=access         # The name of the cookie in which the token will be\n    SECURE_ONLY=True                  # Instructing the browser to accept the token only if https\n    SECURE_BLOCK_TRIES=5              # Number of attempts to enter the wrong password before the account is blocked\n    SECURE_OTP_ENABLED=True           # Use 2FA via one-time passwords\n    SECURE_OTP_BLOCK_TRIES=3          # Number of attempts to transfer OTP before logout\n    SECURE_OTP_ISSUER=Localhost inc.  # The OTP ISSUER transmitted to user when 2FA is enabled\n    SECURE_STRICT_VERIFICATION=True   # Strict verification for re-entering the password\n\nTo redefine:\n\n```python\nfrom authentication.settings import settings\n\nsettings.SECURE_COOKIE_NAME = \"new_name\"\n```\n\n[To set up a database connection](https://github.com/mtuciru/ConnectKit-Database/blob/master/README.md).\n\nTo enable authorization endpoints:\n\n```python\nfrom fastapi import FastAPI\nfrom authentication import router as auth_router\n\napp = FastAPI()\napp.include_router(auth_router, prefix=\"/api/auth\")\n\n```\n\nTo get the current account or session:\n\n```python\nfrom fastapi import APIRouter, Depends\nfrom authentication import get_account, get_session\nfrom authentication.models import Account, AccountSession\nfrom authentication.errors import auth_errors, with_errors\n\nrouter = APIRouter()\n\n\n@router.get(\"/test\", responses=with_errors(*auth_errors))\nasync def test(account: Account = Depends(get_account)):\n    print(account)\n\n\n@router.get(\"/test2\", responses=with_errors(*auth_errors))\nasync def test2(account_session: AccountSession = Depends(get_session)):\n    print(account_session)\n\n```\n\nThe `get_session` function checks for the presence of a session and the passage of 2FA.\n\nThe `get_account` function checks the same as `get_session`, as well as the account activation status.\n\nIf the login is not completed or outdated, HttpException will be raised from the list of `auth_errors` exceptions.\n\nTo implement the registration form, manually add users and administrative work:\n\n```python\nfrom authentication import (NewAccount, login_rules, password_rules,\n                            login_type, password_type,\n                            create_new_account, delete_account,\n                            block_account, unblock_account, get_block_status,\n                            get_status_otp, disable_otp)\nfrom pydantic import BaseModel, EmailStr\n\n# Creating a new user\n\ntry:\n    new_acc = NewAccount(\n        login=\"root\",  # The user's unique login is set by the login_rules rule\n        password=\"password\",  # The user's password is set by the password_rules rule\n        properties={  # User properties required in a specific task, Dict[str, Any]\n            \"name\": \"name\"\n        },\n        active=True  # Is the account activated, False by default\n    )\n    account = await create_new_account(new_acc)\nexcept ValueError as e:\n    # The user already exists, or there is a validation error in the New Account\n    pass\n\n\n# Example of a registration scheme\n\nclass UserRegistration(BaseModel):\n    login: login_type\n    nickname: str\n    email: EmailStr\n    password: password_type\n\n\n# Deleting an account\nawait delete_account(account)\n\n# Getting the blocking status (bool, Optional[str])\nblock, reason = await get_block_status(account)\n\n# Getting 2FA status\notp_enabled = await get_status_otp(account)\n\n# Account blocking (a blocked account cannot log in)\nawait block_account(account, \"reason\")\n\n# Unblocking account\nawait unblock_account(account)\n\n# Forced disable of 2FA\nawait disable_otp(account)\n\n\n```\n\nAuthentication diagram:\n\n![Authentication diagram](./login.jpg)\n\nToken update diagram:\n\n![Token update diagram](./refresh.jpg)\n\n## License\n\n___\n\nConnectKit FastAPIAuthentication is [MIT License](./LICENSE).",
    "bugtrack_url": null,
    "license": "The MIT License (MIT)\n        Copyright \u00a9 2024 MTUCI Open Source\n        \n        Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \u201cSoftware\u201d), 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:\n        \n        The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n        \n        THE SOFTWARE IS PROVIDED \u201cAS IS\u201d, 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": "User JWT Authentication for FastAPI services",
    "version": "1.4.0",
    "project_urls": {
        "Homepage": "https://github.com/mtuciru/ConnectKit-FastAPIAuthentication",
        "Repository": "https://github.com/mtuciru/ConnectKit-FastAPIAuthentication.git"
    },
    "split_keywords": [
        "connectkit",
        " authentication",
        " jwt",
        " cookie",
        " otp",
        " totp",
        " fastapi"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d68a2cfa8a308b205ce92b00a72019b56ce7394886a6a62926f2aa4ae5ebbd45",
                "md5": "141cf57bad77c500164c0ba08283b3e2",
                "sha256": "a1199eeafa5499be83c5253302c578ab825fcc50f348c01dff225c7c28786c49"
            },
            "downloads": -1,
            "filename": "connectkit_fastapiauthentication-1.4.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "141cf57bad77c500164c0ba08283b3e2",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 15202,
            "upload_time": "2024-06-14T12:19:36",
            "upload_time_iso_8601": "2024-06-14T12:19:36.717532Z",
            "url": "https://files.pythonhosted.org/packages/d6/8a/2cfa8a308b205ce92b00a72019b56ce7394886a6a62926f2aa4ae5ebbd45/connectkit_fastapiauthentication-1.4.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "598816b07d358bedf33a250bc30b364ae4cfc127c2c64fe371ad444c185cdf1c",
                "md5": "f488355c3a916496aa51ea61ecb6e821",
                "sha256": "f222fdf038f2db1062470d89874ac29a33d2b8cf826f9cc14d75d7b392763e01"
            },
            "downloads": -1,
            "filename": "connectkit_fastapiauthentication-1.4.0.tar.gz",
            "has_sig": false,
            "md5_digest": "f488355c3a916496aa51ea61ecb6e821",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 13952,
            "upload_time": "2024-06-14T12:19:38",
            "upload_time_iso_8601": "2024-06-14T12:19:38.441220Z",
            "url": "https://files.pythonhosted.org/packages/59/88/16b07d358bedf33a250bc30b364ae4cfc127c2c64fe371ad444c185cdf1c/connectkit_fastapiauthentication-1.4.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-14 12:19:38",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "mtuciru",
    "github_project": "ConnectKit-FastAPIAuthentication",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "connectkit-fastapiauthentication"
}
        
Elapsed time: 0.27223s