jw-python/src/python/jw/util/auth/Auth.py
Jan Lindemann 819d6283bd
All checks were successful
CI / Packaging - Kali Linux (pull_request) Successful in 5m43s
CI / Packaging - OpenSUSE Tumbleweed (pull_request) Successful in 5m58s
CI / Packaging test (pull_request) Successful in 0s
auth.Auth: Add methods __eq__() and .__hash__()
Entity instances are compared by identity. The forge clients create a fresh
Owner object on every lookup, so two objects denoting the same user are
never equal, and equality-based matching - permission checks, caches keyed
on the entity - does not work.

Give Entity value equality: two entities are equal when they carry the same
kind and the same name. __hash__() is derived from the same fields, so
entities remain usable as dict keys and in sets.

Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.6.0
Signed-off-by: Jan Lindemann <jan@janware.com>
2026-11-25 12:10:40 +01:00

220 lines
5.7 KiB
Python

from __future__ import annotations
import abc
from enum import Enum, Flag, auto
from typing import TYPE_CHECKING, Any, Self, Sequence, TypeAlias, cast, override
from ..Config import Config
from ..enum_helper import kebab_to_pascal
from ..log import ERR, WARNING, log
from ..misc import load_object
from ..stree.StringTree import StringTree
if TYPE_CHECKING:
from typing import Mapping
class Access(Enum): # export
Read = auto()
Modify = auto()
Create = auto()
Delete = auto()
class ProjectFlags(Flag): # export
NoFlags = auto()
Contributing = auto()
Active = auto()
class Kind(Flag):
Group = auto()
User = auto()
Both = Group | User
class Entity(abc.ABC): # export
@override
def __eq__(self, other: Any) -> bool:
if not isinstance(other, Entity):
return NotImplemented
return (self.kind, self.name) == (other.kind, other.name)
@override
def __hash__(self) -> int:
return hash((self.kind, self.name))
@abc.abstractmethod
def _kind(self) -> Kind:
...
@property
def kind(self) -> Kind:
return self._kind()
@abc.abstractmethod
def _name(self) -> str:
...
@property
def name(self) -> str:
return self._name()
def _display_name(self) -> str:
return self._name()
@property
def display_name(self) -> str:
return self._display_name()
def _email(self) -> str:
return 'no-email@example.com'
@property
def email(self) -> str:
return self._email()
@abc.abstractmethod
def _groups(self) -> Sequence[Group]:
...
@property
def groups(self) -> Sequence[Group]:
return self._groups()
@abc.abstractmethod
def _projects(self, flags: ProjectFlags) -> Sequence[str]:
...
def projects(self, flags: ProjectFlags) -> Sequence[str]:
return self._projects(flags)
User: TypeAlias = Entity
Group: TypeAlias = Entity
class Auth(abc.ABC): # export
@classmethod
def load(
cls,
conf: Config | dict[str, Any] | StringTree,
base_type: type | None = None,
tp: str | None = None,
class_name_filter: str | None = None,
module_path: list[str] = ['jwutils.auth.{type}.Auth'],
module_extra_path: list[str] = [],
*args: Any,
**kwargs: Any,
) -> Self:
# == Prepare arguments
# -- conf
if isinstance(conf, dict):
conf = StringTree.from_dict(conf)
if isinstance(conf, StringTree):
conf = Config(tree = conf)
# -- tp
if tp is None:
val = conf.get('type')
if val is None:
msg = 'No type specified in auth configuration'
conf.dump(ERR, msg)
raise Exception(msg)
tp = val
# -- class_name_filter
if class_name_filter is None:
class_name_filter = 'Auth'
# -- base_type
if base_type is None:
base_type = cls
# -- Strings path and class_name_filter
Type = kebab_to_pascal(tp)
macros = {'type': tp, 'Type': Type}
path = [p.format(**macros) for p in module_path + module_extra_path]
class_name_filter = class_name_filter.format(**macros)
# == Do it
return cast(
'Self',
load_object(path, base_type, class_name_filter, conf, *args, **kwargs)
)
def __init__(self, conf: Config, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.__conf = conf
self.__base_entity_by_email: dict[str, Entity] | None = None
@property
def conf(self) -> Config:
return self.__conf
@abc.abstractmethod
def _access(
self, what: str, access_type: Access | None, who: Entity | Group | None
) -> bool:
...
def access(
self,
what: str,
access_type: Access | None = None,
who: Entity | Group | None = None
) -> bool:
return self._access(what, access_type, who)
@abc.abstractmethod
def _current_entity(self) -> Entity:
...
@property
def current_entity(self) -> Entity:
return self._current_entity()
@abc.abstractmethod
def _entity(self, name: str, kind: Kind) -> Entity:
...
def entity(self, name: str, kind: Kind) -> Entity:
return self._entity(name, kind)
@abc.abstractmethod
def _entities(self, kind: Kind) -> Mapping[str, Entity]:
...
def entities(self, kind: Kind) -> Mapping[str, Entity]:
return self._entities(kind)
def _entity_by_email(self, email: str, kind: Kind) -> Entity:
if self.__base_entity_by_email is None:
ret: dict[str, Entity] = dict()
entities = self._entities(kind)
for entity in entities.values():
ret[entity.email] = entity
self.__base_entity_by_email = ret
return self.__base_entity_by_email[email]
def entity_by_email(self, email: str, kind: Kind) -> Entity:
return self._entity_by_email(email, kind)
def user_by_email(self, email: str) -> Entity:
return self._entity_by_email(email, Kind.User)
# -- Convenience / legacy wrappers
def projects(self, name: str, flags: ProjectFlags) -> Sequence[str]:
log(
WARNING,
'Using Auth.projects() is deprecated. Use Entity.projects() instead!'
)
entity = self.entity(name, Kind.User)
return entity.projects(flags)
@property
def users(self) -> Mapping[str, Entity]:
return self.entities(Kind.User)
def user(self, name: str) -> Entity:
return self.entity(name, Kind.User)