Skip to main content
userharbor

GitHub License Tests Codecov PyPI - Python Version PyPI - Version Code style: black Linting: Ruff uv Pytest Zensical

userharbor-sqlalchemy provides a SQLAlchemy-based UserStore implementation for userharbor.

It stores:

  • users
  • email verification tokens
  • sessions
  • password reset tokens
  • password hashes
  • roles
  • permissions
  • user-to-role assignments
  • role-to-permission assignments

Each user has at most one active email verification token and one active password reset token. Storing a new token of either kind removes that user's previous token. Users can have multiple active sessions.

The package only handles persistence. It does not send emails, expose HTTP endpoints, or implement application-specific authentication flows.

Usernames preserve their original casing while lookup and uniqueness use a Unicode case-folded key. The default model stores that key in the unique, indexed username_key column.


Installation

pip install userharbor-sqlalchemy

This package depends on userharbor and SQLAlchemy 2.x.


Example usage

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from userharbor import UserHarbor
from userharbor_sqlalchemy import SQLAlchemyUserStore


class EmailSender:
    def send_verification(
        self,
        username: str,
        email: str,
        verification_token: str,
    ) -> None:
        print(f"Send verification token to {email}: {verification_token}")

    def send_password_reset(
        self,
        username: str,
        email: str,
        reset_token: str,
    ) -> None:
        print(f"Send password reset token to {email}: {reset_token}")

    def send_email_verified(self, username: str, email: str) -> None:
        print(f"Email verified for {email}")

    def send_password_changed(self, username: str, email: str) -> None:
        print(f"Password changed for {email}")

    def send_account_deleted(self, username: str, email: str) -> None:
        print(f"Account deleted for {email}")


engine = create_engine("sqlite:///users.db")
SessionLocal = sessionmaker(bind=engine)

store = SQLAlchemyUserStore(SessionLocal)
store.metadata.create_all(engine)
email_sender = EmailSender()

harbor = UserHarbor(
    secret_key="your-secret-key",
    store=store,
    email_sender=email_sender,
)

harbor.register(
    username="jane",
    email="jane@example.com",
    password="StrongPassword123!",
)

harbor.verify_email("verification-token-from-email")

session_token = harbor.login(
    username="jane",
    password="StrongPassword123!",
)

current_user = harbor.get_current_user(session_token)
print(current_user.username)

harbor.roles.create("admin")
harbor.permissions.create("users.delete")
harbor.roles.grant_permission("admin", "users.delete")
harbor.grant_role("jane", "admin")

if harbor.has_permission(session_token, "users.delete"):
    print("User can delete users")

harbor.logout(session_token)

For real applications, replace EmailSender with an implementation that sends verification and password reset messages through your email provider.


Transactions

SQLAlchemyUserStore.transaction() provides a transaction context used by UserHarbor for multi-step operations such as email verification, password reset, password change, account deletion, and role or permission assignment. Successful blocks are committed; exceptions roll back all changes from the block.


Custom user models

A custom user model must provide username_key in addition to username, email, password_hash, and verified:

username: Mapped[str] = mapped_column(String(255), primary_key=True)
username_key: Mapped[str] = mapped_column(String(255), unique=True, index=True)

SQLAlchemyUserStore.create_user() fills username_key with username.casefold(). The unique constraint prevents accounts whose usernames differ only by casing, while username keeps the spelling selected during registration.


License

UserHarbor SQLAlchemy is released under the MIT License.

Metadata

Release files for userharbor-sqlalchemy 0.6.2

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

Source distribution (sdist)

Source distribution for userharbor-sqlalchemy 0.6.2
File Size Uploaded
userharbor_sqlalchemy-0.6.2.tar.gz 6.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for userharbor-sqlalchemy 0.6.2
File Interpreter ABI Platform
userharbor_sqlalchemy-0.6.2-py3-none-any.whl Python 3 none any Details

Total release size: 13.5 kB

Release files / userharbor_sqlalchemy-0.6.2.tar.gz

Download URL userharbor_sqlalchemy-0.6.2.tar.gz
Size 6.0 kB
Tags Source
SHA-256 checksum
How to use checksums
691a918d18f5c229692efa0e27da73fd461ddeabcf501aced2de77a360c4df8b
BLAKE2b-256 checksum
How to use checksums
4a09ca7cb41fd33c0fe5a650dabd3ee8a8981c4899e92ba5c7a134093fa190f6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.10 {"installer":{"name":"uv","version":"0.12.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"22.04","id":"jammy","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / userharbor_sqlalchemy-0.6.2-py3-none-any.whl

Download URL userharbor_sqlalchemy-0.6.2-py3-none-any.whl
Size 7.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
14712c712f49458ad7291303c1ee8e0c9d1e0e6b28d2a27f17aabb25f9d1cf35
BLAKE2b-256 checksum
How to use checksums
a3e453fb83f2f13c051b126d33f2175c4a802b085e7cf5fe582e4d190e562eff
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.10 {"installer":{"name":"uv","version":"0.12.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"22.04","id":"jammy","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release history Release notifications | RSS feed

0.7.0

2 release files

This release

0.6.2 This release

2 release files

0.6.1

2 release files

0.6.0

2 release files

0.5.0

2 release files

0.4.0

2 release files

0.3.0

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.0

2 release files

0.0.0

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