Skip to main content

Starlite Sessions Toolkit

Project description

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

starlite-sessions-1.2.0.tar.gz (8.8 kB view details)

Uploaded Source

Built Distribution

starlite_sessions-1.2.0-py3-none-any.whl (7.9 kB view details)

Uploaded Python 3

File details

Details for the file starlite-sessions-1.2.0.tar.gz.

File metadata

  • Download URL: starlite-sessions-1.2.0.tar.gz
  • Upload date:
  • Size: 8.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.2.1 CPython/3.10.7 Linux/5.15.0-1020-azure

File hashes

Hashes for starlite-sessions-1.2.0.tar.gz
Algorithm Hash digest
SHA256 9f309a2f9da82e78dbc5142ae56084d7df44aab6d0de4cea1aceef411df806d7
MD5 f652bc2ed11310c3cb4d770ab31e2fb9
BLAKE2b-256 0968a1b4f13f4a199d4ddcf9ed20fd1f7a1dfe146bcb0100d0c712989734b06a

See more details on using hashes here.

File details

Details for the file starlite_sessions-1.2.0-py3-none-any.whl.

File metadata

  • Download URL: starlite_sessions-1.2.0-py3-none-any.whl
  • Upload date:
  • Size: 7.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.2.1 CPython/3.10.7 Linux/5.15.0-1020-azure

File hashes

Hashes for starlite_sessions-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 31143fcacb73055abecf68595db31136acd999c2f4d014a2cd19f297d1c83287
MD5 004487ce4f3a479809adfd4d8fb75f07
BLAKE2b-256 0974ff3dccc4d722e0b10cc7ebf2b826bbe5f8c1530a595e25cba373e92de279

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page