guest role; guide section ticking

This commit is contained in:
2026-08-27 13:02:35 -04:00
parent d38a599292
commit 4da6c6aa36
45 changed files with 830 additions and 243 deletions

View File

@@ -12,6 +12,46 @@ ADR-007 and ADR-002.
### Added
- **A guide's sections can be ticked off while you read it.** Only checklist
items were tickable, which answered "what have I done" but not the question a
long procedure actually raises - where was I. Somebody looks away to do the
thing the guide asked for and looks back at a wall of text. Every step and
every heading now carries a checkbox in the reader; ticking one strikes it
through and fades it rather than hiding it, because scanning back up the page
has to still show what was done. Headings count as well as steps: a guide
converted from an HTML article often has fifty headings and no steps at all.
Progress is per browser and per version, as it already was for checklists -
shopfloor PCs share a login, so one technician's ticks must not greet the
next person on that bay.
- **A guest is a role now, not a switch per feature.** Whether somebody with no
account may see something was answered one feature at a time: a
`securesend_allow_guests` setting, an enable flag per kiosk, and very nearly a
third for guides - each with its own settings page and its own hand-written
branch inside a route. It is a permissions question, and this app already
administers permissions per role, so anyone not signed in now holds the
seeded `guest` role. It starts with nothing, so an upgrade opens no door; a
site opens one by ticking a box in the same role grid it uses for everybody
else, and closes it the same way - taking effect on the next request, not the
next restart. `require_permission` consults the role when there is no token,
which is the whole mechanism.
What a guest may be granted is bounded: any `.view` or `.read` permission,
plus writes a plugin has explicitly declared safe to perform without an
account (`get_guest_grantable_permissions`, contract 0.21.0). Secure Send
declares its create permission, because sending a password to a vendor is the
one write the product means to offer somebody who never signs in. Everything
else is refused by the API and greyed out in the grid rather than warned
about. A guest write records no creator - the audit trail can say when and
from where, never who - and that is the reason for the bar.
GE-Enforce and Slides gained read permissions (`geenforce.view`,
`slides.view`) so they can be opened to guests without handing out the manage
right; their read routes accept either, so nothing an existing manager could
reach has moved. The navigation endpoint now returns only what the caller can
actually reach, so a signed-out visitor sees the pages that were opened to
them rather than a sidebar of links that bounce off a login page.
- **USB check-in / check-out audit report.** CMMC removable-media tracking is an
audit obligation and there was no report for it - answering "who had this
drive, and when" meant paging through the check-in/out list by hand. The

View File

