A newly created user held no roles and no permissions, so the sidebar filtered every nav item away and the account appeared broken. Adds three prebuilt scopes (Reporter, Operator, Technician) derived from the live permission catalog by verb rather than hand-listed, so a new plugin permission lands in the right scope automatically instead of silently going ungranted. users.view is granted to all three since a user who cannot see the directory cannot collaborate; users.create/edit/delete stay admin-only. Role.seedscopes() is additive and idempotent, seeded via flask seed permissions, and preserves custom grants on rerun. Reporter guard: the auth model is additive across admin, direct grants and roles, so Reporter cannot be expressed as merely fewer grants - a direct endpoint-action grant would silently re-arm a read-only account. Rather than change the global permission predicate and alter every route's semantics, _check_scope_grants() rejects the invalid combination at write time on both create and update. The update path validates the effective post-update state, so demoting a Technician to Reporter is refused while a stale endpoint grant remains rather than quietly leaving a read-only user with write authority. Validation runs before the User object is constructed. Assigning user.roles first put the relationship into the session autoflush path while the User was still unattached; nothing broke because the refusal returns before db.session.add(), but it left a trap where any query added below that point would autoflush a half-built user and surface later as an orphan row. Verified with -W error::sqlalchemy.exc.SAWarning: 25 passed.
620 lines
26 KiB
Python
620 lines
26 KiB
Python
"""User and authentication models."""
|
|
|
|
from datetime import datetime, timezone
|
|
from shopdb.extensions import db
|
|
from .base import BaseModel
|
|
|
|
|
|
# Association table for user roles (many-to-many)
|
|
userroles = db.Table(
|
|
'userroles',
|
|
db.Column('userid', db.Integer, db.ForeignKey('users.userid'), primary_key=True),
|
|
db.Column('roleid', db.Integer, db.ForeignKey('roles.roleid'), primary_key=True)
|
|
)
|
|
|
|
# Association table for role permissions (many-to-many)
|
|
rolepermissions = db.Table(
|
|
'rolepermissions',
|
|
db.Column('roleid', db.Integer, db.ForeignKey('roles.roleid'), primary_key=True),
|
|
db.Column('permissionid', db.Integer, db.ForeignKey('permissions.permissionid'), primary_key=True)
|
|
)
|
|
|
|
# Association table for DIRECT per-user permissions (many-to-many).
|
|
#
|
|
# A grant here is an ordinary permission, identical in power to one held through
|
|
# a role - it counts toward the API token scope ceiling and everything else. It
|
|
# exists because a site of 5-7 operators should be able to give one person one
|
|
# capability without minting a role for them, which would otherwise turn the
|
|
# role list into a mixture of job titles and single-capability flags.
|
|
#
|
|
# Anything that answers "what may this user do" MUST fold this in. There are two
|
|
# such surfaces and they are computed separately: haspermission() (the predicate
|
|
# authorization uses) and getpermissions() (the list baked into JWT claims and
|
|
# read by the frontend authStore). Teaching only one of them makes the server and
|
|
# the UI disagree silently.
|
|
userpermissions = db.Table(
|
|
'userpermissions',
|
|
db.Column('userid', db.Integer, db.ForeignKey('users.userid'), primary_key=True),
|
|
db.Column('permissionid', db.Integer, db.ForeignKey('permissions.permissionid'), primary_key=True)
|
|
)
|
|
|
|
|
|
class Permission(db.Model):
|
|
"""
|
|
Permission model for granular access control.
|
|
|
|
Permissions are predefined and assigned to roles.
|
|
"""
|
|
__tablename__ = 'permissions'
|
|
|
|
permissionid = db.Column(db.Integer, primary_key=True)
|
|
name = db.Column(db.String(50), unique=True, nullable=False)
|
|
description = db.Column(db.String(255))
|
|
category = db.Column(db.String(50), default='general') # For grouping in UI
|
|
|
|
# Core permission catalog. This is CORE ONLY - permissions for a plugin
|
|
# domain (machines, computers, printers, network, knowledgebase,
|
|
# notifications, usb, warranty, measuringtools) live in that plugin's
|
|
# BasePlugin.get_permissions() hook, not here (plugin-is-the-product). The
|
|
# merged core+plugins view is full_permission_catalog() below.
|
|
CORE_PERMISSIONS = [
|
|
# Assets
|
|
('assets.view', 'View assets', 'assets'),
|
|
('assets.create', 'Create assets', 'assets'),
|
|
('assets.edit', 'Edit assets', 'assets'),
|
|
('assets.delete', 'Delete assets', 'assets'),
|
|
# Applications
|
|
('applications.view', 'View applications', 'applications'),
|
|
# Deliberately NOT '.view': reading the catalogue and pulling the bytes
|
|
# are different acts. A script body is SYSTEM-context PowerShell and an
|
|
# installer is a vendor binary, so the routes that serve them are gated
|
|
# here rather than on the metadata permission a site may hand to guests.
|
|
('applications.download',
|
|
'Download application installers and script bodies', 'applications'),
|
|
('applications.create', 'Create applications', 'applications'),
|
|
('applications.edit', 'Edit applications', 'applications'),
|
|
('applications.delete', 'Delete applications', 'applications'),
|
|
# Reports
|
|
('reports.view', 'View reports', 'reports'),
|
|
('reports.export', 'Export reports', 'reports'),
|
|
# Settings
|
|
('settings.view', 'View settings', 'admin'),
|
|
('settings.edit', 'Edit settings', 'admin'),
|
|
# Users
|
|
('users.view', 'View users', 'admin'),
|
|
('users.create', 'Create users', 'admin'),
|
|
('users.edit', 'Edit users', 'admin'),
|
|
('users.delete', 'Delete users', 'admin'),
|
|
# Audit
|
|
('audit.view', 'View audit logs', 'admin'),
|
|
# Deliberately separate from audit.view: reading the log and destroying
|
|
# history are different acts, and many people need only the first.
|
|
('audit.purge', 'Delete audit log entries past the retention period', 'admin'),
|
|
# API tokens
|
|
('apitokens.create', 'Create and manage API tokens', 'apitokens'),
|
|
# Collector service tokens. A token scoped to ONLY this permission is a
|
|
# collector service token: it authorizes the collector ingest API and
|
|
# nothing else (scoped tokens pass require_permission only for listed
|
|
# perms, and this perm gates no other route). See collector.py.
|
|
('collector.ingest', 'Submit collector payloads (fleet reporting)',
|
|
'collector'),
|
|
]
|
|
|
|
def __repr__(self):
|
|
return f"<Permission {self.name}>"
|
|
|
|
@classmethod
|
|
def seed_entries(cls, entries):
|
|
"""Idempotently create Permission rows from (name, desc, category)
|
|
tuples (or equivalent dicts). Returns how many were created."""
|
|
created = 0
|
|
for name, description, category in normalize_permission_entries(entries):
|
|
if not cls.query.filter_by(name=name).first():
|
|
perm = cls(name=name, description=description, category=category)
|
|
db.session.add(perm)
|
|
created += 1
|
|
return created
|
|
|
|
@classmethod
|
|
def seed(cls):
|
|
"""Seed the full permission catalog (core plus enabled plugins)."""
|
|
return cls.seed_entries(full_permission_catalog())
|
|
|
|
|
|
def normalize_permission_entries(entries):
|
|
"""Coerce catalog entries to (name, description, category) tuples.
|
|
|
|
Accepts tuples/lists in that order, or dicts with those keys, so a plugin
|
|
may return either shape from get_permissions().
|
|
"""
|
|
normalized = []
|
|
for entry in entries or []:
|
|
if isinstance(entry, dict):
|
|
normalized.append((
|
|
entry['name'],
|
|
entry.get('description', ''),
|
|
entry.get('category', 'general'),
|
|
))
|
|
else:
|
|
name, description, category = entry
|
|
normalized.append((name, description, category))
|
|
return normalized
|
|
|
|
|
|
def full_permission_catalog(include_disabled=False):
|
|
"""The full permission catalog: core permissions plus every LOADED plugin's
|
|
get_permissions().
|
|
|
|
By default only ENABLED plugins contribute, so a disabled plugin's
|
|
permissions are not offered for new scope grants or role edits (existing
|
|
Permission rows and role links persist - see the get_permissions docstring).
|
|
Pass include_disabled=True to include all installed plugins.
|
|
|
|
Follows the dashboard.py consumer pattern: a broken plugin is re-raised in
|
|
dev/test and isolated (logged) in prod. Returns (name, description,
|
|
category) tuples.
|
|
"""
|
|
from flask import current_app, has_app_context
|
|
|
|
catalog = list(Permission.CORE_PERMISSIONS)
|
|
if not has_app_context():
|
|
return catalog
|
|
pm = current_app.extensions.get('plugin_manager')
|
|
if not pm:
|
|
return catalog
|
|
|
|
for name, plugin in pm.get_all_plugins().items():
|
|
if not include_disabled and not pm.registry.is_enabled(name):
|
|
continue
|
|
try:
|
|
catalog.extend(
|
|
normalize_permission_entries(plugin.get_permissions()))
|
|
except Exception:
|
|
if current_app.config.get('DEBUG') or current_app.config.get('TESTING'):
|
|
raise
|
|
current_app.logger.exception(
|
|
'Plugin %s get_permissions failed', name)
|
|
return catalog
|
|
|
|
|
|
# Core permissions a site MAY grant the guest role. Declared, not derived.
|
|
# Each one has been read against what its routes actually return.
|
|
#
|
|
# Deliberately absent, with the reason, so nobody re-adds them by reflex:
|
|
# settings.view - every setting row, and secret masking is a substring test
|
|
# audit.view - usernames, addresses, and the before/after of every change
|
|
# users.view - gates nothing; list_users is require_role('admin')
|
|
CORE_GUEST_GRANTABLE = {
|
|
# Aggregate counts only; no row-level data reaches the caller.
|
|
'reports.view',
|
|
# Catalogue metadata. Safe only because the bytes moved to
|
|
# applications.download, which is not grantable.
|
|
'applications.view',
|
|
# Assets, and the global search over them. Safe only because search now
|
|
# gates each domain on its own permission: holding this reaches assets and
|
|
# nothing else, where it used to reach the staff directory and the USB,
|
|
# notification and network domains too.
|
|
'assets.view',
|
|
}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Prebuilt user scopes
|
|
# ---------------------------------------------------------------------------
|
|
#
|
|
# Why these exist: before them the only roles were `admin` and `guest`, so a new
|
|
# user was given nothing, held no permissions, and the sidebar correctly hid
|
|
# every link. There was no rung between "runs the site" and "sees nothing".
|
|
#
|
|
# The four scopes, as specified:
|
|
# admin - unchanged. Bypasses every check in haspermission(); NOT seeded
|
|
# here and NOT described by a grant list, because it holds
|
|
# everything by rule rather than by grant.
|
|
# operator - full record access except deletion, which stays admin-only.
|
|
# technician - read-only on records. Cannot create or edit.
|
|
# reporter - reads everything and exports reports. No action capability.
|
|
#
|
|
# DERIVED, not hardcoded, and this is the opposite choice to
|
|
# CORE_GUEST_GRANTABLE above. That set is declared name-by-name because it
|
|
# governs what an ANONYMOUS visitor may reach, where the bar is "could this be
|
|
# public forever" and a wrong answer leaks to the internet. These scopes govern
|
|
# authenticated internal staff, and the catalog is plugin-driven: roughly sixty
|
|
# permissions across fifteen plugins, growing whenever a plugin is added. A
|
|
# hardcoded list would silently omit every future plugin, so a Technician would
|
|
# lose access to new modules by default and the failure would look like a
|
|
# permissions bug rather than a stale list.
|
|
#
|
|
# So scopes are computed from the catalog by verb, minus an explicit exclusion
|
|
# set. Adding a plugin extends the scopes automatically; keeping something OUT
|
|
# of them is the thing that requires a deliberate code change.
|
|
|
|
# Verbs that mutate records. Split by which scope may hold them.
|
|
_EDIT_VERBS = ('create', 'edit', 'restock', 'manage', 'publish')
|
|
_DESTRUCTIVE_VERBS = ('delete', 'purge')
|
|
|
|
# Never granted by ANY prebuilt scope, regardless of verb. Each is either an
|
|
# administrative capability, a machine-to-machine credential, or a payload that
|
|
# a scope-holder should not get merely for being staff.
|
|
SCOPE_NEVER_GRANT = {
|
|
# Administrative surface. A scope is not a way to become an admin.
|
|
'settings.view', 'settings.edit',
|
|
# users.view is deliberately ABSENT: every scope may see who exists, so an
|
|
# operator can tell whether an account is already there before asking an
|
|
# admin to make one. Creating, editing, and deleting accounts stay
|
|
# admin-only, so seeing the directory grants no power over it.
|
|
'users.create', 'users.edit', 'users.delete',
|
|
'audit.view', 'audit.purge',
|
|
'apitokens.create',
|
|
# Service-token permissions: these authorize machines, not people. Granting
|
|
# one to a human scope would let a person impersonate the collector or the
|
|
# GE-Enforce client.
|
|
'collector.ingest',
|
|
'geenforce.fetch',
|
|
'geenforce.report',
|
|
# Bytes, not metadata: SYSTEM-context PowerShell bodies and vendor
|
|
# installers. Deliberately separate from applications.view for exactly this
|
|
# reason (see the CORE_PERMISSIONS comment), so scopes must not undo that.
|
|
'applications.download',
|
|
# The big four endpoint actions. These are per-user direct grants chosen by
|
|
# checkbox in the user editor, NOT role grants - that is the whole point of
|
|
# the Phase A2 split. A scope that granted them would take the choice away
|
|
# from the person creating the account.
|
|
'endpoints.restart',
|
|
'endpoints.runscript',
|
|
'endpoints.updateapp',
|
|
'endpoints.corptools',
|
|
# Fleet-wide and agent-distribution capabilities, admin-only by nature.
|
|
'endpoints.fleet',
|
|
'endpoints.agentpackage',
|
|
'endpoints.agentupdate',
|
|
}
|
|
|
|
# Endpoint actions offered as per-user checkboxes in the user editor. Held here
|
|
# rather than in the endpoints plugin because the USER EDITOR is what needs the
|
|
# list, and core cannot import a plugin. Kept in sync by
|
|
# test_scope_endpoint_actions_match_the_plugin.
|
|
SCOPE_ENDPOINT_ACTIONS = (
|
|
'endpoints.restart',
|
|
'endpoints.runscript',
|
|
'endpoints.updateapp',
|
|
'endpoints.corptools',
|
|
)
|
|
|
|
|
|
def _permission_verb(name):
|
|
"""The verb half of a dotted permission name ('assets.edit' -> 'edit')."""
|
|
return name.rsplit('.', 1)[-1] if '.' in name else ''
|
|
|
|
|
|
def scope_permission_names(scope, catalog=None):
|
|
"""Permission names a prebuilt scope grants, derived from the catalog.
|
|
|
|
Returns a sorted list so seeding and tests are deterministic.
|
|
|
|
reporter - every non-excluded permission whose verb is neither a mutation
|
|
nor a destruction, plus reports.export. The export is a read
|
|
that produces a file, not an action against a machine, and the
|
|
user asked for it by name.
|
|
technician - the same reads. Identical to reporter at ROLE level: the two
|
|
differ by what the user editor offers alongside the role, where
|
|
a technician may be given endpoint action checkboxes and a
|
|
reporter may not.
|
|
operator - the reads plus the editing verbs, still never the destructive
|
|
ones. Deletion stays admin-only, per the user's instruction.
|
|
"""
|
|
if catalog is None:
|
|
catalog = full_permission_catalog()
|
|
names = {entry[0] for entry in normalize_permission_entries(catalog)}
|
|
names -= SCOPE_NEVER_GRANT
|
|
|
|
readable = {
|
|
name for name in names
|
|
if _permission_verb(name) not in _EDIT_VERBS
|
|
and _permission_verb(name) not in _DESTRUCTIVE_VERBS
|
|
}
|
|
if scope in ('reporter', 'technician'):
|
|
return sorted(readable)
|
|
if scope == 'operator':
|
|
return sorted(
|
|
readable | {
|
|
name for name in names
|
|
if _permission_verb(name) in _EDIT_VERBS
|
|
})
|
|
raise ValueError(f'Unknown scope: {scope!r}')
|
|
|
|
|
|
# The seeded scopes, in the order the user editor should offer them. `admin` is
|
|
# absent on purpose: it already exists, is created by `seed admin`, and holds
|
|
# everything by bypass rather than by grant.
|
|
PREBUILT_SCOPES = (
|
|
('operator',
|
|
'Full access to records except deletion, which stays with admins. '
|
|
'Endpoint actions are granted per user by checkbox.',
|
|
'#0D6EFD'),
|
|
('technician',
|
|
'Read-only on records: cannot create, edit, or delete, and cannot author '
|
|
'policy. Endpoint actions are granted per user by checkbox.',
|
|
'#0DCAF0'),
|
|
('reporter',
|
|
'Views everything and exports reports. Holds no action capability and '
|
|
'cannot be granted one.',
|
|
'#6F42C1'),
|
|
)
|
|
|
|
# Scopes that may NOT hold the per-user endpoint action grants, enforced
|
|
# server-side in the user API. Reporter's defining property is that it holds no
|
|
# action capability EVEN when someone tries to grant one directly.
|
|
SCOPES_DENIED_ENDPOINT_ACTIONS = frozenset({'reporter'})
|
|
|
|
|
|
def guest_grantable_permissions():
|
|
"""Which permissions the guest role may be granted.
|
|
|
|
Every entry is DECLARED, by core below or by a plugin through
|
|
get_guest_grantable_permissions(). Nothing qualifies by being spelled a
|
|
particular way.
|
|
|
|
It used to: any name ending `.view` or `.read` was grantable, on the
|
|
reasoning that reading is the safe default. That is true of a permission
|
|
that gates a list of asset numbers and false of one that gates bytes, and
|
|
the suffix cannot tell them apart. `applications.view` reached the
|
|
SYSTEM-context PowerShell bodies and the installer binaries;
|
|
`backups.view` returned the full payload the separate backups.download
|
|
permission exists to protect; `assets.view` gated a global search that
|
|
queries the staff directory. None of those were decided. They were named.
|
|
|
|
So the rule is inverted: a permission is grantable when somebody wrote it
|
|
down, having looked at what it actually serves. Adding one is a code
|
|
change, which is the point - it puts the decision in a diff rather than in
|
|
a suffix.
|
|
|
|
Naming one here does not open it. It makes the checkbox available in the
|
|
role grid; a site still has to tick it.
|
|
|
|
The bar, for a read: could an anonymous visitor hold this, forever, and
|
|
would the site be content with everything it returns? For a write, add
|
|
that the act can never be attributed to anybody.
|
|
"""
|
|
from flask import current_app, has_app_context
|
|
|
|
catalog = full_permission_catalog()
|
|
known = {name for name, _, _ in catalog}
|
|
grantable = {name for name in CORE_GUEST_GRANTABLE if name in known}
|
|
|
|
if not has_app_context():
|
|
return grantable
|
|
pm = current_app.extensions.get('plugin_manager')
|
|
if not pm:
|
|
return grantable
|
|
|
|
for name, plugin in pm.get_all_plugins().items():
|
|
if not pm.registry.is_enabled(name):
|
|
continue
|
|
try:
|
|
blessed = plugin.get_guest_grantable_permissions() or []
|
|
except Exception:
|
|
if current_app.config.get('DEBUG') or current_app.config.get('TESTING'):
|
|
raise
|
|
current_app.logger.exception(
|
|
'Plugin %s get_guest_grantable_permissions failed', name)
|
|
continue
|
|
# A plugin may only bless permissions that exist and that it owns the
|
|
# naming of; a typo must not silently widen anything.
|
|
grantable |= {p for p in blessed if p in known}
|
|
return grantable
|
|
|
|
|
|
class Role(BaseModel):
|
|
"""User role model."""
|
|
__tablename__ = 'roles'
|
|
|
|
roleid = db.Column(db.Integer, primary_key=True)
|
|
rolename = db.Column(db.String(50), unique=True, nullable=False)
|
|
description = db.Column(db.Text)
|
|
color = db.Column(db.String(20), comment='CSS color for the role badge')
|
|
|
|
# Permissions relationship
|
|
permissions = db.relationship(
|
|
'Permission',
|
|
secondary=rolepermissions,
|
|
backref=db.backref('roles', lazy='dynamic')
|
|
)
|
|
|
|
def __repr__(self):
|
|
return f"<Role {self.rolename}>"
|
|
|
|
# The role a caller with no account is treated as holding.
|
|
#
|
|
# Guest access used to be a per-feature boolean setting - one for the
|
|
# Secure Send page, one for each kiosk, one proposed for guides - which
|
|
# meant every new question about what a signed-out visitor may see was
|
|
# answered by writing more code. It is a permissions question, and this app
|
|
# already administers permissions per role, so a guest is now simply a role
|
|
# holding no permissions until somebody grants it some.
|
|
GUEST = 'guest'
|
|
|
|
def haspermission(self, permission_name: str) -> bool:
|
|
"""Check if role has a specific permission."""
|
|
# Admin role has all permissions
|
|
if self.rolename == 'admin':
|
|
return True
|
|
return any(p.name == permission_name for p in self.permissions)
|
|
|
|
@classmethod
|
|
def guest(cls):
|
|
"""The guest role, or None on a site that has not been seeded yet."""
|
|
return cls.query.filter_by(rolename=cls.GUEST).first()
|
|
|
|
@classmethod
|
|
def seedguest(cls):
|
|
"""Create the guest role if it is missing. Returns True if created.
|
|
|
|
Seeded with NO permissions, which is the same behaviour every site has
|
|
today: an unauthenticated request is refused. What a guest may do is a
|
|
decision each site makes in the role grid, not one it inherits from an
|
|
upgrade.
|
|
"""
|
|
if cls.query.filter_by(rolename=cls.GUEST).first() is not None:
|
|
return False
|
|
db.session.add(cls(
|
|
rolename=cls.GUEST,
|
|
description=('Anyone who is not signed in. Holds nothing by '
|
|
'default; grant it a permission to open that up to '
|
|
'people with no account.'),
|
|
color='#6C757D',
|
|
))
|
|
return True
|
|
|
|
@classmethod
|
|
def seedscopes(cls):
|
|
"""Create the prebuilt scope roles and sync their grants.
|
|
|
|
Returns {'created': [rolename...], 'granted': {rolename: n}}.
|
|
|
|
Idempotent, and ADDITIVE on re-run. A second run creates nothing and
|
|
adds only grants the role is missing; it never REMOVES a permission from
|
|
an existing role.
|
|
|
|
That asymmetry is deliberate. Re-running has to add, because the grant
|
|
lists are derived from a plugin-driven catalog: install a plugin, re-run
|
|
the seed, and Technicians should gain read access to the new module
|
|
without anyone editing a list. But it must not remove, because the role
|
|
grid is an administrative surface and a site may have deliberately given
|
|
Operator something extra. A revoking seed would silently undo that
|
|
decision on the next deploy, which is a worse failure than a role
|
|
holding one grant more than the default - the first is invisible, the
|
|
second is on screen in the role editor.
|
|
|
|
Consequence worth stating plainly: this cannot be used to TIGHTEN a
|
|
scope after the fact. If a permission is ever added to
|
|
SCOPE_NEVER_GRANT, roles already holding it keep it, and revoking is a
|
|
separate deliberate migration.
|
|
"""
|
|
catalog = full_permission_catalog()
|
|
result = {'created': [], 'granted': {}}
|
|
|
|
for rolename, description, color in PREBUILT_SCOPES:
|
|
role = cls.query.filter_by(rolename=rolename).first()
|
|
if role is None:
|
|
role = cls(rolename=rolename, description=description,
|
|
color=color)
|
|
db.session.add(role)
|
|
db.session.flush()
|
|
result['created'].append(rolename)
|
|
|
|
wanted = set(scope_permission_names(rolename, catalog=catalog))
|
|
held = {p.name for p in role.permissions}
|
|
missing = wanted - held
|
|
if not missing:
|
|
continue
|
|
|
|
# Only link permissions that actually exist as rows. A name in the
|
|
# catalog with no Permission row means `seed permissions` has not
|
|
# run for that plugin yet; the next run picks it up.
|
|
rows = Permission.query.filter(Permission.name.in_(missing)).all()
|
|
for permission in rows:
|
|
role.permissions.append(permission)
|
|
if rows:
|
|
result['granted'][rolename] = len(rows)
|
|
|
|
return result
|
|
|
|
def getpermissionnames(self) -> list:
|
|
"""Get list of permission names."""
|
|
if self.rolename == 'admin':
|
|
return [p[0] for p in full_permission_catalog()]
|
|
return [p.name for p in self.permissions]
|
|
|
|
|
|
class User(BaseModel):
|
|
"""User model for authentication."""
|
|
__tablename__ = 'users'
|
|
|
|
userid = db.Column(db.Integer, primary_key=True)
|
|
username = db.Column(db.String(100), unique=True, nullable=False, index=True)
|
|
email = db.Column(db.String(255), unique=True, nullable=False)
|
|
passwordhash = db.Column(db.String(255), nullable=False)
|
|
|
|
# Profile
|
|
firstname = db.Column(db.String(100))
|
|
lastname = db.Column(db.String(100))
|
|
|
|
# Status
|
|
lastlogindate = db.Column(db.DateTime)
|
|
failedlogins = db.Column(db.Integer, default=0)
|
|
lockeduntil = db.Column(db.DateTime)
|
|
# Forced password change: set true when an admin creates the account, so the
|
|
# user is steered through a password change before landing in the app.
|
|
mustchangepassword = db.Column(db.Boolean, default=False, nullable=False)
|
|
|
|
# Relationships
|
|
roles = db.relationship(
|
|
'Role',
|
|
secondary=userroles,
|
|
backref=db.backref('users', lazy='dynamic')
|
|
)
|
|
|
|
# Permissions granted to this user directly, outside any role. See the
|
|
# userpermissions table comment for why these exist and what must fold them.
|
|
directpermissions = db.relationship(
|
|
'Permission',
|
|
secondary=userpermissions,
|
|
lazy='joined'
|
|
)
|
|
|
|
def __repr__(self):
|
|
return f"<User {self.username}>"
|
|
|
|
@property
|
|
def islocked(self):
|
|
"""Check if account is locked."""
|
|
if self.lockeduntil:
|
|
return datetime.now(timezone.utc).replace(tzinfo=None) < self.lockeduntil
|
|
return False
|
|
|
|
def hasrole(self, rolename: str) -> bool:
|
|
"""Check if user has a specific role."""
|
|
return any(r.rolename == rolename for r in self.roles)
|
|
|
|
def haspermission(self, permission_name: str) -> bool:
|
|
"""Check if user has a permission, through any role or directly.
|
|
|
|
A direct grant is not a lesser kind of permission: it is honoured here
|
|
exactly like a role grant, which is what keeps the API token scope
|
|
ceiling correct without any change to the ceiling itself. Both ceiling
|
|
checks (mint time in core/api/apitokens.py and per-request in
|
|
utils/authz.py) call this method.
|
|
"""
|
|
# Admin role has all permissions
|
|
if self.hasrole('admin'):
|
|
return True
|
|
if any(p.name == permission_name for p in self.directpermissions):
|
|
return True
|
|
return any(r.haspermission(permission_name) for r in self.roles)
|
|
|
|
def getdirectpermissionnames(self) -> list:
|
|
"""Permission names granted to this user directly, ignoring roles.
|
|
|
|
The user editor needs the DIRECT grants alone so a checkbox reflects
|
|
what is stored on the user rather than what a role happens to supply;
|
|
getpermissions() deliberately cannot answer that because it folds both.
|
|
"""
|
|
return sorted(p.name for p in self.directpermissions)
|
|
|
|
def getpermissions(self) -> list:
|
|
"""Get list of all permission names, from roles and direct grants.
|
|
|
|
This is the LIST surface: it feeds JWT claims and the frontend
|
|
authStore. It must agree with haspermission(), the predicate surface, or
|
|
the UI hides controls the server would allow (or worse, shows ones it
|
|
would refuse).
|
|
"""
|
|
if self.hasrole('admin'):
|
|
return [p[0] for p in full_permission_catalog()]
|
|
|
|
perms = set()
|
|
for role in self.roles:
|
|
perms.update(role.getpermissionnames())
|
|
perms.update(p.name for p in self.directpermissions)
|
|
return list(perms)
|