auth: Merge users and groups into Entity

Rename the AuthEntity class to Entity, because the Auth prefix is
redundant if used in / imported from the auth module.

Next, put all relevant properties into that class, and make User and
Group a TypeAlias of that type. Introduce an Enum, "Kind", to allow a
distinction. See the previous commits for a rationale.

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2026-07-13 19:35:49 +02:00 • committed by janware DevOps
commit 0e660dc58b
Signed by: DevOps
SSH key fingerprint: SHA256:cZiw7ExG5q3KAVm7Jse3rGITowu0VjgUgNMPbifmY8g
3 changed files with 289 additions and 145 deletions

View file

@ -3,17 +3,17 @@ from __future__ import annotations
import abc
from enum import Enum, Flag, auto
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, TypeAlias
from ..log import ERR
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 Any, Self, Sequence
from ..Config import Config
from ..stree.StringTree import StringTree
from typing import Any, Mapping, Self, Sequence
class Access(Enum): # export
Read = auto()
@ -26,10 +26,19 @@ class ProjectFlags(Flag): # export
Contributing = auto()
Active = auto()
class AuthEntity(abc.ABC): # export
class Kind(Enum):
Group = auto()
User = auto()
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
class Entity(abc.ABC): # export
@abc.abstractmethod
def _kind(self) -> Kind:
...
@property
def kind(self) -> Kind:
return self._kind()
@abc.abstractmethod
def _name(self) -> str:
@ -53,22 +62,6 @@ class AuthEntity(abc.ABC): # export
def email(self) -> str:
return self._email()
class Group(AuthEntity): # export
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
def __repr__(self):
return f'Group({self.name})'
class User(AuthEntity): # export
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
def __repr__(self):
return f'User({self.name})'
@abc.abstractmethod
def _groups(self) -> Sequence[Group]:
...
@ -78,29 +71,75 @@ class User(AuthEntity): # export
return self._groups()
@abc.abstractmethod
def _email(self) -> str:
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, tp: str = '') -> Self:
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 = ['jwutils.auth.{type}.Auth'],
module_extra_path = [],
*args,
**kwargs,
) -> Self:
# == Prepare arguments
# -- conf
if isinstance(conf, dict):
conf = StringTree.from_dict(conf)
if isinstance(conf, StringTree):
conf = Config(tree = conf)
if tp == '':
# -- 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
return load_object(f'jwutils.auth.{tp}.Auth', Auth, 'Auth', conf)
def __init__(self, conf: Config):
# -- 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 load_object(
path,
base_type,
class_name_filter,
conf,
*args,
**kwargs,
)
def __init__(self, conf: Config, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.__conf = conf
self.__base_user_by_email: dict[str, User] | None = None
self.__base_entity_by_email: dict[str, Entity] | None = None
@property
def conf(self):
@ -108,7 +147,7 @@ class Auth(abc.ABC): # export
@abc.abstractmethod
def _access(
self, what: str, access_type: Access | None, who: User | Group | None
self, what: str, access_type: Access | None, who: Entity | Group | None
) -> bool:
...
@ -116,48 +155,60 @@ class Auth(abc.ABC): # export
self,
what: str,
access_type: Access | None = None,
who: User | Group | None = None
who: Entity | Group | None = None
) -> bool:
return self._access(what, access_type, who)
@abc.abstractmethod
def _current_user(self) -> User:
def _current_entity(self) -> Entity:
...
@property
def current_user(self) -> User:
return self._current_user()
def current_entity(self) -> Entity:
return self._current_entity()
@abc.abstractmethod
def _user(self, name) -> User:
def _entity(self, name, kind: Kind) -> Entity:
...
def user(self, name) -> User:
return self._user(name)
def entity(self, name: str, kind: Kind) -> Entity:
return self._entity(name, kind)
@abc.abstractmethod
def _users(self) -> dict[str, User]:
def _entities(self, kind: Kind) -> Mapping[str, Entity]:
...
def _user_by_email(self, email: str) -> User:
if self.__base_user_by_email is None:
ret: dict[str, User] = dict()
users = self._users()
for user in users.values():
ret[user.email] = user
self.__base_user_by_email = ret
return self.__base_user_by_email[email]
def entities(self, kind: Kind) -> Mapping[str, Entity]:
return self._entities(kind)
def user_by_email(self, email) -> User:
return self._user_by_email(email)
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]
@property
def users(self) -> dict[str, User]:
return self._users()
def entity_by_email(self, email: str, kind: Kind) -> Entity:
return self._entity_by_email(email, kind)
@abc.abstractmethod
def _projects(self, name, flags: ProjectFlags) -> Sequence[str]:
...
def user_by_email(self, email: str) -> Entity:
return self._entity_by_email(email, Kind.User)
# -- Convenience / legacy wrappers
def projects(self, name, flags: ProjectFlags) -> Sequence[str]:
return self._projects(name, flags)
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)

