Complete admin package restructuring
This commit is contained in:
24
packages/sshecret-admin/src/sshecret_admin/auth/__init__.py
Normal file
24
packages/sshecret-admin/src/sshecret_admin/auth/__init__.py
Normal file
@ -0,0 +1,24 @@
|
||||
"""Authentication related module."""
|
||||
|
||||
from .authentication import (
|
||||
authenticate_user,
|
||||
create_access_token,
|
||||
create_refresh_token,
|
||||
check_password,
|
||||
decode_token,
|
||||
verify_password,
|
||||
)
|
||||
from .models import User, Token, PasswordDB
|
||||
|
||||
|
||||
__all__ = [
|
||||
"PasswordDB",
|
||||
"Token",
|
||||
"User",
|
||||
"authenticate_user",
|
||||
"check_password",
|
||||
"create_access_token",
|
||||
"create_refresh_token",
|
||||
"decode_token",
|
||||
"verify_password",
|
||||
]
|
||||
@ -0,0 +1,95 @@
|
||||
"""Authentication utilities."""
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import cast, Any
|
||||
|
||||
import bcrypt
|
||||
import jwt
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from sshecret_admin.core.settings import AdminServerSettings
|
||||
from .models import User, TokenData
|
||||
from .exceptions import AuthenticationFailedError
|
||||
|
||||
JWT_ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
||||
# I know refresh tokens are supposed to be long-lived, but 6 hours for a
|
||||
# sensitive application, seems reasonable.
|
||||
REFRESH_TOKEN_EXPIRE_HOURS = 6
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def create_token(
|
||||
settings: AdminServerSettings,
|
||||
data: dict[str, Any],
|
||||
expires_delta: timedelta,
|
||||
) -> str:
|
||||
"""Create access token."""
|
||||
to_encode = data.copy()
|
||||
expire = datetime.now(timezone.utc) + expires_delta
|
||||
to_encode.update({"exp": expire})
|
||||
encoded_jwt = jwt.encode(to_encode, settings.secret_key, algorithm=JWT_ALGORITHM)
|
||||
return str(encoded_jwt)
|
||||
|
||||
|
||||
def create_access_token(
|
||||
settings: AdminServerSettings,
|
||||
data: dict[str, Any],
|
||||
expires_delta: timedelta | None = None,
|
||||
) -> str:
|
||||
"""Create access token."""
|
||||
if not expires_delta:
|
||||
expires_delta = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
return create_token(settings, data, expires_delta)
|
||||
|
||||
|
||||
def create_refresh_token(
|
||||
settings: AdminServerSettings,
|
||||
data: dict[str, Any],
|
||||
expires_delta: timedelta | None = None,
|
||||
) -> str:
|
||||
"""Create access token."""
|
||||
if not expires_delta:
|
||||
expires_delta = timedelta(hours=REFRESH_TOKEN_EXPIRE_HOURS)
|
||||
return create_token(settings, data, expires_delta)
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
"""Verify password against stored hash."""
|
||||
return bcrypt.checkpw(plain_password.encode(), hashed_password.encode())
|
||||
|
||||
|
||||
def check_password(plain_password: str, hashed_password: str) -> None:
|
||||
"""Check password.
|
||||
|
||||
If password doesn't match, throw AuthenticationFailedError.
|
||||
"""
|
||||
if not verify_password(plain_password, hashed_password):
|
||||
raise AuthenticationFailedError()
|
||||
|
||||
|
||||
def authenticate_user(session: Session, username: str, password: str) -> User | None:
|
||||
"""Authenticate user."""
|
||||
user = session.exec(select(User).where(User.username == username)).first()
|
||||
if not user:
|
||||
return None
|
||||
if not verify_password(password, user.hashed_password):
|
||||
return None
|
||||
return user
|
||||
|
||||
|
||||
def decode_token(settings: AdminServerSettings, token: str) -> TokenData | None:
|
||||
"""Decode token."""
|
||||
try:
|
||||
payload = jwt.decode(token, settings.secret_key, algorithms=[JWT_ALGORITHM])
|
||||
username = cast("str | None", payload.get("sub"))
|
||||
if not username:
|
||||
return None
|
||||
|
||||
token_data = TokenData(username=username)
|
||||
return token_data
|
||||
except jwt.InvalidTokenError as e:
|
||||
LOG.debug("Could not decode token: %s", e, exc_info=True)
|
||||
return None
|
||||
@ -0,0 +1,30 @@
|
||||
"""Authentication related exceptions."""
|
||||
from typing import override
|
||||
|
||||
from .models import LoginError
|
||||
|
||||
|
||||
class AuthenticationFailedError(Exception):
|
||||
"""Authentication failed."""
|
||||
|
||||
@override
|
||||
def __init__(self, message: str | None = None) -> None:
|
||||
"""Initialize exception class."""
|
||||
if not message:
|
||||
message = "Invalid user or password."
|
||||
super().__init__(message)
|
||||
self.login_error: LoginError = LoginError(
|
||||
title="Authentication Failed", message=message
|
||||
)
|
||||
|
||||
|
||||
class AuthenticationNeededError(Exception):
|
||||
"""Authentication needed error."""
|
||||
|
||||
@override
|
||||
def __init__(self, message: str | None = None) -> None:
|
||||
"""Initialize exception class."""
|
||||
if not message:
|
||||
message = "You need to be logged in to continue."
|
||||
super().__init__(message)
|
||||
self.login_error: LoginError = LoginError(title="Unauthorized", message=message)
|
||||
71
packages/sshecret-admin/src/sshecret_admin/auth/models.py
Normal file
71
packages/sshecret-admin/src/sshecret_admin/auth/models.py
Normal file
@ -0,0 +1,71 @@
|
||||
"""Models for authentication."""
|
||||
|
||||
from datetime import datetime
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import SQLModel, Field
|
||||
|
||||
|
||||
JWT_ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
||||
# I know refresh tokens are supposed to be long-lived, but 6 hours for a
|
||||
# sensitive application, seems reasonable.
|
||||
REFRESH_TOKEN_EXPIRE_HOURS = 6
|
||||
|
||||
|
||||
class User(SQLModel, table=True):
|
||||
"""Users."""
|
||||
|
||||
username: str = Field(unique=True, primary_key=True)
|
||||
hashed_password: str
|
||||
disabled: bool = Field(default=False)
|
||||
created_at: datetime | None = Field(
|
||||
default=None,
|
||||
sa_type=sa.DateTime(timezone=True),
|
||||
sa_column_kwargs={"server_default": sa.func.now()},
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
|
||||
class PasswordDB(SQLModel, table=True):
|
||||
"""Password database."""
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
encrypted_password: str
|
||||
|
||||
created_at: datetime | None = Field(
|
||||
default=None,
|
||||
sa_type=sa.DateTime(timezone=True),
|
||||
sa_column_kwargs={"server_default": sa.func.now()},
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
updated_at: datetime | None = Field(
|
||||
default=None,
|
||||
sa_type=sa.DateTime(timezone=True),
|
||||
sa_column_kwargs={"onupdate": sa.func.now(), "server_default": sa.func.now()},
|
||||
)
|
||||
|
||||
|
||||
def init_db(engine: sa.Engine) -> None:
|
||||
"""Create database."""
|
||||
SQLModel.metadata.create_all(engine)
|
||||
|
||||
|
||||
class TokenData(SQLModel):
|
||||
"""Token data."""
|
||||
|
||||
username: str | None = None
|
||||
|
||||
|
||||
class Token(SQLModel):
|
||||
access_token: str
|
||||
token_type: str
|
||||
|
||||
|
||||
class LoginError(SQLModel):
|
||||
"""Login Error model."""
|
||||
# TODO: Remove this.
|
||||
|
||||
title: str
|
||||
message: str
|
||||
|
||||
Reference in New Issue
Block a user