authup


Nameauthup JSON
Version 0.5.1 PyPI version JSON
download
home_pagehttps://authup.org
SummaryPython plugins for the Authup authentication and authorization framework
upload_time2023-04-24 09:39:23
maintainer
docs_urlNone
authorMichael Graf
requires_python>=3.7,<4.0
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            [![CI](https://github.com/migraf/authup-py/actions/workflows/main.yml/badge.svg)](https://github.com/migraf/authup-py/actions/workflows/main.yml)
[![codecov](https://codecov.io/gh/migraf/authup-py/branch/main/graph/badge.svg?token=qILJEFdh8I)](https://codecov.io/gh/migraf/authup-py)
![PyPI - Python Version](https://img.shields.io/pypi/pyversions/authup)
![PyPI - Downloads](https://img.shields.io/pypi/dw/authup)
[![Maintainability](https://api.codeclimate.com/v1/badges/520401d6c07170a6e413/maintainability)](https://codeclimate.com/github/migraf/authup-py/maintainability)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

# Authup Python Plugins

This repository contains python plugins for using the [Authup](https://authup.org) authentication and authorization
framework in the python language.
The plugins are used to integrate Authup with different python frameworks and libraries.

## Supported Python frameworks

### Client
| Plugin                                      | Extra        | Sync | Async |
|---------------------------------------------|--------------|:----:|------:|
| [httpx](https://github.com/encode/httpx)    |              |  ✅   |     ✅ |
| [requests](https://github.com/psf/requests) | `[requests]` |  ✅   |     ❌ |

### Server

| Plugin                                                        | Extra       | Sync | Async | Middleware | User |
|---------------------------------------------------------------|-------------|:----:|------:|------------|------|
| [FastApi](https://fastapi.tiangolo.com/)                      | `[fastapi]` |  ✅   |     ✅ | ✅          | ✅    |
| [ASGI](https://asgi.readthedocs.io/en/latest/specs/main.html) | `[asgi]`    |  ❌   |     ✅ | ✅          | ✅    |
| [Flask](https://flask.palletsprojects.com/en/2.2.x/)          | `[flask]`   |  ⏳   |     ⏳ | ⏳          | ⏳    |

Table of Contents
=================

* [Authup Python Plugins](#authup-python-plugins)
   * [Supported Python frameworks](#supported-python-frameworks)
      * [Client](#client)
      * [Server](#server)
   * [Installation](#installation)
      * [Extra dependencies](#extra-dependencies)
   * [How to use](#how-to-use)
      * [httpx](#httpx)
      * [requests](#requests)
      * [ASGI Middleware](#asgi-middleware)
         * [Optional user injection](#optional-user-injection)
      * [FastAPI Dependency](#fastapi-dependency)
         * [Basic user dependency](#basic-user-dependency)
         * [Require permissions](#require-permissions)
   * [How to develop](#how-to-develop)
      * [Install](#install)
      * [Test](#test)


## Installation

The plugins are available via [PyPi](https://pypi.org/project/authup-py/).

```bash
pip install authup-py
```

### Extra dependencies
The plugin for the project's base library [httpx](https://github.com/encode/httpx) needs no extra dependencies. To
use the additional plugins for other libraries, you need to install with the corresponding extra i.e. for `requests`:

```bash
pip install authup-py[requests]
```

## How to use
All the plugins share the underlying `Authup` class. The class is initialized with the url of the Authup server and
the credentials you would like to use (username/password or robot_id/secret).    
The class provides both sync and async methods for the different authentication and authorization flows.

```python

from authup import Authup

authup = Authup(
    url="https://authup.org",
    username="username",
    password="password"
)

authup_robot = Authup(
    url="https://authup.org",
    robot_id="robot",
    robot_secret="secret"
)

```

The following plugins all expect the same arguments as the `Authup` class with the addition of the
app as a first argument for server side libraries (e.g. FastApi, Flask).

### httpx
For synchronously using the plugin with [httpx](https://github.com/encode/httpx) , you can use the `AuthupHttpx` class and pass an instance to your
`httpx.Client` or a basic `httpx.Request` as the `auth` parameter:

```python
import httpx
from authup.plugins.httpx import AuthupHttpx

authup = AuthupHttpx(
    url="https://authup.org",
    username="username",
    password="password",
)

# Use the authup instance as the auth parameter for the httpx client
client = httpx.Client(auth=authup)

with client:
    response = client.get("https://authup.org")
    print(response.status_code)


# Use the authup instance as the auth parameter for a top level request function
request = httpx.get("https://authup.org", auth=authup)

```

It works the same way for the asynchronous httpx client:

```python
import httpx
from authup.plugins.httpx import AuthupHttpxAsync

authup = AuthupHttpxAsync(
    url="https://authup.org",
    username="username",
    password="password",
)

async with httpx.AsyncClient(auth=authup) as client:
    response = await client.get("https://authup.org")
    print(response.status_code)

```

### requests
Since [requests](https://github.com/psf/requests) is a synchronous library, the plugin is also synchronous. You can use the `AuthupRequests` class and
use it with the `requests.Session` or the `requests.request` functions:
> **Note**
> Requires the `requests` extra to be installed. `pip install authup-py[requests]`

```python
import requests
from authup.plugins.requests import AuthupRequests

authup = AuthupRequests(
    url="https://authup.org",
    username="username",
    password="password",
)

# Use the authup instance as the auth parameter for the requests session
with requests.Session() as session:
    session.auth = authup
    response = session.get("https://authup.org")
    print(response.status_code)

# Use the authup instance as the auth parameter for a top level request function
response = requests.get("https://authup.org", auth=authup)
print(response.status_code)

```

### ASGI Middleware

The `AuthupASGIMiddleware` class can be used as an ASGI middleware for any ASGI framework (i.e. FastAPI, Starlette). 
The middleware will check the incoming requests for a valid token and otherwise return a 401 response. If you pass the
optional `user` parameter, the middleware will inject the user object into the request scope (`r.state.user`).

The first argument is the ASGI application and the second argument is the URL of the authup instance.
> **Note**
> Requires the `asgi` extra to be installed. `pip install authup-py[asgi]`

The following shows a simple example for using the middleware with a FastAPI application but it should work with any ASGI framework.

> **Note**
> Expects a running authup instance available at the given URL.
> 
```python
from fastapi import FastAPI
from authup.plugins.asgi import AuthupASGIMiddleware

app = FastAPI()

authup_url = "https://authup.org"  # change to your authup instance
@app.get("/test")
async def test():
    return {"message": "Hello World"}

# register the middleware pass the authup url as argument
app.add_middleware(AuthupASGIMiddleware, authup_url=authup_url)

```
Now you can access the `/test` endpoint without a token and will receive a 401 response. When using a valid token, you will receive the expected response.

```python
import httpx
from authup.plugins.httpx import AuthupHttpx

# no token or invalid token raises 401
response = httpx.get("http://localhost:8000/test") # 401
print(response.status_code)

# valid token receives the expected response
authup = AuthupHttpx(
    url="https://authup.org",
    username="username",
    password="password",
)

response = httpx.get("http://localhost:8000/test", auth=authup) # 200
print(response.status_code)

```

#### Optional user injection
Set the `user` parameter to `True` when adding the middleware to your ASGI application:

```python
from fastapi import FastAPI, Request
from authup.plugins.asgi import AuthupASGIMiddleware

app = FastAPI()

authup_url = "https://authup.org"  # change to your authup instance
@app.get("/test-user")
async def test(request: Request):
    return {"user": request.state.user}

# register the middleware pass the authup url as argument
app.add_middleware(AuthupASGIMiddleware, authup_url=authup_url, user=True)

```

Calling the `/test-user` endpoint without a token will return a 401 response. When using a valid token, the user object 
will be injected into the request scope, and you will receive the expected response containing your user.

### FastAPI Dependency
The `AuthupUser` class can be used as a FastAPI dependency. 
It will check the incoming requests for a valid token and otherwise return a 401 response. If the token is valid a user object
will be available in the dependency call.

#### Basic user dependency
The following shows a simple example for using the dependency with a FastAPI application that will return the user
object obtained from the token.

```python
from fastapi import FastAPI, Depends
from authup.plugins.fastapi import AuthupUser
from authup import User


app = FastAPI()

user_dependency = AuthupUser(url="http://localhost:3010")

@app.get("/test")
async def user_test(user: User = Depends(user_dependency)):
    return {"user": user.dict()}

```

#### Require permissions
You can also require specific permissions for the user. The following example will only allow users with the 
`client_add` permission and a power level of over `100`. Otherwise, a 401 response will be returned.

```python
from fastapi import FastAPI, Depends
from authup.plugins.fastapi import AuthupUser
from authup import User
from authup.permissions import Permission

permissions = [
        Permission(name="client_add", inverse=False, power=100),
    ]

required_permissions = AuthupUser(
    url="http://localhost:3010",
    permissions=permissions,
)

app = FastAPI()

@app.get("/test")
async def user_test(user: User = Depends(required_permissions)):
    return {"user": user.dict()}

```



## How to develop

### Install

Requires [poetry](https://python-poetry.org/) and [pre-commit](https://pre-commit.com/) and python 3.7+.

```shell
poetry install --with dev --all-extras
```

Install pre-commit hooks

```shell
poetry run pre-commit install
```

### Test

```shell
poetry run pytest
```


            

Raw data

            {
    "_id": null,
    "home_page": "https://authup.org",
    "name": "authup",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7,<4.0",
    "maintainer_email": "",
    "keywords": "",
    "author": "Michael Graf",
    "author_email": "michael.graf3110@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/c7/b0/c6d39b938ae4ef0bf3287260ca983d45b1cc002f60504e3b9e8c25c8f1d6/authup-0.5.1.tar.gz",
    "platform": null,
    "description": "[![CI](https://github.com/migraf/authup-py/actions/workflows/main.yml/badge.svg)](https://github.com/migraf/authup-py/actions/workflows/main.yml)\n[![codecov](https://codecov.io/gh/migraf/authup-py/branch/main/graph/badge.svg?token=qILJEFdh8I)](https://codecov.io/gh/migraf/authup-py)\n![PyPI - Python Version](https://img.shields.io/pypi/pyversions/authup)\n![PyPI - Downloads](https://img.shields.io/pypi/dw/authup)\n[![Maintainability](https://api.codeclimate.com/v1/badges/520401d6c07170a6e413/maintainability)](https://codeclimate.com/github/migraf/authup-py/maintainability)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n\n# Authup Python Plugins\n\nThis repository contains python plugins for using the [Authup](https://authup.org) authentication and authorization\nframework in the python language.\nThe plugins are used to integrate Authup with different python frameworks and libraries.\n\n## Supported Python frameworks\n\n### Client\n| Plugin                                      | Extra        | Sync | Async |\n|---------------------------------------------|--------------|:----:|------:|\n| [httpx](https://github.com/encode/httpx)    |              |  \u2705   |     \u2705 |\n| [requests](https://github.com/psf/requests) | `[requests]` |  \u2705   |     \u274c |\n\n### Server\n\n| Plugin                                                        | Extra       | Sync | Async | Middleware | User |\n|---------------------------------------------------------------|-------------|:----:|------:|------------|------|\n| [FastApi](https://fastapi.tiangolo.com/)                      | `[fastapi]` |  \u2705   |     \u2705 | \u2705          | \u2705    |\n| [ASGI](https://asgi.readthedocs.io/en/latest/specs/main.html) | `[asgi]`    |  \u274c   |     \u2705 | \u2705          | \u2705    |\n| [Flask](https://flask.palletsprojects.com/en/2.2.x/)          | `[flask]`   |  \u23f3   |     \u23f3 | \u23f3          | \u23f3    |\n\nTable of Contents\n=================\n\n* [Authup Python Plugins](#authup-python-plugins)\n   * [Supported Python frameworks](#supported-python-frameworks)\n      * [Client](#client)\n      * [Server](#server)\n   * [Installation](#installation)\n      * [Extra dependencies](#extra-dependencies)\n   * [How to use](#how-to-use)\n      * [httpx](#httpx)\n      * [requests](#requests)\n      * [ASGI Middleware](#asgi-middleware)\n         * [Optional user injection](#optional-user-injection)\n      * [FastAPI Dependency](#fastapi-dependency)\n         * [Basic user dependency](#basic-user-dependency)\n         * [Require permissions](#require-permissions)\n   * [How to develop](#how-to-develop)\n      * [Install](#install)\n      * [Test](#test)\n\n\n## Installation\n\nThe plugins are available via [PyPi](https://pypi.org/project/authup-py/).\n\n```bash\npip install authup-py\n```\n\n### Extra dependencies\nThe plugin for the project's base library [httpx](https://github.com/encode/httpx) needs no extra dependencies. To\nuse the additional plugins for other libraries, you need to install with the corresponding extra i.e. for `requests`:\n\n```bash\npip install authup-py[requests]\n```\n\n## How to use\nAll the plugins share the underlying `Authup` class. The class is initialized with the url of the Authup server and\nthe credentials you would like to use (username/password or robot_id/secret).    \nThe class provides both sync and async methods for the different authentication and authorization flows.\n\n```python\n\nfrom authup import Authup\n\nauthup = Authup(\n    url=\"https://authup.org\",\n    username=\"username\",\n    password=\"password\"\n)\n\nauthup_robot = Authup(\n    url=\"https://authup.org\",\n    robot_id=\"robot\",\n    robot_secret=\"secret\"\n)\n\n```\n\nThe following plugins all expect the same arguments as the `Authup` class with the addition of the\napp as a first argument for server side libraries (e.g. FastApi, Flask).\n\n### httpx\nFor synchronously using the plugin with [httpx](https://github.com/encode/httpx) , you can use the `AuthupHttpx` class and pass an instance to your\n`httpx.Client` or a basic `httpx.Request` as the `auth` parameter:\n\n```python\nimport httpx\nfrom authup.plugins.httpx import AuthupHttpx\n\nauthup = AuthupHttpx(\n    url=\"https://authup.org\",\n    username=\"username\",\n    password=\"password\",\n)\n\n# Use the authup instance as the auth parameter for the httpx client\nclient = httpx.Client(auth=authup)\n\nwith client:\n    response = client.get(\"https://authup.org\")\n    print(response.status_code)\n\n\n# Use the authup instance as the auth parameter for a top level request function\nrequest = httpx.get(\"https://authup.org\", auth=authup)\n\n```\n\nIt works the same way for the asynchronous httpx client:\n\n```python\nimport httpx\nfrom authup.plugins.httpx import AuthupHttpxAsync\n\nauthup = AuthupHttpxAsync(\n    url=\"https://authup.org\",\n    username=\"username\",\n    password=\"password\",\n)\n\nasync with httpx.AsyncClient(auth=authup) as client:\n    response = await client.get(\"https://authup.org\")\n    print(response.status_code)\n\n```\n\n### requests\nSince [requests](https://github.com/psf/requests) is a synchronous library, the plugin is also synchronous. You can use the `AuthupRequests` class and\nuse it with the `requests.Session` or the `requests.request` functions:\n> **Note**\n> Requires the `requests` extra to be installed. `pip install authup-py[requests]`\n\n```python\nimport requests\nfrom authup.plugins.requests import AuthupRequests\n\nauthup = AuthupRequests(\n    url=\"https://authup.org\",\n    username=\"username\",\n    password=\"password\",\n)\n\n# Use the authup instance as the auth parameter for the requests session\nwith requests.Session() as session:\n    session.auth = authup\n    response = session.get(\"https://authup.org\")\n    print(response.status_code)\n\n# Use the authup instance as the auth parameter for a top level request function\nresponse = requests.get(\"https://authup.org\", auth=authup)\nprint(response.status_code)\n\n```\n\n### ASGI Middleware\n\nThe `AuthupASGIMiddleware` class can be used as an ASGI middleware for any ASGI framework (i.e. FastAPI, Starlette). \nThe middleware will check the incoming requests for a valid token and otherwise return a 401 response. If you pass the\noptional `user` parameter, the middleware will inject the user object into the request scope (`r.state.user`).\n\nThe first argument is the ASGI application and the second argument is the URL of the authup instance.\n> **Note**\n> Requires the `asgi` extra to be installed. `pip install authup-py[asgi]`\n\nThe following shows a simple example for using the middleware with a FastAPI application but it should work with any ASGI framework.\n\n> **Note**\n> Expects a running authup instance available at the given URL.\n> \n```python\nfrom fastapi import FastAPI\nfrom authup.plugins.asgi import AuthupASGIMiddleware\n\napp = FastAPI()\n\nauthup_url = \"https://authup.org\"  # change to your authup instance\n@app.get(\"/test\")\nasync def test():\n    return {\"message\": \"Hello World\"}\n\n# register the middleware pass the authup url as argument\napp.add_middleware(AuthupASGIMiddleware, authup_url=authup_url)\n\n```\nNow you can access the `/test` endpoint without a token and will receive a 401 response. When using a valid token, you will receive the expected response.\n\n```python\nimport httpx\nfrom authup.plugins.httpx import AuthupHttpx\n\n# no token or invalid token raises 401\nresponse = httpx.get(\"http://localhost:8000/test\") # 401\nprint(response.status_code)\n\n# valid token receives the expected response\nauthup = AuthupHttpx(\n    url=\"https://authup.org\",\n    username=\"username\",\n    password=\"password\",\n)\n\nresponse = httpx.get(\"http://localhost:8000/test\", auth=authup) # 200\nprint(response.status_code)\n\n```\n\n#### Optional user injection\nSet the `user` parameter to `True` when adding the middleware to your ASGI application:\n\n```python\nfrom fastapi import FastAPI, Request\nfrom authup.plugins.asgi import AuthupASGIMiddleware\n\napp = FastAPI()\n\nauthup_url = \"https://authup.org\"  # change to your authup instance\n@app.get(\"/test-user\")\nasync def test(request: Request):\n    return {\"user\": request.state.user}\n\n# register the middleware pass the authup url as argument\napp.add_middleware(AuthupASGIMiddleware, authup_url=authup_url, user=True)\n\n```\n\nCalling the `/test-user` endpoint without a token will return a 401 response. When using a valid token, the user object \nwill be injected into the request scope, and you will receive the expected response containing your user.\n\n### FastAPI Dependency\nThe `AuthupUser` class can be used as a FastAPI dependency. \nIt will check the incoming requests for a valid token and otherwise return a 401 response. If the token is valid a user object\nwill be available in the dependency call.\n\n#### Basic user dependency\nThe following shows a simple example for using the dependency with a FastAPI application that will return the user\nobject obtained from the token.\n\n```python\nfrom fastapi import FastAPI, Depends\nfrom authup.plugins.fastapi import AuthupUser\nfrom authup import User\n\n\napp = FastAPI()\n\nuser_dependency = AuthupUser(url=\"http://localhost:3010\")\n\n@app.get(\"/test\")\nasync def user_test(user: User = Depends(user_dependency)):\n    return {\"user\": user.dict()}\n\n```\n\n#### Require permissions\nYou can also require specific permissions for the user. The following example will only allow users with the \n`client_add` permission and a power level of over `100`. Otherwise, a 401 response will be returned.\n\n```python\nfrom fastapi import FastAPI, Depends\nfrom authup.plugins.fastapi import AuthupUser\nfrom authup import User\nfrom authup.permissions import Permission\n\npermissions = [\n        Permission(name=\"client_add\", inverse=False, power=100),\n    ]\n\nrequired_permissions = AuthupUser(\n    url=\"http://localhost:3010\",\n    permissions=permissions,\n)\n\napp = FastAPI()\n\n@app.get(\"/test\")\nasync def user_test(user: User = Depends(required_permissions)):\n    return {\"user\": user.dict()}\n\n```\n\n\n\n## How to develop\n\n### Install\n\nRequires [poetry](https://python-poetry.org/) and [pre-commit](https://pre-commit.com/) and python 3.7+.\n\n```shell\npoetry install --with dev --all-extras\n```\n\nInstall pre-commit hooks\n\n```shell\npoetry run pre-commit install\n```\n\n### Test\n\n```shell\npoetry run pytest\n```\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Python plugins for the Authup authentication and authorization framework",
    "version": "0.5.1",
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "cca508557d7769293d25741d4a81c960a16deb69b0bc1e0c2624d1e4fabb22d9",
                "md5": "e08724bc4f70083280e48494354f60d2",
                "sha256": "4ac5cd66657f3ac6830a6156518d0e4fe93414210114d9441a056696cd9727af"
            },
            "downloads": -1,
            "filename": "authup-0.5.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "e08724bc4f70083280e48494354f60d2",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7,<4.0",
            "size": 22628,
            "upload_time": "2023-04-24T09:39:21",
            "upload_time_iso_8601": "2023-04-24T09:39:21.131423Z",
            "url": "https://files.pythonhosted.org/packages/cc/a5/08557d7769293d25741d4a81c960a16deb69b0bc1e0c2624d1e4fabb22d9/authup-0.5.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c7b0c6d39b938ae4ef0bf3287260ca983d45b1cc002f60504e3b9e8c25c8f1d6",
                "md5": "8a5c121f21b4ace41ae669e59aca33d8",
                "sha256": "39ea44090fe40e5f00ffc51579a7c583210cb7f0e1ec7bc3195796952c69d106"
            },
            "downloads": -1,
            "filename": "authup-0.5.1.tar.gz",
            "has_sig": false,
            "md5_digest": "8a5c121f21b4ace41ae669e59aca33d8",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7,<4.0",
            "size": 17038,
            "upload_time": "2023-04-24T09:39:23",
            "upload_time_iso_8601": "2023-04-24T09:39:23.601422Z",
            "url": "https://files.pythonhosted.org/packages/c7/b0/c6d39b938ae4ef0bf3287260ca983d45b1cc002f60504e3b9e8c25c8f1d6/authup-0.5.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-04-24 09:39:23",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "lcname": "authup"
}
        
Elapsed time: 0.05701s