View file

@ -1,80 +1,105 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, override
from ...Config import Config
from ...log import WARNING, slog
from ..Auth import Access
from ..Auth import Auth as AuthBase
from ..Auth import Group as GroupBase
from ..Auth import ProjectFlags
from ..Auth import User as UserBase
from ..Auth import Entity as EntityBase
from ..Auth import Group as Group # Needed by jwutils utility layer
from ..Auth import User as User # Needed by jwutils utility layer
from ..Auth import Kind, ProjectFlags
if TYPE_CHECKING:
from typing import Sequence
from typing import Mapping, Sequence
from ...Config import Config
class Entity(EntityBase): # export
class Group(GroupBase): # export
def __init__(self, *, auth: AuthBase, name: str, **kwargs):
super().__init__(**kwargs)
self.__name = name
self.__auth = auth
def _name(self) -> str:
return self.__name
class User(UserBase): # export
def __init__(self, *, auth: AuthBase, name: str, conf: Config, **kwargs):
def __init__(
self,
*,
auth: AuthBase,
name: str,
conf: Config,
kind: Kind,
**kwargs,
):
super().__init__(**kwargs)
self.__name = name
self.__conf = conf
self.__kind = kind
self.__auth = auth
self.__groups: list[GroupBase] | None = None
self.__groups: list[Entity] | None = None
self.__email: str = conf['email']
@property
def conf(self):
return self.__conf
@override
def _name(self) -> str:
return self.__name
def _groups(self) -> Sequence[GroupBase]:
@override
def _groups(self) -> Sequence[Entity]:
if self.__kind != Kind.User:
return []
if self.__groups is None:
name: str = ''
ret: list[GroupBase] = []
ret: list[Entity] = []
for name in self.conf['groups']:
ret.append(Group(auth = self.__auth, name = name))
ret.append(
Entity(
auth = self.__auth,
name = name,
kind = Kind.Group,
conf = Config(),
)
)
self.__groups = ret
return self.__groups
@override
def _email(self) -> str:
return self.__email
@override
def _kind(self) -> Kind:
return self.__kind
@override
def _projects(self, flags: ProjectFlags) -> Sequence[str]:
return []
class Auth(AuthBase): # export
def __init__(self, *, conf: Config, **kwargs):
def __init__(self, conf: Config, **kwargs):
super().__init__(conf, **kwargs)
self.___users: dict[str, UserBase] | None = None
self.___users: dict[str, EntityBase] | None = None
self.__groups = None
self.__current_user: UserBase | None = None
self.__user_by_email: dict[str, UserBase] | None = None
self.__current_user: EntityBase | None = None
self.__user_by_email: dict[str, EntityBase] | None = None
@property
def __users(self) -> dict[str, UserBase]:
def __users(self) -> dict[str, EntityBase]:
if self.___users is None:
ret: dict[str, UserBase] = {}
ret: dict[str, EntityBase] = {}
for name in self.conf.entries('user'):
conf = self.conf.branch('user.' + name)
assert conf is not None, 'Config is None'
ret[name] = User(auth = self, name = name, conf = conf)
ret[name] = Entity(
auth = self,
name = name,
conf = conf,
kind = Kind.User,
)
self.___users = ret
return self.___users
@override
def _access(
self, what: str, access_type: Access | None, who: UserBase | GroupBase | None
self, what: str, access_type: Access | None, who: EntityBase | None
) -> bool: # type: ignore
slog(
WARNING,
@ -82,24 +107,40 @@ class Auth(AuthBase): # export
)
return False
def _user(self, name) -> UserBase:
@override
def _entity(self, name: str, kind: Kind) -> EntityBase:
if kind != Kind.User:
raise NotImplementedError(
'Support for retrieving groups is not implemented'
)
return self.__users[name]
def _users(self) -> dict[str, UserBase]:
@override
def _entities(self, kind: Kind) -> Mapping[str, EntityBase]:
if kind != Kind.User:
raise NotImplementedError(
'Support for retrieving all groups is not implemented'
)
return self.__users
def _current_user(self) -> UserBase:
@override
def _current_entity(self) -> EntityBase:
if self.__current_user is None:
self.__current_user = self._user(self.conf['current_user'])
self.__current_user = self._entity(
self.conf['current_user'],
kind = Kind.User,
)
return self.__current_user
def _user_by_email(self, email: str) -> UserBase:
@override
def _entity_by_email(self, email: str, kind: Kind) -> EntityBase:
if kind != Kind.User:
raise NotImplementedError(
'Support for retrieving groups by email is not implemented'
)
if self.__user_by_email is None:
ret: dict[str, UserBase] = dict()
ret: dict[str, EntityBase] = dict()
for user in self.__users.values():
ret[user.email] = user
self.__user_by_email = ret
return self.__user_by_email[email]
def _projects(self, name, flags: ProjectFlags) -> Sequence[str]:
return []