@@ -11,7 +11,9 @@
</div>
</div>
<div class="sidebar-search">
<!-- Global search is authenticated; offering the box to a signed-out
reader gives them a control that can only answer 401. -->
<div v-if="authStore.isAuthenticated" class="sidebar-search">
<input
v-model="searchQuery"
type="text"
@@ -222,8 +224,23 @@ function buildNavItems(items) {
// Drop items the user cannot reach: a nav item may carry a `permission`
// (e.g. Slides -> slides.manage); hide it from anyone who lacks it so the
// link does not dead-end at the router guard. Admins hold every permission.
const visible = items.filter(item =>
!item.permission || authStore.hasPermission(item.permission))
//
// A signed-out visitor sees only what a plugin has declared guest-reachable.
// Without this the sidebar offers a signed-out reader the whole app and every
// link bounces them to the login page, which reads as a broken site rather
// than as a closed door.
// A nav item may name one permission or several; holding ANY of them is
// enough. GE-Enforce and Slides need that: the page is reachable by a
// manager and by a plain viewer, and they hold different strings.
const holds = item => {
if (!item.permission) return true
const names = Array.isArray(item.permission) ? item.permission : [item.permission]
return names.some(name => authStore.hasPermission(name))
}
// A signed-out visitor gets whatever the server sent, which is already
// filtered to what the guest role can reach - hasPermission knows nothing
// about guests, so asking it here would hide everything.
const visible = authStore.isAuthenticated ? items.filter(holds) : items
const known = new Set(NAV_SECTIONS.map(s => s.key).filter(Boolean))
const bucket = item => {

View File

@@ -225,6 +225,17 @@
<p class="text-muted" style="font-size: 0.85rem; margin: 0 0 0.5rem 0">
Select which actions this role can perform
</p>
<!-- The guest role is everyone who is not signed in, so what it may
hold is bounded: reads, plus the few writes a plugin has
declared safe to do anonymously. The rest are disabled here
rather than refused on save, so the limit is visible while the
decision is being made. -->
<p v-if="editingRole?.isguest" class="guest-note">
This role is <strong>everyone who is not signed in</strong>.
Anything ticked here is readable by anybody who can reach this
site, with no account and no name in the audit log. Greyed-out
permissions cannot be given to guests at all.
</p>
<div class="permissions-grid">
<div v-for="(perms, category) in permissionsGrouped" :key="category" class="permission-category">
<div class="category-header">
@@ -239,10 +250,14 @@
</label>
</div>
<div class="category-perms">
<label v-for="p in perms" :key="p.name" class="checkbox-label perm-item">
<label v-for="p in perms" :key="p.name" class="checkbox-label perm-item"
:class="{ 'perm-blocked': !mayGrant(p.name) }"
:title="mayGrant(p.name) ? null
: 'A guest cannot be given this. Reading is grantable; a write has to be declared safe to do without an account.'">
<input
type="checkbox"
:value="p.name"
:disabled="!mayGrant(p.name)"
v-model="roleForm.permissions"
>
{{ p.description }}
@@ -382,19 +397,33 @@ function formatCategory(cat) {
return cat.charAt(0).toUpperCase() + cat.slice(1)
}
// Which permissions this role is allowed to hold at all. Only the guest role
// is bounded; the API sends the list it will accept, so the grid and the server
// cannot disagree about it.
function mayGrant(name) {
if (!editingRole.value?.isguest) return true
const grantable = editingRole.value?.grantable
return Array.isArray(grantable) ? grantable.includes(name) : false
}
function isCategoryFullySelected(category) {
const catPerms = permissionsGrouped.value[category] || []
const catPerms = (permissionsGrouped.value[category] || [])
.filter(p => mayGrant(p.name))
return catPerms.length > 0 && catPerms.every(p => roleForm.permissions.includes(p.name))
}
function isCategoryPartiallySelected(category) {
const catPerms = permissionsGrouped.value[category] || []
const catPerms = (permissionsGrouped.value[category] || [])
.filter(p => mayGrant(p.name))
const selected = catPerms.filter(p => roleForm.permissions.includes(p.name))
return selected.length > 0 && selected.length < catPerms.length
}
function toggleCategory(category, checked) {
const catPerms = permissionsGrouped.value[category] || []
// Ticking a whole category must not try to grant a guest something the API
// will refuse - the header checkbox would then look broken.
const catPerms = (permissionsGrouped.value[category] || [])
.filter(p => mayGrant(p.name))
const permNames = catPerms.map(p => p.name)
if (checked) {
@@ -780,4 +809,13 @@ onMounted(loadData)
font-size: 0.85rem;
padding: 0.25rem 0;
}
.perm-blocked { opacity: 0.45; cursor: not-allowed; }
.guest-note {
font-size: 0.85rem;
color: var(--warning);
border-left: 3px solid var(--warning);
padding-left: 0.6rem;
margin: 0 0 0.75rem;
}
</style>

View File

@@ -77,7 +77,6 @@ def _summary(revision, islatest=False):
@backups_bp.route('/kinds', methods=['GET'])
@jwt_required()
@require_permission('backups.view')
def list_kinds():
"""Registered backup kinds, for UI that needs to enumerate them."""
@@ -94,7 +93,6 @@ def list_kinds():
@backups_bp.route('/asset/<int:assetid>', methods=['GET'])
@jwt_required()
@require_permission('backups.view')
def asset_revisions(assetid):
"""Revision history for one asset, newest first.
@@ -130,7 +128,6 @@ def asset_revisions(assetid):
@backups_bp.route('/asset/<int:assetid>/info', methods=['GET'])
@jwt_required()
@require_permission('backups.view')
def asset_info(assetid):
"""A kind's 'at a glance' card, built from its LATEST revision.
@@ -190,7 +187,6 @@ def asset_info(assetid):
@backups_bp.route('/revisions/<int:backuprevisionid>', methods=['GET'])
@jwt_required()
@require_permission('backups.view')
def get_revision(backuprevisionid):
"""One revision, including its parsed payload where there is one."""
@@ -207,7 +203,6 @@ def get_revision(backuprevisionid):
@backups_bp.route('/revisions/<int:backuprevisionid>/download', methods=['GET'])
@jwt_required()
@require_permission('backups.download')
def download_revision(backuprevisionid):
"""Render a revision back to its native file format.
@@ -282,7 +277,6 @@ def download_revision(backuprevisionid):
@backups_bp.route('/revisions/<int:backuprevisionid>/diff', methods=['GET'])
@jwt_required()
@require_permission('backups.view')
def diff_revision(backuprevisionid):
"""Diff two revisions of the same asset+kind.
@@ -372,7 +366,6 @@ def _diffprojections(old, new):
@backups_bp.route('/dashboard/stale', methods=['GET'])
@jwt_required()
@require_permission('backups.view')
def dashboard_stale():
"""Chains whose backup has stopped running.

View File

@@ -55,7 +55,6 @@ def get_computer_type(type_id: int):
@computers_bp.route('/types', methods=['POST'])
@jwt_required()
@require_permission('computers.create')
def create_computer_type():
"""Create a new computer type."""
@@ -93,7 +92,6 @@ def create_computer_type():
@computers_bp.route('/types/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_permission('computers.edit')
def update_computer_type(type_id: int):
"""Update a computer type."""
@@ -127,7 +125,6 @@ def update_computer_type(type_id: int):
@computers_bp.route('/types/<int:type_id>', methods=['DELETE'])
@jwt_required()
@require_permission('computers.delete')
def delete_computer_type(type_id: int):
"""Delete a computer type. Refused if any PC still uses it."""
@@ -159,7 +156,6 @@ def list_protocols():
@computers_bp.route('/protocols', methods=['POST'])
@jwt_required()
@require_permission('computers.edit')
def create_protocol():
data = request.get_json() or {}
@@ -180,7 +176,6 @@ def create_protocol():
@computers_bp.route('/protocols/<int:protocol_id>', methods=['PUT', 'PATCH'])
@jwt_required()
@require_permission('computers.edit')
def update_protocol(protocol_id):
p = db.session.get(AccessProtocol, protocol_id)
@@ -199,7 +194,6 @@ def update_protocol(protocol_id):
@computers_bp.route('/protocols/<int:protocol_id>', methods=['DELETE'])
@jwt_required()
@require_permission('computers.edit')
def delete_protocol(protocol_id):
p = db.session.get(AccessProtocol, protocol_id)
@@ -505,7 +499,6 @@ def get_computer_by_hostname(hostname: str):
@computers_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('computers.create')
def create_computer():
"""
@@ -620,7 +613,6 @@ def create_computer():
@computers_bp.route('/<int:computer_id>', methods=['PUT'])
@jwt_required()
@require_permission('computers.edit')
def update_computer(computer_id: int):
"""Update computer (both Asset and Computer records)."""
@@ -732,7 +724,6 @@ def update_computer(computer_id: int):
@computers_bp.route('/<int:computer_id>', methods=['DELETE'])
@jwt_required()
@require_permission('computers.delete')
def delete_computer(computer_id: int):
"""Delete (soft delete) computer."""
@@ -785,7 +776,6 @@ def get_installed_apps(computer_id: int):
@computers_bp.route('/<int:computer_id>/apps', methods=['POST'])
@jwt_required()
@require_permission('computers.create')
def add_installed_app(computer_id: int):
"""Add an installed application to a computer."""
@@ -842,7 +832,6 @@ def add_installed_app(computer_id: int):
@computers_bp.route('/<int:computer_id>/apps/<int:app_id>', methods=['DELETE'])
@jwt_required()
@require_permission('computers.delete')
def remove_installed_app(computer_id: int, app_id: int):
"""Remove an installed application from a computer."""
@@ -870,7 +859,6 @@ def remove_installed_app(computer_id: int, app_id: int):
# =============================================================================
@computers_bp.route('/<int:computer_id>/report', methods=['POST'])
@jwt_required()
@require_permission('computers.create')
def report_status(computer_id: int):
"""
@@ -954,7 +942,6 @@ def dashboard_summary():
@computers_bp.route('/dashboard/quiet', methods=['GET'])
@jwt_required()
@require_permission('computers.view')
def dashboard_quiet():
"""PCs that WERE reporting, have stopped, and are still meant to be in use.
@@ -1008,7 +995,6 @@ def dashboard_quiet():
@computers_bp.route('/dashboard/sharedmachines', methods=['GET'])
@jwt_required()
@require_permission('computers.view')
def dashboard_sharedmachines():
"""Machine numbers claimed by more than one PC, with nothing filed under

View File

@@ -20,6 +20,7 @@ from sqlalchemy.exc import IntegrityError
from shopdb.api import (
db, cache, success_response, error_response, ErrorCodes, require_permission,
require_any_permission,
authorized_service_token, Setting, Application,
)
@@ -338,8 +339,7 @@ def post_report():
# -- admin read surface (P2 adds full CRUD + publish) -------------------------
@geenforce_bp.route('/scopes', methods=['GET'])
@jwt_required()
@require_permission('geenforce.manage')
@require_any_permission('geenforce.view', 'geenforce.manage')
def list_scopes():
"""List imaging PC-type scopes with entry + published-version counts."""
scopes = ManifestScope.query.order_by(
@@ -364,8 +364,7 @@ def list_scopes():
@geenforce_bp.route('/scopes/<int:scopeid>/preview', methods=['GET'])
@jwt_required()
@require_permission('geenforce.manage')
@require_any_permission('geenforce.view', 'geenforce.manage')
def preview_scope(scopeid):
"""Render the DRAFT manifest JSON a publish would freeze (review before ship)."""
scope = db.session.get(ManifestScope, scopeid)
@@ -377,8 +376,7 @@ def preview_scope(scopeid):
@geenforce_bp.route('/applications', methods=['GET'])
@jwt_required()
@require_permission('geenforce.manage')
@require_any_permission('geenforce.view', 'geenforce.manage')
def list_applications():
"""The core Applications catalog (id + name) for the curated entry->app link
picker in the entry editor."""
@@ -446,7 +444,6 @@ def _apply_app_link(entry, payload):
@geenforce_bp.route('/scopes', methods=['POST'])
@jwt_required()
@require_permission('geenforce.manage')
def create_scope():
payload = request.get_json(silent=True) or {}
@@ -475,8 +472,7 @@ def create_scope():
@geenforce_bp.route('/scopes/<int:scopeid>', methods=['GET'])
@jwt_required()
@require_permission('geenforce.manage')
@require_any_permission('geenforce.view', 'geenforce.manage')
def get_scope(scopeid):
scope = db.session.get(ManifestScope, scopeid)
if not scope:
@@ -487,7 +483,6 @@ def get_scope(scopeid):
@geenforce_bp.route('/scopes/<int:scopeid>', methods=['PUT'])
@jwt_required()
@require_permission('geenforce.manage')
def update_scope(scopeid):
scope = db.session.get(ManifestScope, scopeid)
@@ -510,7 +505,6 @@ def update_scope(scopeid):
@geenforce_bp.route('/scopes/<int:scopeid>', methods=['DELETE'])
@jwt_required()
@require_permission('geenforce.manage')
def delete_scope(scopeid):
scope = db.session.get(ManifestScope, scopeid)
@@ -533,7 +527,6 @@ def _validate_entry(payload):
@geenforce_bp.route('/scopes/<int:scopeid>/entries', methods=['POST'])
@jwt_required()
@require_permission('geenforce.manage')
def create_entry(scopeid):
scope = db.session.get(ManifestScope, scopeid)
@@ -558,7 +551,6 @@ def create_entry(scopeid):
@geenforce_bp.route('/entries/<int:entryid>', methods=['PUT'])
@jwt_required()
@require_permission('geenforce.manage')
def update_entry(entryid):
entry = db.session.get(ManifestEntry, entryid)
@@ -587,7 +579,6 @@ def update_entry(entryid):
@geenforce_bp.route('/entries/<int:entryid>', methods=['DELETE'])
@jwt_required()
@require_permission('geenforce.manage')
def delete_entry(entryid):
entry = db.session.get(ManifestEntry, entryid)
@@ -599,7 +590,6 @@ def delete_entry(entryid):
@geenforce_bp.route('/scopes/<int:scopeid>/entries/reorder', methods=['PUT'])
@jwt_required()
@require_permission('geenforce.manage')
def reorder_entries(scopeid):
"""Set entry order from a list of entryids (the ordering contract)."""
@@ -621,8 +611,7 @@ def reorder_entries(scopeid):
# -- simulate: "what would this PC get" ---------------------------------------
@geenforce_bp.route('/scopes/<int:scopeid>/simulate', methods=['GET'])
@jwt_required()
@require_permission('geenforce.manage')
@require_any_permission('geenforce.view', 'geenforce.manage')
def simulate_scope(scopeid):
"""Which draft entries apply to a given machine profile, and why the rest
are filtered out (reuses the engine-mirror filters)."""
@@ -662,8 +651,7 @@ def simulate_scope(scopeid):
# -- compliance: "how much of the fleet has this app" -------------------------
@geenforce_bp.route('/scopes/<int:scopeid>/compliance', methods=['GET'])
@jwt_required()
@require_permission('geenforce.manage')
@require_any_permission('geenforce.view', 'geenforce.manage')
def scope_compliance(scopeid):
"""Fleet-install coverage per app-linked entry (from collected PC data).
@@ -684,7 +672,6 @@ PAYLOAD_MAX_BYTES = 1024 * 1024
@geenforce_bp.route('/entries/<int:entryid>/payload', methods=['POST'])
@jwt_required()
@require_permission('geenforce.publish')
def upload_entry_payload(entryid):
"""Store an inline payload (<= 1 MB) for an entry and point the entry at it."""
@@ -709,8 +696,7 @@ def upload_entry_payload(entryid):
@geenforce_bp.route('/entries/<int:entryid>/payload', methods=['GET'])
@jwt_required()
@require_permission('geenforce.manage')
@require_any_permission('geenforce.view', 'geenforce.manage')
def download_entry_payload(entryid):
"""Return the stored inline payload bytes for an entry (404 if none)."""
entry = db.session.get(ManifestEntry, entryid)
@@ -730,7 +716,6 @@ def download_entry_payload(entryid):
# -- publish lifecycle (geenforce.publish) ------------------------------------
@geenforce_bp.route('/scopes/<int:scopeid>/publish', methods=['POST'])
@jwt_required()
@require_permission('geenforce.publish')
def publish_scope_route(scopeid):
scope = db.session.get(ManifestScope, scopeid)
@@ -759,8 +744,7 @@ def publish_scope_route(scopeid):
@geenforce_bp.route('/scopes/<int:scopeid>/publish-preflight', methods=['GET'])
@jwt_required()
@require_permission('geenforce.manage')
@require_any_permission('geenforce.view', 'geenforce.manage')
def publish_preflight(scopeid):
"""Would publishing this scope outrun the fleet's enforcer lib?
@@ -781,8 +765,7 @@ def publish_preflight(scopeid):
@geenforce_bp.route('/scopes/<int:scopeid>/versions', methods=['GET'])
@jwt_required()
@require_permission('geenforce.manage')
@require_any_permission('geenforce.view', 'geenforce.manage')
def list_versions(scopeid):
scope = db.session.get(ManifestScope, scopeid)
if not scope:
@@ -801,8 +784,7 @@ def list_versions(scopeid):
@geenforce_bp.route('/scopes/<int:scopeid>/versions/<int:versionnumber>',
methods=['GET'])
@jwt_required()
@require_permission('geenforce.manage')
@require_any_permission('geenforce.view', 'geenforce.manage')
def get_version(scopeid, versionnumber):
version = ManifestPublishedVersion.query.filter_by(
scopeid=scopeid, versionnumber=versionnumber).first()
@@ -830,8 +812,7 @@ def _normalize_cidrs(raw):
@geenforce_bp.route('/config', methods=['GET'])
@jwt_required()
@require_permission('geenforce.manage')
@require_any_permission('geenforce.view', 'geenforce.manage')
def get_config():
"""Plugin config: the on-share export root + the client IP allowlist."""
shareroot = Setting.query.filter_by(key=SHAREROOT_SETTING).first()
@@ -843,7 +824,6 @@ def get_config():
@geenforce_bp.route('/config', methods=['PUT'])
@jwt_required()
@require_permission('geenforce.publish')
def put_config():
payload = request.get_json(silent=True) or {}
@@ -870,7 +850,6 @@ def put_config():
@geenforce_bp.route('/scopes/<int:scopeid>/export-share', methods=['POST'])
@jwt_required()
@require_permission('geenforce.publish')
def export_share_route(scopeid):
"""Write the scope's current published JSON to the configured share root
@@ -892,7 +871,6 @@ def export_share_route(scopeid):
@geenforce_bp.route('/scopes/<int:scopeid>/rollback', methods=['POST'])
@jwt_required()
@require_permission('geenforce.publish')
def rollback_scope_route(scopeid):
scope = db.session.get(ManifestScope, scopeid)
@@ -1221,8 +1199,7 @@ def _report_stale_cutoff():
@geenforce_bp.route('/reports', methods=['GET'])
@jwt_required()
@require_permission('geenforce.manage')
@require_any_permission('geenforce.view', 'geenforce.manage')
def list_reports():
"""Latest enforcement report per PC (fleet compliance view).
@@ -1328,8 +1305,7 @@ def list_reports():
@geenforce_bp.route('/reports/<int:reportid>', methods=['GET'])
@jwt_required()
@require_permission('geenforce.manage')
@require_any_permission('geenforce.view', 'geenforce.manage')
def get_report(reportid):
"""One report with per-entry outcomes (self-heal / failure detail)."""
report = db.session.get(ManifestEnforcementReport, reportid)
@@ -1358,8 +1334,7 @@ def get_report(reportid):
@geenforce_bp.route('/dashboard/failures', methods=['GET'])
@jwt_required()
@require_permission('geenforce.manage')
@require_any_permission('geenforce.view', 'geenforce.manage')
def dashboard_failures():
"""Entries that FAILED on their PC's most recent enforcement cycle.

View File

@@ -106,6 +106,8 @@ class GeEnforcePlugin(BasePlugin):
def get_permissions(self) -> List:
"""RBAC permissions this plugin owns (edit vs ship are split)."""
return [
('geenforce.view', 'View imaging PC types and manifests',
'geenforce'),
('geenforce.manage', 'Edit imaging PC types and manifest drafts',
'geenforce'),
('geenforce.publish', 'Publish, roll back, and export manifests',
@@ -125,6 +127,9 @@ class GeEnforcePlugin(BasePlugin):
'icon': 'shield',
'route': '/geenforce/manifests',
'position': 46,
# The READ permission: managing implies it, and it is the one a
# site can hand to guests.
'permission': ['geenforce.view', 'geenforce.manage'],
'section': 'fleet',
},
]

View File

@@ -14,7 +14,7 @@ from datetime import datetime
import json
import re
from flask import Blueprint, request, Response
from flask import Blueprint, request, Response, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity, current_user
from shopdb.api import (
@@ -42,9 +42,25 @@ ALLOWEDIMAGETYPES = {
}
def _currentuser():
"""The signed-in user, or None.
`current_user` is a LocalProxy, so `current_user is not None` is True even
when nobody is signed in - the proxy exists, the user behind it does not.
Under a required JWT that never showed; the read routes are jwt-optional
now, and the first guest request found it by way of
"'NoneType' object has no attribute 'haspermission'".
"""
try:
return current_user._get_current_object()
except Exception:
return None
def _userid():
if current_user is not None:
return current_user.userid
user = _currentuser()
if user is not None:
return user.userid
try:
return int(get_jwt_identity())
except (TypeError, ValueError):
@@ -59,8 +75,12 @@ def _has(permission):
the decorator makes, including the admin bypass that lives inside
haspermission.
"""
return bool(current_user is not None
and current_user.haspermission(permission))
user = _currentuser()
return bool(user is not None and user.haspermission(permission))
def _signedin():
return _currentuser() is not None
def _mayedit(guide):
@@ -101,7 +121,6 @@ def _slugify(title, guideid=None):
# ---------------------------------------------------------------- reading ---
@guides_bp.route('', methods=['GET'])
@jwt_required()
@require_permission('guides.view')
def list_guides():
"""Published guides, plus the caller's own drafts if they can author.
@@ -109,9 +128,15 @@ def list_guides():
A half-written procedure on a shop floor is worse than no procedure, so
drafts are invisible to readers - but an author must be able to find their
own, or drafting is a trap door.
A guest reaches this only if the guest role has been granted guides.view.
A guest is never an author, so the draft branches below cannot open for one.
"""
caneditall = _has('guides.edit')
mine = _userid()
# A guest has no user id, and `createdby == None` is a real match in SQL
# against every guide imported without an author. Their drafts are not
# theirs; nobody's are.
mine = _userid() if _signedin() else -1
# Match against the PUBLISHED text for anything the caller is only allowed
# to read, and against the working copy only for guides they may edit.
@@ -185,7 +210,6 @@ def list_guides():
@guides_bp.route('/tags', methods=['GET'])
@jwt_required()
@require_permission('guides.view')
def list_tags():
"""Every tag in use, with a count, for the filter chips.
@@ -215,7 +239,6 @@ def list_tags():
@guides_bp.route('/<slug>', methods=['GET'])
@jwt_required()
@require_permission('guides.view')
def read_guide(slug):
"""What a reader gets: the published revision.
@@ -257,7 +280,6 @@ def read_guide(slug):
@guides_bp.route('/<int:guideid>/working', methods=['GET'])
@jwt_required()
@require_permission('guides.view')
def read_working(guideid):
"""The working copy, for the editor."""
@@ -275,7 +297,6 @@ def read_working(guideid):
@guides_bp.route('/<int:guideid>/revisions', methods=['GET'])
@jwt_required()
@require_permission('guides.view')
def list_revisions(guideid):
guide = db.session.get(Guide, guideid)
@@ -298,7 +319,6 @@ def list_revisions(guideid):
@guides_bp.route('/revisions/<int:revisionid>', methods=['GET'])
@jwt_required()
@require_permission('guides.view')
def read_revision(revisionid):
"""One revision by id.
@@ -327,8 +347,40 @@ def read_revision(revisionid):
# ---------------------------------------------------------------- writing ---
def _attachimages(guide, blocks):
"""Attach the images this guide's blocks reference but nothing owns yet.
An image pasted into a guide that has not been saved is uploaded with no
guideid - there is no id to give it. The upload route says the editor
attaches it on save, and the editor never did: it only sends a guideid when
the guide already has one. So a screenshot pasted while writing a NEW guide
stayed unattached forever.
An unattached image is visible to editors and to whoever uploaded it, and
to nobody else - so the guide looked right to the person who wrote it and
showed "Image unavailable" to every reader. Attaching on save is what makes
the image belong to the guide, and therefore readable by anyone allowed to
read the guide once it is published.
Only images nothing else owns are claimed: an image already attached to
another guide is left alone rather than stolen by whoever references it.
"""
referenced = set()
for block in blocks or []:
if isinstance(block, dict) and block.get('imageid') is not None:
try:
referenced.add(int(block['imageid']))
except (TypeError, ValueError):
continue
if not referenced:
return
(GuideImage.query
.filter(GuideImage.guideimageid.in_(referenced))
.filter(GuideImage.guideid.is_(None))
.update({'guideid': guide.guideid}, synchronize_session=False))
@guides_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('guides.create')
def create_guide():
data = request.get_json(silent=True) or {}
@@ -353,13 +405,15 @@ def create_guide():
db.session.rollback()
return error_response(ErrorCodes.VALIDATION_ERROR, str(exc))
# The first save is exactly when a pasted image has no owner yet.
_attachimages(guide, guide.blocks)
db.session.commit()
return success_response(guide.to_dict(includeblocks=True),
message='Guide created')
@guides_bp.route('/<int:guideid>', methods=['PUT'])
@jwt_required()
@require_permission('guides.view')
def update_guide(guideid):
guide = db.session.get(Guide, guideid)
@@ -387,6 +441,8 @@ def update_guide(guideid):
db.session.rollback()
return error_response(ErrorCodes.VALIDATION_ERROR, str(exc))
_attachimages(guide, guide.blocks)
# The slug is set once, at create, and does NOT follow the title.
#
# _slugify's own docstring says the slug is stored so that renaming cannot
@@ -409,7 +465,6 @@ def update_guide(guideid):
@guides_bp.route('/<int:guideid>/publish', methods=['POST'])
@jwt_required()
@require_permission('guides.publish')
def publish_guide(guideid):
guide = db.session.get(Guide, guideid)
@@ -425,7 +480,6 @@ def publish_guide(guideid):
@guides_bp.route('/<int:guideid>/unpublish', methods=['POST'])
@jwt_required()
@require_permission('guides.publish')
def unpublish_guide(guideid):
guide = db.session.get(Guide, guideid)
@@ -437,7 +491,6 @@ def unpublish_guide(guideid):
@guides_bp.route('/<int:guideid>/restore/<int:revisionid>', methods=['POST'])
@jwt_required()
@require_permission('guides.view')
def restore_revision(guideid, revisionid):
guide = db.session.get(Guide, guideid)
@@ -458,7 +511,6 @@ def restore_revision(guideid, revisionid):
@guides_bp.route('/<int:guideid>', methods=['DELETE'])
@jwt_required()
@require_permission('guides.delete')
def delete_guide(guideid):
guide = db.session.get(Guide, guideid)
@@ -472,7 +524,6 @@ def delete_guide(guideid):
# ----------------------------------------------------------------- images ---
@guides_bp.route('/images', methods=['POST'])
@jwt_required()
@require_permission('guides.create')
def upload_image():
"""Take a pasted or dropped image.
@@ -553,9 +604,16 @@ def _mayseeimage(image):
@guides_bp.route('/images/<int:imageid>', methods=['GET'])
@jwt_required()
@require_permission('guides.view')
def serve_image(imageid):
"""The image itself, under the same rule as the guide that holds it.
A guest who may read a published guide must see its screenshots, or every
image renders as "Image unavailable" and the guide looks broken.
_mayseeimage already answers correctly for somebody holding nothing - it
requires the PUBLISHED revision to reference the image - so a guest needs no
separate branch here.
"""
image = db.session.get(GuideImage, imageid)
if image is None:
return error_response(ErrorCodes.NOT_FOUND, 'Image not found', http_code=404)

View File

@@ -114,6 +114,52 @@ def build_cli():
click.echo(' imported as /guides/{} (draft, revision {})'
.format(guide.slug, guide.revision))
@guides_cli.command('fix-images')
@click.option('--apply/--dry-run', default=False,
help='Write to the database. The default reports only.')
@with_appcontext
def fix_images(apply):
"""Attach images a guide references but nothing owns.
An image pasted into a guide that had not been saved yet was uploaded
with no guideid, and nothing ever attached it. Editors and the uploader
could see it; every other reader got "Image unavailable" on a published
guide. Saving a guide attaches its images now, but a guide nobody edits
again would stay broken, so this repairs what is already stored.
"""
orphans = GuideImage.query.filter(GuideImage.guideid.is_(None)).all()
if not orphans:
click.echo('No unattached images.')
return
wanted = {}
for guide in Guide.query.all():
for block in guide.blocks or []:
if isinstance(block, dict) and block.get('imageid') is not None:
try:
wanted.setdefault(int(block['imageid']), guide)
except (TypeError, ValueError):
continue
fixed = 0
for image in orphans:
guide = wanted.get(image.guideimageid)
if guide is None:
click.echo(' image {} is referenced by no guide - left alone'
.format(image.guideimageid))
continue
click.echo(' image {} -> guide {} ({})'.format(
image.guideimageid, guide.guideid, guide.slug))
if apply:
image.guideid = guide.guideid
fixed += 1
if not apply:
click.echo('{} would be attached. Pass --apply to write.'.format(fixed))
return
db.session.commit()
click.echo('{} image(s) attached.'.format(fixed))
@guides_cli.command('export')
@click.option('--out', 'outdir', required=True,
type=click.Path(file_okay=False),

View File

@@ -2,14 +2,36 @@
<div class="gb-blocks" :class="{ 'gb-interactive': interactive }">
<template v-for="(block, index) in blocks" :key="block.id || index">
<!--
A heading and a step can be ticked off while reading, not just a
checklist item. On a long procedure the question is not "what have I
done" so much as "where was I" - somebody looks away to do the thing
the guide asked for, and looks back at a wall of text. A struck-through
section is where they were.
Reading only: in the editor a tick would be an edit.
-->
<h2 v-if="block.type === 'heading'" :id="anchorFor(block)" class="gb-heading"
v-html="inline(block.text)"></h2>
:class="{ 'gb-sectiondone': isTicked(block.id) }">
<input v-if="interactive" type="checkbox" class="gb-sectiontick"
:checked="isTicked(block.id)"
:aria-label="'Mark this section done'"
@change="toggle(block.id, $event.target.checked)">
<span v-html="inline(block.text)"></span>
</h2>
<p v-else-if="block.type === 'paragraph'" class="gb-para"
v-html="inline(block.text)"></p>
<div v-else-if="block.type === 'step'" class="gb-step">
<span class="gb-stepnum">Step {{ stepNumber(index) }}</span>
<div v-else-if="block.type === 'step'" class="gb-step"
:class="{ 'gb-sectiondone': isTicked(block.id) }">
<label class="gb-stepnum">
<input v-if="interactive" type="checkbox" class="gb-sectiontick"
:checked="isTicked(block.id)"
:aria-label="'Mark step ' + stepNumber(index) + ' done'"
@change="toggle(block.id, $event.target.checked)">
Step {{ stepNumber(index) }}
</label>
<h3 v-if="block.title" v-html="inline(block.title)"></h3>
<div v-if="block.text" v-html="inline(block.text)"></div>
</div>
@@ -193,6 +215,20 @@ function select (block) {
dark mode work with no dark-mode code. */
.gb-blocks { line-height: 1.65; }
.gb-heading { margin: 1.6rem 0 0.6rem; font-size: 1.35rem; color: var(--text); }
/* A ticked section is struck through and faded, not hidden: somebody scanning
back up the page has to be able to read what they already did. */
.gb-sectiondone { text-decoration: line-through; opacity: 0.55; }
.gb-sectiondone .gb-stepnum { text-decoration: none; }
.gb-sectiontick {
/* Touch-sized: a guide is read on a shopfloor PC, often with gloves on. */
width: 1.1rem;
height: 1.1rem;
margin-right: 0.5rem;
vertical-align: middle;
cursor: pointer;
}
.gb-heading .gb-sectiontick { text-decoration: none; }
.gb-para { margin: 0 0 0.9rem; color: var(--text); }
.gb-step {

View File

@@ -6,15 +6,20 @@
* checkboxes are live in exactly one of them.
*
* meta.plugin = 'guides' so the ADR-009 router guard redirects when the backend
* plugin is disabled. Every route requires auth because every guides API route
* is behind JWT plus a guides.* permission.
* plugin is disabled.
*
* READING does not require auth; WRITING does. The read routes are gated on
* guides.view, and a signed-out visitor holds whatever the GUEST role has been
* granted - so the role decides, not the router. Sending a guest to /login when
* the site has granted them guides.view would make the grant look broken;
* letting them through when it has not costs one 401 the view already handles.
*/
export default [
{
path: 'guides',
name: 'guides',
component: () => import('./views/GuidesList.vue'),
meta: { requiresAuth: true, plugin: 'guides' }
meta: { plugin: 'guides' }
},
{
path: 'guides/new',
@@ -26,7 +31,7 @@ export default [
path: 'guides/:slug',
name: 'guide-view',
component: () => import('./views/GuideView.vue'),
meta: { requiresAuth: true, plugin: 'guides' }
meta: { plugin: 'guides' }
},
{
path: 'guides/:guideid/edit',

View File

@@ -122,10 +122,14 @@ function resetProgress () {
saveProgress()
}
// Everything that can be ticked: checklist items, and the sections a reader
// crosses off to keep their place - a step, or a heading on a guide that has
// no steps at all (a converted article often has fifty headings and none).
const totalChecks = computed(() => {
let total = 0
for (const block of guide.value?.blocks || []) {
if (block.type === 'checklist') total += (block.items || []).length
else if (block.type === 'step' || block.type === 'heading') total += 1
}
return total
})

View File

@@ -90,6 +90,10 @@ class GuidesPlugin(BasePlugin):
'icon': 'book-open',
'route': '/guides',
'position': 8,
# The nav endpoint hides an item whose permission the caller
# does not hold, so a signed-out visitor sees Guides only when
# the guest role has been granted guides.view.
'permission': 'guides.view',
},
]

View File

@@ -124,11 +124,21 @@ def plaintext(blocks):
def checklistitemcount(blocks):
"""How many tickable items a guide has, for the list and the progress bar."""
"""How many tickable things a guide has, for the card and the progress bar.
Checklist items, plus the sections a reader crosses off to keep their place:
a step, or a heading. A guide converted from an article often has fifty
headings and no steps at all, and "0 steps to tick" on a card that is
entirely tickable reads as a broken feature.
"""
total = 0
for block in blocks or []:
if isinstance(block, dict) and block.get('type') == 'checklist':
if not isinstance(block, dict):
continue
if block.get('type') == 'checklist':
total += len(block.get('items') or [])
elif block.get('type') in ('step', 'heading'):
total += 1
return total

View File

@@ -197,7 +197,6 @@ def track_click(link_id: int):
@knowledgebase_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('kb.create')
def create_article():
"""Create a new knowledge base article."""
@@ -231,7 +230,6 @@ def create_article():
@knowledgebase_bp.route('/<int:link_id>', methods=['PUT'])
@jwt_required()
@require_permission('kb.edit')
def update_article(link_id: int):
"""Update a knowledge base article."""
@@ -261,7 +259,6 @@ def update_article(link_id: int):
@knowledgebase_bp.route('/<int:link_id>', methods=['DELETE'])
@jwt_required()
@require_permission('kb.delete')
def delete_article(link_id: int):
"""Delete (deactivate) a knowledge base article."""

View File

@@ -55,7 +55,6 @@ def get_machine_type(type_id: int):
@machines_bp.route('/types', methods=['POST'])
@jwt_required()
@require_permission('machines.create')
def create_machine_type():
"""Create a new machine type."""
@@ -92,7 +91,6 @@ def create_machine_type():
@machines_bp.route('/types/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_permission('machines.edit')
def update_machine_type(type_id: int):
"""Update a machine type."""
@@ -126,7 +124,6 @@ def update_machine_type(type_id: int):
@machines_bp.route('/types/<int:type_id>', methods=['DELETE'])
@jwt_required()
@require_permission('machines.delete')
def delete_machine_type(type_id: int):
"""Delete a machine type. Refused if any asset still uses it."""
@@ -324,7 +321,6 @@ def get_machine_by_asset(asset_id: int):
@machines_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('machines.create')
def create_machine():
"""
@@ -418,7 +414,6 @@ def create_machine():
@machines_bp.route('/<int:machine_id>', methods=['PUT'])
@jwt_required()
@require_permission('machines.edit')
def update_machine(machine_id: int):
"""Update machine (both Asset and Machine records)."""
@@ -501,7 +496,6 @@ def update_machine(machine_id: int):
@machines_bp.route('/<int:machine_id>', methods=['DELETE'])
@jwt_required()
@require_permission('machines.delete')
def delete_machine(machine_id: int):
"""Delete (soft delete) machine."""
@@ -578,7 +572,6 @@ def dashboard_summary():
@machines_bp.route('/dashboard/outofservice', methods=['GET'])
@jwt_required()
@require_permission('machines.view')
def dashboard_outofservice():
"""Machines whose status says they are not running.

View File

@@ -75,7 +75,6 @@ def get_type(type_id: int):
@measuringtools_bp.route('/types', methods=['POST'])
@jwt_required()
@require_permission('measuringtools.create')
def create_type():
"""Create a measuring-tool type (reactivates a soft-deleted same-named one)."""
@@ -108,7 +107,6 @@ def create_type():
@measuringtools_bp.route('/types/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_permission('measuringtools.edit')
def update_type(type_id: int):
"""Update a measuring-tool type."""
@@ -130,7 +128,6 @@ def update_type(type_id: int):
@measuringtools_bp.route('/types/<int:type_id>', methods=['DELETE'])
@jwt_required()
@require_permission('measuringtools.delete')
def delete_type(type_id: int):
"""Delete a measuring-tool type. Refused if any tool still uses it."""
@@ -239,7 +236,6 @@ def _asset_type_id():
@measuringtools_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('measuringtools.create')
def create_tool():
"""Create a measuring tool: one Asset core row + one extension row."""
@@ -305,7 +301,6 @@ _TOOL_FIELDS = ('measuringtooltypeid', 'calibrationintervaldays',
@measuringtools_bp.route('/<int:tool_id>', methods=['PUT'])
@jwt_required()
@require_permission('measuringtools.edit')
def update_tool(tool_id: int):
"""Update a measuring tool (asset core fields + extension in one payload)."""
@@ -357,7 +352,6 @@ def update_tool(tool_id: int):
@measuringtools_bp.route('/<int:tool_id>', methods=['DELETE'])
@jwt_required()
@require_permission('measuringtools.delete')
def delete_tool(tool_id: int):
"""Soft delete a measuring tool (deactivates its asset)."""

View File

@@ -85,7 +85,6 @@ def get_network_device_type(type_id: int):
@network_bp.route('/types', methods=['POST'])
@jwt_required()
@require_permission('network.create')
def create_network_device_type():
"""Create a new network device type."""
@@ -123,7 +122,6 @@ def create_network_device_type():
@network_bp.route('/types/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_permission('network.edit')
def update_network_device_type(type_id: int):
"""Update a network device type."""
@@ -158,7 +156,6 @@ def update_network_device_type(type_id: int):
@network_bp.route('/types/<int:type_id>', methods=['DELETE'])
@jwt_required()
@require_permission('network.delete')
def delete_network_device_type(type_id: int):
"""Delete a network device type. Refused if any device still uses it."""
@@ -347,7 +344,6 @@ def get_network_device_by_hostname(hostname: str):
@network_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('network.create')
def create_network_device():
"""
@@ -464,7 +460,6 @@ def create_network_device():
@network_bp.route('/<int:device_id>', methods=['PUT'])
@jwt_required()
@require_permission('network.edit')
def update_network_device(device_id: int):
"""Update network device (both Asset and NetworkDevice records)."""
@@ -559,7 +554,6 @@ def update_network_device(device_id: int):
@network_bp.route('/<int:device_id>', methods=['DELETE'])
@jwt_required()
@require_permission('network.delete')
def delete_network_device(device_id: int):
"""Delete (soft delete) network device."""
@@ -690,7 +684,6 @@ def get_vlan(vlan_id: int):
@network_bp.route('/vlans', methods=['POST'])
@jwt_required()
@require_permission('network.create')
def create_vlan():
"""Create a new VLAN."""
@@ -732,7 +725,6 @@ def create_vlan():
@network_bp.route('/vlans/<int:vlan_id>', methods=['PUT'])
@jwt_required()
@require_permission('network.edit')
def update_vlan(vlan_id: int):
"""Update a VLAN."""
@@ -778,7 +770,6 @@ def update_vlan(vlan_id: int):
@network_bp.route('/vlans/<int:vlan_id>', methods=['DELETE'])
@jwt_required()
@require_permission('network.delete')
def delete_vlan(vlan_id: int):
"""Delete (soft delete) a VLAN."""
@@ -932,7 +923,6 @@ def _asset_detail_url(assettype, assetid):
@network_bp.route('/subnets', methods=['POST'])
@jwt_required()
@require_permission('network.create')
def create_subnet():
"""Create a new subnet."""
@@ -998,7 +988,6 @@ def create_subnet():
@network_bp.route('/subnets/<int:subnet_id>', methods=['PUT'])
@jwt_required()
@require_permission('network.edit')
def update_subnet(subnet_id: int):
"""Update a subnet."""
@@ -1049,7 +1038,6 @@ def update_subnet(subnet_id: int):
@network_bp.route('/subnets/<int:subnet_id>', methods=['DELETE'])
@jwt_required()
@require_permission('network.delete')
def delete_subnet(subnet_id: int):
"""Delete (soft delete) a subnet."""

View File

@@ -257,7 +257,6 @@ def list_notification_types():
@notifications_bp.route('/types', methods=['POST'])
@jwt_required()
@require_permission('notifications.create')
def create_notification_type():
"""Create a new notification type."""
@@ -293,7 +292,6 @@ def create_notification_type():
@notifications_bp.route('/types/<int:type_id>', methods=['PUT', 'PATCH'])
@jwt_required()
@require_permission('notifications.create')
def update_notification_type(type_id: int):
"""Update a notification type, including its auto-expiry rule."""
@@ -405,7 +403,6 @@ def get_notification(notification_id: int):
@notifications_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('notifications.create')
def create_notification():
"""Create a new notification."""
@@ -465,7 +462,6 @@ def create_notification():
@notifications_bp.route('/<int:notification_id>', methods=['PUT'])
@jwt_required()
@require_permission('notifications.edit')
def update_notification(notification_id: int):
"""Update a notification."""
@@ -532,7 +528,6 @@ def update_notification(notification_id: int):
@notifications_bp.route('/<int:notification_id>', methods=['DELETE'])
@jwt_required()
@require_permission('notifications.delete')
def delete_notification(notification_id: int):
"""Delete (soft delete) a notification."""

View File

@@ -29,7 +29,6 @@ printedparts_bp = Blueprint('printedparts', __name__)
@printedparts_bp.route('/items', methods=['GET'])
@jwt_required()
@require_permission('printedparts.view')
def list_items():
"""List printed items, paginated; search + low-stock filter."""
@@ -56,7 +55,6 @@ def list_items():
@printedparts_bp.route('/items/<int:item_id>', methods=['GET'])
@jwt_required()
@require_permission('printedparts.view')
def get_item(item_id: int):
"""Get one printed item with its recent transactions."""
@@ -101,7 +99,6 @@ def _mint_itemcode(item):
@printedparts_bp.route('/items', methods=['POST'])
@jwt_required()
@require_permission('printedparts.create')
def create_item():
"""Create a printed item.
@@ -141,7 +138,6 @@ def create_item():
@printedparts_bp.route('/items/<int:item_id>', methods=['PUT'])
@jwt_required()
@require_permission('printedparts.edit')
def update_item(item_id: int):
"""Update catalog fields. Quantity moves ONLY through the ledger."""
@@ -174,7 +170,6 @@ def update_item(item_id: int):
@printedparts_bp.route('/items/<int:item_id>', methods=['DELETE'])
@jwt_required()
@require_permission('printedparts.delete')
def delete_item(item_id: int):
"""Soft-retire an item; its ledger history stays."""
@@ -188,7 +183,6 @@ def delete_item(item_id: int):
@printedparts_bp.route('/items/<int:item_id>/restore', methods=['POST'])
@jwt_required()
@require_permission('printedparts.delete')
def restore_item(item_id: int):
"""Bring a retired item back; code, photo, and history are intact."""
@@ -204,7 +198,6 @@ def restore_item(item_id: int):
# --- item image: the models.py upload/serve/delete trio ---------------------
@printedparts_bp.route('/items/<int:item_id>/image', methods=['POST'])
@jwt_required()
@require_permission('printedparts.edit')
def upload_item_image(item_id: int):
"""Upload (or replace) the photo for an item (multipart file=<image>)."""
@@ -240,7 +233,6 @@ def serve_item_image(filename):
@printedparts_bp.route('/items/<int:item_id>/image', methods=['DELETE'])
@jwt_required()
@require_permission('printedparts.delete')
def delete_item_image(item_id: int):
"""Clear an item image; delete the file only if this plugin owns it."""
@@ -387,7 +379,6 @@ def _alert_team_webhook():
@printedparts_bp.route('/items/<int:item_id>/restock', methods=['POST'])
@jwt_required()
@require_permission('printedparts.restock')
def restock_item(item_id: int):
"""Add freshly printed stock. Body: {quantity, badge}."""
@@ -410,7 +401,6 @@ def restock_item(item_id: int):
@printedparts_bp.route('/items/<int:item_id>/adjust', methods=['POST'])
@jwt_required()
@require_permission('printedparts.restock')
def adjust_item(item_id: int):
"""Correct the count (damage, recount). Body: {quantitychange, reason, badge}."""
@@ -668,7 +658,6 @@ def _uploader_name():
@printedparts_bp.route('/items/<int:item_id>/files', methods=['GET'])
@jwt_required()
@require_permission('printedparts.view')
def list_item_files(item_id: int):
"""Revision history, newest first."""
@@ -678,7 +667,6 @@ def list_item_files(item_id: int):
@printedparts_bp.route('/items/<int:item_id>/files', methods=['POST'])
@jwt_required()
@require_permission('printedparts.edit')
def upload_item_file(item_id: int):
"""Upload the next revision of the item's print file.
@@ -747,7 +735,6 @@ def download_item_file(file_id: int):
@printedparts_bp.route('/files/<int:file_id>', methods=['DELETE'])
@jwt_required()
@require_permission('printedparts.delete')
def delete_item_file(file_id: int):
"""Remove a bad revision (wrong file uploaded). History otherwise stays."""

View File

@@ -107,6 +107,9 @@ class PrintedpartsPlugin(BasePlugin):
'icon': 'box',
'route': '/printedparts',
'position': 27,
# Named so the nav can hide it from anybody - a signed-out
# visitor included - who does not hold it.
'permission': 'printedparts.view',
'section': 'assets',
},
]

View File

@@ -68,7 +68,6 @@ def get_printer_type(type_id: int):
@printers_asset_bp.route('/types', methods=['POST'])
@jwt_required()
@require_permission('printers.create')
def create_printer_type():
"""Create a new printer type."""
@@ -105,7 +104,6 @@ def create_printer_type():
@printers_asset_bp.route('/types/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_permission('printers.edit')
def update_printer_type(type_id: int):
"""Update a printer type."""
@@ -129,7 +127,6 @@ def update_printer_type(type_id: int):
@printers_asset_bp.route('/types/<int:type_id>', methods=['DELETE'])
@jwt_required()
@require_permission('printers.delete')
def delete_printer_type(type_id: int):
"""Delete a printer type. Refused if any printer still uses it."""
@@ -161,7 +158,6 @@ def list_drivers():
@printers_asset_bp.route('/drivers', methods=['POST'])
@jwt_required()
@require_permission('printers.create')
def create_driver():
data = request.get_json() or {}
@@ -180,7 +176,6 @@ def create_driver():
@printers_asset_bp.route('/drivers/<int:driver_id>', methods=['PUT'])
@jwt_required()
@require_permission('printers.edit')
def update_driver(driver_id):
d = db.session.get(PrinterDriver, driver_id)
@@ -197,7 +192,6 @@ def update_driver(driver_id):
@printers_asset_bp.route('/drivers/<int:driver_id>', methods=['DELETE'])
@jwt_required()
@require_permission('printers.delete')
def delete_driver(driver_id):
d = db.session.get(PrinterDriver, driver_id)
@@ -993,7 +987,6 @@ def get_asset_printer_assignment(asset_id: int):
@printers_asset_bp.route('/assignments/for-asset/<int:asset_id>', methods=['PUT'])
@jwt_required()
@require_permission('printers.edit')
def set_asset_printer_assignment(asset_id: int):
"""Reconcile one asset's whole printer assignment in a single call.
@@ -1498,7 +1491,6 @@ def _observed_host_block(hostname, asset, index):
@printers_asset_bp.route('/observed/<hostname>', methods=['GET'])
@jwt_required()
@require_permission('printers.view')
def observed_for_host(hostname: str):
"""What a host last reported, each queue judged against what it is assigned.
@@ -1536,7 +1528,6 @@ def observed_for_host(hostname: str):
@printers_asset_bp.route('/observed/for-asset/<int:asset_id>', methods=['GET'])
@jwt_required()
@require_permission('printers.view')
def observed_for_asset(asset_id: int):
"""The same comparison, reached from an asset page: one block per host.
@@ -1649,7 +1640,6 @@ def _seed_source_hostnames(asset):
@printers_asset_bp.route('/assignments/seed-from-observed/<int:asset_id>',
methods=['POST'])
@jwt_required()
@require_permission('printers.edit')
def seed_assignment_from_observed(asset_id: int):
"""Write what a PC observed as the assignment of the asset in the path.
@@ -1840,7 +1830,6 @@ def get_printer_by_asset(asset_id: int):
@printers_asset_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('printers.create')
def create_printer():
"""
@@ -1944,7 +1933,6 @@ def create_printer():
@printers_asset_bp.route('/<int:printer_id>', methods=['PUT'])
@jwt_required()
@require_permission('printers.edit')
def update_printer(printer_id: int):
"""Update printer (both Asset and Printer records)."""
@@ -2031,7 +2019,6 @@ def update_printer(printer_id: int):
@printers_asset_bp.route('/<int:printer_id>', methods=['DELETE'])
@jwt_required()
@require_permission('printers.delete')
def delete_printer(printer_id: int):
"""Delete (soft delete) printer."""
@@ -2303,7 +2290,6 @@ def printer_lookup():
@printers_asset_bp.route('/supplies/refresh', methods=['POST'])
@jwt_required()
@require_permission('printers.create')
def refresh_supplies_cache():
"""Clear cached Zabbix supply data so the next read pulls fresh values.
@@ -2485,7 +2471,6 @@ def list_model_supplies(modelnumberid: int):
@printers_asset_bp.route('/models/<int:modelnumberid>/supplies', methods=['POST'])
@jwt_required()
@require_permission('printers.create')
def create_model_supply(modelnumberid: int):
"""Add a supply to a model."""
@@ -2526,7 +2511,6 @@ def create_model_supply(modelnumberid: int):
@printers_asset_bp.route('/supplies/<int:modelsupplyid>', methods=['PUT'])
@jwt_required()
@require_permission('printers.edit')
def update_model_supply(modelsupplyid: int):
"""Update a model supply."""
@@ -2571,7 +2555,6 @@ def update_model_supply(modelsupplyid: int):
@printers_asset_bp.route('/supplies/<int:modelsupplyid>', methods=['DELETE'])
@jwt_required()
@require_permission('printers.delete')
def delete_model_supply(modelsupplyid: int):
"""Delete a model supply."""
@@ -2615,7 +2598,6 @@ def _reordertip(supply):
@printers_asset_bp.route('/dashboard/supplies', methods=['GET'])
@jwt_required()
@require_permission('printers.view')
def dashboard_supplies():
"""Printers needing a cartridge, flattened to one row per printer.

View File

@@ -14,7 +14,7 @@ from flask_jwt_extended import jwt_required
from werkzeug.utils import secure_filename
from shopdb.api import (db, success_response, error_response, ErrorCodes,
require_permission)
require_permission, require_any_permission)
from shopdb.api import send_upload
from ..models import TvSlide
@@ -90,8 +90,7 @@ def serve_image(surface, filename):
# =============================================================================
@slides_bp.route('/<surface>', methods=['GET'])
@jwt_required()
@require_permission('slides.manage')
@require_any_permission('slides.view', 'slides.manage')
def list_slides(surface):
if not _valid_surface(surface):
return error_response(ErrorCodes.VALIDATION_ERROR, 'Unknown surface')
@@ -108,7 +107,6 @@ def list_slides(surface):
@slides_bp.route('/<surface>/upload', methods=['POST'])
@jwt_required()
@require_permission('slides.manage')
def upload_slides(surface):
if not _valid_surface(surface):
@@ -153,7 +151,6 @@ def upload_slides(surface):
@slides_bp.route('/<surface>/order', methods=['POST'])
@jwt_required()
@require_permission('slides.manage')
def reorder_slides(surface):
if not _valid_surface(surface):
@@ -169,7 +166,6 @@ def reorder_slides(surface):
@slides_bp.route('/<surface>/delete', methods=['POST'])
@jwt_required()
@require_permission('slides.manage')
def delete_slides(surface):
if not _valid_surface(surface):
@@ -195,7 +191,6 @@ def delete_slides(surface):
@slides_bp.route('/<surface>/<int:slideid>', methods=['PATCH'])
@jwt_required()
@require_permission('slides.manage')
def update_slide(surface, slideid):
if not _valid_surface(surface):

View File

@@ -63,6 +63,7 @@ class SlidesPlugin(BasePlugin):
non-admin role so a curator can manage the lobby TV + screensaver
without full admin. Admins hold it by default."""
return [
('slides.view', 'View the slide decks', 'slides'),
('slides.manage',
'Manage lobby display and screensaver slides', 'slides'),
]
@@ -76,7 +77,10 @@ class SlidesPlugin(BasePlugin):
'icon': 'image',
'route': '/settings/slides',
'position': 7,
'permission': 'slides.manage',
# The read permission: a manager holds it implicitly through
# the route's require_any_permission, and it is the one a site
# can grant to guests.
'permission': ['slides.view', 'slides.manage'],
},
]

View File

@@ -70,6 +70,19 @@ class ToolsPlugin(BasePlugin):
('tools.secrets', 'Create secure send links', 'tools'),
]
def get_guest_grantable_permissions(self) -> List[str]:
"""Creating a secure send link is meant to work without an account.
Somebody standing at a bench needs to send a password to a vendor. The
recipient never had an account, and often neither does the sender - the
unguessable token is the authorisation, and the link is one-view.
A guest-created link records no creator. The audit trail says when and
from where, and never who. That is the cost, and it is why this is the
only write in the product offered to guests at all.
"""
return ['tools.secrets']
def get_settings_defaults(self) -> List[dict]:
"""The one switch this plugin owns.

View File

@@ -338,7 +338,6 @@ def get_usb_device(device_id):
@usb_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('usb.create')
def create_usb_device():
"""Add a device (starts checked-in)."""
@@ -385,7 +384,6 @@ def create_usb_device():
@usb_bp.route('/<device_id>', methods=['PUT'])
@jwt_required()
@require_permission('usb.edit')
def update_usb_device(device_id):
"""Edit device_desc / device_owner / locker_location / status."""
@@ -428,7 +426,6 @@ def update_usb_device(device_id):
@usb_bp.route('/<device_id>/retire', methods=['POST'])
@jwt_required()
@require_permission('usb.edit')
def retire_usb_device(device_id):
"""Retire a device (status -> retired)."""
@@ -463,7 +460,6 @@ def retire_usb_device(device_id):
# =============================================================================
@usb_bp.route('/<device_id>/checkout', methods=['POST'])
@jwt_required()
@require_permission('usb.create')
def checkout_device(device_id):
"""Check a device out to a badge."""
@@ -528,7 +524,6 @@ def checkout_device(device_id):
@usb_bp.route('/<device_id>/checkin', methods=['POST'])
@jwt_required()
@require_permission('usb.create')
def checkin_device(device_id):
"""Check a device back in from a badge."""
@@ -1111,7 +1106,6 @@ AUDITCOLUMNS = ['timestamp', 'action', 'device_id', 'device_desc', 'badge',
@usb_bp.route('/reports/audit', methods=['GET'])
@jwt_required()
@require_permission('usb.view')
def report_audit():
"""Every check-out and check-in in the window, newest first.

