imia

raw JSON →
0.5.3 verified Fri May 01 auth: no python

Full stack authentication library for ASGI frameworks. Version 0.5.3, requires Python >=3.8.0. Active development with regular minor releases.

pip install imia
error TypeError: find_by_id() missing 1 required positional argument: 'user_id'
cause UserProvider method signature change in v0.5.1: now expects connection as first argument.
fix
Update method to: async def find_by_id(self, connection: HTTPConnection, user_id: Any): ...
error ModuleNotFoundError: No module named 'imia.authentication'
cause The 'authentication' module was added in v0.5.1. Using an older version of imia.
fix
Upgrade imia to v0.5.1 or later: pip install imia>=0.5.1
error ModuleNotFoundError: No module named 'sqlalchemy'
cause Since v0.5.3, sqlalchemy is an optional dependency. It is not installed by default.
fix
Install imia with the sqlalchemy extra: pip install imia[sqlalchemy]
breaking In v0.5.1, UserProvider methods (e.g., find_by_id, find_by_login) now require an HTTPConnection instance as the first argument. Old custom providers will fail with TypeError.
fix Update all UserProvider method signatures to include connection: HTTPConnection as first parameter.
deprecated In v0.5.3, sqlalchemy and aiosqlite are no longer core dependencies; they are optional extras. Installing imia without extras will not include these libraries.
fix Install with pip install imia[sqlalchemy] if using SQLAlchemy support.
gotcha The authenticate function (added in v0.5.1) is in imia.authentication module, not at package root. Importing from imia.authenticate will fail.
fix Use 'from imia.authentication import authenticate'.
pip install imia[sqlalchemy]

Minimal ASGI app with imia authentication middleware using in-memory user storage.

from imia import AuthenticationMiddleware, LoginManager
from imia.providers import InMemoryUserProvider
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
import os

# Define a user provider (must implement find_by_id with connection arg)
class MyUserProvider(InMemoryUserProvider):
    async def find_by_id(self, connection, user_id):
        # InMemoryUserProvider already does this, but override for custom logic
        return await super().find_by_id(connection, user_id)

provider = MyUserProvider({
    '1': {'id': '1', 'name': 'Alice'},
    '2': {'id': '2', 'name': 'Bob'},
})

login_manager = LoginManager(provider)

async def homepage(request):
    user = request['user']
    return JSONResponse({'user': user['name'] if user else None})

app = Starlette(routes=[Route('/', homepage)])
app.add_middleware(AuthenticationMiddleware, login_manager=login_manager)