View file

@ -1,6 +1,6 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, override
import ldap # type: ignore[import-untyped]
@ -8,67 +8,87 @@ from ...ldap import bind
from ...log import DEBUG, ERR, WARNING, slog
from ..Auth import Access
from ..Auth import Auth as AuthBase
from ..Auth import Group as GroupBase
from ..Auth import ProjectFlags
from ..Auth import User as UserBase
from ..Auth import Entity as EntityBase
from ..Auth import Group as Group # Needed by jwutils utility layer
from ..Auth import Kind, ProjectFlags
from ..Auth import User as User # Needed by jwutils utility layer
if TYPE_CHECKING:
from typing import Sequence
from typing import Mapping, Sequence
from ...Config import Config
class Group(GroupBase): # export
class Entity(EntityBase):
def __init__(self, *, auth: AuthBase, name: str, **kwargs):
super().__init__(**kwargs)
self.__name = name
self.__auth = auth
def _name(self) -> str:
return self.__name
class User(UserBase):
def __init__(self, *, auth: AuthBase, name: str, cn: str, email: str, **kwargs):
def __init__(
self,
*,
auth: AuthBase,
name: str,
cn: str,
email: str,
kind: Kind,
**kwargs,
):
super().__init__(**kwargs)
self.__auth = auth
self.__name = name
self.__cn = cn
self.__email = email
self.__groups: list[GroupBase] | None = None
self.__groups: list[Entity] | None = None
self.__kind = kind
@override
def _name(self) -> str:
return self.__name
def _groups(self) -> Sequence[GroupBase]:
@override
def _groups(self) -> Sequence[Entity]:
raise NotImplementedError
@override
def _email(self) -> str:
return self.__email
@override
def _display_name(self) -> str:
return self.__cn
@override
def _projects(self, flags: ProjectFlags) -> Sequence[str]:
if flags & ProjectFlags.Contributing:
# TODO: Ask LDAP
slog(
WARNING,
'Querying LDAP for projects a user contributes to is not '
'implemented, ignoring'
)
return []
@override
def _kind(self) -> Kind:
return self.__kind
class Auth(AuthBase): # export
def __init__(self, *, conf: Config, **kwargs):
super().__init__(conf, **kwargs)
self.___users: dict[str, UserBase] | None = None
self.___user_by_email: dict[str, User] | None = None
def __init__(self, conf: Config, *args, **kwargs):
super().__init__(conf, *args, **kwargs)
self.___users: dict[str, EntityBase] | None = None
self.___user_by_email: dict[str, EntityBase] | None = None
self.__groups = None
self.__current_user: User | None = None
self.__current_user: Entity | None = None
self.__user_base_dn = conf['user_base_dn']
self.__conn = self.__bind()
self.__dummy = self.load(conf, 'dummy')
self.__dummy = AuthBase.load(conf, tp = 'dummy')
def __bind(self):
return bind(self.conf)
@property
def __users(self) -> dict[str, UserBase]:
def __users(self) -> dict[str, EntityBase]:
if self.___users is None:
ret: dict[str, UserBase] = {}
ret_by_email: dict[str, User] = {}
ret: dict[str, EntityBase] = {}
ret_by_email: dict[str, EntityBase] = {}
for res in self.__conn.find(
self.__user_base_dn,
ldap.SCOPE_SUBTREE, # pyright: ignore[reportAttributeAccessIssue]
@ -90,7 +110,13 @@ class Auth(AuthBase): # export
if not emails:
slog(DEBUG, f'No email for user "{uid}", skipping')
continue
user = User(auth = self, name = uid, cn = cn, email = emails[0])
user = self._create_entity(
auth = self,
name = uid,
cn = cn,
email = emails[0],
kind = Kind.User,
)
ret[uid] = user
for email in emails:
ret_by_email[email] = user
@ -105,13 +131,33 @@ class Auth(AuthBase): # export
return self.___users
@property
def __user_by_email(self) -> dict[str, UserBase]:
def __user_by_email(self) -> dict[str, Entity]:
if self.___user_by_email is None:
self.__users
return self.___user_by_email # type: ignore # We are sure that ___user_by_email is not None at this point
def _create_entity(
self,
*,
auth: Auth,
name: str,
cn: str,
email: str,
kind: Kind,
**kwargs,
):
return Entity(
auth = auth,
name = name,
cn = cn,
email = email,
kind = kind,
**kwargs,
)
@override
def _access(
self, what: str, access_type: Access | None, who: UserBase | GroupBase | None
self, what: str, access_type: Access | None, who: EntityBase | None
) -> bool: # type: ignore
slog(
WARNING,
@ -119,28 +165,34 @@ class Auth(AuthBase): # export
)
return False
def _user(self, name) -> UserBase:
@override
def _entity(self, name: str, kind: Kind) -> EntityBase:
if kind != Kind.User:
raise NotImplementedError(
'Support for retrieving groups is not implemented'
)
try:
return self.__users[name]
except:
slog(ERR, f'No such user: "{name}"')
raise
def _user_by_email(self, email: str) -> UserBase:
@override
def _entity_by_email(self, email: str, kind: Kind) -> Entity:
if kind != Kind.User:
raise NotImplementedError(
'Support for retrieving groups by email is not implemented'
)
return self.__user_by_email[email]
def _current_user(self) -> User:
@override
def _current_entity(self) -> Entity:
raise NotImplementedError
def _users(self) -> dict[str, UserBase]:
return self.__users
def _projects(self, name, flags: ProjectFlags) -> Sequence[str]:
if flags & ProjectFlags.Contributing:
# TODO: Ask LDAP
slog(
WARNING,
'Querying LDAP for projects a user contributes to is not '
'implemented, ignoring'
@override
def _entities(self, kind: Kind) -> Mapping[str, EntityBase]:
if kind != Kind.User:
raise NotImplementedError(
'Support for retrieving all groups is not implemented'
)
return []
return self.__users