View File

@@ -197,7 +197,6 @@ def get_warranty(warrantyid):
@warranty_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('warranty.create')
def create_warranty():
data = request.get_json() or {}
@@ -220,7 +219,6 @@ def create_warranty():
@warranty_bp.route('/<int:warrantyid>', methods=['PUT'])
@jwt_required()
@require_permission('warranty.edit')
def update_warranty(warrantyid):
warranty = db.session.get(Warranty, warrantyid)
@@ -250,7 +248,6 @@ def update_warranty(warrantyid):
@warranty_bp.route('/<int:warrantyid>', methods=['DELETE'])
@jwt_required()
@require_permission('warranty.delete')
def delete_warranty(warrantyid):
warranty = db.session.get(Warranty, warrantyid)
@@ -266,7 +263,6 @@ def delete_warranty(warrantyid):
# =============================================================================
@warranty_bp.route('/<int:warrantyid>/refresh', methods=['POST'])
@jwt_required()
@require_permission('warranty.edit')
def refresh_warranty(warrantyid):
warranty = db.session.get(Warranty, warrantyid)
@@ -296,7 +292,6 @@ def refresh_warranty(warrantyid):
# =============================================================================
@warranty_bp.route('/sync/dell', methods=['POST'])
@jwt_required()
@require_permission('warranty.edit')
def sync_dell():
"""Look up every asset serial (= Dell service tag) that has no warranty yet
@@ -414,7 +409,6 @@ def warranty_report():
@warranty_bp.route('/dashboard/expiring', methods=['GET'])
@jwt_required()
@require_permission('warranty.view')
def dashboard_expiring():
"""Warranties running out, and ones that already have.
@@ -498,7 +492,6 @@ def _hostname(asset):
# =============================================================================
@warranty_bp.route('/<int:warrantyid>/proof', methods=['POST'])
@jwt_required()
@require_permission('warranty.edit')
def upload_proof(warrantyid):
"""Upload (or replace) the proof-of-cover document for a warranty."""
@@ -548,7 +541,6 @@ def upload_proof(warrantyid):
@warranty_bp.route('/proof/<path:filename>', methods=['GET'])
@jwt_required()
@require_permission('warranty.view')
def serve_proof(filename):
"""Download a proof document.
@@ -566,7 +558,6 @@ def serve_proof(filename):
@warranty_bp.route('/<int:warrantyid>/proof', methods=['DELETE'])
@jwt_required()
@require_permission('warranty.edit')
def delete_proof(warrantyid):
"""Remove a warranty's proof document."""

