Skip to main content
Archived

This project has been archived by its maintainers, and is no longer receiving any updates.

Starlite Sessions

Starlite logo

PyPI - License PyPI - Python Version

Quality Gate Status Coverage

Maintainability Rating Security Rating Reliability Rating Code Smells

Discord Matrix

This library offers simple session based authentication for Starlite.

Checkout the docs📚.

Installation

pip install starlite-sessions

Example

import os
from typing import Any, Optional, Literal

from pydantic import BaseModel, EmailStr, SecretStr
from starlite import OpenAPIConfig, Request, Starlite, get, post

from starlite_sessions import SessionAuth


# Let's assume we have a User model that is a pydantic model.
# This though is not required - we need some sort of user class -
# but it can be any arbitrary value, e.g. an SQLAlchemy model,
# a representation of a MongoDB  etc.
class User(BaseModel):
    id: str
    name: str
    email: EmailStr


# we also have pydantic types for two different
# kinds of POST request bodies: one for creating
# a user, e.g. "sign-up", and the other for logging
# an existing user in.
class UserCreatePayload(BaseModel):
    name: str
    email: EmailStr
    password: SecretStr


class UserLoginPayload(BaseModel):
    email: EmailStr
    password: SecretStr


# The SessionAuth class requires a handler callable
# that takes the session dictionary, and returns the
# 'User' instance correlating to it.
#
# The session dictionary itself is a value the user decides
# upon. So for example, it might be a simple dictionary
# that holds a user id, for example: { "user_id": "abcd123" }
#
# Note: The callable can be either sync or async - both will work.
async def retrieve_user_handler(session: dict[str, Any]) -> Optional[User]:
    # insert logic here to retrieve the user instance based on the session data.
    ...


# The minimal configuration required by the library is the
# callable for the 'retrieve_user_handler', and a bytes value for
# the secret used to encrypt the session cookie.
#
# Important: secrets should never be hardcoded, and its considered
# best practice to inject secrets via env.
#
# Important: the secret should be a 16, 24 or 32
# characters long byte string (128/192/256 bit).
#
# Tip: It's also a good idea to use the pydantic settings
# management functionality.
session_auth = SessionAuth(
    retrieve_user_handler=retrieve_user_handler,
    secret=os.environ.get("JWT_SECRET", os.urandom(16)),
    # exclude any URLs that should not have authentication.
    # We exclude the documentation URLs, signup and login.
    exclude=["/login", "/signup", "/schema"],
)


@post("/login")
async def login(data: UserLoginPayload, request: Request) -> User:
    # we received log-in data via post.
    # out login handler should retrieve from persistence (a db etc.)
    # the user data and verify that the login details
    # are correct. If we are using passwords, we should check that
    # the password hashes match etc. We will simply assume that we
    # have done all of that we now have a user value:
    user: User = ...

    # once verified we can create a session.
    # to do this we simply need to call the Starlite
    # 'Request.set_session' method, which accepts either dictionaries
    # or pydantic models. In our case, we can simply record a
    # simple dictionary with the user ID value:
    request.set_session({"user_id": user.id})

    # you can do whatever we want here. In this case, we will simply return the user data:
    return user


@post("/signup")
async def signup(data: UserCreatePayload, request: Request) -> User:
    # this is similar to the login handler, except here we should
    # insert into persistence - after doing whatever extra
    # validation we might require. We will assume that this is done,
    # and we now have a user instance with an assigned ID value:
    user: User = ...

    # we are creating a session the same as we do in the
    # 'login_handler' above:
    request.set_session({"user_id": user.id})

    # and again, you can add whatever logic is required here, we
    # will simply return the user:
    return user


# the endpoint below requires the user to be already authenticated
# to be able to access it.
@get("/user")
def get_user(request: Request[User, dict[Literal["user_id"], str]]) -> Any:
    # because this route requires authentication, we can access
    # `request.user`, which is the authenticated user returned
    # by the 'retrieve_user_handler' function we passed to SessionAuth.
    return request.user


# We add the session security schema to the OpenAPI config.
openapi_config = OpenAPIConfig(
    title="My API",
    version="1.0.0",
    components=[session_auth.openapi_components],
    security=[session_auth.security_requirement],
)

# We initialize the app instance, passing to it the
# 'jwt_auth.middleware' and the 'openapi_config'.
app = Starlite(
    route_handlers=[login, signup, get_user],
    middleware=[session_auth.middleware],
    openapi_config=openapi_config,
)

Contributing

Starlite and all its official libraries are open to contributions big and small.

You can always join our discord server or join our Matrix space to discuss contributions and project maintenance. For guidelines on how to contribute to this library, please see CONTRIBUTING.md in the repository's root.

Metadata

Release files for starlite-sessions 1.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for starlite-sessions 1.2.0
File Size Uploaded
starlite-sessions-1.2.0.tar.gz 8.8 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for starlite-sessions 1.2.0
File Interpreter ABI Platform
starlite_sessions-1.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 16.7 kB

Release files / starlite-sessions-1.2.0.tar.gz

Download URL starlite-sessions-1.2.0.tar.gz
Size 8.8 kB
Tags Source
SHA-256 checksum
How to use checksums
9f309a2f9da82e78dbc5142ae56084d7df44aab6d0de4cea1aceef411df806d7
BLAKE2b-256 checksum
How to use checksums
0968a1b4f13f4a199d4ddcf9ed20fd1f7a1dfe146bcb0100d0c712989734b06a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.2.1 CPython/3.10.7 Linux/5.15.0-1020-azure

Release files / starlite_sessions-1.2.0-py3-none-any.whl

Download URL starlite_sessions-1.2.0-py3-none-any.whl
Size 7.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
31143fcacb73055abecf68595db31136acd999c2f4d014a2cd19f297d1c83287
BLAKE2b-256 checksum
How to use checksums
0974ff3dccc4d722e0b10cc7ebf2b826bbe5f8c1530a595e25cba373e92de279
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.2.1 CPython/3.10.7 Linux/5.15.0-1020-azure

Release history Release notifications | RSS feed

This release

1.2.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page