用户/账号管理,系统日志

This commit is contained in:
Zzzz
2026-04-27 22:56:27 +08:00
parent f80f2b807f
commit f99002e664
32 changed files with 2801 additions and 2 deletions
@@ -51,3 +51,96 @@ Server logs may contain technical stack traces for developers. User-facing JSP
pages should receive concise messages. Durable system logs should record the
operation, actor, failure category, and correlation details needed to locate
the server-side exception.
---
## Scenario: Admin User Management Audit And System Log Viewer
### 1. Scope / Trigger
- Trigger: administrator user/account management writes durable audit rows, and
`/admin/system-logs` reads those rows through a Servlet -> Service -> DAO ->
MySQL flow.
- The viewer is read-only; mutation belongs to the business service that owns
the operation being audited.
### 2. Signatures
- DB signature: `system_logs(id, operator_id, operator_role, operation_type,
target_table, target_id, result_status, message, request_ip, created_at)`.
- DAO signatures: `SystemLogDao.search(criteria)`,
`SystemLogDao.findOperationTypes()`, and
`SystemLogDao.create(connection, log)`.
- Service signatures:
`SystemLogService.searchLogs(AuthenticatedUser actor, SystemLogSearchCriteria criteria)`
and user-management methods that accept `requestIp` for audit rows.
- Routes: `GET /admin/system-logs`; user-management audit sources include
`POST /admin/users`, `POST /admin/users/update`, and
`POST /admin/users/deactivate`.
### 3. Contracts
- `/admin/system-logs` requires `VIEW_SYSTEM_LOGS`; user-management write
routes require `MANAGE_USERS`.
- Search criteria fields are `operationType`, `keyword`, `createdFrom`, and
`createdTo`; dates use `YYYY-MM-DD`.
- System-log result rows are newest-first and may include missing joined user
names. Entity display helpers must render an operator label as display name,
username, `User #<id>`, or `System` in that order.
- JSPs must use safe JavaBean helpers such as `operatorLabel`,
`operatorMetaText`, `resultStatusCode`, and `resultStatusName`; do not put raw
database status strings into CSS class names.
- Audit messages must summarize actions with IDs/usernames/roles, never
passwords, raw credentials, password hashes, or request bodies.
### 4. Validation & Error Matrix
- Unauthenticated or unauthorized viewer -> `You do not have permission to view
system logs.`
- `operationType` longer than 64 characters -> field error on `operationType`.
- `keyword` longer than 120 characters -> field error on `keyword`.
- Invalid date text -> `Start date must use YYYY-MM-DD.` or `End date must use
YYYY-MM-DD.`
- `createdFrom` after `createdTo` -> field error on `createdTo`.
- DAO failure while loading logs -> server-side Java logger entry plus `System
log service is temporarily unavailable. Please try again later.`
- Audit insert failure inside a user-management transaction -> rollback the
mutating operation and return the user-management unavailable message.
### 5. Good/Base/Bad Cases
- Good: user creation and its `user.create` audit row commit in the same
transaction, including `operator_id`, `operator_role`, `target_table=users`,
`target_id`, `result_status=success`, and `request_ip`.
- Base: a system log with `operator_id` but no joined user displays as
`User #<id>`, not as `System`.
- Bad: a JSP renders `class="status-${log.resultStatus}"` from an arbitrary
database value.
### 6. Tests Required
- Service checks for permission denial, criteria validation, date-range
validation, DAO failure fallback, newest-first/search DAO contract, and empty
results.
- User-management service checks for audit log creation on create/update/
deactivate and rollback when audit creation fails inside the transaction.
- Entity/display checks for operator fallback labels and normalized result
status CSS codes.
- JSP scan confirming no scriptlet, SQL, JDBC, password, or password-hash
rendering in admin/log pages.
### 7. Wrong vs Correct
#### Wrong
```jsp
<span class="status-${log.resultStatus}">${log.resultStatus}</span>
```
#### Correct
```jsp
<span class="status-${log.resultStatusCode}">
<c:out value="${log.resultStatusName}" />
</span>
```
@@ -0,0 +1,11 @@
{"file": ".trellis/spec/backend/index.md", "reason": "Backend architecture and checklist for verification"}
{"file": ".trellis/spec/backend/directory-structure.md", "reason": "Verify new Java classes follow expected package layout"}
{"file": ".trellis/spec/backend/database-guidelines.md", "reason": "Verify schema/DAO changes are safe and consistent"}
{"file": ".trellis/spec/backend/error-handling.md", "reason": "Verify validation and ServiceResult behavior"}
{"file": ".trellis/spec/backend/logging-guidelines.md", "reason": "Verify audit/system-log behavior"}
{"file": ".trellis/spec/backend/quality-guidelines.md", "reason": "Backend quality checks"}
{"file": ".trellis/spec/frontend/index.md", "reason": "Frontend checklist for JSP changes"}
{"file": ".trellis/spec/frontend/component-guidelines.md", "reason": "Verify UI consistency for admin forms/tables/alerts"}
{"file": ".trellis/spec/frontend/type-safety.md", "reason": "Verify Servlet/JSP attribute contracts"}
{"file": ".trellis/spec/frontend/quality-guidelines.md", "reason": "Frontend quality checks"}
{"file": ".trellis/tasks/archive/2026-04/00-bootstrap-guidelines/research/project-requirements.md", "reason": "Verify implementation remains aligned with project requirements"}
@@ -0,0 +1,12 @@
{"file": ".trellis/spec/backend/index.md", "reason": "Backend architecture and pre-development checklist for JSP/Servlet/MySQL implementation"}
{"file": ".trellis/spec/backend/directory-structure.md", "reason": "Expected controller/service/DAO/entity package layout"}
{"file": ".trellis/spec/backend/database-guidelines.md", "reason": "Schema, JDBC DAO, and migration safety rules for users and system logs"}
{"file": ".trellis/spec/backend/error-handling.md", "reason": "ServiceResult and validation/error behavior for admin workflows"}
{"file": ".trellis/spec/backend/logging-guidelines.md", "reason": "System-log/audit-log behavior and Java logging conventions"}
{"file": ".trellis/spec/backend/quality-guidelines.md", "reason": "Backend quality bar before coding and build checks"}
{"file": ".trellis/spec/frontend/index.md", "reason": "Frontend JSP/CSS conventions and checklist"}
{"file": ".trellis/spec/frontend/directory-structure.md", "reason": "JSP placement and static asset organization"}
{"file": ".trellis/spec/frontend/component-guidelines.md", "reason": "Existing UI patterns for forms, tables, alerts, and navigation"}
{"file": ".trellis/spec/frontend/type-safety.md", "reason": "Servlet-to-JSP request attribute and validation contracts"}
{"file": ".trellis/spec/frontend/quality-guidelines.md", "reason": "Frontend verification expectations"}
{"file": ".trellis/tasks/archive/2026-04/00-bootstrap-guidelines/research/project-requirements.md", "reason": "Original project scope and library-management requirements"}
@@ -0,0 +1,100 @@
# Admin User Management And System Logs
## Goal
Implement the next administrator feature slice for the JSP + Servlet + MySQL library-management system: user/account management and system log viewing.
## What I already know
* The user asked to continue developing the program.
* The project is a Java 11 Maven WAR application using JSP + Servlet on Tomcat and MySQL through JDBC DAO classes.
* Existing implemented slices include login, role/permission checks, dashboard navigation, book catalog/search, book management, reader profile/eligibility management, borrowing circulation, reader loan history, overdue visibility, and a report center.
* Recent commits show the latest completed feature slices were borrowing circulation and the report center.
* Current routes include `/login`, `/logout`, `/dashboard`, role homes, `/catalog`, `/books`, `/readers`, `/borrowing`, `/reader/loans`, and `/reports`.
* The schema already defines `users`, `roles`, `permissions`, `role_permissions`, `system_logs`, `readers`, `book_categories`, `books`, and `borrow_records`.
* Permissions already include `manage_users` and `view_system_logs`, but there are no dedicated user-management or system-log UI/controller/service/DAO slices in the current codebase.
* The user asked whether user/account management and system-log viewing can be completed together; they are closely related administrator backend features and should be implemented in one task.
## Assumptions (temporary)
* The feature should build on the existing library-management roadmap rather than refactor unrelated infrastructure.
* User/account management and system logs should share the administrator area, navigation pattern, and authorization style where practical.
## Open Questions
* None blocking. MVP scope is locked to user/account management plus read-only system-log viewing.
## Requirements (evolving)
* Preserve the existing JSP -> Servlet -> Service -> DAO -> MySQL layering.
* Keep authorization consistent with `PermissionPolicy` and `AuthorizationFilter`.
* Reuse existing card, form, table, alert, and header patterns for JSP/CSS work.
* Add or update schema/data-access/service/controller/JSP pieces only for user/account management and system-log viewing.
### User / Account Management
* Administrators can open a user-management page from the administrator dashboard/header area.
* Administrators can list users with username, display name, role, active state, created time, and updated time.
* Administrators can search/filter users by keyword, role, and active state.
* Administrators can create user accounts for administrator, librarian, and reader roles.
* Account creation requires username, display name, role, active state, and password.
* Account update allows display name, role, active state, and password reset when a new password is provided.
* Usernames must be unique and normalized consistently with login behavior.
* Passwords must use the existing `PasswordHasher`; no plain-text password storage.
* Deactivation should be supported through the same user edit/update path or a clear action; physical deletion is out of scope.
* Reader-account creation does not need to automatically create or link a reader profile in this MVP. Existing reader profile management may continue to link by user id.
* Administrators should not accidentally lock out all administrator access. At minimum, block deactivating the currently logged-in administrator's own account and block changing their own role away from administrator.
### System Log Viewing
* Administrators can open a system-log page from the administrator dashboard/header area.
* System-log viewing is read-only in this MVP.
* Logs should show operator id/name when available, operation type, detail, IP address when available, and created time.
* Logs can be filtered by operation type, keyword, and date range when practical within existing schema.
* The newest logs should appear first.
* Empty and error states should use existing JSP alert/empty-state conventions.
### Audit Logging
* User-management create/update/deactivate actions should write system-log rows.
* Login/logout logging can remain as existing Java logger output unless implementing database audit logging is cheap and consistent.
* Log write failures should not make normal user-management operations appear successful if the business transaction depends on the log row; otherwise, keep behavior conservative and explain in code via service result/logging.
## Acceptance Criteria (evolving)
* [ ] Administrator can open user management from the admin area.
* [ ] Administrator can list, search, create, update, and deactivate user accounts.
* [ ] User create/update validation handles required fields, duplicate username, valid role, active state, and optional password reset.
* [ ] User passwords are hashed with the existing password hashing utility.
* [ ] The current administrator cannot deactivate their own account or change their own role away from administrator.
* [ ] Administrator can open read-only system logs from the admin area.
* [ ] System logs show newest entries first and support practical filtering.
* [ ] User-management changes create system-log entries.
* [ ] Routes are protected by `manage_users` / `view_system_logs` authorization as appropriate.
* [ ] Feature follows existing validation and `ServiceResult` behavior.
* [ ] Maven build/check commands pass where available.
## Definition of Done (team quality bar)
* Tests added/updated where appropriate.
* Lint/typecheck/build checks are green.
* Docs/notes updated if behavior changes.
* Rollout/rollback considered if risky.
## Out of Scope (explicit)
* No unrelated visual redesign.
* No broad framework migration.
* No destructive database reset requirement.
* No role/permission editor UI.
* No automatic reader-profile creation/linking from user creation.
* No system-log deletion/export/retention policy.
* No password self-service or email reset workflow.
## Technical Notes
* `src/main/webapp/WEB-INF/web.xml` defines the current Servlet mappings.
* `src/main/resources/db/schema.sql` already contains user, permission, and system log tables.
* `src/main/java/com/mzh/library/entity/Permission.java` includes `MANAGE_USERS` and `VIEW_SYSTEM_LOGS`.
* `src/main/java/com/mzh/library/filter/AuthorizationFilter.java` maps `/admin` to `MANAGE_USERS`.
* `src/main/webapp/WEB-INF/jsp/dashboard.jsp` and `role-home.jsp` describe administrator account, role, permission, and system-maintenance entry points, but those are not fully implemented yet.
@@ -0,0 +1,26 @@
{
"id": "continue-development",
"name": "continue-development",
"title": "brainstorm: 继续开发程序",
"description": "",
"status": "in_progress",
"dev_type": null,
"scope": null,
"package": null,
"priority": "P2",
"creator": "Zzzz",
"assignee": "Zzzz",
"createdAt": "2026-04-27",
"completedAt": null,
"branch": null,
"base_branch": "master",
"worktree_path": null,
"commit": null,
"pr_url": null,
"subtasks": [],
"children": [],
"parent": null,
"relatedFiles": [],
"notes": "",
"meta": {}
}