View File

@@ -57,7 +57,7 @@ from .plugins import plugin_manager
# permission / empty / position. BREAKING for any plugin still using the old
# shape, which is why it is recorded here: the change itself shipped earlier
# without a bump, and a contract that changes silently is not a contract.
__contract_version__ = '0.20.0'
__contract_version__ = '0.21.0'
# Product release version (see ADR-007). The product version and the
# plugin-contract version above are distinct series with independent

View File

@@ -68,7 +68,7 @@ from shopdb.utils.responses import (
from shopdb.utils.pagination import get_pagination_params, paginate_query
# Authorization decorators for gating plugin write routes
from shopdb.utils.authz import require_permission, require_role
from shopdb.utils.authz import require_permission, require_any_permission, require_role
# Service-token authorization for unattended plugin endpoints (collector,
# GE-Enforce fetch, ...): checks a scoped managed token without exposing token
@@ -298,6 +298,7 @@ __all__ = [
'paginate_query',
# Authorization decorators
'require_permission',
'require_any_permission',
'require_role',
'service_token_authorized',
'authorized_service_token',

View File

@@ -784,13 +784,20 @@ def fix_controls_direction():
@seed_cli.command('permissions')
@with_appcontext
def seed_permissions():
"""Seed predefined permissions."""
"""Seed predefined permissions, and the guest role that can hold them."""
from shopdb.extensions import db
from shopdb.core.models import Permission
from shopdb.core.models import Permission, Role
created = Permission.seed()
# Seeded here rather than in `seed admin` so an existing site picks it up
# on the upgrade it already runs. It holds nothing until somebody grants
# it something, so seeding it changes no behaviour.
guest = Role.seedguest()
db.session.commit()
click.echo(click.style(f"{created} permissions created.", fg='green'))
if guest:
click.echo(click.style(
"guest role created (holds no permissions).", fg='green'))
@seed_cli.command('settings')

View File

@@ -86,7 +86,6 @@ def list_apitokens():
@apitokens_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('apitokens.create')
def create_apitoken():
"""Create a token for the caller. Returns the full secret ONCE.
@@ -141,7 +140,6 @@ def create_apitoken():
@apitokens_bp.route('/<int:tokenid>', methods=['PUT'])
@jwt_required()
@require_permission('apitokens.create')
def update_apitoken(tokenid: int):
"""Rename, rescope, or deactivate a token. Own token, or any if admin.
@@ -183,7 +181,6 @@ def update_apitoken(tokenid: int):
@apitokens_bp.route('/<int:tokenid>', methods=['DELETE'])
@jwt_required()
@require_permission('apitokens.create')
def revoke_apitoken(tokenid: int):
"""Revoke (deactivate) a token. Own token, or any if admin."""

View File

@@ -180,7 +180,6 @@ def get_application(app_id: int):
@applications_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('applications.create')
def create_application():
"""Create a new application."""
@@ -224,7 +223,6 @@ def create_application():
@applications_bp.route('/<int:app_id>', methods=['PUT'])
@jwt_required()
@require_permission('applications.edit')
def update_application(app_id: int):
"""Update an application."""
@@ -270,7 +268,6 @@ def update_application(app_id: int):
@applications_bp.route('/<int:app_id>', methods=['DELETE'])
@jwt_required()
@require_permission('applications.delete')
def delete_application(app_id: int):
"""Delete (deactivate) an application."""
@@ -303,7 +300,6 @@ def list_versions(app_id: int):
@applications_bp.route('/<int:app_id>/versions', methods=['POST'])
@jwt_required()
@require_permission('applications.create')
def create_version(app_id: int):
"""Create a new version for an application."""
@@ -397,7 +393,6 @@ def list_machine_applications(machine_id: int):
@applications_bp.route('/machines/<int:machine_id>', methods=['POST'])
@jwt_required()
@require_permission('applications.create')
def install_application(machine_id: int):
"""Install an application on a computer."""
@@ -449,7 +444,6 @@ def install_application(machine_id: int):
@applications_bp.route('/machines/<int:machine_id>/<int:app_id>', methods=['DELETE'])
@jwt_required()
@require_permission('applications.delete')
def uninstall_application(machine_id: int, app_id: int):
"""Uninstall an application from a computer."""
@@ -474,7 +468,6 @@ def uninstall_application(machine_id: int, app_id: int):
@applications_bp.route('/machines/<int:machine_id>/<int:app_id>', methods=['PUT'])
@jwt_required()
@require_permission('applications.edit')
def update_installed_app(machine_id: int, app_id: int):
"""Update installed application (e.g., change version)."""
@@ -516,7 +509,6 @@ def update_installed_app(machine_id: int, app_id: int):
# =============================================================================
@applications_bp.route('/<int:app_id>/image', methods=['POST'])
@jwt_required()
@require_permission('applications.edit')
def upload_application_image(app_id: int):
"""Upload (or replace) an application's image.
@@ -555,7 +547,6 @@ def serve_application_image(filename):
@applications_bp.route('/<int:app_id>/image', methods=['DELETE'])
@jwt_required()
@require_permission('applications.edit')
def delete_application_image(app_id: int):
"""Remove an application's image and clear the field."""
@@ -574,7 +565,6 @@ def delete_application_image(app_id: int):
@applications_bp.route('/<int:app_id>/package', methods=['POST'])
@jwt_required()
@require_permission('applications.edit')
def upload_application_package(app_id: int):
"""Upload (or replace) the installer for an application.
@@ -627,7 +617,6 @@ def upload_application_package(app_id: int):
@applications_bp.route('/package/<path:filename>', methods=['GET'])
@jwt_required()
@require_permission('applications.view')
def serve_application_package(filename):
"""Download an uploaded installer.
@@ -640,7 +629,6 @@ def serve_application_package(filename):
@applications_bp.route('/<int:app_id>/package', methods=['DELETE'])
@jwt_required()
@require_permission('applications.edit')
def delete_application_package(app_id: int):
"""Remove an uploaded installer and clear the path it set."""

View File

@@ -60,7 +60,6 @@ def get_asset_type(type_id: int):
@assets_bp.route('/types', methods=['POST'])
@jwt_required()
@require_permission('assets.create')
def create_asset_type():
"""Create a new asset type."""
@@ -92,7 +91,6 @@ def create_asset_type():
@assets_bp.route('/types/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_permission('assets.edit')
def update_asset_type(type_id: int):
"""Update an asset type's display fields (color/icon/description). The name,
@@ -148,7 +146,6 @@ def get_asset_status(status_id: int):
@assets_bp.route('/statuses', methods=['POST'])
@jwt_required()
@require_permission('assets.create')
def create_asset_status():
"""Create a new asset status."""
@@ -177,7 +174,6 @@ def create_asset_status():
@assets_bp.route('/statuses/<int:status_id>', methods=['PUT'])
@jwt_required()
@require_permission('assets.edit')
def update_asset_status(status_id: int):
"""Update an asset status."""
@@ -206,7 +202,6 @@ def update_asset_status(status_id: int):
@assets_bp.route('/statuses/<int:status_id>', methods=['DELETE'])
@jwt_required()
@require_permission('assets.delete')
def delete_asset_status(status_id: int):
"""Delete an asset status. Refused if any asset still uses it."""
@@ -241,7 +236,6 @@ def list_relationship_types():
@assets_bp.route('/relationshiptypes', methods=['POST'])
@jwt_required()
@require_permission('assets.create')
def create_relationship_type():
"""Create a new asset relationship type."""
@@ -288,7 +282,6 @@ def _rel_type_dict(t):
@assets_bp.route('/relationshiptypes/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_permission('assets.edit')
def update_relationship_type(type_id: int):
"""Update a relationship type."""
@@ -308,7 +301,6 @@ def update_relationship_type(type_id: int):
@assets_bp.route('/relationshiptypes/<int:type_id>', methods=['DELETE'])
@jwt_required()
@require_permission('assets.delete')
def delete_relationship_type(type_id: int):
"""Delete a relationship type. Refused if any relationship still uses it."""
@@ -437,7 +429,6 @@ def get_asset(asset_id: int):
@assets_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('assets.create')
def create_asset():
"""Create a new asset."""
@@ -489,7 +480,6 @@ def create_asset():
@assets_bp.route('/<int:asset_id>', methods=['PUT'])
@jwt_required()
@require_permission('assets.edit')
def update_asset(asset_id: int):
"""Update an asset."""
@@ -542,7 +532,6 @@ def update_asset(asset_id: int):
@assets_bp.route('/<int:asset_id>', methods=['DELETE'])
@jwt_required()
@require_permission('assets.delete')
def delete_asset(asset_id: int):
"""Delete (soft delete) an asset."""
@@ -733,7 +722,6 @@ def get_asset_relationships(asset_id: int):
@assets_bp.route('/relationships', methods=['POST'])
@jwt_required()
@require_permission('assets.create')
def create_asset_relationship():
"""Create a relationship between two assets.
@@ -884,7 +872,6 @@ def create_asset_relationship():
@assets_bp.route('/relationships/<int:rel_id>', methods=['DELETE'])
@jwt_required()
@require_permission('assets.delete')
def delete_asset_relationship(rel_id: int):
"""Delete an asset relationship.

View File

@@ -52,7 +52,6 @@ def _resolve_full_names(ssos):
@auditlogs_bp.route('', methods=['GET'])
@jwt_required()
@require_permission('audit.view')
def list_auditlogs():
"""
@@ -136,7 +135,6 @@ def list_auditlogs():
@auditlogs_bp.route('/entity/<entitytype>/<int:entityid>', methods=['GET'])
@jwt_required()
@require_permission('audit.view')
def get_entity_history(entitytype: str, entityid: int):
"""Get audit history for a specific entity."""
@@ -149,7 +147,6 @@ def get_entity_history(entitytype: str, entityid: int):
@auditlogs_bp.route('/stats', methods=['GET'])
@jwt_required()
@require_permission('audit.view')
def get_stats():
"""Get audit log statistics."""
@@ -198,7 +195,6 @@ def db_func_count_by(column):
@auditlogs_bp.route('/retention', methods=['GET'])
@jwt_required()
@require_permission('audit.view')
def get_retention():
"""Size of the log and what the configured retention would remove.
@@ -212,7 +208,6 @@ def get_retention():
@auditlogs_bp.route('/purge', methods=['POST'])
@jwt_required()
@require_permission('audit.purge')
def purge_auditlogs():
"""Delete entries older than the retention window.

View File

@@ -187,6 +187,26 @@ def get_navigation():
# Sort by position
all_items.sort(key=lambda x: x.get('position', 99))
# A signed-out visitor is shown only what the guest role can actually
# reach. Without this the sidebar offers them the whole app and every link
# bounces off a 401, which reads as a broken site rather than a closed
# door. An item with no declared permission is treated as members-only: a
# plugin opts into being guest-visible by naming the permission its page
# needs, which is the same string the API already gates on.
from flask_jwt_extended import verify_jwt_in_request
from shopdb.utils.authz import currentuser, guestholds
verify_jwt_in_request(optional=True)
def guestmayreach(item):
declared = item.get('permission')
if not declared:
return False
names = declared if isinstance(declared, list) else [declared]
return any(guestholds(name) for name in names)
if currentuser() is None:
all_items = [item for item in all_items if guestmayreach(item)]
return success_response(all_items)

View File

@@ -115,7 +115,6 @@ def apply_transform(asset, transform):
@mappositions_bp.route('/transform', methods=['POST'])
@jwt_required()
@require_permission('assets.edit')
def transform_positions():
"""Move every placed marker on a level by a transform read off landmarks.
@@ -225,7 +224,6 @@ def transform_positions():
# =============================================================================
@mappositions_bp.route('/positions', methods=['POST'])
@jwt_required()
@require_permission('assets.edit')
def set_positions():
"""Set positions for many assets at once.
@@ -301,7 +299,6 @@ def set_positions():
@mappositions_bp.route('/verify', methods=['POST'])
@jwt_required()
@require_permission('assets.edit')
def verify_positions():
"""Mark markers as reviewed against the current drawing without moving them.
@@ -330,7 +327,6 @@ def verify_positions():
# =============================================================================
@mappositions_bp.route('/snapshots', methods=['GET'])
@jwt_required()
@require_permission('assets.view')
def list_snapshots():
"""Snapshots, newest first. Metadata only - the positions are large."""
@@ -341,7 +337,6 @@ def list_snapshots():
@mappositions_bp.route('/snapshots/<int:snapshotid>/restore', methods=['POST'])
@jwt_required()
@require_permission('assets.edit')
def restore_snapshot(snapshotid):
"""Put the positions in this snapshot back.

View File

@@ -525,7 +525,6 @@ def pc_relationships():
@reports_bp.route('/email', methods=['POST'])
@jwt_required()
@require_permission('reports.export')
def email_report():
"""Email a report's data as an HTML table (on-demand delivery).

View File

@@ -277,7 +277,6 @@ def get_setting(key: str):
@settings_bp.route('/<key>', methods=['PUT'])
@jwt_required()
@require_permission('settings.edit')
def update_setting(key: str):
"""Update a setting value."""
@@ -336,7 +335,6 @@ def update_setting(key: str):
@settings_bp.route('/test-email', methods=['POST'])
@jwt_required()
@require_permission('settings.edit')
def test_email():
"""Send a test email to verify SMTP configuration.
@@ -374,7 +372,6 @@ def test_email():
@settings_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('settings.edit')
def create_setting():
"""Create a new setting (admin only)."""
@@ -986,7 +983,6 @@ def build_default_settings():
@settings_bp.route('/seed', methods=['POST'])
@jwt_required()
@require_permission('settings.edit')
def seed_default_settings():
"""Seed default settings if they don't exist."""

View File

@@ -6,7 +6,8 @@ from werkzeug.security import generate_password_hash
from shopdb.extensions import db
from shopdb.core.models import (
User, Role, Permission, AuditLog, full_permission_catalog)
User, Role, Permission, AuditLog, full_permission_catalog,
guest_grantable_permissions)
from shopdb.utils.responses import success_response, error_response, ErrorCodes
from shopdb.utils.authz import require_role
@@ -266,6 +267,9 @@ def list_permissions():
def list_roles():
"""List all roles with their permissions."""
roles = Role.query.order_by(Role.rolename).all()
# What a guest MAY be granted, so the grid can grey out the rest rather
# than letting somebody tick a box the API will refuse.
guestgrantable = sorted(guest_grantable_permissions())
return success_response([{
'roleid': r.roleid,
'rolename': r.rolename,
@@ -273,7 +277,9 @@ def list_roles():
'color': r.color,
'usercount': r.users.count(),
'permissions': [p.name for p in r.permissions],
'isadmin': r.rolename == 'admin'
'isadmin': r.rolename == 'admin',
'isguest': r.rolename == Role.GUEST,
'grantable': guestgrantable if r.rolename == Role.GUEST else None,
} for r in roles])
@@ -344,6 +350,20 @@ def update_role(roleid: int):
# Update permissions
if 'permissions' in data and role.rolename != 'admin':
# The guest role is anyone with no account, so what it may hold is
# bounded: reads, plus the handful of writes a plugin has explicitly
# declared safe to do anonymously. Refused at the door rather than
# warned about - a checkbox that quietly makes deleting an asset
# anonymous is not a warning anybody reads twice.
if role.rolename == Role.GUEST:
allowed = guest_grantable_permissions()
refused = sorted(set(data['permissions']) - allowed)
if refused:
return error_response(
ErrorCodes.VALIDATION_ERROR,
'The guest role cannot hold {}. A guest may be granted any '
'view permission, and only writes a plugin has declared '
'safe to do without an account.'.format(', '.join(refused)))
old_perms = [p.name for p in role.permissions]
perms = Permission.query.filter(Permission.name.in_(data['permissions'])).all()
new_perms = [p.name for p in perms]
@@ -377,6 +397,14 @@ def delete_role(roleid: int):
if role.rolename == 'admin':
return error_response(ErrorCodes.VALIDATION_ERROR, 'Cannot delete the admin role')
# Deleting the guest role does not close the door, it removes the only
# place the door is described. Revoke its permissions instead.
if role.rolename == Role.GUEST:
return error_response(
ErrorCodes.VALIDATION_ERROR,
'Cannot delete the guest role. To close guest access, clear its '
'permissions.')
if role.users.count() > 0:
return error_response(ErrorCodes.VALIDATION_ERROR, f'Role is assigned to {role.users.count()} user(s)')

View File

@@ -13,7 +13,8 @@ from .mapsnapshot import MapPositionSnapshot
from .operatingsystem import OperatingSystem
from .relationship import AssetRelationship, RelationshipType, RelationshipTypePropagation
from .communication import Communication, CommunicationType
from .user import User, Role, Permission, full_permission_catalog
from .user import (User, Role, Permission, full_permission_catalog,
guest_grantable_permissions)
from .application import Application, AppVersion
from .supportteam import SupportTeam, SupportTeamContact
from .setting import Setting
@@ -57,6 +58,7 @@ __all__ = [
'Role',
'Permission',
'full_permission_catalog',
'guest_grantable_permissions',
# Applications
'Application',
'AppVersion',

View File

@@ -152,6 +152,53 @@ def full_permission_catalog(include_disabled=False):
return catalog
def guest_grantable_permissions():
"""Which permissions the guest role may be granted.
Reading is the safe default and covers almost everything a site wants to
open up: any `.view` or `.read` permission may be handed to guests.
A write is different - it lets somebody with no account change this
database, and the audit trail can then say when and from where but never
who. So a write has to be BLESSED by whoever owns it, through the plugin's
get_guest_grantable_permissions(). Secure Send is the case that exists:
creating a one-view link for somebody is the whole point of the page, and
the page has always been usable by people with no account here.
Everything else is refused at the door rather than warned about, because a
checkbox that quietly makes deleting an asset anonymous is not a warning
anybody reads twice.
"""
from flask import current_app, has_app_context
catalog = full_permission_catalog()
grantable = {name for name, _, _ in catalog
if name.endswith('.view') or name.endswith('.read')}
if not has_app_context():
return grantable
pm = current_app.extensions.get('plugin_manager')
if not pm:
return grantable
known = {name for name, _, _ in catalog}
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'
@@ -171,6 +218,16 @@ class Role(BaseModel):
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
@@ -178,6 +235,31 @@ class Role(BaseModel):
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
def getpermissionnames(self) -> list:
"""Get list of permission names."""
if self.rolename == 'admin':

View File

@@ -104,6 +104,23 @@ class BasePlugin(ABC):
"""
return []
def get_guest_grantable_permissions(self) -> List[str]:
"""Permissions this plugin allows a site to grant to the GUEST role.
A guest is anyone with no account. Any `.view` or `.read` permission is
grantable without asking a plugin - reading is the safe default. This
hook is for the exception: a WRITE that is genuinely meant to be usable
by somebody who never signs in.
Naming one here does not open it. It makes the checkbox available in
the role grid; a site still has to tick it. Return [] (the default) and
none of this plugin's writes can ever be made anonymous.
The bar: could this action be attributed to nobody, forever, and still
be defensible in the audit log? If not, leave it out.
"""
return []
def get_settings_defaults(self) -> List[Dict]:
"""Declare the Setting rows this plugin owns.

View File

@@ -10,13 +10,34 @@ or not a separate @jwt_required is also present. The admin role bypasses every
permission check (see User.haspermission), so an admin never needs individual
permissions granted.
THE GUEST ROLE
Somebody with no token is not nobody: they hold the `guest` role. If that role
has been granted the permission a route asks for, the request proceeds; if it
has not - and by default it holds nothing at all - the answer is 401, exactly
as before.
This replaced a growing pile of per-feature booleans (`securesend_allow_guests`,
one per kiosk, one nearly written for guides). Every one of them answered the
same question in its own vocabulary, in its own settings page, checked by its
own hand-written branch inside a route. What a signed-out visitor may see is a
permissions question, and this app already administers permissions per role.
So: a site opens a door by ticking a box in the role grid, and a plugin needs
no code at all to participate. A feature FLAG is still a flag - whether a kiosk
screen exists at this site is not the same question as who may read it.
Usage:
@assets_bp.route('/<int:asset_id>', methods=['DELETE'])
@jwt_required()
@require_permission('assets.delete')
def delete_asset(asset_id):
...
A separate @jwt_required() above these is redundant - they verify the request
themselves - and it is actively wrong now: it refuses a request with no token
before the guest role can be consulted, so a permission granted to guests would
appear to do nothing.
"""
from functools import wraps
@@ -26,6 +47,45 @@ from flask_jwt_extended import verify_jwt_in_request, current_user, get_jwt
from shopdb.utils.responses import error_response, ErrorCodes
def currentuser():
"""The signed-in user, or None.
`current_user` is a LocalProxy: the proxy object exists whether or not
anybody is behind it, so `current_user is None` is False even for a request
with no token. Under a required JWT that never showed, because the request
was refused before reaching here. With optional verification it shows
immediately, as "'NoneType' object has no attribute 'haspermission'".
"""
try:
return current_user._get_current_object()
except Exception:
return None
def guestholds(permission_name: str) -> bool:
"""Whether the guest role has been granted this permission.
Read every time, not cached. Revoking guest access is what somebody does the
moment they realise what they opened up, and it has to bite on the very next
request - a cache keyed to the app context outlives a request whenever one
is pushed around several (which is exactly how the test client behaves, and
how the revoke test caught it). One small indexed query on the rare path is
worth more than that risk.
A site with no guest role yet - an older database, seeded before this
existed - answers no, which is the behaviour it already had.
"""
from shopdb.core.models import Role
try:
role = Role.guest()
except Exception:
# A database that cannot answer must not turn into an open door.
return False
if role is None:
return False
return any(p.name == permission_name for p in role.permissions)
def require_permission(permission_name: str):
"""Gate a route behind a single permission. Admin role bypasses.
@@ -36,10 +96,15 @@ def require_permission(permission_name: str):
def decorator(view_func):
@wraps(view_func)
def wrapper(*args, **kwargs):
# verify jwt first so current_user is loaded (idempotent if the
# route also has @jwt_required)
verify_jwt_in_request()
if current_user is None:
# Optional, so a request with no token reaches the guest check
# below rather than being refused by the JWT layer before this
# decorator can have an opinion. A request that DOES carry a token
# is still verified, and a bad one still fails here.
verify_jwt_in_request(optional=True)
user = currentuser()
if user is None:
if guestholds(permission_name):
return view_func(*args, **kwargs)
return error_response(
ErrorCodes.UNAUTHORIZED,
'Authentication required',
@@ -53,7 +118,7 @@ def require_permission(permission_name: str):
# everything), so the scope list is the real limiter - the
# admin bypass is suspended.
allowed = (permission_name in patscopes
and current_user.haspermission(permission_name))
and user.haspermission(permission_name))
if not allowed:
return error_response(
ErrorCodes.FORBIDDEN,
@@ -61,7 +126,54 @@ def require_permission(permission_name: str):
http_code=403
)
return view_func(*args, **kwargs)
if not current_user.haspermission(permission_name):
if not user.haspermission(permission_name):
return error_response(
ErrorCodes.FORBIDDEN,
'You do not have permission to perform this action',
http_code=403
)
return view_func(*args, **kwargs)
return wrapper
return decorator
def require_any_permission(*permission_names):
"""Gate a route behind ANY ONE of several permissions. Admin bypasses.
For a read that two different rights should reach. GE-Enforce and Slides
are the cases: a GET was gated on the MANAGE permission, because managing
was the only thing anybody did there. Splitting a read permission out would
have locked out every existing manager, so a read now accepts either, and
the read permission is the one a site can hand to a guest.
A scoped PAT must carry one of the names, and its owner must hold that same
one - the intersection rule of require_permission, applied per name.
"""
def decorator(view_func):
@wraps(view_func)
def wrapper(*args, **kwargs):
verify_jwt_in_request(optional=True)
user = currentuser()
if user is None:
if any(guestholds(name) for name in permission_names):
return view_func(*args, **kwargs)
return error_response(
ErrorCodes.UNAUTHORIZED,
'Authentication required',
http_code=401
)
patscopes = get_jwt().get('patscopes')
if patscopes is not None:
allowed = any(name in patscopes and user.haspermission(name)
for name in permission_names)
if not allowed:
return error_response(
ErrorCodes.FORBIDDEN,
'This API token is not scoped for this action',
http_code=403
)
return view_func(*args, **kwargs)
if not any(user.haspermission(name) for name in permission_names):
return error_response(
ErrorCodes.FORBIDDEN,
'You do not have permission to perform this action',
@@ -83,7 +195,8 @@ def require_role(rolename: str):
@wraps(view_func)
def wrapper(*args, **kwargs):
verify_jwt_in_request()
if current_user is None:
user = currentuser()
if user is None:
return error_response(
ErrorCodes.UNAUTHORIZED,
'Authentication required',
@@ -95,7 +208,7 @@ def require_role(rolename: str):
'Scoped API tokens cannot access role-gated endpoints',
http_code=403
)
if not current_user.hasrole(rolename):
if not user.hasrole(rolename):
return error_response(
ErrorCodes.FORBIDDEN,
f'{rolename.capitalize()} access required',

View File

@@ -0,0 +1,190 @@
"""The guest role: what somebody with no account may do.
Guest access used to be a per-feature boolean - one for Secure Send, one per
kiosk, one nearly written for guides - each with its own settings page and its
own hand-written branch inside a route. This replaced all of that with a role,
so the question is answered where every other permission question is answered.
The contract these tests hold:
- a guest holds nothing by default, so an upgrade opens no door
- granting the guest role a permission is what opens one
- revoking it closes the door on the next request, not the next restart
- a guest can never be granted a write unless its owner declared it safe
- a signed-in caller is unaffected by any of it
"""
import pytest
from shopdb.core.models import Permission, Role
@pytest.fixture
def guestrole(db):
"""The seeded guest role, holding nothing."""
Permission.seed()
Role.seedguest()
db.session.commit()
return Role.guest()
def grant(db, role, *names):
role.permissions = Permission.query.filter(Permission.name.in_(names)).all()
db.session.commit()
# ---------------------------------------------------------------------------
# The default: nothing
# ---------------------------------------------------------------------------
def test_a_guest_holds_nothing_by_default(guestrole):
"""An upgrade must not open a door a site never asked to open."""
assert guestrole.permissions == []
def test_a_guest_is_refused_a_read_nobody_granted(client, guestrole):
response = client.get('/api/auditlogs')
assert response.status_code == 401
def test_a_guest_is_refused_a_write(client, guestrole):
response = client.post('/api/assets', json={'assetnumber': 'GUEST-1'})
assert response.status_code == 401
# ---------------------------------------------------------------------------
# Granting, and taking it back
# ---------------------------------------------------------------------------
def test_granting_the_guest_role_a_view_opens_that_read(client, db, guestrole):
grant(db, guestrole, 'audit.view')
response = client.get('/api/auditlogs')
assert response.status_code == 200
def test_a_grant_does_not_leak_into_neighbouring_permissions(client, db, guestrole):
"""audit.view is not apitokens.view. The role holds exactly what it was
given."""
grant(db, guestrole, 'audit.view')
assert client.get('/api/apitokens').status_code == 401
def test_a_write_stays_shut_even_when_a_read_is_open(client, db, guestrole):
grant(db, guestrole, 'audit.view')
assert client.post('/api/assets', json={'assetnumber': 'X'}).status_code == 401
def test_revoking_closes_the_door_on_the_next_request(client, db, guestrole):
"""Not on the next restart. Revoking is what somebody does the moment they
realise what they opened up, and it has to take effect then."""
grant(db, guestrole, 'audit.view')
assert client.get('/api/auditlogs').status_code == 200
guestrole.permissions = []
db.session.commit()
assert client.get('/api/auditlogs').status_code == 401
def test_a_site_with_no_guest_role_behaves_as_it_always_did(client, db):
"""An older database, seeded before any of this existed."""
role = Role.guest()
if role is not None:
db.session.delete(role)
db.session.commit()
assert client.get('/api/auditlogs').status_code == 401
# ---------------------------------------------------------------------------
# The guardrail
# ---------------------------------------------------------------------------
def test_a_view_permission_is_grantable(app):
from shopdb.core.models import guest_grantable_permissions
with app.app_context():
grantable = guest_grantable_permissions()
assert 'assets.view' in grantable
assert 'reports.view' in grantable
def test_a_write_permission_is_not_grantable(app):
from shopdb.core.models import guest_grantable_permissions
with app.app_context():
grantable = guest_grantable_permissions()
for name in ('assets.delete', 'assets.create', 'users.create',
'settings.edit'):
assert name not in grantable, name
def test_the_api_refuses_to_grant_a_guest_a_write(client, db, auth_headers,
guestrole):
"""Refused at the door rather than warned about: a checkbox that quietly
makes deleting an asset anonymous is not a warning anybody reads twice."""
response = client.put('/api/users/roles/{}'.format(guestrole.roleid),
headers=auth_headers,
json={'permissions': ['assets.delete']})
assert response.status_code == 400
assert 'assets.delete' in response.get_json()['data']['error']['message']
assert guestrole.permissions == []
def test_the_api_allows_granting_a_guest_a_view(client, db, auth_headers,
guestrole):
response = client.put('/api/users/roles/{}'.format(guestrole.roleid),
headers=auth_headers,
json={'permissions': ['audit.view']})
assert response.status_code == 200
assert [p.name for p in guestrole.permissions] == ['audit.view']
def test_the_guest_role_cannot_be_deleted(client, auth_headers, guestrole):
"""Deleting it does not close the door, it removes the only place the door
is described."""
response = client.delete('/api/users/roles/{}'.format(guestrole.roleid))
assert response.status_code in (401, 403)
response = client.delete('/api/users/roles/{}'.format(guestrole.roleid),
headers=auth_headers)
assert response.status_code == 400
assert Role.guest() is not None
def test_the_role_list_says_what_a_guest_may_hold(client, auth_headers,
guestrole):
"""So the grid can grey the rest out rather than letting somebody tick a
box the API will refuse."""
rows = client.get('/api/users/roles', headers=auth_headers).get_json()['data']
guest = next(r for r in rows if r['rolename'] == 'guest')
assert guest['isguest'] is True
assert 'assets.view' in guest['grantable']
assert 'assets.delete' not in guest['grantable']
other = next((r for r in rows if r['rolename'] != 'guest'), None)
if other is not None:
assert other['grantable'] is None, 'only the guest role is bounded'
# ---------------------------------------------------------------------------
# Signed-in callers are unaffected
# ---------------------------------------------------------------------------
def test_a_member_still_needs_their_own_permission(client, member_headers,
db, guestrole):
"""A grant to guests is not a grant to everybody: a signed-in member
without the permission is still refused, with 403 rather than 401 because
signing in would not change the answer."""
grant(db, guestrole, 'audit.view')
response = client.get('/api/auditlogs', headers=member_headers)
assert response.status_code == 403
def test_an_admin_is_unaffected(client, auth_headers, guestrole):
assert client.get('/api/auditlogs', headers=auth_headers).status_code == 200
def test_a_bad_token_is_still_refused(client, db, guestrole):
"""Optional verification tolerates a MISSING token, not a broken one - a
forged token must not be quietly downgraded to guest access."""
grant(db, guestrole, 'audit.view')
response = client.get('/api/auditlogs',
headers={'Authorization': 'Bearer not.a.token'})
assert response.status_code == 422

View File

@@ -559,3 +559,20 @@ def test_renaming_a_guide_does_not_move_its_url(client, db, author):
assert fixed.status_code == 200
assert fixed.get_json()['data']['slug'] == slug, 'the URL must not move'
assert fixed.get_json()['data']['title'] == 'Replacing a marker controller'
def test_a_section_counts_as_something_to_tick():
"""A reader crosses off a step or a heading to keep their place, so those
count towards progress too. A guide converted from an article often has
fifty headings and no steps at all, and "0 steps to tick" on a card that is
entirely tickable reads as a broken feature."""
from plugins.guides.services.blocks import checklistitemcount
blocks = [
_block('b1', 'heading', text='Before you start'),
_block('b2', 'paragraph', text='Not tickable.'),
_block('b3', 'step', title='Do the thing'),
_block('b4', 'checklist', items=[{'id': 'i1', 'text': 'One'},
{'id': 'i2', 'text': 'Two'}]),
_block('b5', 'code', text='echo hi'),
]
# heading + step + two checklist items
assert checklistitemcount(blocks) == 4