Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ed713d2cb | ||
|
|
b070358446 | ||
|
|
cd1034e962 | ||
|
|
bd881ada09 | ||
|
|
e62c83a187 | ||
|
|
4f38f6b167 | ||
|
|
518901a6d8 | ||
|
|
7aa5c4b921 | ||
|
|
81ef54f996 | ||
|
|
7fc3adfe05 | ||
|
|
8a527e9ffe | ||
|
|
adc62ac436 | ||
|
|
1523dc566b | ||
|
|
d715073ab2 | ||
|
|
10f59c5ca8 | ||
|
|
b9912478e0 | ||
|
|
01603e9ece | ||
|
|
9d811df86a | ||
|
|
877a6b07ad | ||
|
|
c4ff538a8a | ||
|
|
256ad936f8 | ||
|
|
059107fbaa | ||
|
|
e240a9c37f | ||
|
|
dd9bbbe036 | ||
|
|
091503a820 | ||
|
|
6598b58cb8 | ||
|
|
5ce684168a | ||
|
|
6c6734baa3 | ||
|
|
39708224ad | ||
|
|
f6fe246ad0 | ||
|
|
f7ec74c7f0 | ||
|
|
a0146be325 | ||
|
|
bbf268e00a | ||
|
|
c82498e5d8 | ||
|
|
8f301e0ce5 | ||
|
|
44dace109b | ||
|
|
21bef0e4aa |
No files matched your search
@@ -76,6 +76,18 @@ After running `04`, `SELECT LENGTH(password) FROM \`service-system\`.\`user\` WH
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| `openspec/changes/archive/2026-11-30-add-admin-email-listing/sql/01-email-module.sql` | Adds the Emails back-office module (`BO_EMAILS`). |
|
||||
| `openspec/changes/archive/2026-11-30-add-admin-login-security/sql/01-login-audit.sql` | Creates the `login_audit` table (admin login history; the lockout reads it). DDL: run it with a user that may create tables, not the services' user. |
|
||||
| `openspec/changes/archive/2026-11-30-add-admin-login-security/sql/02-lockout-settings.sql` | Adds `ADMIN_LOGIN_MAX_ATTEMPT` (5) and sets the admin block period to 15 minutes: 5 failed sign-ins in 15 minutes lock the username. |
|
||||
| `openspec/changes/archive/2026-11-30-add-admin-login-security/sql/03-login-security-module.sql` | Adds the Login security back-office module (`BO_LOGIN_SECURITY`). |
|
||||
|
||||
`99-rollback.sql` in the same folder undoes the three and deletes the login history.
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| `openspec/changes/archive/2026-11-30-add-admin-audit-log/sql/01-audit-event.sql` | Creates `service-log`.`audit_event` (the admin audit trail). DDL: run it with a user that may create tables, not the services' user. |
|
||||
| `openspec/changes/archive/2026-11-30-add-admin-audit-log/sql/02-audit-log-module.sql` | Adds the Audit log back-office module (`BO_AUDIT_LOG`). No role gets it; super admins grant it under Roles. |
|
||||
|
||||
`99-rollback.sql` in the same folder undoes the two and deletes the audit trail.
|
||||
|
||||
**Database user:**
|
||||
- Create one user with `SELECT, INSERT, UPDATE, DELETE, EXECUTE` on the five schemas. EXECUTE is needed: service-member calls a stored function.
|
||||
@@ -93,6 +105,7 @@ The services publish and subscribe through Google Pub/Sub. It is not replaced in
|
||||
- **Project:** use a Google Cloud project, and give its id as `GCP_PROJECT`.
|
||||
- **Service account:** create one with the Pub/Sub Publisher and Pub/Sub Subscriber roles, and download a JSON key. Mount the key into every Java image except `api-gateway` (section 7), and set `GCP_CREDENTIAL_FILE=file:/var/secrets/gcp/key.json`.
|
||||
- **Topics and subscriptions:** use `local/pubsub/topics.txt`. Each line is a topic name, optionally followed by a subscription name. Some topics appear on several lines with different subscriptions (e.g. `update-sync-topic`): create each topic once, then every subscription listed for it. Subscriptions use default settings.
|
||||
- **Audit log:** `audit-event-topic` with `audit-event-subscription` carries admin audit events from mobile-api to service-log. It is in `topics.txt`; service-log also creates both at startup if they are missing. Keep the subscription's default of not retaining acknowledged messages: the events carry admin usernames and IPs. `AUDIT_RETENTION_DAYS` (section 6) must be at least 1, or service-log does not start.
|
||||
|
||||
## 6. Environment variables
|
||||
|
||||
@@ -155,6 +168,12 @@ The keys:
|
||||
| `JWT_SECRET` | Secret | Same value as `JWT_TOKEN` |
|
||||
| `CUSTOMER_PORTAL_BASE_URL` | Plain | The customer portal is not deployed in phase 1. When unset, it falls back to a Tastefully address that only the member referral link uses, which Co-Lite does not use. Set it once a customer portal exists. |
|
||||
|
||||
**`service-log`:**
|
||||
|
||||
| Variable | Kind | Value |
|
||||
|---|---|---|
|
||||
| `AUDIT_RETENTION_DAYS` | Plain | Optional (default 730). Admin audit events older than this many days are deleted daily at 03:30. |
|
||||
|
||||
**`api-gateway`:** only `JWT_TOKEN` (same value as everywhere). No Pub/Sub, Redis or database settings, and no `key.json` mount. It reads its client keys from the mounted `appkeys.json` (section 7).
|
||||
|
||||
**`admin-portal`:**
|
||||
@@ -264,6 +283,7 @@ data:
|
||||
## 10. Known gaps at go-live
|
||||
|
||||
- **No email provider yet.** Staff onboarding does not need one: the admin types each new user's first password, and "Set temporary password" on a user's page unlocks a user who forgot theirs. Both force a password change at the next sign-in. Forgot-password and "Send password reset" still create an email with a temporary password. Nobody receives it, but `service-email` saves every email first, so a super admin (or a role granted Emails) can read it under **Emails** and pass the password on in person. The user must change it at the next sign-in. Grant Emails narrowly: it shows every saved email, including other users' temporary passwords, member email-verification codes, and contact or distributor form submissions with the sender's personal data.
|
||||
- **Sign-in lockout.** 5 failed sign-ins within 15 minutes lock a username, even with the right password, until 15 minutes after the first of those failures, and unknown usernames are counted too. Anyone who knows a username can therefore lock it on purpose. An admin with **Login security** can unlock it at once (Locked tab), and can change the limits there. If every super admin is locked, wait out the period. The lock check fails open: if `service-system` is down, sign-in still works without the lockout.
|
||||
- **Reference data from Tastefully.** It still holds some Tastefully business text (message templates with a phone number, bank account and form links; a public image bucket URL; Tastefully usernames in audit columns). Review it before go-live.
|
||||
- **Other Tastefully defaults.** The sender addresses in `service-email` and the `CUSTOMER_PORTAL_BASE_URL` fallback point at Tastefully. Override them as described in section 6.
|
||||
- **Leaked SMS key.** An SMS360 API key from Tastefully was in `service-email`'s config and is in git history. It has been removed from the config, but it must be rotated with SMS360 before go-live, by whoever owns that Tastefully account.
|
||||
|
||||
+10
-7
@@ -20,7 +20,7 @@ Source: whiteboard session (transcribed 2026-11-26). Items marked **[?]** were u
|
||||
| 2 | Leads module | Assign leads to sales team | ✓ |
|
||||
| 3 | Built-in WhatsApp | WhatsApp messaging inside the system | ✓ |
|
||||
| 4 | Home — create event | Create event per lead | not ticked |
|
||||
| 5 | QR | Show event details? / scan QR | ✓ |
|
||||
| 5 | QR | Multi-purpose QR: event details, event check-in, later other uses (see Answered) | ✓ |
|
||||
| 6 | Voucher | INS own voucher; partner voucher | ✓ |
|
||||
| 7 | Event milestone | Track events joined (Achievement Board) | ✓ |
|
||||
| 8 | Gamification | Experience / service giveaway: (i) Spin & Win, (ii) Blindbox. Prizes: IPTV test kit, Omada, CCTV? | ✓ |
|
||||
@@ -36,16 +36,19 @@ Source: whiteboard session (transcribed 2026-11-26). Items marked **[?]** were u
|
||||
|
||||
## Open Questions
|
||||
|
||||
- "Tastetuny" **[?]** written under the deadline — project or client name?
|
||||
- QR: should scanning show event details, check the member in, or both?
|
||||
- Gamification prizes: confirm IPTV test kit, Omada, CCTV.
|
||||
- Who are "INS" and "CV" — the two partnering brands (CV = Containerverse?)?
|
||||
- Left edge of the board was cut off — any missing items?
|
||||
- Gamification prizes: none chosen yet (IPTV test kit, Omada, CCTV were ideas only). To be confirmed.
|
||||
|
||||
## Answered (2026-11-30)
|
||||
|
||||
- **"Tastetuny"** on the board is Tastefully, the platform Co-Lite is cloned from.
|
||||
- **QR:** a QR code can carry different purposes: event details, an event check-in, and later other uses. Scanning does what the code is for. This improves on Tastefully's existing QR feature, which is only a starting point.
|
||||
- **INS and CV** are the two companies that will use the system as a test run. Each sees only its own data at go-live; super admins see all (see Tenancy below).
|
||||
- **Left edge of the board:** nothing missing for now.
|
||||
|
||||
## Decisions (2026-11-26)
|
||||
|
||||
- **Base:** Clone of Tastefully (`~/Projects/tastefully`, Solvway platform).
|
||||
- **Tenancy:** Single company at go-live. No second company planned soon. New tables still carry a company id so a later SaaS move is a migration, not a rebuild.
|
||||
- **Tenancy:** ~~Single company at go-live.~~ Changed 2026-11-30: two companies (INS and CV) at go-live, each seeing only its own data (leads, events, users and the rest). Super admins see every company's data. New tables carry a company id; admin APIs and screens must filter by it.
|
||||
- **Modules dropped:** MLM modules (bonus, stockist, tree, inventory, related jobs).
|
||||
- **Admin portal:** Rebuild as a Next.js admin portal, modelled on babyboo's `solvway-admin-portal` (shell, auth, roles, tables). The Tastefully Thymeleaf backoffice is ported over for reference only; it is not deployed or extended.
|
||||
- Every admin screen needs a JSON admin API in `mobile-api` (`/api/admin/**`). Tastefully has none today; babyboo's admin controllers for auth, users, roles, audit log and content are adaptable. Events, check-in, rewards and vouchers admin APIs must be built new.
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
# Admin Audit Log — Design
|
||||
|
||||
Date: 2026-11-30. Change id: `add-admin-audit-log`.
|
||||
|
||||
## Intent
|
||||
|
||||
Nothing in Co-Lite records who did what in the admin portal. When an admin edits a user, changes a role's grants, edits or exports leads, or opens a saved email (which can hold a temporary password), the only trace is a line in the application log. Sign-ins are the exception: the `login_audit` table covers them (`add-admin-login-security`).
|
||||
|
||||
The user wants an audit trail before go-live (2027-01-15) and a screen to read it. Scope was agreed on 2026-11-30, with lead edits recording field names only, not values.
|
||||
|
||||
Reference: babyboo's `add-portal-audit-log` (archive `2026-11-19`) and `audit-log-readable-actions` (`2026-11-20`). This design ports the admin half of that work, trimmed.
|
||||
|
||||
## Goals
|
||||
|
||||
- Record an audit event for every admin write through mobile-api, and for chosen sensitive reads.
|
||||
- Record refused attempts (a missing module grant, for example) when the token is valid, so the actor is known.
|
||||
- Store before/after values only for an allow-list of fields.
|
||||
- Provide an `/audit-log` screen in the admin portal with filters and a detail view, behind its own module.
|
||||
- Delete events after 2 years, automatically.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Member and public calls. The customer portal's public lead capture has no actor.
|
||||
- Sign-in, sign-out and own password change. `login_audit` already records these; the audit log neither duplicates nor links to them.
|
||||
- Page views and ordinary reads (the existing response-time log covers traffic).
|
||||
- Reviving or cleaning up the legacy `back_office_access_log`, `/log/save` and similar. They are unused; removing them belongs in a separate change.
|
||||
|
||||
## Anti-goals
|
||||
|
||||
- Any password, token, raw request body, or lead personal data (name, phone, email, notes) in an audit row.
|
||||
- An audit write that slows down or fails the admin's action.
|
||||
- Audit rows that anyone without `BO_AUDIT_LOG` can read.
|
||||
|
||||
## Approaches considered
|
||||
|
||||
- **A. Pub/Sub from mobile-api's `AppAccessAspect` to services-log (chosen).** The aspect already sees every admin call (the user, its `@AdminModule` code, the outcome) and already publishes a `ResponseTime` record per call to services-log over Pub/Sub. One more message type on the same path is the smallest change. It is asynchronous, and losing an event is acceptable.
|
||||
- **B. A synchronous REST call from mobile-api to services-log, like `login_audit`.** Simpler to test, but it adds a network hop to every admin write, and it needs its own error handling.
|
||||
- **C. Explicit calls inside each service method.** Easy to forget on new endpoints. Rejected: the aspect covers new endpoints by default.
|
||||
|
||||
## Design
|
||||
|
||||
### Event table `service-log`.`audit_event`
|
||||
|
||||
| Column | Meaning |
|
||||
|---|---|
|
||||
| `id` | PK |
|
||||
| `company_id` | the actor's company (nullable) |
|
||||
| `occurred_at` | server time of the call |
|
||||
| `actor` | admin username |
|
||||
| `module` | the handler's `@AdminModule` code (for example `BO_USERS`) |
|
||||
| `action` | readable action code (see below) |
|
||||
| `http_method`, `path_template` | for example `PUT /api/admin/users/{id}`: the template, never the concrete path or the query |
|
||||
| `target_id` | the record acted on: the first path variable, when there is one |
|
||||
| `outcome`, `http_status` | `SUCCESS` or `FAILURE`, plus the status code |
|
||||
| `client_ip` | forwarded browser IP (nullable) |
|
||||
| `changes` | JSON, nullable: `{field: {before, after}}` for allow-listed fields, or `{fields: [..]}` for lead edits |
|
||||
|
||||
Indexes: `occurred_at`, `(actor, occurred_at)`, `(module, action, occurred_at)`. The DDL and the module row go in the change's `sql/` folder and in `local/seed/03-colite.sql`.
|
||||
|
||||
### What is recorded
|
||||
|
||||
- **Every non-GET handler under `/api/admin/**`,** except:
|
||||
- `AdminAuthController`'s login, logout, refresh, forgot-password and change-password. Sign-in history covers these, or they have no actor.
|
||||
- `first-login` is recorded.
|
||||
- POSTs that only read, marked with `@Audited(skip = true)`. Today that is event-lead `match`.
|
||||
- **Sensitive GETs, marked with `@Audited`:**
|
||||
- the lead export;
|
||||
- the event-lead export;
|
||||
- the email detail (opening an email).
|
||||
- **Refusals:** a valid admin token refused by the access check (missing module, not super admin, pending first login) is recorded as `FAILURE` with the status. Calls without a valid token are not recorded, because there is no actor.
|
||||
|
||||
### Action codes
|
||||
|
||||
`@Audited(action = "...")` names an action explicitly. Without one, the code is derived from the handler: drop an `Admin` prefix and a `Controller` suffix, then convert both parts to UPPER_SNAKE. For example, `AdminUserController.update` becomes `USER_UPDATE`. Explicit names are used where the derived one would be unclear:
|
||||
- `USER_SET_TEMPORARY_PASSWORD`;
|
||||
- `USER_SEND_PASSWORD_RESET`;
|
||||
- `ROLE_SET_MODULES`;
|
||||
- `LEAD_EXPORT`;
|
||||
- `EVENT_LEAD_EXPORT`;
|
||||
- `EMAIL_VIEW`.
|
||||
|
||||
### Before/after (allow-listed)
|
||||
|
||||
The handler's service supplies the values through a small request-scoped holder (babyboo's `AuditChanges`). Nothing is diffed generically from request bodies.
|
||||
|
||||
- **Admin user update and create:** `roles` (role names) and `enabled`.
|
||||
- **Role module grants:** module codes added and removed.
|
||||
- **Lead edit and event-lead edit:** the names of the fields that changed, no values. This was the user's call.
|
||||
- **Login-security settings** (lockout and password rules): the changed setting names with before and after. These are not personal data.
|
||||
|
||||
### Write path
|
||||
|
||||
- After the handler returns or throws, `AppAccessAspect` builds an `AuditEvent` and publishes it to the new Pub/Sub topic `audit-event`. The `AuditEvent` message class lives in core-libs, shared by mobile-api and services-log.
|
||||
- services-log subscribes on `audit-event-log`, which it creates at startup like its existing subscriptions, and saves the event.
|
||||
- A publish failure is logged at WARN and swallowed. The existing response-time publishing is unchanged.
|
||||
|
||||
### Client IP
|
||||
|
||||
- The portal's server-side calls to mobile-api already send `X-Client-Ip` on every request (`app/lib/server/mobileApi.ts`, the last `x-forwarded-for` hop), so the portal needs no change.
|
||||
- mobile-api stores the value for reading only.
|
||||
|
||||
### Retention
|
||||
|
||||
A scheduled purge in services-log deletes events older than `audit.retention-days` (default 730) in batches, modelled on the existing response-time archive scheduler. The setting is an environment variable.
|
||||
|
||||
### Reading
|
||||
|
||||
- services-log gets `POST /log/audit/search`. It takes filters (actor, module, action, outcome, date range) and paging, returns newest first, and caps the page size at 100.
|
||||
- services-log also gets `GET /log/audit/{id}`.
|
||||
- Both are reached through the gateway with the admin's token, like the other services. Only mobile-api holds a gateway key (`docs/deployment.md` section 7).
|
||||
- mobile-api adds `GET /api/admin/audit-log` and `GET /api/admin/audit-log/{id}` under `@AdminModule("BO_AUDIT_LOG")`.
|
||||
|
||||
### Admin portal
|
||||
|
||||
- **`/audit-log`:** a paged list (newest first) with columns time, who, module, action, target, outcome and IP.
|
||||
- **Filters:** who, module (select), action, outcome and From/To date.
|
||||
- **Detail page:** the event, plus a before/after table, or a list of changed field names for lead edits.
|
||||
- **Copy and gating:** all copy goes through `t()`. The page is gated by `RequireModule` and `ROUTE_MODULES`.
|
||||
- **Module row:** `(41100000, 'BO_AUDIT_LOG', 'Audit log', 'BO', 'M', 40000000, '/audit-log', 'ScrollText')`. It has no role grants, so only super admins see it until it is granted.
|
||||
|
||||
## My calls (check these)
|
||||
|
||||
- Pub/Sub, asynchronous, best-effort. A lost event is acceptable, as in babyboo.
|
||||
- Reads go through the gateway with the admin's token. babyboo switched to in-cluster calls because other api-key holders existed; Co-Lite has only mobile-api.
|
||||
- `first-login` is recorded and the other auth endpoints are not.
|
||||
- The login-security settings record values, since they are not personal data. User changes record role names and the enabled flag only.
|
||||
- Retention is 730 days, set by environment variable rather than on a screen.
|
||||
- Legacy `/log/save` and the old access-log tables are left alone.
|
||||
|
||||
## Left to the builder
|
||||
|
||||
- The exact JSON shape of `changes`, as long as the detail view can render it.
|
||||
- Column widths, so the list fits at 1280 px without horizontal scrolling (babyboo hit this).
|
||||
@@ -0,0 +1,150 @@
|
||||
# Admin Login Security and Own Password Change — Design
|
||||
|
||||
Date: 2026-11-30. Change id: `add-admin-login-security`.
|
||||
|
||||
## Intent
|
||||
|
||||
Before go-live (2027-01-15), staff must be able to change their own password, and the admin login must resist password guessing. Today nothing counts failed logins: anyone who reaches the login page can try passwords without limit. The admin portal has no way to change your own password, and no way to see or unlock locked staff.
|
||||
|
||||
The user chose a persisted login history (babyboo's `login_audit` approach) over a Redis counter, because the history also serves the later audit-log viewer.
|
||||
|
||||
## Goals
|
||||
|
||||
- Every admin login attempt, logout and unlock is recorded with time, username, outcome, client IP and user agent.
|
||||
- After a configured number of failed attempts in a configured period, the username is locked. A locked username is refused even with the right password.
|
||||
- An admin can see locked staff and unlock them.
|
||||
- An admin can read the login history, filtered by username, outcome and date.
|
||||
- An admin can edit the lockout settings and the admin password rules.
|
||||
- Any signed-in admin can change their own password from the user menu.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Session policy (logout revocation, sliding sessions, single session). babyboo bundled this; it stays out.
|
||||
- MFA, CAPTCHA, password aging and password history.
|
||||
- Member, stockist and customer logins. Admin (type A) only.
|
||||
- Purging old `login_audit` rows. The volume is small for one company; add a purge when it matters.
|
||||
|
||||
## Anti-goals
|
||||
|
||||
- A services-system outage must not lock out every admin. The lock check fails open on infrastructure errors.
|
||||
- The login answer must not reveal whether a username exists.
|
||||
- A failed audit write must not block a valid login.
|
||||
|
||||
## Approaches considered
|
||||
|
||||
- **A. Redis counter:** one key per username with a TTL. Cheapest, but keeps no history.
|
||||
- **B. Persisted `login_audit` table (chosen):** lock state is derived from the history. It costs a new table and deploy SQL, and it gives the history the audit viewer needs.
|
||||
- **C. In-memory counter like the legacy backoffice:** lost on restart and not shared between instances. Rejected.
|
||||
|
||||
## Design
|
||||
|
||||
### Where it is enforced
|
||||
|
||||
In mobile-api `AdminAuthController.login`, not in services-auth (babyboo's choice). Reason: in Co-Lite only the admin portal is public (Traefik, `docs/deployment.md` section 8), and only mobile-api holds a gateway key (`appkeys.json`, section 7). Every admin login therefore passes through `AdminAuthController.login`. Enforcing there leaves the shared services-auth credential path untouched.
|
||||
|
||||
### Table
|
||||
|
||||
`service-system`.`login_audit`, created by SQL in the change folder and in `local/seed/03-colite.sql`:
|
||||
|
||||
| Column | Type | Note |
|
||||
|---|---|---|
|
||||
| `id` | BIGINT PK auto | |
|
||||
| `company_id` | BIGINT NULL | the user's company when the username matches a user, else NULL |
|
||||
| `username` | VARCHAR(191) | as typed, trimmed, cut to 191 |
|
||||
| `datetime` | DATETIME | server time |
|
||||
| `event` | VARCHAR(20) | `LOGIN_SUCCESS`, `LOGIN_FAIL`, `LOGIN_LOCKED`, `LOGOUT`, `UNLOCK_RESET`, `PASSWORD_CHANGED` |
|
||||
| `ip_address` | VARCHAR(64) | |
|
||||
| `user_agent` | VARCHAR(512) | cut to 512 |
|
||||
| `message` | VARCHAR(255) | for example who unlocked |
|
||||
|
||||
Indexes: `(username, datetime)` for the lock count and `(event, datetime)` for the listing.
|
||||
|
||||
### Lock rule
|
||||
|
||||
Settings live in `system_property`:
|
||||
|
||||
- `ADMIN_LOGIN_BLOCK_PERIOD` (type `ADMIN_LOGIN_BLOCK`): the value is the period length. Status `Y` turns lockout on.
|
||||
- `ADMIN_LOGIN_BLOCK_TIME_UNIT`: S, M, H or D.
|
||||
- **New row** `ADMIN_LOGIN_MAX_ATTEMPT` (type `ADMIN_LOGIN_BLOCK`): the number of failures that locks.
|
||||
|
||||
The seeded period is 1 minute, which is too weak. Deploy SQL sets the defaults to **5 attempts in 15 minutes**.
|
||||
|
||||
A username is locked when lockout is on and the number of `LOGIN_FAIL` rows meets both conditions below, and that number is at least the maximum:
|
||||
|
||||
- the row is newer than (now minus period);
|
||||
- the row is newer than the latest `LOGIN_SUCCESS`, `UNLOCK_RESET` or `PASSWORD_CHANGED` for that username.
|
||||
|
||||
The lock ends by itself once the failures age out of the period. Logout does not reset the count.
|
||||
|
||||
Failures are counted for any username, known or not. A locked answer therefore does not show that the account exists. Trade-off: anyone can lock a real admin out for one period by guessing wrong. The Unlock button and the expiry limit the damage.
|
||||
|
||||
### services-system `/loginSecurity`
|
||||
|
||||
All rules are read and written here:
|
||||
|
||||
- `GET /loginSecurity/isLocked/{username}`: `{locked: boolean}`.
|
||||
- `POST /loginSecurity/record`: `{username, event, ip, userAgent, message}`. Fills `company_id` from the user table.
|
||||
- `POST /loginSecurity/audit`: paged and filtered (username contains, event, from, to), newest first.
|
||||
- `GET /loginSecurity/locked`: the usernames locked now, with failure count, last failure time and when the lock ends.
|
||||
- `POST /loginSecurity/unlock/{username}`: writes `UNLOCK_RESET` with the unlocking admin in `message`.
|
||||
- `GET` and `POST /loginSecurity/config`: lockout on/off, max attempts, period and unit.
|
||||
- Password rules: `GET` and `POST` for the `ADMIN_PWD_FORMAT` rows. Only status and value can change; rows cannot be added or removed.
|
||||
|
||||
### mobile-api login flow
|
||||
|
||||
1. Blank username or password returns 401 `BAD_LOGIN`, as today, and nothing is recorded.
|
||||
2. Call `isLocked`. If the answer is locked, record `LOGIN_LOCKED` and return 401 with code `ACCOUNT_LOCKED` and the message "Too many failed sign-ins. Try again later or ask an administrator to unlock your account." If services-system errors, log a warning and carry on (fail open).
|
||||
3. Run the existing credential check. A bad password, an unknown user or a disabled user records `LOGIN_FAIL`. A success records `LOGIN_SUCCESS`.
|
||||
4. Recording is best-effort: a failure is logged and never changes the answer.
|
||||
|
||||
Logout records `LOGOUT`.
|
||||
|
||||
The client IP and user agent come from the portal: its login and logout routes forward `X-Forwarded-For` (first hop, as set by Traefik) and `User-Agent`. mobile-api uses them for the audit only, never for any decision.
|
||||
|
||||
### Own password change
|
||||
|
||||
`POST /api/admin/auth/change-password` takes `{currentPassword, newPassword, confirmPassword}`. Any signed-in admin may call it, except one with a pending first-login change, who uses first-login instead.
|
||||
|
||||
- A missing field returns 400 `REQUIRED_FIELD`.
|
||||
- New and confirm differ: 400 `PASSWORD_MISMATCH`.
|
||||
- New equals current: 400 `PASSWORD_SAME`.
|
||||
- New fails `ADMIN_PWD_FORMAT`: 400 `PASSWORD_POLICY`.
|
||||
- A wrong current password records `LOGIN_FAIL` and returns 400 `CURRENT_PASSWORD_WRONG`. A stolen session therefore cannot guess the password without limit: the failures lock the username like failed logins do.
|
||||
- If the username is locked: 400 `ACCOUNT_LOCKED`, checked before the current password.
|
||||
- On success: save the bcrypt of the new password, keep `login = Y`, record `PASSWORD_CHANGED`, return 204. The session stays signed in.
|
||||
|
||||
The builder decides how to check the current password. Prefer the bcrypt match services-auth already uses over issuing and revoking a throwaway token.
|
||||
|
||||
### Admin portal
|
||||
|
||||
- **User menu:** a "Change password" item opens a dialog with current, new and confirm fields, reusing `PasswordFields`. On success it shows a toast and closes. Errors show the server message through `t()`.
|
||||
- **Login page:** shows the `ACCOUNT_LOCKED` message when the server returns that code.
|
||||
- **New screen `/login-security`:** module `BO_LOGIN_SECURITY`, id `41000000`, url `/login-security`, a shield-style icon. It has three tabs:
|
||||
1. **History:** a DataTable with time, username, event, IP and user agent. Filters: username, event, from date, to date.
|
||||
2. **Locked:** username, failures, last failure and lock end, with an Unlock button that asks for confirmation.
|
||||
3. **Settings:** lockout on/off, max attempts, period and unit; then each admin password rule with an on/off switch and a value.
|
||||
- Settings changes and unlocks log `{action} by {admin}` in mobile-api.
|
||||
|
||||
### Deploy SQL (in the change folder; also in the local seed)
|
||||
|
||||
1. `CREATE TABLE login_audit`.
|
||||
2. Insert `ADMIN_LOGIN_MAX_ATTEMPT` = 5, status Y. Update the period to 15, keeping unit `M`.
|
||||
3. Insert the module row `BO_LOGIN_SECURITY`.
|
||||
|
||||
A rollback script drops the table and both rows.
|
||||
|
||||
## My calls (check these)
|
||||
|
||||
- Enforcement sits in mobile-api, not services-auth, because mobile-api is the only path in.
|
||||
- Defaults: 5 attempts in 15 minutes.
|
||||
- Failures are counted for unknown usernames too, so a lock does not reveal which accounts exist.
|
||||
- A wrong current password on change-password counts as a failed login.
|
||||
- Changing your password does not sign out your other sessions. That belongs to session policy, which is a non-goal.
|
||||
- The Settings tab is gated only by the module grant, like the other screens, and every change is logged. It is not limited to super admins.
|
||||
- There is no purge of `login_audit`.
|
||||
|
||||
## Left to the builder
|
||||
|
||||
- The exact DataTable columns on phone widths and the icon choice.
|
||||
- Pagination limits: follow `AdminEmailService` (max 100).
|
||||
- Whether the lock query is a single SQL query or a JPA query plus code, as long as the rule above holds.
|
||||
@@ -1,5 +1,6 @@
|
||||
# topic [subscription] - one per line; created in the Pub/Sub emulator before services start
|
||||
activate-member-topic activate-member-subscription
|
||||
audit-event-topic audit-event-subscription
|
||||
backoffice-topic backoffice-subscription
|
||||
batch-transfer-member-topic batch-transfer-member-subscription
|
||||
camunda-new-registration-topic camunda-new-registration-subscription
|
||||
|
||||
@@ -124,3 +124,56 @@ INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `ic
|
||||
-- add-admin-email-listing/sql/01-email-module.sql
|
||||
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||
(40900000, 'BO_EMAILS', 'Emails', 'BO', 'M', 40000000, '/emails', 'Mail');
|
||||
|
||||
-- add-admin-login-security/sql/01-login-audit.sql
|
||||
CREATE TABLE IF NOT EXISTS `login_audit` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`company_id` bigint NULL COMMENT 'the user''s company when the username matches a user',
|
||||
`username` varchar(191) COLLATE utf8mb4_general_ci NOT NULL COMMENT 'compared like `user`.`username`',
|
||||
`datetime` datetime NOT NULL,
|
||||
`event` varchar(20) NOT NULL COMMENT 'LOGIN_SUCCESS | LOGIN_FAIL | LOGIN_LOCKED | LOGOUT | UNLOCK_RESET | PASSWORD_CHANGED',
|
||||
`ip_address` varchar(64) NULL,
|
||||
`user_agent` varchar(512) NULL,
|
||||
`message` varchar(255) NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_login_audit_username_dt` (`username`, `datetime`),
|
||||
KEY `idx_login_audit_event_dt` (`event`, `datetime`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- add-admin-login-security/sql/02-lockout-settings.sql
|
||||
INSERT INTO `system_property` (`param`, `status`, `type`, `value`)
|
||||
SELECT 'ADMIN_LOGIN_MAX_ATTEMPT', 'Y', 'ADMIN_LOGIN_BLOCK', '5'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `system_property` WHERE `param` = 'ADMIN_LOGIN_MAX_ATTEMPT' AND `type` = 'ADMIN_LOGIN_BLOCK');
|
||||
|
||||
UPDATE `system_property` SET `value` = '15', `status` = 'Y'
|
||||
WHERE `param` = 'ADMIN_LOGIN_BLOCK_PERIOD' AND `type` = 'ADMIN_LOGIN_BLOCK';
|
||||
|
||||
-- add-admin-login-security/sql/03-login-security-module.sql
|
||||
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||
(41000000, 'BO_LOGIN_SECURITY', 'Login security', 'BO', 'M', 40000000, '/login-security', 'Shield');
|
||||
|
||||
-- add-admin-audit-log/sql/02-audit-log-module.sql (still USE `service-system` from above)
|
||||
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||
(41100000, 'BO_AUDIT_LOG', 'Audit log', 'BO', 'M', 40000000, '/audit-log', 'ScrollText');
|
||||
|
||||
-- add-admin-audit-log/sql/01-audit-event.sql
|
||||
USE `service-log`;
|
||||
CREATE TABLE IF NOT EXISTS `audit_event` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`company_id` bigint NULL,
|
||||
`occurred_at` datetime(6) NOT NULL,
|
||||
`actor` varchar(191) NOT NULL,
|
||||
`module` varchar(64) NULL,
|
||||
`action` varchar(128) NOT NULL,
|
||||
`http_method` varchar(16) NULL,
|
||||
`path_template` varchar(255) NULL,
|
||||
`target_id` varchar(128) NULL,
|
||||
`outcome` varchar(16) NOT NULL COMMENT 'SUCCESS | FAILURE',
|
||||
`http_status` int NULL,
|
||||
`client_ip` varchar(64) NULL,
|
||||
`changes` text NULL COMMENT 'JSON: allow-listed before/after, or changed field names',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_audit_event_occurred_at` (`occurred_at`),
|
||||
KEY `idx_audit_event_actor` (`actor`, `occurred_at`),
|
||||
KEY `idx_audit_event_module_action` (`module`, `action`, `occurred_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
File renamed without changes.
@@ -0,0 +1,100 @@
|
||||
# Design
|
||||
|
||||
Full design with approaches and the user's approved calls: `docs/superpowers/specs/2026-11-30-admin-audit-log-design.md`.
|
||||
|
||||
## Context
|
||||
|
||||
- **`AppAccessAspect`** (`solvway-mobile-api/.../useraccess/AppAccessAspect.java`) wraps every controller method. It already:
|
||||
- knows the admin from the JWT;
|
||||
- resolves `@AdminModule` from the method, falling back to the class;
|
||||
- refuses with 403 on a missing module, super admin required or pending reset;
|
||||
- publishes a `ResponseTime` record per call to services-log over Pub/Sub (`response-time-log-topic`).
|
||||
- **services-log** stores in MySQL schema `service-log` with JPA. It creates its topics and subscriptions at startup (`configuration/PubSubConfig.java`), listens in `pubsub/PubSubListener.java`, and archives response times on a schedule (`scheduler/ResponseTimeLogArchiveScheduler.java`).
|
||||
- **Local Pub/Sub:** the emulator creates the topics listed in `local/pubsub/topics.txt`.
|
||||
- **Client IP:** the portal already forwards `X-Client-Ip` on every call (`app/lib/server/mobileApi.ts`).
|
||||
- **babyboo reference:**
|
||||
- core-libs `model/AuditEvent.java`;
|
||||
- mobile-api `useraccess/Audited.java`, `useraccess/AuditChanges.java` and the audit part of `useraccess/AppAccessAspect.java`;
|
||||
- `service/AuditLogService.java` and `controller/AdminAuditLogController.java`;
|
||||
- services-log `controller/AuditEventController.java`, `model/AuditEventLog.java`, `repo/AuditEventLogRepository.java` and `service/AuditEventLogPurge.java`;
|
||||
- portal `app/audit-log/page.tsx` and `app/api/audit-log/**`.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- record admin writes, refusals and three sensitive reads;
|
||||
- record allow-listed changes;
|
||||
- delete events after 730 days;
|
||||
- an Audit log screen.
|
||||
|
||||
**Non-Goals:**
|
||||
- member and public calls;
|
||||
- page views;
|
||||
- sign-ins (covered by `login_audit`);
|
||||
- legacy `/log/save` cleanup.
|
||||
|
||||
## Decisions
|
||||
|
||||
1. **`AuditEvent` in core-libs:** fields `companyId`, `occurredAt`, `actor`, `module`, `action`, `httpMethod`, `pathTemplate`, `targetId`, `outcome`, `httpStatus`, `clientIp` and `changes` (a JSON string). It is the shared contract, so it lands first.
|
||||
|
||||
2. **Table `service-log`.`audit_event`:**
|
||||
- Columns follow the event fields.
|
||||
- `changes` is TEXT.
|
||||
- Indexes: `occurred_at`, `(actor, occurred_at)` and `(module, action, occurred_at)`.
|
||||
|
||||
3. **What the aspect records:**
|
||||
- **Writes:** every handler under a class mapped to `/api/admin` whose HTTP method is not GET.
|
||||
- **Sensitive GETs:** handlers annotated `@Audited` (lead export, event-lead export, email detail).
|
||||
- **Skipped:** handlers annotated `@Audited(skip = true)` (event-lead `match`) and every `AdminAuthController` handler except `firstLogin`.
|
||||
- **Actor required:** only calls whose admin token resolved to a user are recorded. A refusal at the access check (403 from the module or super-admin check, or `PASSWORD_RESET_REQUIRED`) for such a user is recorded as `FAILURE`.
|
||||
|
||||
4. **Event fields, as the aspect builds them:**
|
||||
- **Action:** `@Audited(action)`; otherwise derived from the handler: drop an `Admin` prefix and a `Controller` suffix, then UPPER_SNAKE both parts and join them, so `AdminUserController.update` becomes `USER_UPDATE`.
|
||||
- **Path template:** the class `@RequestMapping` plus the method mapping, for example `/api/admin/users/{id}`.
|
||||
- **Target id:** the last path variable (the record acted on, e.g. the event lead in `/event-leads/{eventUuid}/leads/{eventLeadUuid}`). `@Audited(target = false)` records none: the unlock path carries a username as typed at a failed sign-in, which can be a mistyped password.
|
||||
- **Outcome:**
|
||||
- `SUCCESS` for a 2xx `ResponseEntity`, or when there is no `ResponseEntity`;
|
||||
- otherwise `FAILURE` with the status, taken from a non-2xx `ResponseEntity` or from a thrown `ResponseStatusException`;
|
||||
- any other exception is `FAILURE` with 500.
|
||||
- **Client IP:** the `X-Client-Ip` header.
|
||||
|
||||
5. **`AuditChanges`:** a request-scoped holder. Services call `AuditChanges.put(field, before, after)` or `AuditChanges.fields(names...)`, and the aspect serialises the result into `changes`. The allow-list is enforced where the values are supplied:
|
||||
- `AdminUserService` create and update: `roles` (role names) and `enabled`;
|
||||
- `AdminRoleService` set modules: `modules` with the codes added and removed;
|
||||
- `AdminLeadService` and `AdminEventLeadService` edits: changed field names only;
|
||||
- `AdminLoginSecurityService` config and password rules: the changed settings with before and after.
|
||||
|
||||
6. **Publishing:** to `audit-event-topic`, after the handler finishes, through the existing `PubSubUtil` and `PubSubTemplate` pattern used for `ResponseTime`. Any exception is logged at WARN and swallowed.
|
||||
|
||||
7. **services-log:**
|
||||
- Creates `audit-event-topic` and `audit-event-subscription` at startup, like the other topics.
|
||||
- The listener saves each `AuditEvent` as an `AuditEventLog`.
|
||||
- A scheduled purge (daily) deletes rows with `occurred_at` older than `audit.retention-days` (env `AUDIT_RETENTION_DAYS`, default 730), in batches.
|
||||
- **`POST /log/audit/search`:** body `{actor, module, action, outcome, from, to, page, size}`. `actor` and `action` match exactly; `from` and `to` are `yyyy-MM-dd` and inclusive. It returns newest first, caps the size at 100, and answers `{content, totalElements, number, size}`.
|
||||
- **`GET /log/audit/{id}`.**
|
||||
- Both need the admin's token at the gateway, like the other `/log/**` routes.
|
||||
|
||||
8. **mobile-api read API:** `AdminAuditLogController` (`@AdminModule("BO_AUDIT_LOG")`):
|
||||
- `GET /api/admin/audit-log?actor&module&action&outcome&from&to&page&size`;
|
||||
- `GET /api/admin/audit-log/{id}` (404 when missing).
|
||||
- The reads themselves are not audited (GET without `@Audited`).
|
||||
|
||||
9. **Portal `/audit-log`:**
|
||||
- **List:** time, who, module (label from the module's i18n key), action, target, outcome with status, and IP.
|
||||
- **Filters:** who, module select, action, outcome, and From/To `DatePicker`.
|
||||
- **Detail `/audit-log/[id]`:** the event fields, then a changes table (field, before, after), or a list of changed fields when only names were recorded.
|
||||
- **Gating:** `RequireModule` and `ROUTE_MODULES`.
|
||||
- **Proxy:** `app/api/audit-log/[[...path]]/route.ts`, GET only.
|
||||
|
||||
10. **Module row:** `(41100000, 'BO_AUDIT_LOG', 'Audit log', 'BO', 'M', 40000000, '/audit-log', 'ScrollText')`, with no role grants.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- **Lost events:** Pub/Sub publishing is best-effort, so a broker outage loses events. This is accepted, as in babyboo; the application log still carries the existing `... by ...` lines.
|
||||
- **Role names and settings stored as values:** these are not personal data. Lead personal data is never stored; lead edits keep field names only.
|
||||
- **Path variables as targets:** the last path variable is a UUID or id, except the unlock username, which is not recorded. The concrete path is never stored, so no query string, and therefore no search text, ends up in the log.
|
||||
- **Requests refused before the handler:** malformed JSON or a binding error is answered before `AppAccessAspect` runs, so such calls are not recorded.
|
||||
- **Extra reads for before-values:** a lead edit and a login-security settings save read the current values once before saving, only for the audit. The read is best-effort and cannot fail the save; it adds one internal call.
|
||||
- **One company:** reads do not filter by `company_id`. Add the filter when Co-Lite becomes multi-company.
|
||||
- **Retention:** `AUDIT_RETENTION_DAYS` below 1 stops service-log at startup rather than deleting the whole trail.
|
||||
- **Volume:** one row per admin write. With one company and a handful of admins, 730 days is small.
|
||||
@@ -0,0 +1,60 @@
|
||||
# Proposal
|
||||
|
||||
## Why
|
||||
|
||||
Nothing in Co-Lite records who did what in the admin portal. When an admin edits a user, changes a role's grants, edits or exports leads, or opens a saved email (which can hold a temporary password), the only trace is a line in the application log. Sign-ins are the exception: `login_audit` covers them. Go-live is 2027-01-15, and the company needs an audit trail and a screen to read it.
|
||||
|
||||
babyboo built the same thing (`add-portal-audit-log`, archive 2026-11-19, plus `audit-log-readable-actions`, 2026-11-20). This change ports the admin half of that work, trimmed.
|
||||
|
||||
Design: `docs/superpowers/specs/2026-11-30-admin-audit-log-design.md`.
|
||||
|
||||
## What Changes
|
||||
|
||||
- **Recording:**
|
||||
- mobile-api's `AppAccessAspect` publishes an audit event for every admin write under `/api/admin/**`, every refusal of a valid admin token, and three sensitive reads: the lead export, the event-lead export and opening an email.
|
||||
- Sign-in, sign-out, refresh, forgot-password and own password change are not recorded, because `login_audit` covers them or there is no actor.
|
||||
- **Each event:**
|
||||
- who and when; the module and a readable action code;
|
||||
- the method and the path template; the target id;
|
||||
- the outcome and status, and the browser IP.
|
||||
- Before/after values only for an allow-list:
|
||||
- a user's role names and enabled flag;
|
||||
- role module grants;
|
||||
- login-security settings;
|
||||
- for lead edits and event-lead edits, the names of the changed fields only, never the values.
|
||||
- **Transport:** a new Pub/Sub topic `audit-event-topic`. services-log subscribes on `audit-event-subscription` and saves to a new `service-log`.`audit_event` table. Publishing is best-effort: a failure never blocks the admin's action.
|
||||
- **Retention:** services-log deletes events older than `AUDIT_RETENTION_DAYS` (default 730) on a schedule.
|
||||
- **Reading:** services-log gets search and detail endpoints. mobile-api gets `GET /api/admin/audit-log` and `GET /api/admin/audit-log/{id}` under the new module `BO_AUDIT_LOG`.
|
||||
- **Portal:** a new `/audit-log` page with a list, filters and a detail view that shows the changes.
|
||||
- **Not in this change:**
|
||||
- member and public calls;
|
||||
- page views;
|
||||
- removing the unused legacy `/log/save` and `back_office_access_log`.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
- `admin-audit-log`: recording admin actions, refusals and sensitive reads; the allow-listed changes; retention; and the Audit log screen.
|
||||
|
||||
### Modified Capabilities
|
||||
None.
|
||||
|
||||
## Impact
|
||||
|
||||
- **`solvway-core-libs`:** a new `AuditEvent` message class shared by mobile-api and services-log.
|
||||
- **`solvway-services-log`:**
|
||||
- `AuditEventLog` entity and repository;
|
||||
- the topic and subscription setup and the listener;
|
||||
- the purge;
|
||||
- `/log/audit/search` and `/log/audit/{id}`.
|
||||
- **`solvway-mobile-api`:**
|
||||
- the `Audited` annotation and the `AuditChanges` request holder;
|
||||
- publishing in `AppAccessAspect`;
|
||||
- annotations on the sensitive reads and the read-only POST;
|
||||
- changes supplied by the user, role, lead, event-lead and login-security services;
|
||||
- `AdminAuditLogController`.
|
||||
- **`solvway-admin-portal`:** the `/audit-log` pages, a proxy, a service and i18n keys. Client IP is already forwarded on every call.
|
||||
- **Pub/Sub:** a new topic and subscription. They go in `local/pubsub/topics.txt` and `docs/deployment.md` section 5.
|
||||
- **Database:** `sql/01-audit-event.sql` (DDL in `service-log`) and `sql/02-audit-log-module.sql`, mirrored in `local/seed/03-colite.sql`, plus a rollback script.
|
||||
- **Privacy:** no passwords, tokens, request bodies or lead personal data are stored. User role names and login-security settings are stored as values.
|
||||
- No new dependency.
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Admin writes are recorded
|
||||
|
||||
The system SHALL record an audit event for every state-changing admin API call made with a valid admin token, successful or not, holding the time, admin username, module, readable action code, HTTP method, path template (never the concrete path or query), target id, outcome with HTTP status, and client IP. Sign-in, sign-out, token refresh, forgot-password, own password change from the user menu, and calls without a valid admin token SHALL NOT be recorded.
|
||||
|
||||
#### Scenario: A user edit is recorded
|
||||
|
||||
- **WHEN** admin `admin` updates user 4
|
||||
- **THEN** an audit event is saved with actor `admin`, module `BO_USERS`, action `USER_UPDATE`, path template `PUT /api/admin/users/{id}`, target `4`, outcome `SUCCESS`, and the client IP
|
||||
|
||||
#### Scenario: A failed write is recorded
|
||||
|
||||
- **WHEN** an admin's role update is refused with status 400
|
||||
- **THEN** an audit event is saved with outcome `FAILURE` and status 400
|
||||
|
||||
#### Scenario: Sign-in is not recorded
|
||||
|
||||
- **WHEN** an admin signs in or signs out
|
||||
- **THEN** no audit event is saved
|
||||
|
||||
#### Scenario: First-login password change is recorded
|
||||
|
||||
- **WHEN** a new admin sets their password at first login
|
||||
- **THEN** an audit event with action `AUTH_FIRST_LOGIN` is saved
|
||||
|
||||
### Requirement: Refused access is recorded
|
||||
|
||||
The system SHALL record an audit event with outcome `FAILURE` when a valid admin token is refused by the access check (missing module, super admin required, or pending first-login change).
|
||||
|
||||
#### Scenario: Missing module
|
||||
|
||||
- **GIVEN** admin `noevents` has no `BO_EVENTS`
|
||||
- **WHEN** `noevents` tries to create an event
|
||||
- **THEN** the request is refused with 403
|
||||
- **AND** an audit event with actor `noevents`, module `BO_EVENTS` and outcome `FAILURE` is saved
|
||||
|
||||
### Requirement: Sensitive reads are recorded
|
||||
|
||||
The system SHALL record an audit event when an admin exports leads, exports event leads, or opens a saved email. Read-only POST calls marked as such SHALL NOT be recorded.
|
||||
|
||||
#### Scenario: Opening an email
|
||||
|
||||
- **WHEN** an admin opens email 12
|
||||
- **THEN** an audit event with action `EMAIL_VIEW` and target `12` is saved
|
||||
|
||||
#### Scenario: Lead export
|
||||
|
||||
- **WHEN** an admin downloads the lead export
|
||||
- **THEN** an audit event with action `LEAD_EXPORT` is saved
|
||||
|
||||
### Requirement: Allow-listed changes
|
||||
|
||||
The system SHALL attach before and after values only for these fields: a user's role names and enabled flag, a role's granted module codes, and the login-security lockout settings and password rules. For lead and event-lead edits the system SHALL record only the names of the fields that changed, never their values. No audit event SHALL contain a password, token, raw request body, or lead name, phone, email or notes.
|
||||
|
||||
#### Scenario: Role change on a user
|
||||
|
||||
- **WHEN** an admin changes user 4's roles from `Sales` to `Sales, Manager`
|
||||
- **THEN** the event's changes show roles before `Sales` and after `Sales, Manager`
|
||||
|
||||
#### Scenario: Lead edit records field names only
|
||||
|
||||
- **WHEN** an admin changes a lead's phone and notes
|
||||
- **THEN** the event's changes list the fields `phone` and `notes`
|
||||
- **AND** neither the old nor the new phone or notes appear in the event
|
||||
|
||||
### Requirement: Recording never blocks the action
|
||||
|
||||
Recording SHALL be best-effort. A failure to publish or save an audit event MUST NOT change the response of the admin call.
|
||||
|
||||
#### Scenario: Publish failure
|
||||
|
||||
- **GIVEN** the audit event cannot be published
|
||||
- **WHEN** an admin updates a user
|
||||
- **THEN** the update succeeds as usual
|
||||
- **AND** the failure is logged
|
||||
|
||||
### Requirement: Retention
|
||||
|
||||
The system SHALL delete audit events older than the configured retention period, 730 days by default, on a schedule.
|
||||
|
||||
#### Scenario: Old events are purged
|
||||
|
||||
- **WHEN** the purge runs with a retention of 730 days
|
||||
- **THEN** events older than 730 days are deleted
|
||||
- **AND** newer events are kept
|
||||
|
||||
### Requirement: Audit log screen
|
||||
|
||||
The system SHALL let an admin with `BO_AUDIT_LOG` list audit events newest first, paged, filtered by actor, module, action, outcome and date range, and open one event to see its details and changes. An admin without `BO_AUDIT_LOG` SHALL be refused.
|
||||
|
||||
#### Scenario: Filter by actor
|
||||
|
||||
- **WHEN** an admin with `BO_AUDIT_LOG` filters the audit log by actor `admin`
|
||||
- **THEN** only events by `admin` are listed, newest first
|
||||
|
||||
#### Scenario: Event detail
|
||||
|
||||
- **WHEN** an admin opens an event for a role grant change
|
||||
- **THEN** the detail shows the event's fields and the modules added and removed
|
||||
|
||||
#### Scenario: Without the module
|
||||
|
||||
- **WHEN** an admin without `BO_AUDIT_LOG` calls the audit log API or opens `/audit-log`
|
||||
- **THEN** the API answers 403 and the page shows Not authorised
|
||||
@@ -0,0 +1,25 @@
|
||||
-- Co-Lite change add-admin-audit-log: the admin audit trail.
|
||||
-- Target: `service-log`.`audit_event`. Additive only. Run once, after the release package.
|
||||
-- DDL: run with a user that may create tables, not the services' user.
|
||||
-- Written by services-log from the audit-event-topic Pub/Sub messages that mobile-api publishes.
|
||||
USE `service-log`;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `audit_event` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`company_id` bigint NULL,
|
||||
`occurred_at` datetime(6) NOT NULL,
|
||||
`actor` varchar(191) NOT NULL,
|
||||
`module` varchar(64) NULL,
|
||||
`action` varchar(128) NOT NULL,
|
||||
`http_method` varchar(16) NULL,
|
||||
`path_template` varchar(255) NULL,
|
||||
`target_id` varchar(128) NULL,
|
||||
`outcome` varchar(16) NOT NULL COMMENT 'SUCCESS | FAILURE',
|
||||
`http_status` int NULL,
|
||||
`client_ip` varchar(64) NULL,
|
||||
`changes` text NULL COMMENT 'JSON: allow-listed before/after, or changed field names',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_audit_event_occurred_at` (`occurred_at`),
|
||||
KEY `idx_audit_event_actor` (`actor`, `occurred_at`),
|
||||
KEY `idx_audit_event_module_action` (`module`, `action`, `occurred_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Co-Lite change add-admin-audit-log: the Audit log back-office module (area BO).
|
||||
-- Target: `service-system`.`module`. Additive only. Run once, after the release package.
|
||||
-- No role grant: super admins see every module; they grant BO_AUDIT_LOG to other roles under Roles.
|
||||
USE `service-system`;
|
||||
|
||||
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||
(41100000, 'BO_AUDIT_LOG', 'Audit log', 'BO', 'M', 40000000, '/audit-log', 'ScrollText');
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Co-Lite change add-admin-audit-log: rollback of 01-02. Destroys the audit trail.
|
||||
USE `service-system`;
|
||||
DELETE FROM `modules_roles` WHERE `module_id` = 41100000;
|
||||
DELETE FROM `module` WHERE `id` = 41100000;
|
||||
|
||||
USE `service-log`;
|
||||
DROP TABLE IF EXISTS `audit_event`;
|
||||
@@ -0,0 +1,96 @@
|
||||
# Tasks
|
||||
|
||||
Design: `design.md`. All tasks run serially: each builds on the one before.
|
||||
|
||||
## 1. Data and contract
|
||||
|
||||
- [x] 1.1 SQL and Pub/Sub topic.
|
||||
- Files:
|
||||
- `sql/01-audit-event.sql`: `CREATE TABLE IF NOT EXISTS service-log.audit_event` (design decision 2).
|
||||
- `sql/02-audit-log-module.sql`: the module row (design decision 10).
|
||||
- `sql/99-rollback.sql`.
|
||||
- Mirror 01 and 02 in `local/seed/03-colite.sql`, and add `audit-event-topic audit-event-subscription` to `local/pubsub/topics.txt`.
|
||||
- Apply them to the local database and emulator. This is local only.
|
||||
- Scope: `local/**`, `openspec/changes/add-admin-audit-log/sql/**`
|
||||
- Verify: `select` shows the table and the module row.
|
||||
- [x] 1.2 core-libs `AuditEvent` (design decision 1).
|
||||
- Tests first: JSON round trip through the same `PubSubUtil` used for `ResponseTime`.
|
||||
- Scope: `solvway-core-libs/src/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-core-libs verify`
|
||||
|
||||
## 2. services-log
|
||||
|
||||
- [x] 2.1 Storage, listener, purge and read endpoints (design decision 7).
|
||||
- Tests first:
|
||||
- the listener saves an event with every field;
|
||||
- search filters by actor, module, action, outcome and dates, returns newest first, caps the size at 100, and rejects a bad date with 400;
|
||||
- detail answers 404 for an unknown id;
|
||||
- the purge deletes only rows older than the retention and reads the env setting.
|
||||
- Scope: `solvway-services-log/src/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-services-log -am verify`
|
||||
|
||||
## 3. mobile-api
|
||||
|
||||
- [x] 3.1 Recording in `AppAccessAspect`, with `Audited` and `AuditChanges` (design decisions 3, 4 and 6).
|
||||
- Add annotations on the lead export, the event-lead export, the email detail (sensitive) and event-lead `match` (skip).
|
||||
- Tests first:
|
||||
- a write records every field: actor, module, action, method, template, target, outcome and IP;
|
||||
- the derived and the explicit action codes;
|
||||
- a non-2xx response and a thrown status exception record `FAILURE` with the status;
|
||||
- a 403 refusal for a valid user is recorded;
|
||||
- plain GETs, skipped POSTs and the auth endpoints (except first-login) are not recorded;
|
||||
- a call without a user is not recorded;
|
||||
- a publish failure does not change the response;
|
||||
- `AuditChanges` content lands in `changes` and is cleared between requests.
|
||||
- Scope: `solvway-mobile-api/src/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
- [x] 3.2 Allow-listed changes from the services (design decision 5).
|
||||
- Tests first, one per service:
|
||||
- user role names and enabled flag before and after;
|
||||
- role modules added and removed;
|
||||
- lead and event-lead edits record field names only, and no value appears anywhere in `changes`;
|
||||
- login-security config and rules before and after.
|
||||
- Scope: `solvway-mobile-api/src/main/java/**/service/**` plus their tests
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
- [x] 3.3 `AdminAuditLogController` and the read service (design decision 8).
|
||||
- Tests first:
|
||||
- the class-level module;
|
||||
- parameter mapping;
|
||||
- a 404 for an unknown id;
|
||||
- only the given filters are forwarded.
|
||||
- Scope: `solvway-mobile-api/src/**` (new audit-log files, constants, tests)
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
- Live check through the stack:
|
||||
- edit a user and see the event with its changes;
|
||||
- `noevents` creating an event is recorded as `FAILURE`;
|
||||
- opening an email is recorded.
|
||||
|
||||
## 4. Portal
|
||||
|
||||
- [x] 4.1 `/audit-log` list and `/audit-log/[id]` detail, with a proxy, a service and i18n keys (design decision 9).
|
||||
- Tests first:
|
||||
- rows and filters go into the query;
|
||||
- the detail shows a before/after table and a field-name list;
|
||||
- `RequireModule` gates the page;
|
||||
- the proxy is GET only and refuses dot segments.
|
||||
- Scope: `solvway-admin-portal/app/audit-log/**`, `solvway-admin-portal/app/api/audit-log/**`, `solvway-admin-portal/app/lib/**`
|
||||
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`
|
||||
|
||||
## 5. Check and docs
|
||||
|
||||
- [x] 5.1 Browser check and handover.
|
||||
- Playwright on the local stack:
|
||||
- as admin, change a user's roles, change a role's grants, edit a lead, open an email and export leads, then see each in Audit log with its changes;
|
||||
- as `noevents`, try a forbidden action and see it as `FAILURE`;
|
||||
- `noevents` has no Audit log menu entry and sees Not authorized at `/audit-log`;
|
||||
- the list fits at 1280 px, and the pages work at 360 px.
|
||||
- Docs, in `docs/deployment.md`:
|
||||
- section 3: the new SQL;
|
||||
- section 5: the new topic and subscription;
|
||||
- section 6: `AUDIT_RETENTION_DAYS`.
|
||||
- Scope: `docs/deployment.md`
|
||||
- Verify: screenshots, and the steps above observed.
|
||||
|
||||
## Workflow follow-up
|
||||
|
||||
- Whole-branch review, push, PR to main and merge, then archive on its own branch.
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-30
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-30
|
||||
@@ -0,0 +1,115 @@
|
||||
# Design
|
||||
|
||||
Full design with approaches and the user's approved calls: `docs/superpowers/specs/2026-11-30-admin-login-security-design.md`.
|
||||
|
||||
## Context
|
||||
|
||||
- **Admin sign-in path:** the portal's `/api/auth/login` route calls mobile-api `POST /api/admin/auth/login` (`AdminAuthController`). That calls the gateway, then services-auth `/auth/authenticate`, then `loadUserByToken`. Nothing is counted or recorded.
|
||||
- **Only one way in:** only the admin portal is public (Traefik; `docs/deployment.md` section 8). Only mobile-api holds a gateway key (`appkeys.json`, section 7). So `AdminAuthController.login` sees every admin sign-in.
|
||||
- **Existing settings rows** in `service-system`.`system_property`:
|
||||
- `ADMIN_LOGIN_BLOCK_PERIOD` (type `ADMIN_LOGIN_BLOCK`, value 1, status Y);
|
||||
- `ADMIN_LOGIN_BLOCK_TIME_UNIT` (value M);
|
||||
- the `ADMIN_PWD_FORMAT` rules (active: minimum length 8, 1 uppercase, 1 lowercase).
|
||||
- Nothing reads the block rows today.
|
||||
- **Password checks:** services-system `UserController.adminPasswordRuleFailures` applies `ADMIN_PWD_FORMAT`. services-system owns `BCryptPasswordEncoder` (`Config`), and `/setAdminPassword` hashes there.
|
||||
- **Reference:** babyboo archive `2026-09-28-add-admin-login-security`. It enforces in services-auth and adds session policy; Co-Lite does neither.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:** login history, lockout with unlock, editable lockout and password rules, own password change.
|
||||
|
||||
**Non-Goals:**
|
||||
- session policy;
|
||||
- MFA and CAPTCHA;
|
||||
- password aging;
|
||||
- non-admin logins;
|
||||
- purging history.
|
||||
|
||||
## Decisions
|
||||
|
||||
1. **Table `login_audit`** in `service-system`:
|
||||
- Columns: `id`, `company_id` NULL, `username` VARCHAR(191), `datetime`, `event` VARCHAR(20), `ip_address` VARCHAR(64), `user_agent` VARCHAR(512), `message` VARCHAR(255).
|
||||
- Keys: `(username, datetime)` and `(event, datetime)`.
|
||||
- Values are cut to the column sizes before saving.
|
||||
- `company_id` is filled from the user whose `username` matches, else NULL.
|
||||
|
||||
2. **Lock rule, owned by services-system** (`LoginSecurityService`):
|
||||
- **Settings:**
|
||||
- `on` is the status `Y` on `ADMIN_LOGIN_BLOCK_PERIOD`;
|
||||
- `period` is its value;
|
||||
- `unit` is `ADMIN_LOGIN_BLOCK_TIME_UNIT` (S, M, H or D);
|
||||
- `max` is the new row `ADMIN_LOGIN_MAX_ATTEMPT` (type `ADMIN_LOGIN_BLOCK`).
|
||||
- **Locked** means `on` and `count(LOGIN_FAIL where username = ? and datetime > greatest(now - period, latestReset)) >= max`. `latestReset` is the newest `LOGIN_SUCCESS`, `UNLOCK_RESET` or `PASSWORD_CHANGED` for that username.
|
||||
- **Lock end** is the datetime of the oldest counted failure that keeps the count at `max`, plus the period. The locked list uses it, and so do the tests.
|
||||
- **Username matching:** the lock rule uses the trimmed username, cut to 191 characters, the same key the history stores. `login_audit.username` uses `utf8mb4_general_ci`, so it compares like `user.username` (case-insensitive).
|
||||
|
||||
3. **services-system endpoints** (`LoginSecurityController`, under `/loginSecurity`; the gateway gets a matching route):
|
||||
- `GET isLocked/{username}` returns `{locked}`.
|
||||
- `POST record` takes `{username, event, ip, userAgent, message}`.
|
||||
- `POST audit` takes `{username, event, from, to, page, size}`. Dates are `yyyy-MM-dd`. It returns newest first, with size capped at 100.
|
||||
- `GET locked` returns `[{username, failures, lastFailure, lockedUntil}]`. It considers usernames with a `LOGIN_FAIL` inside the period.
|
||||
- `POST unlock` takes `{username, by}` and writes `UNLOCK_RESET` with `message = "unlocked by <by>"`.
|
||||
- `GET config` and `POST config` take `{enabled, maxAttempts, period, unit}`. They validate `maxAttempts` between 1 and 1000, `period` between 1 and 10000, and the unit in S, M, H or D, and return 400 otherwise. The upper limits keep the lock window computable.
|
||||
- `GET passwordRules` and `POST passwordRules` take `[{id, status, value}]`. They only update existing `ADMIN_PWD_FORMAT` rows, and refuse any id outside that type with 400.
|
||||
|
||||
4. **services-system `/user/changeAdminPassword`** takes `{id, currentPassword, newPassword}` and returns one result string:
|
||||
- `OK`;
|
||||
- `NOT_FOUND`: not a type A user, or not enabled;
|
||||
- `CURRENT_PASSWORD_WRONG`: the bcrypt match fails;
|
||||
- `PASSWORD_SAME`;
|
||||
- `PASSWORD_POLICY`: `adminPasswordRuleFailures` is not empty.
|
||||
- On `OK` it saves the bcrypt of the new password and keeps `login = Y`.
|
||||
|
||||
5. **mobile-api sign-in** (`AdminAuthController.login`):
|
||||
- Blank fields: 401 `BAD_LOGIN`, nothing recorded.
|
||||
- Then `isLocked`:
|
||||
- **Locked:** record `LOGIN_LOCKED` and return 401 `{result: "false", code: "ACCOUNT_LOCKED", message: "Too many failed sign-ins. Try again later or ask an administrator to unlock your account."}`.
|
||||
- **Error:** log a warning and continue (fail open).
|
||||
- Then the existing check:
|
||||
- an unknown, wrong, disabled or upstream-failed check records `LOGIN_FAIL`;
|
||||
- a success records `LOGIN_SUCCESS`.
|
||||
- The lock check and recording are methods on `AdminAuthenticationService` (`isLocked`, which fails open, and `record`, which catches and logs every exception). No new class, so the existing controller tests and their mocks stay unchanged.
|
||||
- Logout records `LOGOUT` for the token's user.
|
||||
|
||||
6. **Client IP and user agent:**
|
||||
- The portal's login and logout routes already send `X-Client-Ip` (the last `x-forwarded-for` hop, the one the ingress adds, else `x-real-ip`) and `X-Client-User-Agent` (the browser's user agent) to mobile-api, through `app/lib/server/clientContext.ts`, which was ported from babyboo.
|
||||
- mobile-api reads them from the request for the record only.
|
||||
- They are never used for any decision, since a client can forge them.
|
||||
|
||||
7. **mobile-api `POST /api/admin/auth/change-password`** (`@AdminModule(ANY_ADMIN)`, not `allowPendingReset`, so a pending user gets the existing 403 `PASSWORD_RESET_REQUIRED`):
|
||||
- Missing field: 400 `REQUIRED_FIELD`.
|
||||
- New and confirm differ: 400 `PASSWORD_MISMATCH`.
|
||||
- Locked: 400 `ACCOUNT_LOCKED`.
|
||||
- Otherwise call `/user/changeAdminPassword`:
|
||||
- `CURRENT_PASSWORD_WRONG`: record `LOGIN_FAIL` (message `change-password`) and return 400.
|
||||
- `PASSWORD_SAME` or `PASSWORD_POLICY`: return 400 with that code.
|
||||
- `OK`: record `PASSWORD_CHANGED` and return 204.
|
||||
- Error bodies follow the existing `{code, message}` shape the portal shows through `t()`.
|
||||
|
||||
8. **mobile-api `AdminLoginSecurityController`** (`@AdminModule("BO_LOGIN_SECURITY")`, `/api/admin/login-security`):
|
||||
- `GET audit`;
|
||||
- `GET locked`;
|
||||
- `POST locked/{username}/unlock` (204);
|
||||
- `GET` and `PUT config`;
|
||||
- `GET` and `PUT password-rules`.
|
||||
- Unlock and settings changes log `"{action} by {admin}"`.
|
||||
|
||||
9. **Portal:**
|
||||
- **Header user menu:** a "Change password" item opens `ChangePasswordDialog` (current, new, confirm). It reuses the `PasswordFields` patterns and calls `/api/auth/change-password`.
|
||||
- **Login page:** maps `code === "ACCOUNT_LOCKED"` to the locked message.
|
||||
- **`/login-security`:** gated by `RequireModule` and `ROUTE_MODULES["/login-security"] = "BO_LOGIN_SECURITY"`. Three tabs:
|
||||
- History: a DataTable with `useListFilters` and `useFitPageSize`, filtered by username, event and From/To `DatePicker`.
|
||||
- Locked: rows with an Unlock button and a confirm dialog.
|
||||
- Settings: a lockout form, then a rules table with an on/off switch and a value.
|
||||
- Proxy: `app/api/login-security/[[...path]]/route.ts` for GET, POST and PUT, refusing dot segments. `app/api/auth/change-password/route.ts`.
|
||||
|
||||
10. **Module row:** `(41000000, 'BO_LOGIN_SECURITY', 'Login security', 'BO', 'M', 40000000, '/login-security', 'Shield')`. No role grants, so only super admins see it until granted.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- **Targeted lockout:** anyone can lock a real username for one period by failing on purpose. Mitigations: the lock expires, and admins can unlock. Counting unknown usernames keeps locks from revealing which accounts exist.
|
||||
- **Fail open:** when services-system is down, the lock is not enforced. Accepted: an outage must not lock every admin out, and the password check still runs.
|
||||
- **Concurrency:** two simultaneous wrong guesses may both pass the pre-check, so the count can exceed `max` by the number of parallel requests. Accepted; it is a limit, not a security boundary.
|
||||
- **History growth:** no purge. One company and a handful of staff make this small. A purge can come with the audit viewer.
|
||||
- **Forged IP or user agent:** these are stored for reading only, and never trusted.
|
||||
- **Unauthenticated writes behind the gateway key:** `/loginSecurity/record` needs no user token, so it can write `LOGIN_SUCCESS` or `PASSWORD_CHANGED` rows, and both clear a lock. The older `/blockLoginPeriod/**` routes also skip the token, and their save can rewrite the `ADMIN_LOGIN_BLOCK` rows. Both are reachable only with a gateway api-key from an allowed IP, which today only mobile-api holds (`docs/deployment.md` section 7). A later change can narrow the `/blockLoginPeriod/` bypass to its read endpoints.
|
||||
@@ -0,0 +1,59 @@
|
||||
# Proposal
|
||||
|
||||
## Why
|
||||
|
||||
Go-live is 2027-01-15. Today the admin login counts nothing: anyone who reaches the login page can guess passwords without limit, and nothing records who signed in. Staff also cannot change their own password; only an admin can set a temporary one for them.
|
||||
|
||||
The legacy backoffice blocked a username after 3 failed logins, using an in-memory counter. Co-Lite's new login path (portal, then mobile-api, then services-auth) never ported that rule. babyboo solved the same gap with a persisted `login_audit` table, and this change follows it, trimmed to what Co-Lite needs. The history it keeps will also serve the later audit-log viewer.
|
||||
|
||||
Design: `docs/superpowers/specs/2026-11-30-admin-login-security-design.md`.
|
||||
|
||||
## What Changes
|
||||
|
||||
- **Login history:** every admin login success, failure, locked refusal, logout, unlock and own password change is saved to a new `service-system`.`login_audit` table. Each row has the time, username, client IP and user agent.
|
||||
- **Lockout:**
|
||||
- After a set number of failed logins inside a set period, the username is locked. The defaults are 5 attempts in 15 minutes.
|
||||
- A locked username is refused even with the right password.
|
||||
- The lock ends by itself when the failures age out, or when an admin unlocks it.
|
||||
- The settings reuse the existing `ADMIN_LOGIN_BLOCK` rows in `system_property`, plus one new row for the maximum attempts.
|
||||
- **Enforcement point:** mobile-api `AdminAuthController.login`, the only way in (only the admin portal is public). services-auth is not changed.
|
||||
- **Change my password:** a new `POST /api/admin/auth/change-password` and a dialog in the portal's user menu. It needs the current password and applies the admin password rules. A wrong current password counts as a failed login.
|
||||
- **Login security screen** (`/login-security`, module `BO_LOGIN_SECURITY`):
|
||||
- History tab: login history with filters.
|
||||
- Locked tab: locked usernames with an Unlock button.
|
||||
- Settings tab: edits the lockout settings and the admin password rules (`ADMIN_PWD_FORMAT`).
|
||||
- **Login page:** shows a clear message when the username is locked.
|
||||
- **Not in this change:** session policy (logout revocation, sliding sessions, single session), MFA, CAPTCHA, password aging, member or other non-admin logins, and purging old history.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
- `admin-login-security`: the login history, the lock rule and its enforcement on admin login, unlock, the lockout and password-rule settings, and the Login security screen.
|
||||
- `admin-own-password`: an admin changing their own password.
|
||||
|
||||
### Modified Capabilities
|
||||
None.
|
||||
|
||||
## Impact
|
||||
|
||||
- **`solvway-services-system`:**
|
||||
- A new `LoginAudit` entity and repository, a service and a `/loginSecurity` controller (isLocked, record, audit, locked, unlock, config, password rules).
|
||||
- A new `/user/changeAdminPassword` endpoint that checks the current password with the existing `BCryptPasswordEncoder`.
|
||||
- **`solvway-mobile-api`:**
|
||||
- `AdminAuthController` login and logout record events and check the lock.
|
||||
- New `change-password` endpoint.
|
||||
- New `AdminLoginSecurityController` under `BO_LOGIN_SECURITY`.
|
||||
- **`solvway-admin-portal`:**
|
||||
- The login and logout proxy routes forward the client IP and user agent.
|
||||
- The login page shows the locked message.
|
||||
- Change-password dialog in the header.
|
||||
- New `/login-security` page with proxy routes, a service and i18n keys.
|
||||
- **Database (`sql/` in this change, mirrored in `local/seed/03-colite.sql`):**
|
||||
- Create `login_audit`, with `company_id`.
|
||||
- Insert `ADMIN_LOGIN_MAX_ATTEMPT`.
|
||||
- Set the block period to 15 minutes.
|
||||
- Insert the `BO_LOGIN_SECURITY` module row.
|
||||
- A rollback script.
|
||||
- **Security:** this changes the admin sign-in path. The lock check fails open when services-system errors, so an outage cannot lock everyone out. The audit write is best-effort.
|
||||
- **Docs:** `docs/deployment.md` lists the new SQL.
|
||||
- No new dependency.
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Login history
|
||||
|
||||
The system SHALL record every admin sign-in attempt, sign-out, unlock and own password change, with the time, trimmed username, event, client IP, user agent and, for a known username, the user's company. Events: `LOGIN_SUCCESS`, `LOGIN_FAIL`, `LOGIN_LOCKED`, `LOGOUT`, `UNLOCK_RESET`, `PASSWORD_CHANGED`. Recording SHALL be best-effort and MUST NOT change the sign-in answer. A blank username or password SHALL NOT be recorded.
|
||||
|
||||
#### Scenario: Successful sign-in is recorded
|
||||
|
||||
- **WHEN** `sales1` signs in with the right password
|
||||
- **THEN** a `LOGIN_SUCCESS` record for `sales1` is saved with the time, client IP and user agent
|
||||
|
||||
#### Scenario: Failed sign-in is recorded
|
||||
|
||||
- **WHEN** someone signs in as `sales1` with a wrong password
|
||||
- **THEN** a `LOGIN_FAIL` record for `sales1` is saved
|
||||
|
||||
#### Scenario: Unknown username is recorded
|
||||
|
||||
- **WHEN** someone signs in as `nobody1`, which matches no user
|
||||
- **THEN** a `LOGIN_FAIL` record for `nobody1` is saved with no company
|
||||
|
||||
#### Scenario: Sign-out is recorded
|
||||
|
||||
- **WHEN** `sales1` signs out
|
||||
- **THEN** a `LOGOUT` record for `sales1` is saved
|
||||
|
||||
#### Scenario: History write failure does not block sign-in
|
||||
|
||||
- **GIVEN** the history cannot be written
|
||||
- **WHEN** `sales1` signs in with the right password
|
||||
- **THEN** the sign-in succeeds
|
||||
- **AND** the write failure is logged
|
||||
|
||||
### Requirement: Lockout after repeated failures
|
||||
|
||||
The system SHALL lock a username when lockout is on and its `LOGIN_FAIL` records reach the configured maximum, counting only records inside the configured period and after its latest `LOGIN_SUCCESS`, `UNLOCK_RESET` or `PASSWORD_CHANGED`. The maximum, period, unit and on/off switch SHALL come from settings. Failures SHALL count for unknown usernames too, so a lock does not reveal whether an account exists. The lock SHALL end once the counted failures leave the period.
|
||||
|
||||
#### Scenario: Maximum reached locks the username
|
||||
|
||||
- **GIVEN** lockout is on with a maximum of 5 in 15 minutes
|
||||
- **WHEN** `sales1` fails to sign in 5 times within 15 minutes
|
||||
- **THEN** `sales1` is locked
|
||||
|
||||
#### Scenario: Old failures do not count
|
||||
|
||||
- **GIVEN** lockout is on with a maximum of 5 in 15 minutes
|
||||
- **WHEN** `sales1` has 4 failures within the last 15 minutes and 3 older ones
|
||||
- **THEN** `sales1` is not locked
|
||||
|
||||
#### Scenario: A success resets the count
|
||||
|
||||
- **WHEN** `sales1` fails 4 times, signs in successfully, then fails 4 more times within 15 minutes
|
||||
- **THEN** `sales1` is not locked
|
||||
|
||||
#### Scenario: Lockout switched off
|
||||
|
||||
- **GIVEN** lockout is off
|
||||
- **WHEN** `sales1` fails 10 times within 15 minutes
|
||||
- **THEN** `sales1` is not locked
|
||||
|
||||
### Requirement: Locked username is refused
|
||||
|
||||
The system SHALL refuse sign-in for a locked username before checking the password, with the code `ACCOUNT_LOCKED` and a message telling the user to try later or ask an administrator, and SHALL record `LOGIN_LOCKED`. When the lock state cannot be read because of an infrastructure error, sign-in SHALL proceed to the normal password check.
|
||||
|
||||
#### Scenario: Right password while locked
|
||||
|
||||
- **GIVEN** `sales1` is locked
|
||||
- **WHEN** `sales1` signs in with the right password
|
||||
- **THEN** sign-in is refused with `ACCOUNT_LOCKED`
|
||||
- **AND** no session is issued
|
||||
- **AND** a `LOGIN_LOCKED` record is saved
|
||||
|
||||
#### Scenario: Lock check unavailable
|
||||
|
||||
- **GIVEN** the lock state cannot be read
|
||||
- **WHEN** `sales1` signs in with the right password
|
||||
- **THEN** the sign-in succeeds
|
||||
|
||||
#### Scenario: Portal shows the locked message
|
||||
|
||||
- **WHEN** sign-in is refused with `ACCOUNT_LOCKED`
|
||||
- **THEN** the login page shows the locked message instead of "Invalid username or password"
|
||||
|
||||
### Requirement: Unlock
|
||||
|
||||
The system SHALL let an admin with `BO_LOGIN_SECURITY` list the usernames that are locked now, with their failure count, last failure time and when the lock ends, and SHALL let that admin unlock one. Unlocking SHALL save an `UNLOCK_RESET` record naming the admin who unlocked.
|
||||
|
||||
#### Scenario: Unlock a locked username
|
||||
|
||||
- **GIVEN** `sales1` is locked
|
||||
- **WHEN** an admin with `BO_LOGIN_SECURITY` unlocks `sales1`
|
||||
- **THEN** `sales1` no longer appears in the locked list
|
||||
- **AND** `sales1` can sign in with the right password
|
||||
- **AND** an `UNLOCK_RESET` record for `sales1` names the admin
|
||||
|
||||
### Requirement: Login history screen
|
||||
|
||||
The system SHALL let an admin with `BO_LOGIN_SECURITY` read the login history, newest first and paged, filtered by username, event and date range.
|
||||
|
||||
#### Scenario: Filter by event
|
||||
|
||||
- **WHEN** an admin filters the history by event `LOGIN_FAIL`
|
||||
- **THEN** only `LOGIN_FAIL` records are listed, newest first
|
||||
|
||||
#### Scenario: Without the module
|
||||
|
||||
- **WHEN** an admin without `BO_LOGIN_SECURITY` calls the login-security API
|
||||
- **THEN** the request is refused with 403
|
||||
|
||||
### Requirement: Lockout and password-rule settings
|
||||
|
||||
The system SHALL let an admin with `BO_LOGIN_SECURITY` read and change the lockout settings (on/off, maximum attempts, period, time unit) and the admin password rules (each rule's on/off status and value). The system SHALL reject a maximum below 1 or above 1000, a period below 1 or above 10000, and a time unit other than S, M, H or D. Password rules SHALL only be edited, never added or removed. Every change SHALL write a log line naming the admin.
|
||||
|
||||
#### Scenario: Change the lockout settings
|
||||
|
||||
- **WHEN** an admin sets the maximum to 3 and the period to 30 minutes
|
||||
- **THEN** the next lock decision uses 3 attempts in 30 minutes
|
||||
|
||||
#### Scenario: Invalid setting
|
||||
|
||||
- **WHEN** an admin sets the maximum to 0
|
||||
- **THEN** the change is refused with a validation error and the settings stay as they were
|
||||
|
||||
#### Scenario: Change a password rule
|
||||
|
||||
- **WHEN** an admin sets the minimum length rule to 10
|
||||
- **THEN** a new password of 9 characters is refused by every admin password check
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Change own password
|
||||
|
||||
The system SHALL let a signed-in admin change their own password by giving the current password, a new password and its confirmation. The new password SHALL pass the admin password rules and SHALL differ from the current one. On success the system SHALL keep the admin signed in, keep their first-login state complete, and record `PASSWORD_CHANGED`. An admin whose first-login password change is still pending SHALL use the first-login flow instead.
|
||||
|
||||
#### Scenario: Successful change
|
||||
|
||||
- **WHEN** `sales1` gives the right current password and a new password that passes the rules, twice
|
||||
- **THEN** the new password works at the next sign-in and the old one does not
|
||||
- **AND** `sales1` stays signed in
|
||||
- **AND** a `PASSWORD_CHANGED` record is saved
|
||||
|
||||
#### Scenario: Confirmation differs
|
||||
|
||||
- **WHEN** the new password and its confirmation differ
|
||||
- **THEN** the change is refused with `PASSWORD_MISMATCH`
|
||||
|
||||
#### Scenario: Same as current
|
||||
|
||||
- **WHEN** the new password equals the current password
|
||||
- **THEN** the change is refused with `PASSWORD_SAME`
|
||||
|
||||
#### Scenario: Fails the rules
|
||||
|
||||
- **WHEN** the new password breaks an admin password rule
|
||||
- **THEN** the change is refused with `PASSWORD_POLICY`
|
||||
|
||||
#### Scenario: Pending first login
|
||||
|
||||
- **GIVEN** `sales1` must still complete the first-login password change
|
||||
- **WHEN** `sales1` calls change password
|
||||
- **THEN** the request is refused and `sales1` is sent to the first-login flow
|
||||
|
||||
### Requirement: Wrong current password counts as a failed sign-in
|
||||
|
||||
The system SHALL refuse a change whose current password is wrong with `CURRENT_PASSWORD_WRONG`, and SHALL record it as `LOGIN_FAIL` so that repeated wrong guesses lock the username. A locked username SHALL be refused with `ACCOUNT_LOCKED` before the current password is checked.
|
||||
|
||||
#### Scenario: Wrong current password
|
||||
|
||||
- **WHEN** `sales1` gives a wrong current password
|
||||
- **THEN** the change is refused with `CURRENT_PASSWORD_WRONG`
|
||||
- **AND** a `LOGIN_FAIL` record for `sales1` is saved
|
||||
|
||||
#### Scenario: Locked while changing
|
||||
|
||||
- **GIVEN** `sales1` is locked
|
||||
- **WHEN** `sales1` calls change password with the right current password
|
||||
- **THEN** the change is refused with `ACCOUNT_LOCKED`
|
||||
- **AND** the password is unchanged
|
||||
@@ -0,0 +1,19 @@
|
||||
-- Co-Lite change add-admin-login-security: the admin login history.
|
||||
-- Target: `service-system`.`login_audit`. Additive only. Run once, after the release package.
|
||||
-- Lock state is derived from this table (LOGIN_FAIL rows inside the block period, after the latest
|
||||
-- LOGIN_SUCCESS / UNLOCK_RESET / PASSWORD_CHANGED); there is no stored lock flag.
|
||||
USE `service-system`;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `login_audit` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`company_id` bigint NULL COMMENT 'the user''s company when the username matches a user',
|
||||
`username` varchar(191) COLLATE utf8mb4_general_ci NOT NULL COMMENT 'compared like `user`.`username`',
|
||||
`datetime` datetime NOT NULL,
|
||||
`event` varchar(20) NOT NULL COMMENT 'LOGIN_SUCCESS | LOGIN_FAIL | LOGIN_LOCKED | LOGOUT | UNLOCK_RESET | PASSWORD_CHANGED',
|
||||
`ip_address` varchar(64) NULL,
|
||||
`user_agent` varchar(512) NULL,
|
||||
`message` varchar(255) NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_login_audit_username_dt` (`username`, `datetime`),
|
||||
KEY `idx_login_audit_event_dt` (`event`, `datetime`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
-- Co-Lite change add-admin-login-security: admin lockout settings.
|
||||
-- Target: `service-system`.`system_property`. Run once, after the release package.
|
||||
-- Default: 5 failed sign-ins within 15 minutes lock the username. Editable on the Login security screen.
|
||||
USE `service-system`;
|
||||
|
||||
INSERT INTO `system_property` (`param`, `status`, `type`, `value`)
|
||||
SELECT 'ADMIN_LOGIN_MAX_ATTEMPT', 'Y', 'ADMIN_LOGIN_BLOCK', '5'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `system_property` WHERE `param` = 'ADMIN_LOGIN_MAX_ATTEMPT' AND `type` = 'ADMIN_LOGIN_BLOCK');
|
||||
|
||||
UPDATE `system_property` SET `value` = '15', `status` = 'Y'
|
||||
WHERE `param` = 'ADMIN_LOGIN_BLOCK_PERIOD' AND `type` = 'ADMIN_LOGIN_BLOCK';
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
-- Co-Lite change add-admin-login-security: the Login security back-office module (area BO).
|
||||
-- Target: `service-system`.`module`. Additive only. Run once, after the release package.
|
||||
-- No role grant: super admins see every module; they grant BO_LOGIN_SECURITY to other roles under Roles.
|
||||
USE `service-system`;
|
||||
|
||||
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||
(41000000, 'BO_LOGIN_SECURITY', 'Login security', 'BO', 'M', 40000000, '/login-security', 'Shield');
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Co-Lite change add-admin-login-security: rollback of 01-03. Destroys the login history.
|
||||
USE `service-system`;
|
||||
|
||||
DELETE FROM `modules_roles` WHERE `module_id` = 41000000;
|
||||
DELETE FROM `module` WHERE `id` = 41000000;
|
||||
DELETE FROM `system_property` WHERE `param` = 'ADMIN_LOGIN_MAX_ATTEMPT' AND `type` = 'ADMIN_LOGIN_BLOCK';
|
||||
UPDATE `system_property` SET `value` = '1'
|
||||
WHERE `param` = 'ADMIN_LOGIN_BLOCK_PERIOD' AND `type` = 'ADMIN_LOGIN_BLOCK';
|
||||
DROP TABLE IF EXISTS `login_audit`;
|
||||
@@ -0,0 +1,130 @@
|
||||
# Tasks
|
||||
|
||||
Design: `design.md`. All tasks run serially: each builds on the one before.
|
||||
|
||||
## 1. Data
|
||||
|
||||
- [x] 1.1 SQL for the table, settings and module (design decisions 1, 2 and 10).
|
||||
- Files:
|
||||
- `sql/01-login-audit.sql`: `CREATE TABLE IF NOT EXISTS login_audit`.
|
||||
- `sql/02-lockout-settings.sql`: insert `ADMIN_LOGIN_MAX_ATTEMPT` = 5, status Y, type `ADMIN_LOGIN_BLOCK`. Set `ADMIN_LOGIN_BLOCK_PERIOD` to 15.
|
||||
- `sql/03-login-security-module.sql`: the module row.
|
||||
- `sql/99-rollback.sql`: drops the table, deletes both rows, and sets the period back to 1.
|
||||
- Mirror 01 to 03 in `local/seed/03-colite.sql`.
|
||||
- Apply them to the running local database. This is a local-only, additive change.
|
||||
- Scope: `local/seed/03-colite.sql`, `openspec/changes/add-admin-login-security/sql/**`
|
||||
- Verify: `select` shows the table, both settings and the module row.
|
||||
|
||||
## 2. services-system
|
||||
|
||||
- [x] 2.1 `LoginAudit` entity and repository, `LoginSecurityService` and `LoginSecurityController` (design decisions 2 and 3), plus the gateway route `/loginSecurity/**` to services-system.
|
||||
- Before coding: check how mobile-api reaches services-system before a user has a token (the forgot-password path). Match that for `isLocked` and `record`, and note the finding in the task report.
|
||||
- **Tests first:**
|
||||
- locked at `max` failures inside the period;
|
||||
- not locked when older failures fall outside it;
|
||||
- a `LOGIN_SUCCESS`, `UNLOCK_RESET` or `PASSWORD_CHANGED` resets the count;
|
||||
- lockout off means never locked;
|
||||
- settings are read from `system_property`, with S, M, H and D handled;
|
||||
- `lockedUntil` is computed as the design says;
|
||||
- the locked list includes only locked usernames;
|
||||
- unlock writes `UNLOCK_RESET` with who unlocked;
|
||||
- `record` cuts long values and fills `company_id` for a known username, NULL otherwise;
|
||||
- `audit` filters by username, event and dates, returns newest first, and caps the size at 100;
|
||||
- `config` rejects a max or period below 1 and an unknown unit;
|
||||
- `passwordRules` updates only `ADMIN_PWD_FORMAT` rows and refuses other ids.
|
||||
- Scope: `solvway-services-system/src/**` (new login-security files, tests), `solvway-api-gateway/src/main/resources/application.yml`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-services-system,solvway-api-gateway -am verify`
|
||||
|
||||
- [x] 2.2 `/user/changeAdminPassword` (design decision 4).
|
||||
- **Tests first,** one for each result:
|
||||
- `OK` saves the bcrypt hash and keeps `login = Y`;
|
||||
- `NOT_FOUND` for a non-type-A or disabled user;
|
||||
- `CURRENT_PASSWORD_WRONG`;
|
||||
- `PASSWORD_SAME`;
|
||||
- `PASSWORD_POLICY`.
|
||||
- Scope: `solvway-services-system/src/main/java/**/controller/UserController.java`, its tests
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-services-system -am verify`
|
||||
|
||||
## 3. mobile-api
|
||||
|
||||
- [x] 3.1 Sign-in and sign-out enforcement and recording (design decisions 5 and 6).
|
||||
- **Tests first:**
|
||||
- blank fields record nothing;
|
||||
- locked returns 401 `ACCOUNT_LOCKED`, records `LOGIN_LOCKED`, and never calls services-auth;
|
||||
- a lock-check error continues to the password check;
|
||||
- a wrong password, an unknown user or a disabled user records `LOGIN_FAIL`;
|
||||
- a success records `LOGIN_SUCCESS`;
|
||||
- a record failure does not change the answer;
|
||||
- logout records `LOGOUT`;
|
||||
- the IP and user agent are taken from `X-Client-Ip` and `X-Client-User-Agent`.
|
||||
- Scope: `solvway-mobile-api/src/**` (`AdminAuthController`, a new login-audit client, constants, tests)
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
|
||||
- [x] 3.2 `POST /api/admin/auth/change-password` (design decision 7).
|
||||
- **Tests first:**
|
||||
- each 400 code;
|
||||
- `CURRENT_PASSWORD_WRONG` records `LOGIN_FAIL`;
|
||||
- locked is refused before the services-system call;
|
||||
- success records `PASSWORD_CHANGED` and returns 204;
|
||||
- a pending first-login user gets 403 `PASSWORD_RESET_REQUIRED`.
|
||||
- Scope: `solvway-mobile-api/src/**` (`AdminAuthController`, `AdminAuthenticationService`, request record, tests)
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
|
||||
- [x] 3.3 `AdminLoginSecurityController` and service (design decision 8).
|
||||
- **Tests first:**
|
||||
- class-level `@AdminModule("BO_LOGIN_SECURITY")`;
|
||||
- each endpoint maps its parameters;
|
||||
- unlock passes the admin's username as `by` and returns 204;
|
||||
- a services-system 400 on config or rules passes through as 400 with its message;
|
||||
- unlock and settings changes write the log line.
|
||||
- Scope: `solvway-mobile-api/src/**` (new login-security files, tests)
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
- Live check through the stack, as the dev admin and made-up local users:
|
||||
- fail 5 times and see the lock;
|
||||
- unlock and sign in;
|
||||
- change a password;
|
||||
- edit and restore the settings.
|
||||
|
||||
## 4. Portal
|
||||
|
||||
- [x] 4.1 Sign-in pieces (design decisions 6 and 9).
|
||||
- The login and logout routes forward `X-Client-Ip` and `X-Client-User-Agent`.
|
||||
- The login page shows the locked message on `ACCOUNT_LOCKED`.
|
||||
- Header "Change password" item opens `ChangePasswordDialog`, using the `/api/auth/change-password` route.
|
||||
- **Tests first:**
|
||||
- header forwarding;
|
||||
- the locked message;
|
||||
- the dialog: validation, the server code shown through `t()`, close on 204;
|
||||
- the route passes refusals through with their code.
|
||||
- Scope: `solvway-admin-portal/app/api/auth/**`, `solvway-admin-portal/app/login/**`, `solvway-admin-portal/app/components/app/**`, `solvway-admin-portal/app/components/users/**`, `solvway-admin-portal/app/lib/**`
|
||||
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`
|
||||
|
||||
- [x] 4.2 `/login-security` page with History, Locked and Settings tabs, the proxy route, a service and i18n keys (design decision 9).
|
||||
- **Tests first:**
|
||||
- History rows and filters go into the query;
|
||||
- Locked rows, with Unlock behind a confirm, refreshing the list;
|
||||
- Settings loads, saves, and shows a server validation error;
|
||||
- the rules table saves status and value;
|
||||
- `RequireModule` gates the page;
|
||||
- the proxy refuses dot segments.
|
||||
- Scope: `solvway-admin-portal/app/login-security/**`, `solvway-admin-portal/app/api/login-security/**`, `solvway-admin-portal/app/lib/**`
|
||||
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`
|
||||
|
||||
## 5. Check and docs
|
||||
|
||||
- [x] 5.1 Browser check and handover.
|
||||
- **Playwright on the local stack, with made-up local users:**
|
||||
- fail sign-in until locked and see the locked message;
|
||||
- as admin, see the user under Locked, unlock them, and they sign in;
|
||||
- History shows the events;
|
||||
- change own password from the header, with a wrong current password first, then success;
|
||||
- edit Settings and see a validation error, then restore;
|
||||
- as `noevents`, see no Login security menu entry, and Not authorized at `/login-security`;
|
||||
- check the pages at 360px.
|
||||
- **Docs:** `docs/deployment.md` section 3 lists the new SQL files.
|
||||
- Scope: `docs/deployment.md`
|
||||
- Verify: screenshots, and the steps above observed.
|
||||
|
||||
## Workflow follow-up
|
||||
|
||||
- Whole-branch review, push, PR to main and merge, then archive on its own branch.
|
||||
@@ -0,0 +1,111 @@
|
||||
# admin-audit-log Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
Record who did what in the admin portal: every admin write, chosen sensitive reads and refused attempts, with allow-listed before/after values and no personal data, kept for a configurable retention and readable on the Audit log screen by admins granted `BO_AUDIT_LOG`.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Admin writes are recorded
|
||||
|
||||
The system SHALL record an audit event for every state-changing admin API call made with a valid admin token, successful or not, holding the time, admin username, module, readable action code, HTTP method, path template (never the concrete path or query), target id, outcome with HTTP status, and client IP. Sign-in, sign-out, token refresh, forgot-password, own password change from the user menu, and calls without a valid admin token SHALL NOT be recorded.
|
||||
|
||||
#### Scenario: A user edit is recorded
|
||||
|
||||
- **WHEN** admin `admin` updates user 4
|
||||
- **THEN** an audit event is saved with actor `admin`, module `BO_USERS`, action `USER_UPDATE`, path template `PUT /api/admin/users/{id}`, target `4`, outcome `SUCCESS`, and the client IP
|
||||
|
||||
#### Scenario: A failed write is recorded
|
||||
|
||||
- **WHEN** an admin's role update is refused with status 400
|
||||
- **THEN** an audit event is saved with outcome `FAILURE` and status 400
|
||||
|
||||
#### Scenario: Sign-in is not recorded
|
||||
|
||||
- **WHEN** an admin signs in or signs out
|
||||
- **THEN** no audit event is saved
|
||||
|
||||
#### Scenario: First-login password change is recorded
|
||||
|
||||
- **WHEN** a new admin sets their password at first login
|
||||
- **THEN** an audit event with action `AUTH_FIRST_LOGIN` is saved
|
||||
|
||||
### Requirement: Refused access is recorded
|
||||
|
||||
The system SHALL record an audit event with outcome `FAILURE` when a valid admin token is refused by the access check (missing module, super admin required, or pending first-login change).
|
||||
|
||||
#### Scenario: Missing module
|
||||
|
||||
- **GIVEN** admin `noevents` has no `BO_EVENTS`
|
||||
- **WHEN** `noevents` tries to create an event
|
||||
- **THEN** the request is refused with 403
|
||||
- **AND** an audit event with actor `noevents`, module `BO_EVENTS` and outcome `FAILURE` is saved
|
||||
|
||||
### Requirement: Sensitive reads are recorded
|
||||
|
||||
The system SHALL record an audit event when an admin exports leads, exports event leads, or opens a saved email. Read-only POST calls marked as such SHALL NOT be recorded.
|
||||
|
||||
#### Scenario: Opening an email
|
||||
|
||||
- **WHEN** an admin opens email 12
|
||||
- **THEN** an audit event with action `EMAIL_VIEW` and target `12` is saved
|
||||
|
||||
#### Scenario: Lead export
|
||||
|
||||
- **WHEN** an admin downloads the lead export
|
||||
- **THEN** an audit event with action `LEAD_EXPORT` is saved
|
||||
|
||||
### Requirement: Allow-listed changes
|
||||
|
||||
The system SHALL attach before and after values only for these fields: a user's role names and enabled flag, a role's granted module codes, and the login-security lockout settings and password rules. For lead and event-lead edits the system SHALL record only the names of the fields that changed, never their values. No audit event SHALL contain a password, token, raw request body, or lead name, phone, email or notes.
|
||||
|
||||
#### Scenario: Role change on a user
|
||||
|
||||
- **WHEN** an admin changes user 4's roles from `Sales` to `Sales, Manager`
|
||||
- **THEN** the event's changes show roles before `Sales` and after `Sales, Manager`
|
||||
|
||||
#### Scenario: Lead edit records field names only
|
||||
|
||||
- **WHEN** an admin changes a lead's phone and notes
|
||||
- **THEN** the event's changes list the fields `phone` and `notes`
|
||||
- **AND** neither the old nor the new phone or notes appear in the event
|
||||
|
||||
### Requirement: Recording never blocks the action
|
||||
|
||||
Recording SHALL be best-effort. A failure to publish or save an audit event MUST NOT change the response of the admin call.
|
||||
|
||||
#### Scenario: Publish failure
|
||||
|
||||
- **GIVEN** the audit event cannot be published
|
||||
- **WHEN** an admin updates a user
|
||||
- **THEN** the update succeeds as usual
|
||||
- **AND** the failure is logged
|
||||
|
||||
### Requirement: Retention
|
||||
|
||||
The system SHALL delete audit events older than the configured retention period, 730 days by default, on a schedule.
|
||||
|
||||
#### Scenario: Old events are purged
|
||||
|
||||
- **WHEN** the purge runs with a retention of 730 days
|
||||
- **THEN** events older than 730 days are deleted
|
||||
- **AND** newer events are kept
|
||||
|
||||
### Requirement: Audit log screen
|
||||
|
||||
The system SHALL let an admin with `BO_AUDIT_LOG` list audit events newest first, paged, filtered by actor, module, action, outcome and date range, and open one event to see its details and changes. An admin without `BO_AUDIT_LOG` SHALL be refused.
|
||||
|
||||
#### Scenario: Filter by actor
|
||||
|
||||
- **WHEN** an admin with `BO_AUDIT_LOG` filters the audit log by actor `admin`
|
||||
- **THEN** only events by `admin` are listed, newest first
|
||||
|
||||
#### Scenario: Event detail
|
||||
|
||||
- **WHEN** an admin opens an event for a role grant change
|
||||
- **THEN** the detail shows the event's fields and the modules added and removed
|
||||
|
||||
#### Scenario: Without the module
|
||||
|
||||
- **WHEN** an admin without `BO_AUDIT_LOG` calls the audit log API or opens `/audit-log`
|
||||
- **THEN** the API answers 403 and the page shows Not authorised
|
||||
@@ -0,0 +1,67 @@
|
||||
# admin-emails Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
Let authorised admins read the emails the system has saved, so a temporary password can be passed on in person while no email provider is configured.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Email listing
|
||||
|
||||
The system SHALL let an admin with `BO_EMAILS` list the saved emails, newest first, showing each email's date, recipients, subject and status. The list SHALL filter by recipient, subject and date range, and SHALL be paged. The list SHALL NOT include any email body.
|
||||
|
||||
#### Scenario: Newest first
|
||||
|
||||
- **GIVEN** a forgot-password email to `sales1@example.com` was saved after an earlier email
|
||||
- **WHEN** an admin with `BO_EMAILS` opens the emails listing
|
||||
- **THEN** the forgot-password email is listed first with its date, recipient, subject and status
|
||||
- **AND** no email body is part of the list response
|
||||
|
||||
#### Scenario: Filter by recipient
|
||||
|
||||
- **WHEN** an admin filters the listing by recipient `sales1`
|
||||
- **THEN** only emails with a recipient containing `sales1` are listed
|
||||
|
||||
### Requirement: Email detail
|
||||
|
||||
The system SHALL let an admin with `BO_EMAILS` open one saved email and see its body. The portal SHALL show the body in a sandboxed frame that runs no scripts. Opening an email SHALL write an audit log line naming the email id and the viewer, and that line SHALL NOT contain the body.
|
||||
|
||||
#### Scenario: Read a temporary password
|
||||
|
||||
- **GIVEN** `sales1` used forgot-password and no email provider is configured
|
||||
- **WHEN** an admin with `BO_EMAILS` opens that email
|
||||
- **THEN** the admin sees the body with the temporary password
|
||||
- **AND** the log records that the admin viewed that email, without the body
|
||||
|
||||
#### Scenario: Unknown email
|
||||
|
||||
- **WHEN** an admin opens an email id that does not exist
|
||||
- **THEN** the system answers not found
|
||||
|
||||
### Requirement: Super admin emails protected
|
||||
|
||||
The system SHALL refuse to show the body of an email addressed to a super admin when the caller is not a super admin. The email SHALL still appear in the listing.
|
||||
|
||||
#### Scenario: Regular admin opens a super admin's email
|
||||
|
||||
- **GIVEN** a forgot-password email to a super admin's address
|
||||
- **AND** the caller has `BO_EMAILS` but is not a super admin
|
||||
- **WHEN** the caller opens that email
|
||||
- **THEN** the request is refused and no body is returned
|
||||
|
||||
#### Scenario: Super admin opens it
|
||||
|
||||
- **GIVEN** a forgot-password email to a super admin's address
|
||||
- **WHEN** a super admin opens that email
|
||||
- **THEN** the body is shown
|
||||
|
||||
### Requirement: Emails module gate
|
||||
|
||||
The emails listing and detail SHALL require the `BO_EMAILS` module. The module SHALL be seeded with no role grants, so only super admins can use it until a super admin grants it to a role.
|
||||
|
||||
#### Scenario: Without the module
|
||||
|
||||
- **GIVEN** an admin whose roles do not include `BO_EMAILS`
|
||||
- **WHEN** they call the emails listing or detail
|
||||
- **THEN** the request is refused
|
||||
- **AND** the Emails menu entry is not shown to them
|
||||
@@ -0,0 +1,133 @@
|
||||
# admin-login-security Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
Protect admin sign-in against password guessing: record every admin sign-in, sign-out, unlock and own password change, lock a username after repeated failures, and let authorised admins read the history, unlock staff and edit the lockout and password-rule settings.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Login history
|
||||
|
||||
The system SHALL record every admin sign-in attempt, sign-out, unlock and own password change, with the time, trimmed username, event, client IP, user agent and, for a known username, the user's company. Events: `LOGIN_SUCCESS`, `LOGIN_FAIL`, `LOGIN_LOCKED`, `LOGOUT`, `UNLOCK_RESET`, `PASSWORD_CHANGED`. Recording SHALL be best-effort and MUST NOT change the sign-in answer. A blank username or password SHALL NOT be recorded.
|
||||
|
||||
#### Scenario: Successful sign-in is recorded
|
||||
|
||||
- **WHEN** `sales1` signs in with the right password
|
||||
- **THEN** a `LOGIN_SUCCESS` record for `sales1` is saved with the time, client IP and user agent
|
||||
|
||||
#### Scenario: Failed sign-in is recorded
|
||||
|
||||
- **WHEN** someone signs in as `sales1` with a wrong password
|
||||
- **THEN** a `LOGIN_FAIL` record for `sales1` is saved
|
||||
|
||||
#### Scenario: Unknown username is recorded
|
||||
|
||||
- **WHEN** someone signs in as `nobody1`, which matches no user
|
||||
- **THEN** a `LOGIN_FAIL` record for `nobody1` is saved with no company
|
||||
|
||||
#### Scenario: Sign-out is recorded
|
||||
|
||||
- **WHEN** `sales1` signs out
|
||||
- **THEN** a `LOGOUT` record for `sales1` is saved
|
||||
|
||||
#### Scenario: History write failure does not block sign-in
|
||||
|
||||
- **GIVEN** the history cannot be written
|
||||
- **WHEN** `sales1` signs in with the right password
|
||||
- **THEN** the sign-in succeeds
|
||||
- **AND** the write failure is logged
|
||||
|
||||
### Requirement: Lockout after repeated failures
|
||||
|
||||
The system SHALL lock a username when lockout is on and its `LOGIN_FAIL` records reach the configured maximum, counting only records inside the configured period and after its latest `LOGIN_SUCCESS`, `UNLOCK_RESET` or `PASSWORD_CHANGED`. The maximum, period, unit and on/off switch SHALL come from settings. Failures SHALL count for unknown usernames too, so a lock does not reveal whether an account exists. The lock SHALL end once the counted failures leave the period.
|
||||
|
||||
#### Scenario: Maximum reached locks the username
|
||||
|
||||
- **GIVEN** lockout is on with a maximum of 5 in 15 minutes
|
||||
- **WHEN** `sales1` fails to sign in 5 times within 15 minutes
|
||||
- **THEN** `sales1` is locked
|
||||
|
||||
#### Scenario: Old failures do not count
|
||||
|
||||
- **GIVEN** lockout is on with a maximum of 5 in 15 minutes
|
||||
- **WHEN** `sales1` has 4 failures within the last 15 minutes and 3 older ones
|
||||
- **THEN** `sales1` is not locked
|
||||
|
||||
#### Scenario: A success resets the count
|
||||
|
||||
- **WHEN** `sales1` fails 4 times, signs in successfully, then fails 4 more times within 15 minutes
|
||||
- **THEN** `sales1` is not locked
|
||||
|
||||
#### Scenario: Lockout switched off
|
||||
|
||||
- **GIVEN** lockout is off
|
||||
- **WHEN** `sales1` fails 10 times within 15 minutes
|
||||
- **THEN** `sales1` is not locked
|
||||
|
||||
### Requirement: Locked username is refused
|
||||
|
||||
The system SHALL refuse sign-in for a locked username before checking the password, with the code `ACCOUNT_LOCKED` and a message telling the user to try later or ask an administrator, and SHALL record `LOGIN_LOCKED`. When the lock state cannot be read because of an infrastructure error, sign-in SHALL proceed to the normal password check.
|
||||
|
||||
#### Scenario: Right password while locked
|
||||
|
||||
- **GIVEN** `sales1` is locked
|
||||
- **WHEN** `sales1` signs in with the right password
|
||||
- **THEN** sign-in is refused with `ACCOUNT_LOCKED`
|
||||
- **AND** no session is issued
|
||||
- **AND** a `LOGIN_LOCKED` record is saved
|
||||
|
||||
#### Scenario: Lock check unavailable
|
||||
|
||||
- **GIVEN** the lock state cannot be read
|
||||
- **WHEN** `sales1` signs in with the right password
|
||||
- **THEN** the sign-in succeeds
|
||||
|
||||
#### Scenario: Portal shows the locked message
|
||||
|
||||
- **WHEN** sign-in is refused with `ACCOUNT_LOCKED`
|
||||
- **THEN** the login page shows the locked message instead of "Invalid username or password"
|
||||
|
||||
### Requirement: Unlock
|
||||
|
||||
The system SHALL let an admin with `BO_LOGIN_SECURITY` list the usernames that are locked now, with their failure count, last failure time and when the lock ends, and SHALL let that admin unlock one. Unlocking SHALL save an `UNLOCK_RESET` record naming the admin who unlocked.
|
||||
|
||||
#### Scenario: Unlock a locked username
|
||||
|
||||
- **GIVEN** `sales1` is locked
|
||||
- **WHEN** an admin with `BO_LOGIN_SECURITY` unlocks `sales1`
|
||||
- **THEN** `sales1` no longer appears in the locked list
|
||||
- **AND** `sales1` can sign in with the right password
|
||||
- **AND** an `UNLOCK_RESET` record for `sales1` names the admin
|
||||
|
||||
### Requirement: Login history screen
|
||||
|
||||
The system SHALL let an admin with `BO_LOGIN_SECURITY` read the login history, newest first and paged, filtered by username, event and date range.
|
||||
|
||||
#### Scenario: Filter by event
|
||||
|
||||
- **WHEN** an admin filters the history by event `LOGIN_FAIL`
|
||||
- **THEN** only `LOGIN_FAIL` records are listed, newest first
|
||||
|
||||
#### Scenario: Without the module
|
||||
|
||||
- **WHEN** an admin without `BO_LOGIN_SECURITY` calls the login-security API
|
||||
- **THEN** the request is refused with 403
|
||||
|
||||
### Requirement: Lockout and password-rule settings
|
||||
|
||||
The system SHALL let an admin with `BO_LOGIN_SECURITY` read and change the lockout settings (on/off, maximum attempts, period, time unit) and the admin password rules (each rule's on/off status and value). The system SHALL reject a maximum below 1 or above 1000, a period below 1 or above 10000, and a time unit other than S, M, H or D. Password rules SHALL only be edited, never added or removed. Every change SHALL write a log line naming the admin.
|
||||
|
||||
#### Scenario: Change the lockout settings
|
||||
|
||||
- **WHEN** an admin sets the maximum to 3 and the period to 30 minutes
|
||||
- **THEN** the next lock decision uses 3 attempts in 30 minutes
|
||||
|
||||
#### Scenario: Invalid setting
|
||||
|
||||
- **WHEN** an admin sets the maximum to 0
|
||||
- **THEN** the change is refused with a validation error and the settings stay as they were
|
||||
|
||||
#### Scenario: Change a password rule
|
||||
|
||||
- **WHEN** an admin sets the minimum length rule to 10
|
||||
- **THEN** a new password of 9 characters is refused by every admin password check
|
||||
@@ -0,0 +1,56 @@
|
||||
# admin-own-password Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
Let a signed-in admin change their own password, checked against the current password and the admin password rules, without an administrator.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Change own password
|
||||
|
||||
The system SHALL let a signed-in admin change their own password by giving the current password, a new password and its confirmation. The new password SHALL pass the admin password rules and SHALL differ from the current one. On success the system SHALL keep the admin signed in, keep their first-login state complete, and record `PASSWORD_CHANGED`. An admin whose first-login password change is still pending SHALL use the first-login flow instead.
|
||||
|
||||
#### Scenario: Successful change
|
||||
|
||||
- **WHEN** `sales1` gives the right current password and a new password that passes the rules, twice
|
||||
- **THEN** the new password works at the next sign-in and the old one does not
|
||||
- **AND** `sales1` stays signed in
|
||||
- **AND** a `PASSWORD_CHANGED` record is saved
|
||||
|
||||
#### Scenario: Confirmation differs
|
||||
|
||||
- **WHEN** the new password and its confirmation differ
|
||||
- **THEN** the change is refused with `PASSWORD_MISMATCH`
|
||||
|
||||
#### Scenario: Same as current
|
||||
|
||||
- **WHEN** the new password equals the current password
|
||||
- **THEN** the change is refused with `PASSWORD_SAME`
|
||||
|
||||
#### Scenario: Fails the rules
|
||||
|
||||
- **WHEN** the new password breaks an admin password rule
|
||||
- **THEN** the change is refused with `PASSWORD_POLICY`
|
||||
|
||||
#### Scenario: Pending first login
|
||||
|
||||
- **GIVEN** `sales1` must still complete the first-login password change
|
||||
- **WHEN** `sales1` calls change password
|
||||
- **THEN** the request is refused and `sales1` is sent to the first-login flow
|
||||
|
||||
### Requirement: Wrong current password counts as a failed sign-in
|
||||
|
||||
The system SHALL refuse a change whose current password is wrong with `CURRENT_PASSWORD_WRONG`, and SHALL record it as `LOGIN_FAIL` so that repeated wrong guesses lock the username. A locked username SHALL be refused with `ACCOUNT_LOCKED` before the current password is checked.
|
||||
|
||||
#### Scenario: Wrong current password
|
||||
|
||||
- **WHEN** `sales1` gives a wrong current password
|
||||
- **THEN** the change is refused with `CURRENT_PASSWORD_WRONG`
|
||||
- **AND** a `LOGIN_FAIL` record for `sales1` is saved
|
||||
|
||||
#### Scenario: Locked while changing
|
||||
|
||||
- **GIVEN** `sales1` is locked
|
||||
- **WHEN** `sales1` calls change password with the right current password
|
||||
- **THEN** the change is refused with `ACCOUNT_LOCKED`
|
||||
- **AND** the password is unchanged
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import * as route from "./route";
|
||||
|
||||
const { GET } = route;
|
||||
const req = (url: string) => new Request(url) as unknown as Parameters<typeof GET>[0];
|
||||
const ctx = (path?: string[]) => ({ params: Promise.resolve({ path }) });
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
||||
});
|
||||
|
||||
describe("/api/audit-log/[[...path]]", () => {
|
||||
it("is GET only", () => {
|
||||
expect(Object.keys(route).filter((k) => /^(GET|POST|PUT|PATCH|DELETE)$/.test(k))).toEqual(["GET"]);
|
||||
});
|
||||
|
||||
it("returns 401 without a session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
expect((await GET(req("http://localhost/api/audit-log"), ctx())).status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses dot segments", async () => {
|
||||
expect((await GET(req("http://localhost/api/audit-log/.."), ctx([".."]))).status).toBe(400);
|
||||
expect((await GET(req("http://localhost/api/audit-log/."), ctx(["."]))).status).toBe(400);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forwards the query to the list", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [] } });
|
||||
const res = await GET(req("http://localhost/api/audit-log?actor=a&page=0&size=20"), ctx());
|
||||
expect(res.status).toBe(200);
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/audit-log?actor=a&page=0&size=20", { token: "jwt" });
|
||||
});
|
||||
|
||||
it("forwards one event by encoded id", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: "a/b" } });
|
||||
await GET(req("http://localhost/api/audit-log/a%2Fb"), ctx(["a/b"]));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/audit-log/a%2Fb", { token: "jwt" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
// Read-only proxy for /api/admin/audit-log[/<id>]; mobile-api owns the BO_AUDIT_LOG guard. Audit events are never writable from the portal, so GET is the only method.
|
||||
type Ctx = { params: Promise<{ path?: string[] }> };
|
||||
|
||||
export async function GET(req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { path = [] } = await params;
|
||||
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
|
||||
const target = `/api/admin/audit-log${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${new URL(req.url).search}`;
|
||||
const result = await callMobileApi<unknown>(target, { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import { POST } from "./route";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset();
|
||||
});
|
||||
|
||||
describe("POST /api/auth/change-password: client context", () => {
|
||||
it("forwards the browser IP and user agent for the login history", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: null });
|
||||
const req = new Request("http://localhost/api/auth/change-password", {
|
||||
method: "POST",
|
||||
headers: { "x-forwarded-for": "198.51.100.7", "user-agent": "Browser/1.0" },
|
||||
body: JSON.stringify({ currentPassword: "a", newPassword: "b", confirmPassword: "b" }),
|
||||
}) as unknown as Parameters<typeof POST>[0];
|
||||
await POST(req);
|
||||
expect(mocks.callMobileApi.mock.calls[0][1].headers).toEqual({
|
||||
"X-Client-Ip": "198.51.100.7",
|
||||
"X-Client-User-Agent": "Browser/1.0",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import { POST } from "./route";
|
||||
|
||||
function req(body: unknown) {
|
||||
return new Request("http://localhost/api/auth/change-password", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
}) as unknown as Parameters<typeof POST>[0];
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset();
|
||||
});
|
||||
|
||||
describe("POST /api/auth/change-password", () => {
|
||||
it("returns 401 when there is no session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
const res = await POST(req({}));
|
||||
expect(res.status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forwards only the three password fields and answers 204", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: null });
|
||||
const res = await POST(req({ currentPassword: "Old#1", newPassword: "New#1", confirmPassword: "New#1", extra: 1 }));
|
||||
expect(res.status).toBe(204);
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/auth/change-password", {
|
||||
method: "POST",
|
||||
body: { currentPassword: "Old#1", newPassword: "New#1", confirmPassword: "New#1" },
|
||||
token: "jwt-abc",
|
||||
headers: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("passes a refusal through with its code", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 400, error: "Current password is wrong", code: "CURRENT_PASSWORD_WRONG" });
|
||||
const res = await POST(req({}));
|
||||
expect(res.status).toBe(400);
|
||||
expect(await res.json()).toMatchObject({ error: "Current password is wrong", code: "CURRENT_PASSWORD_WRONG" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
import { clientContextHeaders } from "@/app/lib/server/clientContext";
|
||||
|
||||
/** The signed-in admin changes their own password; only the three fields are forwarded, and nothing is logged. */
|
||||
export async function POST(req: NextRequest) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { currentPassword, newPassword, confirmPassword } = (await req.json().catch(() => ({}))) as {
|
||||
currentPassword?: string;
|
||||
newPassword?: string;
|
||||
confirmPassword?: string;
|
||||
};
|
||||
const result = await callMobileApi<null>("/api/admin/auth/change-password", {
|
||||
method: "POST",
|
||||
body: { currentPassword, newPassword, confirmPassword },
|
||||
token,
|
||||
// The browser IP and user agent go into the login history rows this call writes.
|
||||
headers: clientContextHeaders(req),
|
||||
});
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), setSession: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ setSession: mocks.setSession }));
|
||||
|
||||
import { POST } from "./route";
|
||||
|
||||
function req() {
|
||||
return new Request("http://localhost/api/auth/login", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ username: "sales1", password: "x" }),
|
||||
}) as unknown as Parameters<typeof POST>[0];
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
});
|
||||
|
||||
describe("POST /api/auth/login: locked account", () => {
|
||||
it("keeps the ACCOUNT_LOCKED code on the 401", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 401, error: "Too many failed sign-ins.", code: "ACCOUNT_LOCKED" });
|
||||
const res = await POST(req());
|
||||
expect(res.status).toBe(401);
|
||||
expect(await res.json()).toMatchObject({ error: "Too many failed sign-ins.", code: "ACCOUNT_LOCKED" });
|
||||
});
|
||||
|
||||
it("leaves other 401s without a code", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 401, error: "Invalid username or password" });
|
||||
const res = await POST(req());
|
||||
expect(res.status).toBe(401);
|
||||
expect((await res.json()).code).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -31,9 +31,9 @@ export async function POST(req: NextRequest) {
|
||||
if (!result.ok) {
|
||||
// The mobile-api answers bad credentials with HTTP 401 directly (not the
|
||||
// expired-token signal), so surface it as 401 rather than the generic 400.
|
||||
// A confirmed-locked account comes back as 423 with its own message, which
|
||||
// errorResponse forwards as-is (4xx passthrough).
|
||||
if (result.status === 401) return unauthorized(result.error);
|
||||
// A locked account is also a 401, but carries code ACCOUNT_LOCKED, which the
|
||||
// login page needs to show its own message; errorResponse keeps the code.
|
||||
if (result.status === 401 && result.code !== "ACCOUNT_LOCKED") return unauthorized(result.error);
|
||||
return errorResponse(result);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import { GET, POST, PUT } from "./route";
|
||||
|
||||
const req = (url: string, body?: unknown) =>
|
||||
new Request(url, body === undefined ? undefined : { method: "PUT", body: JSON.stringify(body), headers: { "Content-Type": "application/json" } }) as unknown as Parameters<typeof GET>[0];
|
||||
const ctx = (path?: string[]) => ({ params: Promise.resolve({ path }) });
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
||||
});
|
||||
|
||||
describe("/api/login-security/[[...path]]", () => {
|
||||
it("returns 401 without a session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
expect((await GET(req("http://localhost/api/login-security/locked"), ctx(["locked"]))).status).toBe(401);
|
||||
expect((await PUT(req("http://localhost/api/login-security/config", {}), ctx(["config"]))).status).toBe(401);
|
||||
expect((await POST(req("http://localhost/api/login-security/locked/a/unlock", {}), ctx(["locked", "a", "unlock"]))).status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses dot segments", async () => {
|
||||
expect((await GET(req("http://localhost/api/login-security/.."), ctx([".."]))).status).toBe(400);
|
||||
expect((await POST(req("http://localhost/api/login-security/locked/./unlock"), ctx(["locked", ".", "unlock"]))).status).toBe(400);
|
||||
expect((await PUT(req("http://localhost/api/login-security/.."), ctx([".."]))).status).toBe(400);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("GET forwards the path and query", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [] } });
|
||||
const res = await GET(req("http://localhost/api/login-security/audit?username=a&page=0&size=20"), ctx(["audit"]));
|
||||
expect(res.status).toBe(200);
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/login-security/audit?username=a&page=0&size=20", { token: "jwt" });
|
||||
});
|
||||
|
||||
it("encodes each segment", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: null });
|
||||
await POST(req("http://localhost/api/login-security/locked/a%2Fb/unlock"), ctx(["locked", "a/b", "unlock"]));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/login-security/locked/a%2Fb/unlock", { token: "jwt", method: "POST", body: undefined });
|
||||
});
|
||||
|
||||
it("PUT forwards the JSON body", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { enabled: true } });
|
||||
const body = { enabled: true, maxAttempts: 5, period: 15, unit: "M" };
|
||||
const res = await PUT(req("http://localhost/api/login-security/config", body), ctx(["config"]));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/login-security/config", { token: "jwt", method: "PUT", body });
|
||||
expect(await res.json()).toEqual({ enabled: true });
|
||||
});
|
||||
|
||||
it("POST forwards the JSON body", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { x: 1 } });
|
||||
const r = new Request("http://localhost/api/login-security/x", { method: "POST", body: JSON.stringify({ a: 1 }) }) as unknown as Parameters<typeof GET>[0];
|
||||
await POST(r, ctx(["x"]));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/login-security/x", { token: "jwt", method: "POST", body: { a: 1 } });
|
||||
});
|
||||
|
||||
it("passes an empty upstream body through as 204", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: null });
|
||||
const res = await POST(req("http://localhost/api/login-security/locked/a/unlock"), ctx(["locked", "a", "unlock"]));
|
||||
expect(res.status).toBe(204);
|
||||
});
|
||||
|
||||
it("passes a refusal through with its code", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 400, error: "Max attempts must be at least 1", code: "INVALID_SETTING" });
|
||||
const res = await PUT(req("http://localhost/api/login-security/config", { maxAttempts: 0 }), ctx(["config"]));
|
||||
expect(res.status).toBe(400);
|
||||
expect(await res.json()).toMatchObject({ code: "INVALID_SETTING", error: "Max attempts must be at least 1" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
// Proxy for /api/admin/login-security/**; mobile-api owns the BO_LOGIN_SECURITY guard. Bodies are forwarded, never logged.
|
||||
type Ctx = { params: Promise<{ path?: string[] }> };
|
||||
|
||||
async function forward(method: "GET" | "POST" | "PUT", req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { path = [] } = await params;
|
||||
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
|
||||
const target = `/api/admin/login-security${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${method === "GET" ? new URL(req.url).search : ""}`;
|
||||
let body: unknown;
|
||||
if (method !== "GET") {
|
||||
const text = await req.text();
|
||||
if (text) {
|
||||
try { body = JSON.parse(text); } catch { return badRequest("Invalid request body."); }
|
||||
}
|
||||
}
|
||||
const result = await callMobileApi<unknown>(target, method === "GET" ? { token } : { token, method, body });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
if (result.data === null || result.data === undefined) return new NextResponse(null, { status: 204 });
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
|
||||
export const GET = (req: NextRequest, ctx: Ctx) => forward("GET", req, ctx);
|
||||
export const POST = (req: NextRequest, ctx: Ctx) => forward("POST", req, ctx);
|
||||
export const PUT = (req: NextRequest, ctx: Ctx) => forward("PUT", req, ctx);
|
||||
@@ -0,0 +1,84 @@
|
||||
import { render, screen, within } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ getAuditEvent: vi.fn(), useAdminAuth: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/auditLog", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/auditLog")>()),
|
||||
getAuditEvent: mocks.getAuditEvent,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", () => ({ useParams: () => ({ id: "e2" }) }));
|
||||
|
||||
import AuditEventPage from "./page";
|
||||
|
||||
const EVENT = {
|
||||
id: 2, companyId: 1, occurredAt: "2026-11-30T15:52:00.5", actor: "sales1", module: "BO_USERS", action: "USER_UPDATE",
|
||||
httpMethod: "PUT", pathTemplate: "/api/admin/users/{id}", targetId: "42", outcome: "SUCCESS", httpStatus: 200, clientIp: "10.0.0.5", changes: null as string | null,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.getAuditEvent.mockReset();
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
|
||||
});
|
||||
|
||||
describe("AuditEventPage", () => {
|
||||
it("gates on BO_AUDIT_LOG", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<AuditEventPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
expect(mocks.getAuditEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows a before/after table for put-style changes", async () => {
|
||||
const changes = JSON.stringify({
|
||||
roles: { before: ["A"], after: ["A", "B"] },
|
||||
enabled: { before: false, after: true },
|
||||
lockout: { before: { status: "Y", value: 5 }, after: null },
|
||||
});
|
||||
mocks.getAuditEvent.mockResolvedValue({ ...EVENT, changes });
|
||||
render(<AuditEventPage />);
|
||||
const table = await screen.findByRole("table");
|
||||
expect(within(table).getAllByRole("columnheader").map((h) => h.textContent)).toEqual(["Field", "Before", "After"]);
|
||||
const rows = within(table).getAllByRole("row").slice(1);
|
||||
expect(rows[0]).toHaveTextContent("rolesAA, B");
|
||||
expect(rows[1]).toHaveTextContent("enabledfalsetrue");
|
||||
expect(rows[2]).toHaveTextContent("lockoutstatus: Y, value: 5—");
|
||||
expect(screen.getByText("sales1")).toBeInTheDocument();
|
||||
expect(screen.getByText("/api/admin/users/{id}", { exact: false })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders module grants with a dash before and joined codes after", async () => {
|
||||
const changes = JSON.stringify({
|
||||
modulesAdded: { before: null, after: ["BO_USERS", "BO_LEADS"] },
|
||||
modulesRemoved: { before: null, after: ["BO_EVENTS"] },
|
||||
});
|
||||
mocks.getAuditEvent.mockResolvedValue({ ...EVENT, changes });
|
||||
render(<AuditEventPage />);
|
||||
const rows = within(await screen.findByRole("table")).getAllByRole("row").slice(1);
|
||||
expect(rows[0]).toHaveTextContent("modulesAdded—BO_USERS, BO_LEADS");
|
||||
expect(rows[1]).toHaveTextContent("modulesRemoved—BO_EVENTS");
|
||||
});
|
||||
|
||||
it("lists field names only for {fields: [...]}", async () => {
|
||||
mocks.getAuditEvent.mockResolvedValue({ ...EVENT, changes: JSON.stringify({ fields: ["phone", "notes"] }) });
|
||||
render(<AuditEventPage />);
|
||||
expect(await screen.findByText("phone")).toBeInTheDocument();
|
||||
expect(screen.getByText("notes")).toBeInTheDocument();
|
||||
expect(screen.getByText("Values are not recorded for these fields.")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("table")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows unparsable changes as plain text", async () => {
|
||||
mocks.getAuditEvent.mockResolvedValue({ ...EVENT, changes: "not json {" });
|
||||
render(<AuditEventPage />);
|
||||
expect(await screen.findByText("not json {")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows a message when the event is not found", async () => {
|
||||
mocks.getAuditEvent.mockRejectedValue(new ApiError("NOT_FOUND", 404));
|
||||
render(<AuditEventPage />);
|
||||
expect(await screen.findByText("Audit event not found")).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "Back to audit log" })).toHaveAttribute("href", "/audit-log");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useParams } from "next/navigation";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { Skeleton } from "@/app/components/ui/skeleton";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { formatEmailDate } from "@/app/lib/services/adminEmails";
|
||||
import { getAuditEvent, type AuditEvent } from "@/app/lib/services/auditLog";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
type Parsed = { kind: "fields"; fields: string[] } | { kind: "diff"; rows: [string, unknown, unknown][] } | { kind: "text"; text: string };
|
||||
|
||||
function parseChanges(raw: string): Parsed {
|
||||
try {
|
||||
const obj: unknown = JSON.parse(raw);
|
||||
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
||||
const rec = obj as Record<string, unknown>;
|
||||
if (Array.isArray(rec.fields)) return { kind: "fields", fields: rec.fields.map(String) };
|
||||
const rows = Object.entries(rec).map(([k, v]): [string, unknown, unknown] => {
|
||||
const c = (v ?? {}) as { before?: unknown; after?: unknown };
|
||||
return [k, c.before, c.after];
|
||||
});
|
||||
return { kind: "diff", rows };
|
||||
}
|
||||
} catch { /* shown as plain text below */ }
|
||||
return { kind: "text", text: raw };
|
||||
}
|
||||
|
||||
const show = (v: unknown): string => {
|
||||
if (v === null || v === undefined) return "—";
|
||||
if (Array.isArray(v)) return v.map(show).join(", ");
|
||||
if (typeof v === "object") return Object.entries(v).map(([k, x]) => `${k}: ${show(x)}`).join(", ");
|
||||
return String(v);
|
||||
};
|
||||
|
||||
function Changes({ raw }: { raw: string | null }) {
|
||||
const t = useT();
|
||||
const parsed = useMemo(() => (raw ? parseChanges(raw) : null), [raw]);
|
||||
if (!parsed) return <p className="text-sm text-muted-foreground">{t("AuditNoChanges")}</p>;
|
||||
if (parsed.kind === "text") return <pre className="overflow-x-auto whitespace-pre-wrap break-all text-sm">{parsed.text}</pre>;
|
||||
if (parsed.kind === "fields") {
|
||||
return (
|
||||
<div className="space-y-2 text-sm">
|
||||
<ul className="list-disc pl-5">{parsed.fields.map((f) => <li key={f}>{f}</li>)}</ul>
|
||||
<p className="text-muted-foreground">{t("AuditFieldsOnly")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{t("AuditField")}</TableHead>
|
||||
<TableHead>{t("AuditBefore")}</TableHead>
|
||||
<TableHead>{t("AuditAfter")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{parsed.rows.map(([field, before, after]) => (
|
||||
<TableRow key={field}>
|
||||
<TableCell className="font-medium">{field}</TableCell>
|
||||
<TableCell className="break-words whitespace-normal">{show(before)}</TableCell>
|
||||
<TableCell className="break-words whitespace-normal">{show(after)}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
}
|
||||
|
||||
function AuditEventContent() {
|
||||
const t = useT();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [event, setEvent] = useState<AuditEvent | null>(null);
|
||||
const [error, setError] = useState<"notFound" | "failed" | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- clears the previous event/error before the id-triggered fetch below.
|
||||
setEvent(null);
|
||||
setError(null);
|
||||
getAuditEvent(id)
|
||||
.then((e) => { if (!cancelled) setEvent(e); })
|
||||
.catch((err: unknown) => { if (!cancelled) setError(err instanceof ApiError && err.status === 404 ? "notFound" : "failed"); });
|
||||
return () => { cancelled = true; };
|
||||
}, [id]);
|
||||
|
||||
const back = <Link href="/audit-log" className="mt-4 inline-block text-primary underline-offset-4 hover:underline">{t("AuditBack")}</Link>;
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_AUDIT_LOG")} />
|
||||
{error === "notFound" ? <EmptyState title={t("AuditNotFound")} /> : <ErrorState message={t("AuditLoadFailed")} className="mb-4" />}
|
||||
{back}
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (!event) {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_AUDIT_LOG")} />
|
||||
<Skeleton className="h-64 w-full" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<PageHeader title={event.action} />
|
||||
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-sm">
|
||||
<dt className="text-muted-foreground">{t("LsTime")}</dt>
|
||||
<dd>{formatEmailDate(event.occurredAt)}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditWho")}</dt>
|
||||
<dd className="break-all">{event.actor}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditModule")}</dt>
|
||||
<dd>{event.module ? t(event.module) : "—"}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditAction")}</dt>
|
||||
<dd>{event.action}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditRequest")}</dt>
|
||||
<dd className="break-all">{event.httpMethod} {event.pathTemplate}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditTarget")}</dt>
|
||||
<dd className="break-all">{event.targetId ?? "—"}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditOutcome")}</dt>
|
||||
<dd><Badge variant={event.outcome === "SUCCESS" ? "positive" : "negative"}>{event.outcome} {event.httpStatus}</Badge></dd>
|
||||
<dt className="text-muted-foreground">{t("LsIp")}</dt>
|
||||
<dd>{event.clientIp ?? "—"}</dd>
|
||||
</dl>
|
||||
<section className="space-y-2">
|
||||
<h2 className="text-base font-semibold">{t("AuditChanges")}</h2>
|
||||
<Changes raw={event.changes} />
|
||||
</section>
|
||||
{back}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AuditEventPage() {
|
||||
return (
|
||||
<RequireModule pathname="/audit-log">
|
||||
<AuditEventContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ searchAuditLog: vi.fn(), useAdminAuth: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/auditLog", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/auditLog")>()),
|
||||
searchAuditLog: mocks.searchAuditLog,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import AuditLogPage from "./page";
|
||||
|
||||
const EVENTS = [
|
||||
{ id: 2, companyId: 1, occurredAt: "2026-11-30T15:52:00.5", actor: "sales1", module: "BO_USERS", action: "USER_UPDATE", httpMethod: "PUT", pathTemplate: "/api/admin/users/{id}", targetId: "42", outcome: "FAILURE", httpStatus: 403, clientIp: "10.0.0.5", changes: null },
|
||||
{ id: 1, companyId: 1, occurredAt: "2026-11-29T09:05:00", actor: "admin", module: null, action: "LEAD_EXPORT", httpMethod: "GET", pathTemplate: "/api/admin/leads/export", targetId: null, outcome: "SUCCESS", httpStatus: 200, clientIp: "10.0.0.6", changes: null },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/audit-log");
|
||||
mocks.searchAuditLog.mockReset().mockResolvedValue({ items: EVENTS, total: 2 });
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
|
||||
});
|
||||
|
||||
describe("AuditLogPage", () => {
|
||||
it("renders NotAuthorized without BO_AUDIT_LOG", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<AuditLogPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
expect(mocks.searchAuditLog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("lists rows with module label, outcome badge with status, and a link to the detail", async () => {
|
||||
render(<AuditLogPage />);
|
||||
const table = await screen.findByRole("table");
|
||||
const rows = within(table).getAllByRole("row").slice(1);
|
||||
expect(rows[0]).toHaveTextContent("30/11/2026 15:52");
|
||||
expect(rows[0]).toHaveTextContent("sales1");
|
||||
expect(rows[0]).toHaveTextContent("Users");
|
||||
expect(rows[0]).toHaveTextContent("USER_UPDATE");
|
||||
expect(rows[0]).toHaveTextContent("FAILURE 403");
|
||||
expect(rows[0]).toHaveTextContent("10.0.0.5");
|
||||
expect(within(rows[0]).getByRole("link", { name: "USER_UPDATE" })).toHaveAttribute("href", "/audit-log/2");
|
||||
expect(rows[1]).toHaveTextContent("SUCCESS 200");
|
||||
});
|
||||
|
||||
it("labels lead modules and offers them in the module filter, without BO_AUDIT_LOG", async () => {
|
||||
mocks.searchAuditLog.mockResolvedValue({ items: [{ ...EVENTS[1], module: "BO_LEADS_EXPORT" }], total: 1 });
|
||||
render(<AuditLogPage />);
|
||||
const table = await screen.findByRole("table");
|
||||
expect(within(table).getAllByRole("row")[1]).toHaveTextContent("Lead export");
|
||||
await userEvent.click(screen.getByRole("combobox", { name: "Module" }));
|
||||
expect(await screen.findByRole("option", { name: "Lead editing" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("option", { name: "Lead export" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("option", { name: "Audit log" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows a dash for a null module", async () => {
|
||||
render(<AuditLogPage />);
|
||||
const table = await screen.findByRole("table");
|
||||
expect(within(table).getAllByRole("row")[2]).toHaveTextContent("admin—LEAD_EXPORT");
|
||||
});
|
||||
|
||||
it("puts the filters in the query", async () => {
|
||||
memoryRouter.reset("/audit-log", "outcome=FAILURE&from=2026-11-01&module=BO_USERS");
|
||||
render(<AuditLogPage />);
|
||||
await screen.findByRole("table");
|
||||
expect(mocks.searchAuditLog).toHaveBeenCalledWith(expect.objectContaining({ outcome: "FAILURE", from: "2026-11-01", module: "BO_USERS", page: 1, pageSize: 20 }));
|
||||
await userEvent.type(screen.getByRole("searchbox", { name: "Who" }), "sales");
|
||||
await waitFor(() => expect(mocks.searchAuditLog).toHaveBeenLastCalledWith(expect.objectContaining({ actor: "sales", outcome: "FAILURE" })));
|
||||
});
|
||||
|
||||
it("shows an empty state and an error state", async () => {
|
||||
mocks.searchAuditLog.mockResolvedValue({ items: [], total: 0 });
|
||||
const { unmount } = render(<AuditLogPage />);
|
||||
expect(await screen.findByText("No audit events found")).toBeInTheDocument();
|
||||
unmount();
|
||||
mocks.searchAuditLog.mockRejectedValue(new Error("x"));
|
||||
render(<AuditLogPage />);
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Failed to load the audit log");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { FilterField, FilterPanel, FilterSearch, FilterSelect } from "@/app/components/ui/filter-panel";
|
||||
import { DataTable } from "@/app/components/ui/data-table";
|
||||
import { DatePicker } from "@/app/components/ui/date-picker";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { useListFilters } from "@/app/lib/hooks/useListFilters";
|
||||
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
|
||||
import { ROUTE_MODULES } from "@/app/lib/routeModules";
|
||||
import { formatEmailDate as formatDate } from "@/app/lib/services/adminEmails";
|
||||
import { searchAuditLog, type AuditEvent } from "@/app/lib/services/auditLog";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
const DEFAULTS = { actor: "", module: "", action: "", outcome: "", from: "", to: "" };
|
||||
// The backend stores the handler's @AdminModule code, so the filter lists those: the route modules plus the lead edit/export codes. Audit-log reads are never recorded.
|
||||
const MODULES = [...Object.values(ROUTE_MODULES).filter((m) => m !== "BO_AUDIT_LOG"), "BO_LEADS_EDIT", "BO_LEADS_EXPORT"];
|
||||
|
||||
function AuditLogContent() {
|
||||
const t = useT();
|
||||
const { tableRef, pageSize } = useFitPageSize();
|
||||
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
|
||||
const [data, setData] = useState<{ items: AuditEvent[]; total: number }>({ items: [], total: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (pageSize == null) return;
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the filter/page/reloadKey-triggered fetch below, which is the actual synchronization.
|
||||
setLoading(true);
|
||||
setFailed(false);
|
||||
searchAuditLog({ ...filters, page, pageSize })
|
||||
.then((result) => { if (!cancelled) setData(result); })
|
||||
.catch(() => { if (!cancelled) setFailed(true); })
|
||||
.finally(() => { if (!cancelled) setLoading(false); });
|
||||
return () => { cancelled = true; };
|
||||
}, [filters, page, reloadKey, pageSize]);
|
||||
|
||||
const moduleOptions = useMemo(() => MODULES.map((m) => ({ value: m, label: t(m) })), [t]);
|
||||
const outcomeOptions = useMemo(() => [{ value: "SUCCESS", label: t("AuditSuccess") }, { value: "FAILURE", label: t("AuditFailure") }], [t]);
|
||||
const cut = (text: string | null | undefined, max = "max-w-40") => <span className={`block truncate ${max}`} title={text ?? undefined}>{text}</span>;
|
||||
const columns = useMemo<ColumnDef<AuditEvent, unknown>[]>(
|
||||
() => [
|
||||
{ id: "time", header: t("LsTime"), enableSorting: false, cell: ({ row }) => <span className="whitespace-nowrap">{formatDate(row.original.occurredAt)}</span> },
|
||||
{ id: "actor", header: t("AuditWho"), enableSorting: false, cell: ({ row }) => cut(row.original.actor, "max-w-32") },
|
||||
{ id: "module", header: t("AuditModule"), enableSorting: false, cell: ({ row }) => (row.original.module ? t(row.original.module) : "—") },
|
||||
{
|
||||
id: "action",
|
||||
header: t("AuditAction"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => (
|
||||
<Link href={`/audit-log/${row.original.id}`} title={row.original.action} className="block max-w-48 truncate font-medium text-primary underline-offset-4 hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
|
||||
{row.original.action}
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
{ id: "target", header: t("AuditTarget"), enableSorting: false, cell: ({ row }) => cut(row.original.targetId, "max-w-28") },
|
||||
{
|
||||
id: "outcome",
|
||||
header: t("AuditOutcome"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => (
|
||||
<Badge variant={row.original.outcome === "SUCCESS" ? "positive" : "negative"}>{row.original.outcome} {row.original.httpStatus}</Badge>
|
||||
),
|
||||
},
|
||||
{ accessorKey: "clientIp", header: t("LsIp"), enableSorting: false },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_AUDIT_LOG")} />
|
||||
{failed && <ErrorState message={t("AuditLoadFailed")} onRetry={refetch} className="mb-4" />}
|
||||
<FilterPanel activeCount={activeCount} onClear={clear}>
|
||||
<FilterField label={t("AuditWho")}>
|
||||
<FilterSearch className="w-full" aria-label={t("AuditWho")} value={filters.actor} onChange={(actor) => set({ actor })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("AuditModule")}>
|
||||
<FilterSelect className="w-full" aria-label={t("AuditModule")} allLabel={t("AuditAllModules")} options={moduleOptions} value={filters.module} onChange={(module) => set({ module })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("AuditAction")}>
|
||||
<FilterSearch className="w-full" aria-label={t("AuditAction")} value={filters.action} onChange={(action) => set({ action })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("AuditOutcome")}>
|
||||
<FilterSelect className="w-full" aria-label={t("AuditOutcome")} allLabel={t("AuditAllOutcomes")} options={outcomeOptions} value={filters.outcome} onChange={(outcome) => set({ outcome })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LsFrom")}>
|
||||
<DatePicker aria-label={t("LsFrom")} value={filters.from} onChange={(from) => set({ from })} max={filters.to || undefined} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LsTo")}>
|
||||
<DatePicker aria-label={t("LsTo")} value={filters.to} onChange={(to) => set({ to })} min={filters.from || undefined} />
|
||||
</FilterField>
|
||||
</FilterPanel>
|
||||
<DataTable
|
||||
label={t("BO_AUDIT_LOG")}
|
||||
columns={columns}
|
||||
data={data.items}
|
||||
total={data.total}
|
||||
page={page}
|
||||
pageSize={pageSize ?? MIN_PAGE_SIZE}
|
||||
tableRef={tableRef}
|
||||
onPageChange={setPage}
|
||||
isLoading={loading}
|
||||
rowKey={(r) => String(r.id)}
|
||||
empty={<EmptyState title={activeCount > 0 ? t("AuditNoMatch") : t("AuditNoEvents")} />}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AuditLogPage() {
|
||||
return (
|
||||
<RequireModule pathname="/audit-log">
|
||||
<AuditLogContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
|
||||
vi.mock("@/app/lib/i18n/MessagesProvider", () => ({ useT: () => (k: string) => k }));
|
||||
vi.mock("@/app/lib/services/adminUsers", () => ({ changeOwnPassword: vi.fn() }));
|
||||
|
||||
import ChangePasswordDialog from "./ChangePasswordDialog";
|
||||
|
||||
describe("ChangePasswordDialog labels", () => {
|
||||
it("labels the new password field as the new password", () => {
|
||||
render(<ChangePasswordDialog onClose={() => {}} onDone={() => {}} />);
|
||||
expect(screen.getByLabelText("PwdNew")).toHaveAttribute("autocomplete", "new-password");
|
||||
expect(screen.getByLabelText("PwdCurrent")).toHaveAttribute("autocomplete", "current-password");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
"use client";
|
||||
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { PasswordFields } from "@/app/components/users/PasswordFields";
|
||||
import { changeOwnPassword } from "@/app/lib/services/adminUsers";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
/** The signed-in admin's own password change; mounted only while open, so every field starts empty. */
|
||||
export default function ChangePasswordDialog({ onClose, onDone }: { onClose: () => void; onDone: () => void }) {
|
||||
const t = useT();
|
||||
const [current, setCurrent] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!current || !password || !confirmPassword) return setError("PwdChangeRequired");
|
||||
if (password !== confirmPassword) return setError("UsrPasswordMismatch");
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await changeOwnPassword(current, password, confirmPassword);
|
||||
onClose();
|
||||
onDone();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "PwdChangeRequired");
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(o) => !o && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("PwdChangeMenu")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={submit} className="space-y-4" noValidate>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="current-password">{t("PwdCurrent")}</Label>
|
||||
<Input
|
||||
id="current-password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={current}
|
||||
onChange={(e) => setCurrent(e.target.value)}
|
||||
disabled={saving}
|
||||
/>
|
||||
</div>
|
||||
<PasswordFields
|
||||
passwordLabel="PwdNew"
|
||||
password={password}
|
||||
confirmPassword={confirmPassword}
|
||||
onPassword={setPassword}
|
||||
onConfirmPassword={setConfirmPassword}
|
||||
disabled={saving}
|
||||
/>
|
||||
{error && (
|
||||
<div role="alert" className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
|
||||
{t(error)}
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{t("PwdChangeMenu")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }),
|
||||
usePathname: () => "/",
|
||||
}));
|
||||
vi.mock("@/app/lib/useAclSidebar", () => ({ useAclSidebar: () => [] }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({
|
||||
useAdminAuth: () => ({ name: "Admin User", hasModule: () => false }),
|
||||
}));
|
||||
vi.mock("@/app/lib/theme", () => ({ useTheme: () => ({ theme: "light", toggleTheme: vi.fn() }) }));
|
||||
const mocks = vi.hoisted(() => ({ changeOwnPassword: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/adminUsers", () => ({ changeOwnPassword: mocks.changeOwnPassword }));
|
||||
|
||||
import Header from "./Header";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.changeOwnPassword.mockReset();
|
||||
});
|
||||
|
||||
async function openDialog() {
|
||||
await userEvent.click(screen.getByRole("button", { name: /admin user/i }));
|
||||
await userEvent.click(await screen.findByText("Change password"));
|
||||
}
|
||||
|
||||
describe("Header: change password", () => {
|
||||
it("lists Change password above Sign out", async () => {
|
||||
render(<Header />);
|
||||
await userEvent.click(screen.getByRole("button", { name: /admin user/i }));
|
||||
const items = (await screen.findAllByRole("menuitem")).map((i) => i.textContent);
|
||||
expect(items).toEqual(["Change password", "Logout"]);
|
||||
});
|
||||
|
||||
it("blocks empty fields and mismatched passwords without calling the server", async () => {
|
||||
render(<Header />);
|
||||
await openDialog();
|
||||
await userEvent.click(screen.getByRole("button", { name: "Change password" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Fill in all the password fields.");
|
||||
|
||||
await userEvent.type(screen.getByLabelText("Current password"), "Old#1");
|
||||
await userEvent.type(screen.getByLabelText("New password"), "New#1");
|
||||
await userEvent.type(screen.getByLabelText("Confirm password"), "Other#1");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Change password" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("The passwords do not match.");
|
||||
expect(mocks.changeOwnPassword).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("submits, closes, confirms, and starts empty next time", async () => {
|
||||
mocks.changeOwnPassword.mockResolvedValue(undefined);
|
||||
render(<Header />);
|
||||
await openDialog();
|
||||
expect(screen.getByLabelText("Current password")).toHaveAttribute("autocomplete", "current-password");
|
||||
await userEvent.type(screen.getByLabelText("Current password"), "Old#1");
|
||||
await userEvent.type(screen.getByLabelText("New password"), "New#1");
|
||||
await userEvent.type(screen.getByLabelText("Confirm password"), "New#1");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Change password" }));
|
||||
|
||||
await waitFor(() => expect(mocks.changeOwnPassword).toHaveBeenCalledWith("Old#1", "New#1", "New#1"));
|
||||
await waitFor(() => expect(screen.queryByLabelText("Current password")).not.toBeInTheDocument());
|
||||
expect(screen.getByText("Your password has been changed.")).toBeInTheDocument();
|
||||
|
||||
await openDialog();
|
||||
expect(screen.getByLabelText("Current password")).toHaveValue("");
|
||||
expect(screen.getByLabelText("New password")).toHaveValue("");
|
||||
});
|
||||
|
||||
it("shows the server message on failure and clears the fields on cancel", async () => {
|
||||
mocks.changeOwnPassword.mockRejectedValue(new ApiError("Current password is incorrect.", 400, { code: "CURRENT_PASSWORD_WRONG" }));
|
||||
render(<Header />);
|
||||
await openDialog();
|
||||
await userEvent.type(screen.getByLabelText("Current password"), "bad");
|
||||
await userEvent.type(screen.getByLabelText("New password"), "New#1");
|
||||
await userEvent.type(screen.getByLabelText("Confirm password"), "New#1");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Change password" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Current password is incorrect.");
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
await openDialog();
|
||||
expect(screen.getByLabelText("Current password")).toHaveValue("");
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { LogOut, Menu, Moon, Sun } from "lucide-react";
|
||||
import { KeyRound, LogOut, Menu, Moon, Sun } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useTheme } from "@/app/lib/theme";
|
||||
@@ -20,6 +20,7 @@ import { Sheet, SheetContent, SheetTitle } from "@/app/components/ui/sheet";
|
||||
import Breadcrumbs from "./Breadcrumbs";
|
||||
import { BrandLink, SidebarNav } from "./Sidebar";
|
||||
import LocaleSwitcher from "./LocaleSwitcher";
|
||||
import ChangePasswordDialog from "./ChangePasswordDialog";
|
||||
|
||||
// The authenticated shell's header: user menu reads the signed-in name from
|
||||
// AdminAuthContext (session hydration, Task 5), and logout calls the
|
||||
@@ -31,6 +32,8 @@ export default function Header() {
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const [changingPassword, setChangingPassword] = useState(false);
|
||||
const [changed, setChanged] = useState(false);
|
||||
|
||||
async function handleLogout() {
|
||||
// Best-effort: /api/auth/logout clears the httpOnly cookie regardless of
|
||||
@@ -100,6 +103,10 @@ export default function Header() {
|
||||
<span className="block text-sm font-medium">{name}</span>
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => setChangingPassword(true)}>
|
||||
<KeyRound aria-hidden="true" className="size-4" />
|
||||
{t("PwdChangeMenu")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={handleLogout}>
|
||||
<LogOut aria-hidden="true" className="size-4" />
|
||||
{t("Logout")}
|
||||
@@ -107,6 +114,20 @@ export default function Header() {
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
{changingPassword && (
|
||||
<ChangePasswordDialog
|
||||
onClose={() => setChangingPassword(false)}
|
||||
onDone={() => {
|
||||
setChanged(true);
|
||||
setTimeout(() => setChanged(false), 5000);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{changed && (
|
||||
<div role="status" className="fixed right-4 bottom-4 z-50 rounded-md border bg-card px-4 py-3 text-sm shadow-md">
|
||||
{t("PwdChanged")}
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { Tabs as TabsPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/app/lib/utils"
|
||||
|
||||
function Tabs({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
||||
return (
|
||||
<TabsPrimitive.Root
|
||||
data-slot="tabs"
|
||||
data-orientation={orientation}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"group/tabs flex gap-2 data-[orientation=horizontal]:flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const tabsListVariants = cva(
|
||||
"group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-[orientation=horizontal]/tabs:h-9 group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col data-[variant=line]:rounded-none",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-muted",
|
||||
line: "gap-1 bg-transparent",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function TabsList({
|
||||
className,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.List> &
|
||||
VariantProps<typeof tabsListVariants>) {
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
data-slot="tabs-list"
|
||||
data-variant={variant}
|
||||
className={cn(tabsListVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsTrigger({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
return (
|
||||
<TabsPrimitive.Trigger
|
||||
data-slot="tabs-trigger"
|
||||
className={cn(
|
||||
"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-sm group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent",
|
||||
"data-[state=active]:bg-background data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 dark:data-[state=active]:text-foreground",
|
||||
"after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-right-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
|
||||
return (
|
||||
<TabsPrimitive.Content
|
||||
data-slot="tabs-content"
|
||||
className={cn("flex-1 outline-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }
|
||||
@@ -13,12 +13,14 @@ export function PasswordFields(props: {
|
||||
disabled?: boolean;
|
||||
passwordError?: string;
|
||||
confirmError?: string;
|
||||
/** i18n key for the first field's label; "Password" by default. */
|
||||
passwordLabel?: string;
|
||||
}) {
|
||||
const t = useT();
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="user-password">{t("Password")}</Label>
|
||||
<Label htmlFor="user-password">{t(props.passwordLabel ?? "Password")}</Label>
|
||||
<Input
|
||||
id="user-password"
|
||||
type="password"
|
||||
|
||||
@@ -77,6 +77,12 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
NotFoundBody: "That route does not exist in the back office.",
|
||||
LayoutMetaDescription: "Co-Lite admin back office",
|
||||
LoginInvalidCredentials: "Invalid username or password",
|
||||
LoginAccountLocked: "Too many failed sign-ins. Try again later or ask an administrator to unlock your account.",
|
||||
PwdChangeMenu: "Change password",
|
||||
PwdCurrent: "Current password",
|
||||
PwdNew: "New password",
|
||||
PwdChangeRequired: "Fill in all the password fields.",
|
||||
PwdChanged: "Your password has been changed.",
|
||||
LoginHidePassword: "Hide password",
|
||||
LoginShowPassword: "Show password",
|
||||
ResetAllRequired: "All fields are required.",
|
||||
@@ -318,4 +324,91 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
LeadsSameEmailAs: "Same email as",
|
||||
LeadsSameMobileEmailAs: "Same mobile and email as",
|
||||
LeadsViewLead: "View lead",
|
||||
BO_LOGIN_SECURITY: "Login security",
|
||||
LsTabHistory: "History",
|
||||
LsTabLocked: "Locked",
|
||||
LsTabSettings: "Settings",
|
||||
LsTime: "Time",
|
||||
LsEvent: "Event",
|
||||
LsIp: "IP",
|
||||
LsBrowser: "Browser",
|
||||
LsNote: "Note",
|
||||
LsFrom: "From date",
|
||||
LsTo: "To date",
|
||||
LsAllEvents: "All events",
|
||||
LsEventLoginSuccess: "Login succeeded",
|
||||
LsEventLoginFail: "Login failed",
|
||||
LsEventLoginLocked: "Account locked",
|
||||
LsEventLogout: "Logout",
|
||||
LsEventUnlockReset: "Unlocked by an admin",
|
||||
LsEventPasswordChanged: "Password changed",
|
||||
LsNoHistory: "No sign-in history found",
|
||||
LsNoMatch: "No sign-in history matches your filters",
|
||||
LsHistoryLoadFailed: "Failed to load the sign-in history",
|
||||
LsFailures: "Failures",
|
||||
LsLastFailure: "Last failure",
|
||||
LsLockedUntil: "Locked until",
|
||||
LsUnlock: "Unlock",
|
||||
LsUnlockTitle: "Unlock account",
|
||||
LsUnlockConfirm: "Allow {username} to sign in again?",
|
||||
LsNoLocked: "No locked accounts",
|
||||
LsLockedLoadFailed: "Failed to load the locked accounts",
|
||||
LsUnlockFailed: "Failed to unlock the account",
|
||||
LsLockoutTitle: "Lockout",
|
||||
LsLockoutOn: "Lockout on",
|
||||
LsMaxAttempts: "Max attempts",
|
||||
LsPeriod: "Period",
|
||||
LsUnit: "Unit",
|
||||
LsUnitS: "Seconds",
|
||||
LsUnitM: "Minutes",
|
||||
LsUnitH: "Hours",
|
||||
LsUnitD: "Days",
|
||||
LsSaveLockout: "Save lockout settings",
|
||||
LsLockoutSaved: "Lockout settings saved.",
|
||||
LsRulesTitle: "Password rules",
|
||||
LsRuleOn: "On",
|
||||
LsRuleValue: "Value",
|
||||
LsRuleName: "Rule",
|
||||
LsSaveRules: "Save password rules",
|
||||
LsRulesSaved: "Password rules saved.",
|
||||
LsSettingsLoadFailed: "Failed to load the settings",
|
||||
LsSaveFailed: "Failed to save",
|
||||
BO_AUDIT_LOG: "Audit log",
|
||||
BO_LEADS_EDIT: "Lead editing",
|
||||
BO_LEADS_EXPORT: "Lead export",
|
||||
AuditWho: "Who",
|
||||
AuditModule: "Module",
|
||||
AuditAction: "Action",
|
||||
AuditTarget: "Target",
|
||||
AuditOutcome: "Outcome",
|
||||
AuditAllModules: "All modules",
|
||||
AuditAllOutcomes: "All outcomes",
|
||||
AuditSuccess: "Success",
|
||||
AuditFailure: "Failure",
|
||||
AuditNoEvents: "No audit events found",
|
||||
AuditNoMatch: "No audit events match your filters",
|
||||
AuditLoadFailed: "Failed to load the audit log",
|
||||
AuditNotFound: "Audit event not found",
|
||||
AuditBack: "Back to audit log",
|
||||
AuditRequest: "Request",
|
||||
AuditChanges: "Changes",
|
||||
AuditNoChanges: "No changes recorded.",
|
||||
AuditField: "Field",
|
||||
AuditBefore: "Before",
|
||||
AuditAfter: "After",
|
||||
AuditFieldsOnly: "Values are not recorded for these fields.",
|
||||
PwdRule_INPUT_LENGTH_MIN: "Minimum length",
|
||||
PwdRule_INPUT_LENGTH_MAX: "Maximum length",
|
||||
PwdRule_ALPHABET_LENGTH_MIN: "Minimum letters",
|
||||
PwdRule_ALPHABET_LENGTH_MAX: "Maximum letters",
|
||||
PwdRule_UPPERCASE_LENGTH_MIN: "Minimum uppercase letters",
|
||||
PwdRule_UPPERCASE_LENGTH_MAX: "Maximum uppercase letters",
|
||||
PwdRule_LOWERCASE_LENGTH_MIN: "Minimum lowercase letters",
|
||||
PwdRule_LOWERCASE_LENGTH_MAX: "Maximum lowercase letters",
|
||||
PwdRule_NUMERIC_LENGTH_MIN: "Minimum digits",
|
||||
PwdRule_NUMERIC_LENGTH_MAX: "Maximum digits",
|
||||
PwdRule_SYMBOLIC_LENGTH_MIN: "Minimum symbols",
|
||||
PwdRule_SYMBOLIC_LENGTH_MAX: "Maximum symbols",
|
||||
PwdRule_NO_OTHER_LANGUAGE: "Latin characters only",
|
||||
PwdRule_SPACE_NOT_ALLOWED: "No spaces",
|
||||
};
|
||||
@@ -14,7 +14,7 @@ describe("routeModules", () => {
|
||||
it("leaves other routes ungated", () => {
|
||||
expect(requiredModuleFor("/")).toBeUndefined();
|
||||
expect(requiredModulesFor("/members")).toBeUndefined();
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/emails", "/event-leads", "/events", "/interests", "/leads", "/roles", "/users"]);
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/audit-log", "/emails", "/event-leads", "/events", "/interests", "/leads", "/login-security", "/roles", "/users"]);
|
||||
expect(requiredModuleFor("/emails")).toBe("BO_EMAILS");
|
||||
expect(requiredModuleFor("/leads")).toBe("BO_LEADS");
|
||||
});
|
||||
|
||||
@@ -10,6 +10,8 @@ export const ROUTE_MODULES: Record<string, string> = {
|
||||
"/event-leads": "BO_EVENT_LEADS",
|
||||
"/leads": "BO_LEADS",
|
||||
"/emails": "BO_EMAILS",
|
||||
"/login-security": "BO_LOGIN_SECURITY",
|
||||
"/audit-log": "BO_AUDIT_LOG",
|
||||
};
|
||||
|
||||
export function requiredModuleFor(pathname: string): string | undefined {
|
||||
|
||||
@@ -63,6 +63,11 @@ export async function saveAdminUser(payload: AdminUser): Promise<AdminUser> {
|
||||
: apiPost<AdminUser>("/api/users", payload);
|
||||
}
|
||||
|
||||
/** The signed-in admin changes their own password. */
|
||||
export async function changeOwnPassword(currentPassword: string, newPassword: string, confirmPassword: string): Promise<void> {
|
||||
await apiPost<void>("/api/auth/change-password", { currentPassword, newPassword, confirmPassword });
|
||||
}
|
||||
|
||||
/** Admin-typed temporary password; the user must change it at next sign-in. */
|
||||
export async function setAdminUserPassword(id: number, password: string, confirmPassword: string): Promise<void> {
|
||||
await apiPost<void>(`/api/users/${id}/password`, { password, confirmPassword });
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", () => mocks);
|
||||
|
||||
import { getAuditEvent, searchAuditLog } from "./auditLog";
|
||||
|
||||
beforeEach(() => mocks.apiGet.mockReset());
|
||||
|
||||
describe("auditLog service", () => {
|
||||
it("searchAuditLog sends only non-empty filters with a 0-based page", async () => {
|
||||
mocks.apiGet.mockResolvedValue({ content: [{ id: "e1" }], totalElements: 9 });
|
||||
const out = await searchAuditLog({ actor: "admin", module: "", action: "USER_UPDATE", outcome: "FAILURE", from: "2026-11-01", to: "", page: 2, pageSize: 10 });
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/audit-log?actor=admin&action=USER_UPDATE&outcome=FAILURE&from=2026-11-01&page=1&size=10");
|
||||
expect(out).toEqual({ items: [{ id: "e1" }], total: 9 });
|
||||
});
|
||||
|
||||
it("searchAuditLog tolerates an empty body", async () => {
|
||||
mocks.apiGet.mockResolvedValue(null);
|
||||
expect(await searchAuditLog({ page: 1, pageSize: 10 })).toEqual({ items: [], total: 0 });
|
||||
});
|
||||
|
||||
it("getAuditEvent GETs one event by encoded id", async () => {
|
||||
mocks.apiGet.mockResolvedValue({ id: "a/b" });
|
||||
await getAuditEvent("a/b");
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/audit-log/a%2Fb");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { apiGet } from "@/app/lib/clientApi";
|
||||
|
||||
export interface AuditEvent {
|
||||
id: number;
|
||||
companyId: number;
|
||||
/** Server-local ISO datetime, e.g. "2026-11-30T15:52:00.5". */
|
||||
occurredAt: string;
|
||||
actor: string;
|
||||
module: string | null;
|
||||
action: string;
|
||||
httpMethod: string;
|
||||
pathTemplate: string;
|
||||
targetId: string | null;
|
||||
outcome: "SUCCESS" | "FAILURE";
|
||||
httpStatus: number;
|
||||
clientIp: string | null;
|
||||
/** JSON string: {"<field>": {before, after}} or {"fields": [...]}; null when nothing was recorded. */
|
||||
changes: string | null;
|
||||
}
|
||||
|
||||
export interface AuditLogParams {
|
||||
actor?: string;
|
||||
module?: string;
|
||||
action?: string;
|
||||
outcome?: string;
|
||||
/** "yyyy-MM-dd". */
|
||||
from?: string;
|
||||
to?: string;
|
||||
/** 1-based. */
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
const BASE = "/api/audit-log";
|
||||
|
||||
export async function searchAuditLog(params: AuditLogParams): Promise<{ items: AuditEvent[]; total: number }> {
|
||||
const qs = new URLSearchParams();
|
||||
for (const key of ["actor", "module", "action", "outcome", "from", "to"] as const) if (params[key]) qs.set(key, params[key]);
|
||||
qs.set("page", String(Math.max(0, params.page - 1)));
|
||||
qs.set("size", String(params.pageSize));
|
||||
const raw = await apiGet<{ content?: AuditEvent[]; totalElements?: number } | null>(`${BASE}?${qs}`);
|
||||
const items = Array.isArray(raw?.content) ? raw.content : [];
|
||||
return { items, total: typeof raw?.totalElements === "number" ? raw.totalElements : items.length };
|
||||
}
|
||||
|
||||
export const getAuditEvent = (id: string) => apiGet<AuditEvent>(`${BASE}/${encodeURIComponent(id)}`);
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), apiPut: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", () => mocks);
|
||||
|
||||
import { getConfig, getPasswordRules, listAudit, listLocked, saveConfig, savePasswordRules, unlock } from "./loginSecurity";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset();
|
||||
mocks.apiPost.mockReset();
|
||||
mocks.apiPut.mockReset();
|
||||
});
|
||||
|
||||
describe("loginSecurity service", () => {
|
||||
it("listAudit sends only given filters with a 0-based page", async () => {
|
||||
mocks.apiGet.mockResolvedValue({ content: [{ id: 1 }], totalElements: 9 });
|
||||
const out = await listAudit({ username: "a", event: "LOGIN_FAIL", from: "2026-11-01", page: 2, pageSize: 10 });
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/login-security/audit?username=a&event=LOGIN_FAIL&from=2026-11-01&page=1&size=10");
|
||||
expect(out).toEqual({ items: [{ id: 1 }], total: 9 });
|
||||
});
|
||||
|
||||
it("listAudit tolerates an empty body", async () => {
|
||||
mocks.apiGet.mockResolvedValue(null);
|
||||
expect(await listAudit({ page: 1, pageSize: 10 })).toEqual({ items: [], total: 0 });
|
||||
});
|
||||
|
||||
it("listLocked GETs the locked accounts", async () => {
|
||||
mocks.apiGet.mockResolvedValue([]);
|
||||
await listLocked();
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/login-security/locked");
|
||||
});
|
||||
|
||||
it("unlock POSTs to the encoded username", async () => {
|
||||
await unlock("a b/c");
|
||||
expect(mocks.apiPost).toHaveBeenCalledWith("/api/login-security/locked/a%20b%2Fc/unlock");
|
||||
});
|
||||
|
||||
it("getConfig / saveConfig use the config path", async () => {
|
||||
await getConfig();
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/login-security/config");
|
||||
const cfg = { enabled: true, maxAttempts: 5, period: 15, unit: "M" as const };
|
||||
await saveConfig(cfg);
|
||||
expect(mocks.apiPut).toHaveBeenCalledWith("/api/login-security/config", cfg);
|
||||
});
|
||||
|
||||
it("getPasswordRules / savePasswordRules use the rules path", async () => {
|
||||
await getPasswordRules();
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/login-security/password-rules");
|
||||
const rules = [{ id: 1, status: "Y" as const, value: "8" }];
|
||||
await savePasswordRules(rules);
|
||||
expect(mocks.apiPut).toHaveBeenCalledWith("/api/login-security/password-rules", rules);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi";
|
||||
|
||||
export const LOGIN_EVENTS = ["LOGIN_SUCCESS", "LOGIN_FAIL", "LOGIN_LOCKED", "LOGOUT", "UNLOCK_RESET", "PASSWORD_CHANGED"] as const;
|
||||
export const LOCKOUT_UNITS = ["S", "M", "H", "D"] as const;
|
||||
|
||||
export interface AuditRow {
|
||||
id: number;
|
||||
username: string;
|
||||
/** Server-local "yyyy-MM-ddTHH:mm:ss". */
|
||||
datetime: string;
|
||||
event: string;
|
||||
ipAddress: string | null;
|
||||
userAgent: string | null;
|
||||
message: string | null;
|
||||
}
|
||||
|
||||
export interface AuditParams {
|
||||
username?: string;
|
||||
event?: string;
|
||||
/** "yyyy-MM-dd". */
|
||||
from?: string;
|
||||
to?: string;
|
||||
/** 1-based. */
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
export interface LockedAccount {
|
||||
username: string;
|
||||
failures: number;
|
||||
lastFailure: string | null;
|
||||
lockedUntil: string | null;
|
||||
}
|
||||
|
||||
export interface LockoutConfig {
|
||||
enabled: boolean;
|
||||
maxAttempts: number;
|
||||
period: number;
|
||||
unit: (typeof LOCKOUT_UNITS)[number];
|
||||
}
|
||||
|
||||
export interface PasswordRule {
|
||||
id: number;
|
||||
param: string;
|
||||
status: "Y" | "N";
|
||||
value: string | null;
|
||||
}
|
||||
|
||||
export type PasswordRuleUpdate = Pick<PasswordRule, "id" | "status" | "value">;
|
||||
|
||||
const BASE = "/api/login-security";
|
||||
|
||||
export async function listAudit(params: AuditParams): Promise<{ items: AuditRow[]; total: number }> {
|
||||
const qs = new URLSearchParams();
|
||||
for (const key of ["username", "event", "from", "to"] as const) if (params[key]) qs.set(key, params[key]);
|
||||
qs.set("page", String(Math.max(0, params.page - 1)));
|
||||
qs.set("size", String(params.pageSize));
|
||||
const raw = await apiGet<{ content?: AuditRow[]; totalElements?: number } | null>(`${BASE}/audit?${qs}`);
|
||||
const items = Array.isArray(raw?.content) ? raw.content : [];
|
||||
return { items, total: typeof raw?.totalElements === "number" ? raw.totalElements : items.length };
|
||||
}
|
||||
|
||||
export const listLocked = () => apiGet<LockedAccount[]>(`${BASE}/locked`);
|
||||
export const unlock = (username: string) => apiPost<void>(`${BASE}/locked/${encodeURIComponent(username)}/unlock`);
|
||||
export const getConfig = () => apiGet<LockoutConfig>(`${BASE}/config`);
|
||||
export const saveConfig = (cfg: LockoutConfig) => apiPut<LockoutConfig>(`${BASE}/config`, cfg);
|
||||
export const getPasswordRules = () => apiGet<PasswordRule[]>(`${BASE}/password-rules`);
|
||||
export const savePasswordRules = (rules: PasswordRuleUpdate[]) => apiPut<PasswordRule[]>(`${BASE}/password-rules`, rules);
|
||||
|
||||
export const LOGIN_EVENT_KEYS: Record<string, string> = {
|
||||
LOGIN_SUCCESS: "LsEventLoginSuccess",
|
||||
LOGIN_FAIL: "LsEventLoginFail",
|
||||
LOGIN_LOCKED: "LsEventLoginLocked",
|
||||
LOGOUT: "LsEventLogout",
|
||||
UNLOCK_RESET: "LsEventUnlockReset",
|
||||
PASSWORD_CHANGED: "LsEventPasswordChanged",
|
||||
};
|
||||
|
||||
/** Params with no value to edit: the rule is only on or off. */
|
||||
export const FLAG_RULE_PARAMS = ["NO_OTHER_LANGUAGE", "SPACE_NOT_ALLOWED"];
|
||||
@@ -0,0 +1,156 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listAudit: vi.fn(), listLocked: vi.fn(), unlock: vi.fn(), getConfig: vi.fn(), saveConfig: vi.fn(),
|
||||
getPasswordRules: vi.fn(), savePasswordRules: vi.fn(), useAdminAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/loginSecurity", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/loginSecurity")>()),
|
||||
listAudit: mocks.listAudit, listLocked: mocks.listLocked, unlock: mocks.unlock, getConfig: mocks.getConfig,
|
||||
saveConfig: mocks.saveConfig, getPasswordRules: mocks.getPasswordRules, savePasswordRules: mocks.savePasswordRules,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import LoginSecurityPage from "./page";
|
||||
|
||||
const AUDIT = [
|
||||
{ id: 2, username: "sales1", datetime: "2026-11-30T13:58:18", event: "LOGIN_FAIL", ipAddress: "10.0.0.5", userAgent: "Mozilla/5.0 (X11)", message: "Bad password" },
|
||||
{ id: 1, username: "admin", datetime: "2026-11-29T09:05:00", event: "LOGIN_SUCCESS", ipAddress: "10.0.0.6", userAgent: null, message: null },
|
||||
];
|
||||
const LOCKED = [{ username: "sales1", failures: 5, lastFailure: "2026-11-30T13:58:18", lockedUntil: "2026-11-30T14:13:18" }];
|
||||
const CONFIG = { enabled: true, maxAttempts: 5, period: 15, unit: "M" };
|
||||
const RULES = [
|
||||
{ id: 1, param: "INPUT_LENGTH_MIN", status: "Y", value: "8" },
|
||||
{ id: 2, param: "SPACE_NOT_ALLOWED", status: "N", value: null },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/login-security");
|
||||
mocks.listAudit.mockReset().mockResolvedValue({ items: AUDIT, total: 2 });
|
||||
mocks.listLocked.mockReset().mockResolvedValue(LOCKED);
|
||||
mocks.unlock.mockReset().mockResolvedValue(undefined);
|
||||
mocks.getConfig.mockReset().mockResolvedValue(CONFIG);
|
||||
mocks.saveConfig.mockReset().mockImplementation(async (c) => c);
|
||||
mocks.getPasswordRules.mockReset().mockResolvedValue(RULES);
|
||||
mocks.savePasswordRules.mockReset().mockResolvedValue(RULES);
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
|
||||
});
|
||||
|
||||
describe("LoginSecurityPage", () => {
|
||||
it("renders NotAuthorized without BO_LOGIN_SECURITY", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<LoginSecurityPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
expect(mocks.listAudit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("History lists rows with the event label and a titled browser", async () => {
|
||||
render(<LoginSecurityPage />);
|
||||
const table = await screen.findByRole("table");
|
||||
expect(within(table).getAllByRole("columnheader").map((h) => h.textContent)).toEqual(["Time", "Username", "Event", "IP", "Browser", "Note"]);
|
||||
const rows = within(table).getAllByRole("row").slice(1);
|
||||
expect(rows[0]).toHaveTextContent("30/11/2026 13:58");
|
||||
expect(rows[0]).toHaveTextContent("sales1");
|
||||
expect(rows[0]).toHaveTextContent("Login failed");
|
||||
expect(rows[0]).toHaveTextContent("Bad password");
|
||||
expect(within(rows[0]).getByTitle("Mozilla/5.0 (X11)")).toBeInTheDocument();
|
||||
expect(rows[1]).toHaveTextContent("Login succeeded");
|
||||
});
|
||||
|
||||
it("History puts the filters in the query", async () => {
|
||||
memoryRouter.reset("/login-security", "event=LOGIN_FAIL&from=2026-11-01");
|
||||
render(<LoginSecurityPage />);
|
||||
await screen.findByRole("table");
|
||||
expect(mocks.listAudit).toHaveBeenCalledWith(expect.objectContaining({ event: "LOGIN_FAIL", from: "2026-11-01", page: 1, pageSize: 20 }));
|
||||
await userEvent.type(screen.getByRole("searchbox", { name: "Username" }), "sales");
|
||||
await waitFor(() => expect(mocks.listAudit).toHaveBeenLastCalledWith(expect.objectContaining({ username: "sales", event: "LOGIN_FAIL" })));
|
||||
});
|
||||
|
||||
it("History shows an empty state and an error state", async () => {
|
||||
mocks.listAudit.mockResolvedValue({ items: [], total: 0 });
|
||||
const { unmount } = render(<LoginSecurityPage />);
|
||||
expect(await screen.findByText("No sign-in history found")).toBeInTheDocument();
|
||||
unmount();
|
||||
mocks.listAudit.mockRejectedValue(new Error("LsHistoryLoadFailed"));
|
||||
render(<LoginSecurityPage />);
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Failed to load the sign-in history");
|
||||
});
|
||||
|
||||
async function openTab(name: string) {
|
||||
render(<LoginSecurityPage />);
|
||||
await screen.findByRole("table");
|
||||
await userEvent.click(screen.getByRole("tab", { name }));
|
||||
}
|
||||
|
||||
it("Locked lists accounts; Unlock asks to confirm, calls unlock and reloads", async () => {
|
||||
await openTab("Locked");
|
||||
const row = (await screen.findByText("sales1")).closest("tr")!;
|
||||
expect(row).toHaveTextContent("5");
|
||||
expect(row).toHaveTextContent("30/11/2026 14:13");
|
||||
await userEvent.click(within(row).getByRole("button", { name: "Unlock" }));
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
expect(dialog).toHaveTextContent("sales1");
|
||||
expect(mocks.unlock).not.toHaveBeenCalled();
|
||||
mocks.listLocked.mockResolvedValue([]);
|
||||
await userEvent.click(within(dialog).getByRole("button", { name: "Unlock" }));
|
||||
await waitFor(() => expect(mocks.unlock).toHaveBeenCalledWith("sales1"));
|
||||
expect(await screen.findByText("No locked accounts")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("Locked shows the server message when unlock fails", async () => {
|
||||
mocks.unlock.mockRejectedValue(new Error("Not allowed"));
|
||||
await openTab("Locked");
|
||||
await userEvent.click(await screen.findByRole("button", { name: "Unlock" }));
|
||||
await userEvent.click(within(await screen.findByRole("dialog")).getByRole("button", { name: "Unlock" }));
|
||||
expect(await screen.findByText("Not allowed")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("Settings loads the config, saves it and shows the server validation message", async () => {
|
||||
await openTab("Settings");
|
||||
const max = await screen.findByLabelText("Max attempts");
|
||||
expect(max).toHaveValue(5);
|
||||
expect(screen.getByLabelText("Period")).toHaveValue(15);
|
||||
await userEvent.clear(max);
|
||||
await userEvent.type(max, "3");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Save lockout settings" }));
|
||||
await waitFor(() => expect(mocks.saveConfig).toHaveBeenCalledWith({ enabled: true, maxAttempts: 3, period: 15, unit: "M" }));
|
||||
expect(await screen.findByText("Lockout settings saved.")).toBeInTheDocument();
|
||||
|
||||
mocks.saveConfig.mockRejectedValue(new Error("Max attempts too high"));
|
||||
await userEvent.click(screen.getByRole("button", { name: "Save lockout settings" }));
|
||||
expect(await screen.findByText("Max attempts too high")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Max attempts")).toHaveValue(3);
|
||||
});
|
||||
|
||||
it("Settings rules: labels, flag rules have no value input, one save sends status and value", async () => {
|
||||
await openTab("Settings");
|
||||
const length = await screen.findByLabelText("Minimum length value");
|
||||
expect(length).toHaveValue(8);
|
||||
expect(screen.getByText("No spaces")).toBeInTheDocument();
|
||||
expect(screen.queryByLabelText("No spaces value")).not.toBeInTheDocument();
|
||||
await userEvent.clear(length);
|
||||
await userEvent.type(length, "10");
|
||||
await userEvent.click(screen.getByRole("switch", { name: "No spaces" }));
|
||||
await userEvent.click(screen.getByRole("button", { name: "Save password rules" }));
|
||||
await waitFor(() => expect(mocks.savePasswordRules).toHaveBeenCalledWith([
|
||||
{ id: 1, status: "Y", value: "10" },
|
||||
{ id: 2, status: "Y", value: null },
|
||||
]));
|
||||
expect(await screen.findByText("Password rules saved.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("Settings rules keep the edit and show the server message on error", async () => {
|
||||
mocks.savePasswordRules.mockRejectedValue(new Error("Minimum is above maximum"));
|
||||
await openTab("Settings");
|
||||
const length = await screen.findByLabelText("Minimum length value");
|
||||
await userEvent.clear(length);
|
||||
await userEvent.type(length, "99");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Save password rules" }));
|
||||
expect(await screen.findByText("Minimum is above maximum")).toBeInTheDocument();
|
||||
expect(length).toHaveValue(99);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,377 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { Switch } from "@/app/components/ui/switch";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/app/components/ui/tabs";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
|
||||
import { FilterField, FilterPanel, FilterSearch, FilterSelect } from "@/app/components/ui/filter-panel";
|
||||
import { DataTable } from "@/app/components/ui/data-table";
|
||||
import { DatePicker } from "@/app/components/ui/date-picker";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { useListFilters } from "@/app/lib/hooks/useListFilters";
|
||||
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
|
||||
import { formatEmailDate as formatDate } from "@/app/lib/services/adminEmails";
|
||||
import {
|
||||
FLAG_RULE_PARAMS, LOCKOUT_UNITS, LOGIN_EVENTS, LOGIN_EVENT_KEYS,
|
||||
getConfig, getPasswordRules, listAudit, listLocked, saveConfig, savePasswordRules, unlock,
|
||||
type AuditRow, type LockedAccount, type LockoutConfig, type PasswordRule,
|
||||
} from "@/app/lib/services/loginSecurity";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
const DEFAULTS = { username: "", event: "", from: "", to: "" };
|
||||
const errMessage = (err: unknown, fallback: string) => (err instanceof Error ? err.message : fallback);
|
||||
|
||||
function HistoryTab() {
|
||||
const t = useT();
|
||||
const { tableRef, pageSize } = useFitPageSize();
|
||||
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
|
||||
const [data, setData] = useState<{ items: AuditRow[]; total: number }>({ items: [], total: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (pageSize == null) return;
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the filter/page/reloadKey-triggered fetch below, which is the actual synchronization.
|
||||
setLoading(true);
|
||||
setFailed(false);
|
||||
listAudit({
|
||||
username: filters.username || undefined,
|
||||
event: filters.event || undefined,
|
||||
from: filters.from || undefined,
|
||||
to: filters.to || undefined,
|
||||
page,
|
||||
pageSize,
|
||||
})
|
||||
.then((result) => { if (!cancelled) setData(result); })
|
||||
.catch(() => { if (!cancelled) setFailed(true); })
|
||||
.finally(() => { if (!cancelled) setLoading(false); });
|
||||
return () => { cancelled = true; };
|
||||
}, [filters, page, reloadKey, pageSize]);
|
||||
|
||||
const eventOptions = useMemo(() => LOGIN_EVENTS.map((e) => ({ value: e, label: t(LOGIN_EVENT_KEYS[e]) })), [t]);
|
||||
const columns = useMemo<ColumnDef<AuditRow, unknown>[]>(
|
||||
() => [
|
||||
{ id: "datetime", header: t("LsTime"), enableSorting: false, cell: ({ row }) => formatDate(row.original.datetime) },
|
||||
{ accessorKey: "username", header: t("Username"), enableSorting: false },
|
||||
{ id: "event", header: t("LsEvent"), enableSorting: false, cell: ({ row }) => t(LOGIN_EVENT_KEYS[row.original.event] ?? row.original.event) },
|
||||
{ accessorKey: "ipAddress", header: t("LsIp"), enableSorting: false },
|
||||
{
|
||||
id: "userAgent",
|
||||
header: t("LsBrowser"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => <span className="block max-w-xs truncate" title={row.original.userAgent ?? undefined}>{row.original.userAgent}</span>,
|
||||
},
|
||||
{ accessorKey: "message", header: t("LsNote"), enableSorting: false },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{failed && <ErrorState message={t("LsHistoryLoadFailed")} onRetry={refetch} className="mb-4" />}
|
||||
<FilterPanel activeCount={activeCount} onClear={clear}>
|
||||
<FilterField label={t("Username")}>
|
||||
<FilterSearch className="w-full" aria-label={t("Username")} value={filters.username} onChange={(username) => set({ username })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LsEvent")}>
|
||||
<FilterSelect className="w-full" aria-label={t("LsEvent")} allLabel={t("LsAllEvents")} options={eventOptions} value={filters.event} onChange={(event) => set({ event })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LsFrom")}>
|
||||
<DatePicker aria-label={t("LsFrom")} value={filters.from} onChange={(from) => set({ from })} max={filters.to || undefined} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LsTo")}>
|
||||
<DatePicker aria-label={t("LsTo")} value={filters.to} onChange={(to) => set({ to })} min={filters.from || undefined} />
|
||||
</FilterField>
|
||||
</FilterPanel>
|
||||
<DataTable
|
||||
label={t("LsTabHistory")}
|
||||
columns={columns}
|
||||
data={data.items}
|
||||
total={data.total}
|
||||
page={page}
|
||||
pageSize={pageSize ?? MIN_PAGE_SIZE}
|
||||
tableRef={tableRef}
|
||||
onPageChange={setPage}
|
||||
isLoading={loading}
|
||||
rowKey={(r) => String(r.id)}
|
||||
empty={<EmptyState title={activeCount > 0 ? t("LsNoMatch") : t("LsNoHistory")} />}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function LockedTab() {
|
||||
const t = useT();
|
||||
const [rows, setRows] = useState<LockedAccount[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [target, setTarget] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading ahead of the reloadKey-triggered fetch below.
|
||||
setLoading(true);
|
||||
listLocked()
|
||||
.then((result) => { if (!cancelled) { setRows(result); setError(null); } })
|
||||
.catch((err: unknown) => { if (!cancelled) setError(errMessage(err, "LsLockedLoadFailed")); })
|
||||
.finally(() => { if (!cancelled) setLoading(false); });
|
||||
return () => { cancelled = true; };
|
||||
}, [reloadKey]);
|
||||
|
||||
async function confirmUnlock() {
|
||||
if (!target) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await unlock(target);
|
||||
setError(null);
|
||||
refetch();
|
||||
} catch (err) {
|
||||
setError(errMessage(err, "LsUnlockFailed"));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
setTarget(null);
|
||||
}
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<LockedAccount, unknown>[]>(
|
||||
() => [
|
||||
{ accessorKey: "username", header: t("Username"), enableSorting: false },
|
||||
{ accessorKey: "failures", header: t("LsFailures"), enableSorting: false },
|
||||
{ id: "lastFailure", header: t("LsLastFailure"), enableSorting: false, cell: ({ row }) => formatDate(row.original.lastFailure ?? "") },
|
||||
{ id: "lockedUntil", header: t("LsLockedUntil"), enableSorting: false, cell: ({ row }) => formatDate(row.original.lockedUntil ?? "") },
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => (
|
||||
<Button variant="outline" size="sm" onClick={() => setTarget(row.original.username)}>{t("LsUnlock")}</Button>
|
||||
),
|
||||
},
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
|
||||
{/* ponytail: the locked list is small (only accounts currently locked), so it is shown unpaged. */}
|
||||
<DataTable
|
||||
label={t("LsTabLocked")}
|
||||
columns={columns}
|
||||
data={rows}
|
||||
total={rows.length}
|
||||
page={1}
|
||||
pageSize={Math.max(rows.length, MIN_PAGE_SIZE)}
|
||||
onPageChange={() => {}}
|
||||
isLoading={loading}
|
||||
rowKey={(r) => r.username}
|
||||
empty={<EmptyState title={t("LsNoLocked")} />}
|
||||
/>
|
||||
<Dialog open={target !== null} onOpenChange={(open) => !open && setTarget(null)}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("LsUnlockTitle")}</DialogTitle>
|
||||
<DialogDescription>{t("LsUnlockConfirm", { username: target ?? "" })}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setTarget(null)} disabled={busy}>{t("Cancel")}</Button>
|
||||
<Button onClick={confirmUnlock} disabled={busy}>{t("LsUnlock")}</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
type Notice = { kind: "ok" | "error"; text: string } | null;
|
||||
|
||||
function NoticeLine({ notice }: { notice: Notice }) {
|
||||
if (!notice) return null;
|
||||
return notice.kind === "error"
|
||||
? <p role="alert" className="text-sm text-destructive">{notice.text}</p>
|
||||
: <p role="status" className="text-sm text-foreground">{notice.text}</p>;
|
||||
}
|
||||
|
||||
function LockoutForm() {
|
||||
const t = useT();
|
||||
const [cfg, setCfg] = useState<LockoutConfig | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [notice, setNotice] = useState<Notice>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
getConfig()
|
||||
.then((c) => { if (!cancelled) setCfg(c); })
|
||||
.catch((err: unknown) => { if (!cancelled) setNotice({ kind: "error", text: t(errMessage(err, "LsSettingsLoadFailed")) }); });
|
||||
return () => { cancelled = true; };
|
||||
}, [t]);
|
||||
|
||||
if (!cfg) return <NoticeLine notice={notice} />;
|
||||
|
||||
async function save() {
|
||||
if (!cfg) return;
|
||||
setSaving(true);
|
||||
setNotice(null);
|
||||
try {
|
||||
setCfg(await saveConfig(cfg));
|
||||
setNotice({ kind: "ok", text: t("LsLockoutSaved") });
|
||||
} catch (err) {
|
||||
setNotice({ kind: "error", text: t(errMessage(err, "LsSaveFailed")) });
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
const num = (v: string) => (v === "" ? 0 : Number(v));
|
||||
|
||||
return (
|
||||
<section className="space-y-4 rounded-xl border bg-card p-4">
|
||||
<h2 className="text-base font-semibold">{t("LsLockoutTitle")}</h2>
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch id="ls-enabled" checked={cfg.enabled} onCheckedChange={(enabled) => setCfg({ ...cfg, enabled })} />
|
||||
<Label htmlFor="ls-enabled">{t("LsLockoutOn")}</Label>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ls-max">{t("LsMaxAttempts")}</Label>
|
||||
<Input id="ls-max" type="number" min={1} value={cfg.maxAttempts || ""} onChange={(e) => setCfg({ ...cfg, maxAttempts: num(e.target.value) })} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ls-period">{t("LsPeriod")}</Label>
|
||||
<Input id="ls-period" type="number" min={1} value={cfg.period || ""} onChange={(e) => setCfg({ ...cfg, period: num(e.target.value) })} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label>{t("LsUnit")}</Label>
|
||||
<Select value={cfg.unit} onValueChange={(unit) => setCfg({ ...cfg, unit: unit as LockoutConfig["unit"] })}>
|
||||
<SelectTrigger aria-label={t("LsUnit")} className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{LOCKOUT_UNITS.map((u) => <SelectItem key={u} value={u}>{t(`LsUnit${u}`)}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button onClick={save} disabled={saving}>{t("LsSaveLockout")}</Button>
|
||||
<NoticeLine notice={notice} />
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
type RuleEdit = { status: "Y" | "N"; value: string | null };
|
||||
|
||||
function PasswordRulesForm() {
|
||||
const t = useT();
|
||||
const [rules, setRules] = useState<PasswordRule[] | null>(null);
|
||||
const [edits, setEdits] = useState<Record<number, RuleEdit>>({});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [notice, setNotice] = useState<Notice>(null);
|
||||
|
||||
const load = useCallback((list: PasswordRule[]) => {
|
||||
setRules(list);
|
||||
setEdits(Object.fromEntries(list.map((r) => [r.id, { status: r.status, value: r.value }])));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
getPasswordRules()
|
||||
.then((list) => { if (!cancelled) load(list); })
|
||||
.catch((err: unknown) => { if (!cancelled) setNotice({ kind: "error", text: t(errMessage(err, "LsSettingsLoadFailed")) }); });
|
||||
return () => { cancelled = true; };
|
||||
}, [t, load]);
|
||||
|
||||
if (!rules) return <NoticeLine notice={notice} />;
|
||||
|
||||
async function save() {
|
||||
if (!rules) return;
|
||||
setSaving(true);
|
||||
setNotice(null);
|
||||
try {
|
||||
load(await savePasswordRules(rules.map((r) => ({ id: r.id, ...edits[r.id] }))));
|
||||
setNotice({ kind: "ok", text: t("LsRulesSaved") });
|
||||
} catch (err) {
|
||||
setNotice({ kind: "error", text: t(errMessage(err, "LsSaveFailed")) });
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
const edit = (id: number, patch: Partial<RuleEdit>) => setEdits((e) => ({ ...e, [id]: { ...e[id], ...patch } }));
|
||||
|
||||
return (
|
||||
<section className="space-y-4 rounded-xl border bg-card p-4">
|
||||
<h2 className="text-base font-semibold">{t("LsRulesTitle")}</h2>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{t("LsRuleName")}</TableHead>
|
||||
<TableHead>{t("LsRuleOn")}</TableHead>
|
||||
<TableHead>{t("LsRuleValue")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{rules.map((r) => {
|
||||
const label = t(`PwdRule_${r.param}`);
|
||||
const e = edits[r.id];
|
||||
return (
|
||||
<TableRow key={r.id}>
|
||||
<TableCell>{label}</TableCell>
|
||||
<TableCell>
|
||||
<Switch aria-label={label} checked={e.status === "Y"} onCheckedChange={(on) => edit(r.id, { status: on ? "Y" : "N" })} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{!FLAG_RULE_PARAMS.includes(r.param) && (
|
||||
<Input aria-label={`${label} ${t("LsRuleValue").toLowerCase()}`} type="number" min={0} className="w-24" value={e.value ?? ""} onChange={(ev) => edit(r.id, { value: ev.target.value })} />
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button onClick={save} disabled={saving}>{t("LsSaveRules")}</Button>
|
||||
<NoticeLine notice={notice} />
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function LoginSecurityContent() {
|
||||
const t = useT();
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_LOGIN_SECURITY")} />
|
||||
<Tabs defaultValue="history">
|
||||
<TabsList>
|
||||
<TabsTrigger value="history">{t("LsTabHistory")}</TabsTrigger>
|
||||
<TabsTrigger value="locked">{t("LsTabLocked")}</TabsTrigger>
|
||||
<TabsTrigger value="settings">{t("LsTabSettings")}</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="history"><HistoryTab /></TabsContent>
|
||||
<TabsContent value="locked"><LockedTab /></TabsContent>
|
||||
<TabsContent value="settings" className="space-y-4"><LockoutForm /><PasswordRulesForm /></TabsContent>
|
||||
</Tabs>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function LoginSecurityPage() {
|
||||
return (
|
||||
<RequireModule pathname="/login-security">
|
||||
<LoginSecurityContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiPost: vi.fn() }));
|
||||
vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }));
|
||||
vi.mock("@/app/lib/clientApi", async () => {
|
||||
class ApiError extends Error {
|
||||
status: number;
|
||||
data?: unknown;
|
||||
constructor(message: string, status: number, data?: unknown) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
return { apiPost: mocks.apiPost, ApiError };
|
||||
});
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ refresh: vi.fn() }) }));
|
||||
|
||||
import LoginPage from "./page";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { DEFAULT_MESSAGES } from "@/app/lib/i18n/defaultMessages";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiPost.mockReset();
|
||||
});
|
||||
|
||||
async function submit() {
|
||||
render(<LoginPage />);
|
||||
await userEvent.type(screen.getByLabelText("Username"), "sales1");
|
||||
await userEvent.type(screen.getByLabelText("Password"), "x");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Log in" }));
|
||||
}
|
||||
|
||||
describe("LoginPage: locked account", () => {
|
||||
it("shows the locked message when the body code is ACCOUNT_LOCKED", async () => {
|
||||
mocks.apiPost.mockRejectedValue(new ApiError("server text", 401, { error: "server text", code: "ACCOUNT_LOCKED" }));
|
||||
await submit();
|
||||
expect(await screen.findByText(DEFAULT_MESSAGES.LoginAccountLocked)).toBeInTheDocument();
|
||||
expect(DEFAULT_MESSAGES.LoginAccountLocked).toBe(
|
||||
"Too many failed sign-ins. Try again later or ask an administrator to unlock your account.",
|
||||
);
|
||||
});
|
||||
|
||||
it("shows the server message for other failures", async () => {
|
||||
mocks.apiPost.mockRejectedValue(new ApiError("Invalid username or password", 401, { error: "Invalid username or password" }));
|
||||
await submit();
|
||||
expect(await screen.findByText("Invalid username or password")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,7 @@ import { Button } from "@/app/components/ui/button";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { ErrorState } from "@/app/components/ui/states";
|
||||
import { apiPost } from "@/app/lib/clientApi";
|
||||
import { ApiError, apiPost } from "@/app/lib/clientApi";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import PoweredBy from "@/app/components/app/PoweredBy";
|
||||
@@ -64,7 +64,8 @@ export default function LoginPage() {
|
||||
// replace keeps the root layout, whose locale list was loaded without a token; re-run it.
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "LoginInvalidCredentials");
|
||||
const locked = err instanceof ApiError && (err.data as { code?: unknown } | undefined)?.code === "ACCOUNT_LOCKED";
|
||||
setError(locked ? "LoginAccountLocked" : err instanceof Error ? err.message : "LoginInvalidCredentials");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
@@ -133,6 +133,9 @@ public class JWTAuthFilter implements GlobalFilter, Ordered {
|
||||
|| url.contains("/member/forgetPassword")
|
||||
// Co-Lite admin forgot password (public; answers the same whether or not details match)
|
||||
|| url.equals("/user/resetAdminPassword")
|
||||
// Co-Lite admin sign-in: lock check and its recording run before the user has a token
|
||||
|| (url.matches("/loginSecurity/isLocked/[^/]+") && !url.contains(".."))
|
||||
|| url.equals("/loginSecurity/record")
|
||||
|| url.contains("/geoLocationHierarchy/findByFirstLevelLocation")
|
||||
|| url.contains("/geoLocationHierarchy/findAllByParentId")
|
||||
// public content - no JWT required
|
||||
|
||||
@@ -148,6 +148,10 @@ spring:
|
||||
uri: http://${app.services.name.system}
|
||||
predicates:
|
||||
- Path=/blockLoginPeriod/**
|
||||
- id: loginSecurity
|
||||
uri: http://${app.services.name.system}
|
||||
predicates:
|
||||
- Path=/loginSecurity/**
|
||||
- id: passwordAging
|
||||
uri: http://${app.services.name.system}
|
||||
predicates:
|
||||
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package com.solvway.gateway.filter;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.gateway.model.AuthAppKey;
|
||||
import com.solvway.gateway.model.AuthAppKeyMap;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/** The admin sign-in lock check and its recording run before the user has a token; the rest of /loginSecurity needs one. */
|
||||
class JWTAuthFilterLoginSecurityPathTest {
|
||||
|
||||
private static final String KEY = "gateway-test-key";
|
||||
|
||||
private JWTAuthFilter filter;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
// Built the way AuthAppKeyConfig loads appkeys.json (the constructor is not public).
|
||||
AuthAppKey key = new ObjectMapper().readValue(
|
||||
"{\"key\":\"" + KEY + "\",\"type\":\"BO\",\"ipList\":[\"0.0.0.0/0\"],\"allowList\":[\"/\"]}",
|
||||
AuthAppKey.class);
|
||||
AuthAppKeyMap map = new AuthAppKeyMap();
|
||||
map.add(KEY, key);
|
||||
filter = new JWTAuthFilter();
|
||||
ReflectionTestUtils.setField(filter, "authAppKeyMap", map);
|
||||
}
|
||||
|
||||
private MockServerWebExchange post(String path) {
|
||||
return MockServerWebExchange.from(MockServerHttpRequest.post(path)
|
||||
.header("api-key", KEY)
|
||||
.remoteAddress(new InetSocketAddress("127.0.0.1", 40000)));
|
||||
}
|
||||
|
||||
private MockServerWebExchange get(String path) {
|
||||
return MockServerWebExchange.from(MockServerHttpRequest.get(path)
|
||||
.header("api-key", KEY)
|
||||
.remoteAddress(new InetSocketAddress("127.0.0.1", 40000)));
|
||||
}
|
||||
|
||||
private boolean passes(MockServerWebExchange exchange) {
|
||||
AtomicBoolean called = new AtomicBoolean(false);
|
||||
GatewayFilterChain chain = ex -> {
|
||||
called.set(true);
|
||||
return Mono.empty();
|
||||
};
|
||||
filter.filter(exchange, chain).block();
|
||||
return called.get();
|
||||
}
|
||||
|
||||
@Test
|
||||
void lockCheckNeedsNoUserToken() {
|
||||
assertThat(passes(get("/loginSecurity/isLocked/sales1"))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordNeedsNoUserToken() {
|
||||
assertThat(passes(post("/loginSecurity/record"))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherLoginSecurityEndpointsStillNeedAToken() {
|
||||
for (MockServerWebExchange exchange : new MockServerWebExchange[] {
|
||||
post("/loginSecurity/unlock"), get("/loginSecurity/locked"), post("/loginSecurity/config"),
|
||||
post("/loginSecurity/audit"), post("/loginSecurity/passwordRules"),
|
||||
post("/loginSecurity/record/../unlock"), get("/x/loginSecurity/isLocked/a"), get("/loginSecurity/isLocked/../locked"),
|
||||
get("/loginSecurity/isLocked/a/b") }) {
|
||||
assertThat(passes(exchange)).isFalse();
|
||||
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,6 +125,11 @@
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.jknack</groupId>
|
||||
<artifactId>handlebars</artifactId>
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.solvway.core.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** One admin audit event: published by mobile-api on audit-event-topic, stored by services-log. */
|
||||
@Setter
|
||||
@Getter
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class AuditEvent {
|
||||
public static final String OUTCOME_SUCCESS = "SUCCESS";
|
||||
public static final String OUTCOME_FAILURE = "FAILURE";
|
||||
|
||||
private Long companyId;
|
||||
private LocalDateTime occurredAt;
|
||||
private String actor;
|
||||
private String module;
|
||||
private String action;
|
||||
private String httpMethod;
|
||||
private String pathTemplate;
|
||||
private String targetId;
|
||||
private String outcome;
|
||||
private Integer httpStatus;
|
||||
private String clientIp;
|
||||
/** JSON: {field: {before, after}} for allow-listed fields, or {fields: [..]} for lead edits. */
|
||||
private String changes;
|
||||
}
|
||||
@@ -47,6 +47,9 @@ pubsub:
|
||||
activate-member:
|
||||
subscription: activate-member-subscription
|
||||
topic: activate-member-topic
|
||||
audit-event:
|
||||
subscription: audit-event-subscription
|
||||
topic: audit-event-topic
|
||||
backoffice-message-source-refresh:
|
||||
subscription: backoffice-message-source-refresh-subscription
|
||||
topic: backoffice-message-source-refresh-topic
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.solvway.core.model;
|
||||
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class AuditEventTest {
|
||||
|
||||
private final PubSubUtil util = new PubSubUtil();
|
||||
|
||||
@Test
|
||||
void roundTripsEveryFieldThroughPubSubUtil() {
|
||||
AuditEvent e = new AuditEvent();
|
||||
e.setCompanyId(7L);
|
||||
e.setOccurredAt(LocalDateTime.of(2026, 11, 30, 15, 4, 5, 123_000_000));
|
||||
e.setActor("admin");
|
||||
e.setModule("BO_USERS");
|
||||
e.setAction("USER_UPDATE");
|
||||
e.setHttpMethod("PUT");
|
||||
e.setPathTemplate("/api/admin/users/{id}");
|
||||
e.setTargetId("42");
|
||||
e.setOutcome(AuditEvent.OUTCOME_SUCCESS);
|
||||
e.setHttpStatus(200);
|
||||
e.setClientIp("203.0.113.9");
|
||||
e.setChanges("{\"enabled\":{\"before\":true,\"after\":false}}");
|
||||
|
||||
String json = util.convertToString(e);
|
||||
assertThat(json).contains("\"occurredAt\":\"2026-11-30T15:04:05.123\"");
|
||||
|
||||
AuditEvent back = util.convertToOriginalObject(json.getBytes(StandardCharsets.UTF_8), AuditEvent.class);
|
||||
assertThat(back).usingRecursiveComparison().isEqualTo(e);
|
||||
assertThat(AuditEvent.OUTCOME_FAILURE).isEqualTo("FAILURE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ignoresUnknownFieldsSoTheContractCanGrow() {
|
||||
String json = "{\"actor\":\"admin\",\"action\":\"USER_UPDATE\",\"outcome\":\"SUCCESS\",\"addedLater\":1}";
|
||||
AuditEvent back = util.convertToOriginalObject(json.getBytes(StandardCharsets.UTF_8), AuditEvent.class);
|
||||
assertThat(back).isNotNull();
|
||||
assertThat(back.getActor()).isEqualTo("admin");
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,9 @@ public class PubSubConfig {
|
||||
@Value("${pubsub.response-time-log.topic}")
|
||||
public String responseTimeLogTopic;
|
||||
|
||||
@Value("${pubsub.audit-event.topic}")
|
||||
public String auditEventTopic;
|
||||
|
||||
@Value("${pubsub.email.save-request.topic}")
|
||||
public String emailSaveRequestTopic;
|
||||
|
||||
@@ -35,6 +38,7 @@ public class PubSubConfig {
|
||||
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
executor.submit(() -> pubSubUtil.createTopicIfNotExists(pubSubAdmin, responseTimeLogTopic));
|
||||
executor.submit(() -> pubSubUtil.createTopicIfNotExists(pubSubAdmin, emailSaveRequestTopic));
|
||||
executor.submit(() -> pubSubUtil.createTopicIfNotExists(pubSubAdmin, auditEventTopic));
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.solvway.mobile.api.constant.api;
|
||||
|
||||
public class RestApiLogServiceConstants {
|
||||
|
||||
private RestApiLogServiceConstants() {}
|
||||
|
||||
public static final String API_REST_LOG_AUDIT_SEARCH = "/log/audit/search";
|
||||
public static final String API_REST_LOG_AUDIT_DETAIL = "/log/audit/{id}";
|
||||
}
|
||||
+10
@@ -25,6 +25,7 @@ public class RestApiSystemServiceConstants {
|
||||
public static final String API_REST_SYSTEM_ADMIN_RESET_PASSWORD = "/user/resetAdminPassword";
|
||||
public static final String API_REST_SYSTEM_ADMIN_VALIDATE_PASSWORD_RULES = "/user/validatePasswordFromRulesForAdmin";
|
||||
public static final String API_REST_SYSTEM_ADMIN_SET_PASSWORD = "/user/setAdminPassword";
|
||||
public static final String API_REST_SYSTEM_ADMIN_CHANGE_PASSWORD = "/user/changeAdminPassword";
|
||||
public static final String API_REST_SYSTEM_USER_FIRST_TIME_LOGIN="/user/memberFirstTimeLogin";
|
||||
public static final String API_REST_SYSTEM_USER_VALIDATE_PASSWORD_RULES="/user/validatePasswordFromRulesForMember";
|
||||
|
||||
@@ -91,6 +92,15 @@ public class RestApiSystemServiceConstants {
|
||||
public static final String API_REST_GENERIC_POST_FIND_BY_UUID = "/system/genericPost/findByUuid/{uuid}";
|
||||
public static final String API_REST_GENERIC_POST_CONTENT_FIND_BY_UUID_AND_LOCALE = "/system/genericPost/content/findByPostUuidAndLocale/{uuid}/{locale}";
|
||||
|
||||
//LoginSecurity (admin sign-in lock check and history)
|
||||
public static final String API_REST_LOGIN_SECURITY_IS_LOCKED = "/loginSecurity/isLocked/{username}";
|
||||
public static final String API_REST_LOGIN_SECURITY_RECORD = "/loginSecurity/record";
|
||||
public static final String API_REST_LOGIN_SECURITY_AUDIT = "/loginSecurity/audit";
|
||||
public static final String API_REST_LOGIN_SECURITY_LOCKED = "/loginSecurity/locked";
|
||||
public static final String API_REST_LOGIN_SECURITY_UNLOCK = "/loginSecurity/unlock";
|
||||
public static final String API_REST_LOGIN_SECURITY_CONFIG = "/loginSecurity/config";
|
||||
public static final String API_REST_LOGIN_SECURITY_PASSWORD_RULES = "/loginSecurity/passwordRules";
|
||||
|
||||
//Message
|
||||
public static final String API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE = "/message/findByCodeAndLocale/{code}/{locale}";
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminAuditLogService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/** Audit log screen: search and detail of admin audit events. Reads are not audited. Must stay under {@code controller..} for AppAccessAspect. */
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/audit-log")
|
||||
@RequiredArgsConstructor
|
||||
@AdminModule("BO_AUDIT_LOG")
|
||||
public class AdminAuditLogController {
|
||||
|
||||
private final AdminAuditLogService auditLog;
|
||||
|
||||
@AppAuth
|
||||
@GetMapping
|
||||
public ResponseEntity<Map<String, Object>> list(
|
||||
@RequestParam(required = false) String actor,
|
||||
@RequestParam(required = false) String module,
|
||||
@RequestParam(required = false) String action,
|
||||
@RequestParam(required = false) String outcome,
|
||||
@RequestParam(required = false) String from,
|
||||
@RequestParam(required = false) String to,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ResponseEntity.ok(auditLog.search(actor, module, action, outcome, from, to, page, size));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<Map<String, Object>> detail(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(auditLog.get(id));
|
||||
}
|
||||
}
|
||||
+61
-1
@@ -4,10 +4,12 @@ import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminChangePasswordRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminFirstLoginRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminForgotPasswordRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLoginResponse;
|
||||
import com.solvway.mobile.api.dto.admin.AdminMeResponse;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.model.AuthRequest;
|
||||
import com.solvway.mobile.api.service.AdminAuthenticationService;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
@@ -34,6 +36,8 @@ import java.util.Map;
|
||||
public class AdminAuthController {
|
||||
private static final Map<String, String> BAD_LOGIN =
|
||||
Map.of("result", "false", "message", "Invalid username or password");
|
||||
private static final Map<String, String> ACCOUNT_LOCKED = Map.of("result", "false", "code", "ACCOUNT_LOCKED",
|
||||
"message", "Too many failed sign-ins. Try again later or ask an administrator to unlock your account.");
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
@@ -44,6 +48,11 @@ public class AdminAuthController {
|
||||
if (!StringUtils.hasText(request.getUsername()) || !StringUtils.hasText(request.getPassword())) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(BAD_LOGIN);
|
||||
}
|
||||
String username = request.getUsername().trim();
|
||||
if (adminAuthenticationService.isLocked(username)) {
|
||||
adminAuthenticationService.record(username, "LOGIN_LOCKED", null);
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ACCOUNT_LOCKED);
|
||||
}
|
||||
String token;
|
||||
User u;
|
||||
try {
|
||||
@@ -60,8 +69,10 @@ public class AdminAuthController {
|
||||
token = null;
|
||||
}
|
||||
if (u == null) {
|
||||
adminAuthenticationService.record(username, "LOGIN_FAIL", null);
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(BAD_LOGIN);
|
||||
}
|
||||
adminAuthenticationService.record(username, "LOGIN_SUCCESS", null);
|
||||
return ResponseEntity.ok(new AdminLoginResponse(token, u.getName(), u.getRoles(), u.getAclMenu(),
|
||||
GeneralEnum.LoginStatus.N.equals(u.getLogin()) ? "true" : "false"));
|
||||
}
|
||||
@@ -87,6 +98,46 @@ public class AdminAuthController {
|
||||
return ResponseEntity.ok(Map.of("result", "true"));
|
||||
}
|
||||
|
||||
/** An admin changes their own password; refused while a first-login change is pending. The token stays valid. */
|
||||
@AdminModule(AdminModule.ANY_ADMIN)
|
||||
@AppAuth
|
||||
@PostMapping("/auth/change-password")
|
||||
public ResponseEntity<Void> changePassword(@RequestBody AdminChangePasswordRequest request) {
|
||||
User u = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (u == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
||||
}
|
||||
if (!StringUtils.hasText(request.currentPassword()) || !StringUtils.hasText(request.newPassword())
|
||||
|| !StringUtils.hasText(request.confirmPassword())) {
|
||||
throw coded(HttpStatus.BAD_REQUEST, "Current password, new password and confirmation are required", "REQUIRED_FIELD");
|
||||
}
|
||||
if (!request.newPassword().equals(request.confirmPassword())) {
|
||||
throw coded(HttpStatus.BAD_REQUEST, "Passwords do not match", "PASSWORD_MISMATCH");
|
||||
}
|
||||
if (adminAuthenticationService.isLocked(u.getUsername())) {
|
||||
throw coded(HttpStatus.BAD_REQUEST,
|
||||
"Too many failed sign-ins. Try again later or ask an administrator to unlock your account.", "ACCOUNT_LOCKED");
|
||||
}
|
||||
String result = adminAuthenticationService.changeAdminPassword(u.getId(), request.currentPassword(), request.newPassword());
|
||||
switch (result) {
|
||||
case "OK" -> {
|
||||
adminAuthenticationService.record(u.getUsername(), "PASSWORD_CHANGED", null);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
case "CURRENT_PASSWORD_WRONG" -> {
|
||||
adminAuthenticationService.record(u.getUsername(), "LOGIN_FAIL", "change-password");
|
||||
throw coded(HttpStatus.BAD_REQUEST, "Current password is incorrect", "CURRENT_PASSWORD_WRONG");
|
||||
}
|
||||
case "PASSWORD_SAME" -> throw coded(HttpStatus.BAD_REQUEST, "The new password must differ from the current one", "PASSWORD_SAME");
|
||||
case "PASSWORD_POLICY" -> throw coded(HttpStatus.BAD_REQUEST, "Password does not meet the password policy", "PASSWORD_POLICY");
|
||||
default -> throw coded(HttpStatus.INTERNAL_SERVER_ERROR, "The password was not changed", "SAVE_FAILED");
|
||||
}
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException coded(HttpStatus status, String message, String code) {
|
||||
return new CodedResponseStatusException(status, message, code);
|
||||
}
|
||||
|
||||
/** Always 200 with the same body: the answer must not reveal whether username and email matched. */
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/auth/forgot-password")
|
||||
@@ -105,7 +156,16 @@ public class AdminAuthController {
|
||||
@AppAuth
|
||||
@PostMapping("/auth/logout")
|
||||
public ResponseEntity<Map<String, String>> logout() {
|
||||
authenticationService.logoutToken(HttpReqRespUtils.getJwtToken());
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
try {
|
||||
User u = adminAuthenticationService.loadUserByToken(token); // before the token is revoked
|
||||
if (u != null) {
|
||||
adminAuthenticationService.record(u.getUsername(), "LOGOUT", null);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Logout history skipped: {}", e.getClass().getSimpleName());
|
||||
}
|
||||
authenticationService.logoutToken(token);
|
||||
return ResponseEntity.ok(Map.of("result", "true"));
|
||||
}
|
||||
|
||||
|
||||
+2
@@ -3,6 +3,7 @@ package com.solvway.mobile.api.controller.admin;
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminEmailService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@@ -34,6 +35,7 @@ public class AdminEmailController {
|
||||
return ResponseEntity.ok(adminEmailService.list(recipient, subject, from, to, page, size));
|
||||
}
|
||||
|
||||
@Audited(action = "EMAIL_VIEW")
|
||||
@AppAuth
|
||||
@GetMapping("/emails/{id}")
|
||||
public ResponseEntity<Map<String, Object>> detail(@PathVariable Long id) {
|
||||
|
||||
+2
@@ -6,6 +6,7 @@ import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest;
|
||||
import com.solvway.mobile.api.service.AdminEventLeadService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@@ -48,6 +49,7 @@ public class AdminEventLeadController {
|
||||
return ResponseEntity.ok(adminEventLeadService.salespersonOptions(eventUuid));
|
||||
}
|
||||
|
||||
@Audited(skip = true)
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@PostMapping("/{eventUuid}/match")
|
||||
|
||||
+2
@@ -3,6 +3,7 @@ package com.solvway.mobile.api.controller.admin;
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminEventLeadService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
@@ -20,6 +21,7 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class AdminEventLeadExportController {
|
||||
private final AdminEventLeadService adminEventLeadService;
|
||||
|
||||
@Audited(action = "EVENT_LEAD_EXPORT")
|
||||
@AppAuth
|
||||
@AdminModule(value = "BO_LEADS_EXPORT", also = "BO_EVENT_LEADS")
|
||||
@GetMapping("/{eventUuid}/export")
|
||||
|
||||
+2
@@ -4,6 +4,7 @@ import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.service.AdminLeadService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
@@ -34,6 +35,7 @@ public class AdminLeadController {
|
||||
return ResponseEntity.ok(adminLeadService.list(q, page, size));
|
||||
}
|
||||
|
||||
@Audited(action = "LEAD_EXPORT")
|
||||
@AppAuth
|
||||
@AdminModule(value = "BO_LEADS_EXPORT", also = "BO_LEADS")
|
||||
@GetMapping("/export")
|
||||
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminLoginSecurityService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Login security screen: sign-in history, locked accounts, lockout settings, password rules. Must stay under {@code controller..} for AppAccessAspect. */
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/login-security")
|
||||
@RequiredArgsConstructor
|
||||
@AdminModule("BO_LOGIN_SECURITY")
|
||||
public class AdminLoginSecurityController {
|
||||
|
||||
private final AdminLoginSecurityService loginSecurity;
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/audit")
|
||||
public ResponseEntity<Map<String, Object>> audit(
|
||||
@RequestParam(required = false) String username,
|
||||
@RequestParam(required = false) String event,
|
||||
@RequestParam(required = false) String from,
|
||||
@RequestParam(required = false) String to,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ResponseEntity.ok(loginSecurity.audit(username, event, from, to, page, size));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/locked")
|
||||
public ResponseEntity<List<Map<String, Object>>> locked() {
|
||||
return ResponseEntity.ok(loginSecurity.locked());
|
||||
}
|
||||
|
||||
@Audited(target = false) // the username is whatever was typed at sign-in, possibly a password
|
||||
@AppAuth
|
||||
@PostMapping("/locked/{username}/unlock")
|
||||
public ResponseEntity<Void> unlock(@PathVariable String username) {
|
||||
loginSecurity.unlock(username);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/config")
|
||||
public ResponseEntity<Map<String, Object>> config() {
|
||||
return ResponseEntity.ok(loginSecurity.config());
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@PutMapping("/config")
|
||||
public ResponseEntity<Map<String, Object>> saveConfig(@RequestBody Map<String, Object> config) {
|
||||
return ResponseEntity.ok(loginSecurity.saveConfig(config));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/password-rules")
|
||||
public ResponseEntity<List<Map<String, Object>>> passwordRules() {
|
||||
return ResponseEntity.ok(loginSecurity.passwordRules());
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@PutMapping("/password-rules")
|
||||
public ResponseEntity<List<Map<String, Object>>> savePasswordRules(@RequestBody List<Map<String, Object>> rules) {
|
||||
return ResponseEntity.ok(loginSecurity.savePasswordRules(rules));
|
||||
}
|
||||
}
|
||||
+2
@@ -7,6 +7,7 @@ import com.solvway.mobile.api.dto.admin.AdminRoleRequest;
|
||||
import com.solvway.mobile.api.service.AdminAclService;
|
||||
import com.solvway.mobile.api.service.AdminRoleService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@@ -52,6 +53,7 @@ public class AdminRoleController {
|
||||
public ResponseEntity<List<AdminModuleGrant>> getModules(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(adminAclService.getGrantTree(id));
|
||||
}
|
||||
@Audited(action = "ROLE_SET_MODULES")
|
||||
@AppAuth
|
||||
@AdminModule("BO_ROLES")
|
||||
@PutMapping("/roles/{id}/modules")
|
||||
|
||||
+3
@@ -4,6 +4,7 @@ import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.admin.AdminUserRequest;
|
||||
import com.solvway.mobile.api.service.AdminUserService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@@ -49,12 +50,14 @@ public class AdminUserController {
|
||||
return ResponseEntity.ok(adminUserService.update(id, request));
|
||||
}
|
||||
|
||||
@Audited(action = "USER_SEND_PASSWORD_RESET")
|
||||
@AppAuth
|
||||
@PostMapping("/users/{id}/resetPassword")
|
||||
public ResponseEntity<Map<String, Object>> resetPassword(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(Map.of("updated", adminUserService.resetPassword(id)));
|
||||
}
|
||||
|
||||
@Audited(action = "USER_SET_TEMPORARY_PASSWORD")
|
||||
@AppAuth
|
||||
@PostMapping("/users/{id}/password")
|
||||
public ResponseEntity<Void> setPassword(@PathVariable Long id, @RequestBody Map<String, String> body) {
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.solvway.mobile.api.dto.admin;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record AdminChangePasswordRequest(String currentPassword, String newPassword, String confirmPassword) {
|
||||
|
||||
/** Never print the passwords. */
|
||||
@Override
|
||||
public String toString() {
|
||||
return "AdminChangePasswordRequest[]";
|
||||
}
|
||||
}
|
||||
+10
-1
@@ -5,6 +5,7 @@ import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.dto.admin.AdminModuleGrant;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
@@ -52,8 +53,12 @@ public class AdminAclService {
|
||||
List<Map<String, Object>> modules = modules();
|
||||
Set<Long> known = new HashSet<>();
|
||||
Set<Long> current = new HashSet<>();
|
||||
Map<Long, String> codes = new java.util.HashMap<>();
|
||||
for (Map<String, Object> m : modules) {
|
||||
if (isGrantable(m)) known.add(AdminRoleService.idOf(m));
|
||||
if (isGrantable(m)) {
|
||||
known.add(AdminRoleService.idOf(m));
|
||||
codes.put(AdminRoleService.idOf(m), String.valueOf(m.get("name")));
|
||||
}
|
||||
if (isGrantable(m) && grantedTo(m, roleId)) current.add(AdminRoleService.idOf(m));
|
||||
}
|
||||
Set<Long> wanted = new HashSet<>(moduleIds);
|
||||
@@ -62,6 +67,10 @@ public class AdminAclService {
|
||||
// ponytail: not atomic, adds run before deletes and a failure midway leaves a partial grant; a repeated PUT converges. Upgrade: one services-system endpoint that replaces grants in a transaction.
|
||||
for (Long id : wanted) if (!current.contains(id)) call(RestApiSystemServiceConstants.API_REST_SYSTEM_MODULE_ADD_MODULE_ROLE, id, roleId);
|
||||
for (Long id : current) if (!wanted.contains(id)) call(RestApiSystemServiceConstants.API_REST_SYSTEM_MODULE_DELETE_MODULE_ROLE, id, roleId);
|
||||
List<String> added = wanted.stream().filter(id -> !current.contains(id)).map(codes::get).sorted().toList();
|
||||
List<String> removed = current.stream().filter(id -> !wanted.contains(id)).map(codes::get).sorted().toList();
|
||||
if (!added.isEmpty()) AuditChanges.put("modulesAdded", null, added);
|
||||
if (!removed.isEmpty()) AuditChanges.put("modulesRemoved", null, removed);
|
||||
return getGrantTree(roleId);
|
||||
}
|
||||
|
||||
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.mobile.api.constant.api.RestApiLogServiceConstants;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** Reads the audit trail from services-log for the Audit log screen, turning its 400/404 into coded admin errors. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdminAuditLogService {
|
||||
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
public Map<String, Object> search(String actor, String module, String action, String outcome, String from, String to, int page, int size) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
put(body, "actor", actor);
|
||||
put(body, "module", module);
|
||||
put(body, "action", action);
|
||||
put(body, "outcome", outcome);
|
||||
put(body, "from", from);
|
||||
put(body, "to", to);
|
||||
body.put("page", page);
|
||||
body.put("size", size);
|
||||
try {
|
||||
return restTemplateUtil.postForEntity(url(RestApiLogServiceConstants.API_REST_LOG_AUDIT_SEARCH), MAP, body).getBody();
|
||||
} catch (HttpClientErrorException.BadRequest e) {
|
||||
throw new CodedResponseStatusException(HttpStatus.BAD_REQUEST, reason(e), "INVALID_FILTER");
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Object> get(Long id) {
|
||||
try {
|
||||
return restTemplateUtil.getForEntity(url(RestApiLogServiceConstants.API_REST_LOG_AUDIT_DETAIL), MAP, id).getBody();
|
||||
} catch (HttpClientErrorException.NotFound e) {
|
||||
throw new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Audit event not found", "NOT_FOUND");
|
||||
}
|
||||
}
|
||||
|
||||
private static void put(Map<String, Object> body, String key, String value) {
|
||||
if (StringUtils.hasText(value)) body.put(key, value.trim());
|
||||
}
|
||||
|
||||
private static String reason(HttpClientErrorException e) {
|
||||
try {
|
||||
JsonNode detail = JSON.readTree(e.getResponseBodyAsString()).get("detail");
|
||||
if (detail != null && detail.isTextual() && StringUtils.hasText(detail.asText())) return detail.asText();
|
||||
} catch (Exception ignored) {
|
||||
// empty or unparsable body: fall through to the generic reason
|
||||
}
|
||||
return "Invalid request";
|
||||
}
|
||||
|
||||
private String url(String api) {
|
||||
return restTemplateUtil.getURLforApiService(api);
|
||||
}
|
||||
}
|
||||
+47
@@ -5,16 +5,22 @@ import com.solvway.mobile.api.constant.api.RestApiAuthServiceConstants;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.model.AuthRequest;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class AdminAuthenticationService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
@@ -58,6 +64,14 @@ public class AdminAuthenticationService {
|
||||
return ent.getBody() == null ? 0 : ent.getBody();
|
||||
}
|
||||
|
||||
/** Changes an admin's own password; returns OK, NOT_FOUND, CURRENT_PASSWORD_WRONG, PASSWORD_SAME or PASSWORD_POLICY. */
|
||||
public String changeAdminPassword(Long id, String currentPassword, String newPassword) {
|
||||
ResponseEntity<String> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_ADMIN_CHANGE_PASSWORD),
|
||||
String.class, Map.of("id", id, "currentPassword", currentPassword, "newPassword", newPassword));
|
||||
return ent.getBody() == null ? "NOT_FOUND" : ent.getBody();
|
||||
}
|
||||
|
||||
/** Emails a temporary password when username and email match an admin; returns rows updated (0 = no match). */
|
||||
public int resetAdminPassword(String username, String email) {
|
||||
ResponseEntity<Integer> ent = restTemplateUtil.postForEntity(
|
||||
@@ -65,4 +79,37 @@ public class AdminAuthenticationService {
|
||||
Integer.class, Map.of("username", username, "email", email));
|
||||
return ent.getBody() == null ? 0 : ent.getBody();
|
||||
}
|
||||
|
||||
/** True when services-system says the account is locked; fails open (false) on any error so a fault never blocks sign-in. */
|
||||
public boolean isLocked(String username) {
|
||||
try {
|
||||
ResponseEntity<Map> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_IS_LOCKED),
|
||||
Map.class, username);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null
|
||||
&& Boolean.TRUE.equals(ent.getBody().get("locked"));
|
||||
} catch (Exception e) {
|
||||
log.warn("Login lock check failed, allowing sign-in: {}", e.getClass().getSimpleName());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Best-effort login history entry with the caller's X-Client-IP and X-Client-User-Agent; never throws. */
|
||||
public void record(String username, String event, String message) {
|
||||
try {
|
||||
HttpServletRequest req = RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes a
|
||||
? a.getRequest() : null;
|
||||
Map<String, Object> body = new HashMap<>();
|
||||
body.put("username", username);
|
||||
body.put("event", event);
|
||||
body.put("ip", req == null ? null : req.getHeader("X-Client-IP"));
|
||||
body.put("userAgent", req == null ? null : req.getHeader("X-Client-User-Agent"));
|
||||
body.put("message", message);
|
||||
restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_RECORD),
|
||||
String.class, body);
|
||||
} catch (Exception e) {
|
||||
log.warn("Login history record failed: {}", e.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
-2
@@ -10,6 +10,7 @@ import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -23,6 +24,7 @@ import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
@@ -260,8 +262,17 @@ public class AdminEventLeadService {
|
||||
body.put("nextFollowUpDate", followUp == null ? null : followUp.toString());
|
||||
body.put("notes", trimmed(r.notes()));
|
||||
body.put("doneBy", caller.getUsername());
|
||||
return view(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_UPDATE), MAP, body).getBody(),
|
||||
known, new HashMap<>());
|
||||
Map<String, Object> saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_UPDATE), MAP, body).getBody();
|
||||
// field names only: follow-up values are personal data
|
||||
List<String> changed = new ArrayList<>();
|
||||
if (!Objects.equals(r.salespersonId(), currentSalesperson)) changed.add("salespersonId");
|
||||
if (!Objects.equals(temperature, current.get("temperature"))) changed.add("temperature");
|
||||
if (!Objects.equals(status, current.get("status"))) changed.add("status");
|
||||
if (!new HashSet<>(interestIds).equals(new HashSet<>(longs(current.get("interestIds"))))) changed.add("interestIds");
|
||||
if (!Objects.equals(body.get("nextFollowUpDate"), current.get("nextFollowUpDate") == null ? null : current.get("nextFollowUpDate").toString())) changed.add("nextFollowUpDate");
|
||||
if (!Objects.equals(body.get("notes"), current.get("notes"))) changed.add("notes");
|
||||
if (!changed.isEmpty()) AuditChanges.fields(changed.toArray(String[]::new));
|
||||
return view(saved, known, new HashMap<>());
|
||||
}
|
||||
|
||||
// --- rules ---
|
||||
|
||||
+23
-1
@@ -6,6 +6,7 @@ import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
@@ -19,6 +20,7 @@ import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import static com.solvway.mobile.api.service.AdminEventLeadService.email;
|
||||
import static com.solvway.mobile.api.service.AdminEventLeadService.error;
|
||||
@@ -118,11 +120,31 @@ public class AdminLeadService {
|
||||
body.put("jobTitle", jobTitle);
|
||||
body.put("notes", notes);
|
||||
body.put("doneBy", caller.getUsername());
|
||||
Map<String, Object> before = storedOrNull(caller.getCompanyId(), id);
|
||||
Map<String, Object> saved;
|
||||
try {
|
||||
return detail(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_UPDATE), MAP, body).getBody());
|
||||
saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_UPDATE), MAP, body).getBody();
|
||||
} catch (HttpClientErrorException.NotFound e) {
|
||||
throw notFound();
|
||||
}
|
||||
// field names only: lead values are personal data. No readable before-state means nothing is recorded.
|
||||
if (before != null) {
|
||||
List<String> changed = new ArrayList<>();
|
||||
for (String f : List.of("name", "mobileE164", "email", "companyName", "jobTitle", "notes")) {
|
||||
if (!Objects.equals(before.get(f), body.get(f))) changed.add("mobileE164".equals(f) ? "phone" : f);
|
||||
}
|
||||
if (!changed.isEmpty()) AuditChanges.fields(changed.toArray(String[]::new));
|
||||
}
|
||||
return detail(saved);
|
||||
}
|
||||
|
||||
/** Best-effort read of the lead before it is changed, for the audit trail only. */
|
||||
private Map<String, Object> storedOrNull(Long companyId, long id) {
|
||||
try {
|
||||
return restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_DETAIL), MAP, companyId, id).getBody();
|
||||
} catch (RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Digits to match against the stored E.164 mobile, or null when the term is not a phone-like number. */
|
||||
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/** Passes the Login security screen's calls to services-system, turning its 400s into coded admin errors. */
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdminLoginSecurityService {
|
||||
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<List<Map<String, Object>>> LIST = new ParameterizedTypeReference<>() {};
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
|
||||
public Map<String, Object> audit(String username, String event, String from, String to, int page, int size) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
if (StringUtils.hasText(username)) body.put("username", username.trim());
|
||||
if (StringUtils.hasText(event)) body.put("event", event.trim());
|
||||
if (StringUtils.hasText(from)) body.put("from", from.trim());
|
||||
if (StringUtils.hasText(to)) body.put("to", to.trim());
|
||||
body.put("page", page);
|
||||
body.put("size", size);
|
||||
return post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_AUDIT, MAP, body);
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> locked() {
|
||||
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_LOCKED), LIST).getBody();
|
||||
}
|
||||
|
||||
public void unlock(String username) {
|
||||
String by = callerName();
|
||||
post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_UNLOCK, MAP, Map.of("username", username, "by", by));
|
||||
log.info("login lock for {} cleared by {}", username, by);
|
||||
}
|
||||
|
||||
public Map<String, Object> config() {
|
||||
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_CONFIG), MAP).getBody();
|
||||
}
|
||||
|
||||
public Map<String, Object> saveConfig(Map<String, Object> config) {
|
||||
Map<String, Object> before = readOrNull(this::config);
|
||||
Map<String, Object> saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_CONFIG, MAP, config);
|
||||
if (before != null && saved != null) {
|
||||
for (String key : List.of("enabled", "maxAttempts", "period", "unit")) {
|
||||
if (!Objects.equals(before.get(key), saved.get(key))) AuditChanges.put(key, before.get(key), saved.get(key));
|
||||
}
|
||||
}
|
||||
log.info("lockout settings changed by {}", callerName());
|
||||
return saved;
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> passwordRules() {
|
||||
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_PASSWORD_RULES), LIST).getBody();
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> savePasswordRules(List<Map<String, Object>> rules) {
|
||||
List<Map<String, Object>> before = readOrNull(this::passwordRules);
|
||||
List<Map<String, Object>> saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_PASSWORD_RULES, LIST, rules);
|
||||
if (before != null && saved != null) {
|
||||
Map<Object, Map<String, Object>> old = new HashMap<>();
|
||||
before.forEach(b -> old.put(b.get("param"), b));
|
||||
for (Map<String, Object> now : saved) {
|
||||
Map<String, Object> was = old.get(now.get("param"));
|
||||
if (was != null && !(Objects.equals(was.get("status"), now.get("status")) && Objects.equals(was.get("value"), now.get("value")))) {
|
||||
AuditChanges.put(String.valueOf(now.get("param")), ruleState(was), ruleState(now));
|
||||
}
|
||||
}
|
||||
}
|
||||
log.info("password rules changed by {}", callerName());
|
||||
return saved;
|
||||
}
|
||||
|
||||
private static Map<String, Object> ruleState(Map<String, Object> rule) {
|
||||
Map<String, Object> state = new HashMap<>();
|
||||
state.put("status", rule.get("status"));
|
||||
state.put("value", rule.get("value"));
|
||||
return state;
|
||||
}
|
||||
|
||||
/** Best-effort read of the settings before they change, for the audit trail only. */
|
||||
private static <T> T readOrNull(Supplier<T> read) {
|
||||
try {
|
||||
return read.get();
|
||||
} catch (RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T post(String api, ParameterizedTypeReference<T> type, Object body) {
|
||||
return upstream(() -> restTemplateUtil.postForEntity(url(api), type, body).getBody());
|
||||
}
|
||||
|
||||
private static <T> T upstream(Supplier<T> call) {
|
||||
try {
|
||||
return call.get();
|
||||
} catch (HttpClientErrorException.BadRequest e) {
|
||||
throw new CodedResponseStatusException(HttpStatus.BAD_REQUEST, reason(e), "INVALID_SETTING");
|
||||
}
|
||||
}
|
||||
|
||||
private static String reason(HttpClientErrorException e) {
|
||||
try {
|
||||
JsonNode message = JSON.readTree(e.getResponseBodyAsString()).get("message");
|
||||
if (message != null && message.isTextual() && StringUtils.hasText(message.asText())) return message.asText();
|
||||
} catch (Exception ignored) {
|
||||
// empty or unparsable body: fall through to the generic reason
|
||||
}
|
||||
return "Invalid request";
|
||||
}
|
||||
|
||||
private String callerName() {
|
||||
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (caller == null) throw new CodedResponseStatusException(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
|
||||
return caller.getUsername();
|
||||
}
|
||||
|
||||
private String url(String api) {
|
||||
return restTemplateUtil.getURLforApiService(api);
|
||||
}
|
||||
}
|
||||
+16
-1
@@ -6,6 +6,7 @@ import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.dto.admin.AdminRoleRef;
|
||||
import com.solvway.mobile.api.dto.admin.AdminUserRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -115,6 +116,8 @@ public class AdminUserService {
|
||||
if (adminAuthenticationService.setAdminPassword(((Number) saved.get("id")).longValue(), r.password()) == 0) {
|
||||
throw error(HttpStatus.INTERNAL_SERVER_ERROR, "User created but the password was not stored; set a temporary password", "SAVE_FAILED");
|
||||
}
|
||||
AuditChanges.put("roles", null, sortedRoleNames(user.get("roles")));
|
||||
AuditChanges.put("enabled", null, true);
|
||||
return clean(saved);
|
||||
}
|
||||
|
||||
@@ -132,6 +135,8 @@ public class AdminUserService {
|
||||
if (r.roles() != null && r.roles().isEmpty()) {
|
||||
throw error(HttpStatus.BAD_REQUEST, "At least one role is required", "REQUIRED_FIELD");
|
||||
}
|
||||
List<String> rolesBefore = sortedRoleNames(user.get("roles"));
|
||||
Object enabledBefore = user.get("enabled");
|
||||
if (StringUtils.hasText(r.name())) user.put("name", r.name());
|
||||
if (r.surname() != null) user.put("surname", r.surname());
|
||||
if (StringUtils.hasText(r.email())) user.put("email", r.email());
|
||||
@@ -141,7 +146,12 @@ public class AdminUserService {
|
||||
user.put("status", r.enabled() ? "Y" : "N");
|
||||
}
|
||||
user.put("doneBy", caller.getUsername());
|
||||
return clean(save(user));
|
||||
Map<String, Object> saved = save(user);
|
||||
// names and ids only: never the user's name, surname or email
|
||||
List<String> rolesAfter = sortedRoleNames(user.get("roles"));
|
||||
if (r.roles() != null && !rolesBefore.equals(rolesAfter)) AuditChanges.put("roles", rolesBefore, rolesAfter);
|
||||
if (r.enabled() != null && !r.enabled().equals(enabledBefore)) AuditChanges.put("enabled", enabledBefore, r.enabled());
|
||||
return clean(saved);
|
||||
}
|
||||
|
||||
public int resetPassword(Long id) {
|
||||
@@ -301,6 +311,11 @@ public class AdminUserService {
|
||||
return Comparator.comparing(m -> String.valueOf(m.get(key)).toLowerCase());
|
||||
}
|
||||
|
||||
private static List<String> sortedRoleNames(Object roles) {
|
||||
if (!(roles instanceof List<?> l)) return List.of();
|
||||
return l.stream().map(r -> r instanceof Map<?, ?> rm ? String.valueOf(rm.get("name")) : String.valueOf(r)).sorted().toList();
|
||||
}
|
||||
|
||||
private static String roleNames(Map<String, Object> m) {
|
||||
Object roles = m.get("roles");
|
||||
if (!(roles instanceof List<?> l)) return "";
|
||||
|
||||
+130
-9
@@ -1,10 +1,12 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.enums.GeneralEnum.CmsPlatform;
|
||||
import com.solvway.core.enums.GeneralEnum.FlagYesNo;
|
||||
import com.solvway.core.enums.JwtEnum.JwtCustomClaim;
|
||||
import com.solvway.core.model.AuditEvent;
|
||||
import com.solvway.core.model.Role;
|
||||
import com.solvway.core.model.ResponseTime;
|
||||
import com.solvway.core.model.User;
|
||||
@@ -15,6 +17,7 @@ import com.solvway.core.utils.SnowflakeIdWorker;
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.mobile.api.config.AuthAppKeyConfig;
|
||||
import com.solvway.mobile.api.config.PubSubConfig;
|
||||
import com.solvway.mobile.api.controller.admin.AdminAuthController;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.UserService;
|
||||
@@ -29,6 +32,7 @@ import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
@@ -40,6 +44,7 @@ import org.springframework.web.servlet.HandlerMapping;
|
||||
import java.lang.reflect.Method;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -102,29 +107,144 @@ public class AppAccessAspect {
|
||||
maskKey(apiKey), authAppKey.getList().size());
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid header 'api-key'");
|
||||
}
|
||||
User[] admin = new User[1];
|
||||
Object result = null;
|
||||
Throwable thrown = null;
|
||||
try {
|
||||
if(!shouldSkipAuth(joinPoint)){
|
||||
String jwt = validateJwt();
|
||||
requireAdminAccess(joinPoint, jwt);
|
||||
requireAdminAccess(joinPoint, jwt, admin);
|
||||
requireVerifiedPhoneForCp(joinPoint, apiKey);
|
||||
}
|
||||
return joinPoint.proceed();
|
||||
result = joinPoint.proceed();
|
||||
return result;
|
||||
} catch (ResponseStatusException ex) {
|
||||
thrown = ex;
|
||||
log.warn("[AppAccessAspect] REJECT: {} for method={}", ex.getReason(), methodSig);
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
thrown = ex;
|
||||
log.error(StackTraceUtil.getStackTraceAsJsonString(ex));
|
||||
throw ex;
|
||||
} catch (Error err) {
|
||||
thrown = err;
|
||||
throw err;
|
||||
} finally {
|
||||
long executionTime = System.currentTimeMillis() - start;
|
||||
long uuid = SnowflakeIdWorker.getUUID();
|
||||
String username = getUsernameFromJwt();
|
||||
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
|
||||
ResponseTime logBean = buildResponseTimeLog(uuid, apiKey, username, executionTime, methodSignature);
|
||||
publishLogSafely(logBean);
|
||||
try {
|
||||
long executionTime = System.currentTimeMillis() - start;
|
||||
long uuid = SnowflakeIdWorker.getUUID();
|
||||
String username = getUsernameFromJwt();
|
||||
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
|
||||
ResponseTime logBean = buildResponseTimeLog(uuid, apiKey, username, executionTime, methodSignature);
|
||||
publishLogSafely(logBean);
|
||||
publishAudit(joinPoint, admin[0], result, thrown);
|
||||
} finally {
|
||||
AuditChanges.clear(); // pooled threads: never leave one request's changes for the next
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort audit event for an admin call (add-admin-audit-log). Never throws: a failure is logged at WARN
|
||||
* with the exception class only and the response is unaffected.
|
||||
*/
|
||||
private void publishAudit(ProceedingJoinPoint joinPoint, User admin, Object result, Throwable thrown) {
|
||||
try {
|
||||
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
|
||||
if (!isAdminPath() || !isAudited(method, requestOrNull().getMethod())) {
|
||||
return;
|
||||
}
|
||||
int status = auditStatus(result, thrown);
|
||||
String actor = admin != null ? admin.getUsername() : null;
|
||||
if (actor == null && admin == null && status == HttpStatus.FORBIDDEN.value()) {
|
||||
// Refused before the user was loaded (PASSWORD_RESET_REQUIRED): the actor is the admin token's user.
|
||||
String jwt = HttpReqRespUtils.getJwtToken();
|
||||
if ("A".equals(userTypeClaim(jwt))) {
|
||||
actor = authenticationService.getUsernameFromToken(jwt);
|
||||
}
|
||||
}
|
||||
if (actor == null) {
|
||||
return;
|
||||
}
|
||||
HttpServletRequest request = requestOrNull();
|
||||
AuditEvent event = new AuditEvent();
|
||||
event.setCompanyId(admin != null ? admin.getCompanyId() : null);
|
||||
event.setOccurredAt(LocalDateTime.now());
|
||||
event.setActor(actor);
|
||||
AdminModule onMethod = method.getAnnotation(AdminModule.class);
|
||||
AdminModule declared = onMethod != null ? onMethod : method.getDeclaringClass().getAnnotation(AdminModule.class);
|
||||
event.setModule(declared == null || Arrays.asList(declared.value()).contains(AdminModule.ANY_ADMIN)
|
||||
? null : String.join(",", declared.value()));
|
||||
Audited audited = method.getAnnotation(Audited.class);
|
||||
event.setAction(audited != null && StringUtils.hasText(audited.action()) ? audited.action()
|
||||
: defaultAuditAction(method.getDeclaringClass().getSimpleName(), method.getName()));
|
||||
event.setHttpMethod(request.getMethod());
|
||||
Object pattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
|
||||
event.setPathTemplate(pattern == null ? null : pattern.toString());
|
||||
// The last path variable is the record acted on (/events/{eventUuid}/leads/{eventLeadUuid}); Spring
|
||||
// fills the map in template order.
|
||||
if ((audited == null || audited.target())
|
||||
&& request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE) instanceof Map<?, ?> vars
|
||||
&& !vars.isEmpty()) {
|
||||
Object last = null;
|
||||
for (Object v : vars.values()) last = v;
|
||||
event.setTargetId(String.valueOf(last));
|
||||
}
|
||||
event.setHttpStatus(status);
|
||||
event.setOutcome(status >= 200 && status < 300 ? AuditEvent.OUTCOME_SUCCESS : AuditEvent.OUTCOME_FAILURE);
|
||||
String ip = request.getHeader("X-Client-Ip");
|
||||
event.setClientIp(ip == null || ip.length() <= 64 ? ip : ip.substring(0, 64));
|
||||
Map<String, Object> changes = AuditChanges.current();
|
||||
if (changes != null && !changes.isEmpty()) {
|
||||
event.setChanges(AUDIT_JSON.writeValueAsString(changes));
|
||||
}
|
||||
pubSubUtil.publishMessage(pubSubTemplate, pubSubConfig.auditEventTopic, event);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[AppAccessAspect] audit event dropped: {}", ex.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
private static final ObjectMapper AUDIT_JSON = new ObjectMapper();
|
||||
|
||||
private static HttpServletRequest requestOrNull() {
|
||||
return RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs
|
||||
? attrs.getRequest() : null;
|
||||
}
|
||||
|
||||
/** Writes, and GETs marked {@code @Audited}, unless skipped; login, logout and the like are never recorded. */
|
||||
private static boolean isAudited(Method method, String httpMethod) {
|
||||
Audited audited = method.getAnnotation(Audited.class);
|
||||
if (audited != null && audited.skip()) {
|
||||
return false;
|
||||
}
|
||||
if (method.getDeclaringClass() == AdminAuthController.class && !"firstLogin".equals(method.getName())) {
|
||||
return false;
|
||||
}
|
||||
return !"GET".equalsIgnoreCase(httpMethod) || audited != null;
|
||||
}
|
||||
|
||||
/** {@code AdminUserController.update} becomes {@code USER_UPDATE}. */
|
||||
static String defaultAuditAction(String simpleClassName, String methodName) {
|
||||
String type = simpleClassName.replaceFirst("^Admin(?=.)", "").replaceFirst("(?<=.)Controller$", "");
|
||||
return upperSnake(type) + "_" + upperSnake(methodName);
|
||||
}
|
||||
|
||||
private static String upperSnake(String camel) {
|
||||
return camel.replaceAll("([a-z0-9])([A-Z])", "$1_$2")
|
||||
.replaceAll("([A-Z]+)([A-Z][a-z])", "$1_$2")
|
||||
.toUpperCase(java.util.Locale.ROOT);
|
||||
}
|
||||
|
||||
private static int auditStatus(Object result, Throwable thrown) {
|
||||
if (thrown instanceof ResponseStatusException rse) {
|
||||
return rse.getStatusCode().value();
|
||||
}
|
||||
if (thrown != null) {
|
||||
return HttpStatus.INTERNAL_SERVER_ERROR.value();
|
||||
}
|
||||
return result instanceof ResponseEntity<?> entity ? entity.getStatusCode().value() : HttpStatus.OK.value();
|
||||
}
|
||||
|
||||
private String getUsernameFromJwt() {
|
||||
String username = "APP_PUBLIC";
|
||||
String jwt = HttpReqRespUtils.getJwtToken();
|
||||
@@ -235,7 +355,7 @@ public class AppAccessAspect {
|
||||
private static final long INJECTED_ROLE_ADMIN_ID = 2L;
|
||||
|
||||
/** Admin paths: admin token, live and enabled session, and a granted BO module. Fails closed. */
|
||||
private void requireAdminAccess(ProceedingJoinPoint joinPoint, String jwt) {
|
||||
private void requireAdminAccess(ProceedingJoinPoint joinPoint, String jwt, User[] adminOut) {
|
||||
if (!isAdminPath()) {
|
||||
return;
|
||||
}
|
||||
@@ -247,6 +367,7 @@ public class AppAccessAspect {
|
||||
AdminModule declared = onMethod != null ? onMethod : method.getDeclaringClass().getAnnotation(AdminModule.class);
|
||||
// allowPendingReset is honoured on the method only, so it never opens a whole controller.
|
||||
User admin = adminSessionGuard.check(jwt, onMethod != null && onMethod.allowPendingReset());
|
||||
adminOut[0] = admin;
|
||||
if (declared != null && Arrays.asList(declared.value()).contains(AdminModule.ANY_ADMIN)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* What an audited handler changed, collected for the current request thread and attached to its audit event by
|
||||
* {@link AppAccessAspect}, which always clears it afterwards. Callers pass allow-listed fields only: never
|
||||
* passwords, tokens or identity numbers.
|
||||
*/
|
||||
public final class AuditChanges {
|
||||
|
||||
private static final ThreadLocal<Map<String, Object>> CURRENT = new ThreadLocal<>();
|
||||
|
||||
private AuditChanges() {
|
||||
}
|
||||
|
||||
/** One allow-listed field's value before and after the change. */
|
||||
public static void put(String field, Object before, Object after) {
|
||||
Map<String, Object> changes = CURRENT.get();
|
||||
if (changes == null) {
|
||||
changes = new LinkedHashMap<>();
|
||||
CURRENT.set(changes);
|
||||
}
|
||||
Map<String, Object> change = new LinkedHashMap<>();
|
||||
change.put("before", before);
|
||||
change.put("after", after);
|
||||
changes.put(field, change);
|
||||
}
|
||||
|
||||
/** Names of the fields that changed, without values. */
|
||||
public static void fields(String... names) {
|
||||
Map<String, Object> changes = CURRENT.get();
|
||||
if (changes == null) {
|
||||
changes = new LinkedHashMap<>();
|
||||
CURRENT.set(changes);
|
||||
}
|
||||
changes.put("fields", List.of(names));
|
||||
}
|
||||
|
||||
public static Map<String, Object> current() {
|
||||
return CURRENT.get();
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
CURRENT.remove();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Audit marking for an {@code /api/admin/**} handler, read by {@link AppAccessAspect}. Every non-GET handler is
|
||||
* audited by default; this annotation names the action, makes a sensitive GET audited, or {@code skip = true}
|
||||
* excludes a read-only POST.
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface Audited {
|
||||
|
||||
/** Stable action key; empty means derived from the controller and method name. */
|
||||
String action() default "";
|
||||
|
||||
/** Never audit this handler (read-only POST). */
|
||||
boolean skip() default false;
|
||||
|
||||
/** False when the path variable is free text a person typed (e.g. a username from a failed sign-in): no target is recorded. */
|
||||
boolean target() default true;
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.mobile.api.service.AdminAuditLogService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdminAuditLogControllerTest {
|
||||
|
||||
@Mock private AdminAuditLogService audit;
|
||||
@InjectMocks private AdminAuditLogController controller;
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.standaloneSetup(controller).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void classLevelModule_notOverriddenOrAudited() {
|
||||
assertThat(AdminAuditLogController.class.getAnnotation(AdminModule.class).value()).containsExactly("BO_AUDIT_LOG");
|
||||
for (Method m : AdminAuditLogController.class.getDeclaredMethods()) {
|
||||
assertThat(m.getAnnotation(AdminModule.class)).isNull();
|
||||
assertThat(m.getAnnotation(Audited.class)).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_passesEveryParam() throws Exception {
|
||||
when(audit.search("boss", "LEADS", "UPDATE", "SUCCESS", "2026-11-01", "2026-11-30", 1, 5))
|
||||
.thenReturn(Map.of("content", List.of(Map.of("id", 7))));
|
||||
mvc.perform(get("/api/admin/audit-log").param("actor", "boss").param("module", "LEADS").param("action", "UPDATE")
|
||||
.param("outcome", "SUCCESS").param("from", "2026-11-01").param("to", "2026-11-30")
|
||||
.param("page", "1").param("size", "5"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.content[0].id").value(7));
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_defaultsToFirstPageOfTwenty() throws Exception {
|
||||
when(audit.search(null, null, null, null, null, null, 0, 20)).thenReturn(Map.of());
|
||||
mvc.perform(get("/api/admin/audit-log")).andExpect(status().isOk());
|
||||
verify(audit).search(null, null, null, null, null, null, 0, 20);
|
||||
}
|
||||
|
||||
@Test
|
||||
void detail_returnsEvent() throws Exception {
|
||||
when(audit.get(9L)).thenReturn(Map.of("id", 9));
|
||||
mvc.perform(get("/api/admin/audit-log/9")).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(9));
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminChangePasswordRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.service.AdminAuthenticationService;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.ResultActions;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdminAuthControllerChangePasswordTest {
|
||||
|
||||
@Mock private AdminAuthenticationService auth;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@InjectMocks private AdminAuthController controller;
|
||||
|
||||
private MockMvc mvc;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.standaloneSetup(controller).build();
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private void caller() {
|
||||
User u = new User();
|
||||
u.setId(9L);
|
||||
u.setUsername("admin.user");
|
||||
when(auth.loadUserByToken("tok")).thenReturn(u);
|
||||
}
|
||||
|
||||
private ResultActions change(String current, String next, String confirm) throws Exception {
|
||||
String body = "{\"currentPassword\":" + q(current) + ",\"newPassword\":" + q(next)
|
||||
+ ",\"confirmPassword\":" + q(confirm) + "}";
|
||||
return mvc.perform(post("/api/admin/auth/change-password").contentType(MediaType.APPLICATION_JSON).content(body));
|
||||
}
|
||||
|
||||
private static String q(String s) { return s == null ? "null" : "\"" + s + "\""; }
|
||||
|
||||
private void assertCoded(ResultActions r, HttpStatus status, String code, String message) {
|
||||
Exception ex = r.andReturn().getResolvedException();
|
||||
assertThat(ex).isInstanceOf(CodedResponseStatusException.class);
|
||||
CodedResponseStatusException c = (CodedResponseStatusException) ex;
|
||||
assertThat(c.getStatusCode()).isEqualTo(status);
|
||||
assertThat(c.getCode()).isEqualTo(code);
|
||||
assertThat(c.getReason()).isEqualTo(message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullCaller_is401() throws Exception {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(null);
|
||||
change("old", "new", "new").andExpect(status().isUnauthorized());
|
||||
verify(auth, never()).changeAdminPassword(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankField_is400RequiredField() throws Exception {
|
||||
caller();
|
||||
assertCoded(change("old", " ", "new"), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD",
|
||||
"Current password, new password and confirmation are required");
|
||||
assertCoded(change(null, "new", "new"), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD",
|
||||
"Current password, new password and confirmation are required");
|
||||
verify(auth, never()).changeAdminPassword(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mismatch_is400PasswordMismatch() throws Exception {
|
||||
caller();
|
||||
assertCoded(change("old", "new", "other"), HttpStatus.BAD_REQUEST, "PASSWORD_MISMATCH", "Passwords do not match");
|
||||
verify(auth, never()).changeAdminPassword(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void locked_is400AndServicesSystemNotCalled() throws Exception {
|
||||
caller();
|
||||
when(auth.isLocked("admin.user")).thenReturn(true);
|
||||
assertCoded(change("old", "new", "new"), HttpStatus.BAD_REQUEST, "ACCOUNT_LOCKED",
|
||||
"Too many failed sign-ins. Try again later or ask an administrator to unlock your account.");
|
||||
verify(auth, never()).changeAdminPassword(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void currentPasswordWrong_recordsLoginFailAnd400() throws Exception {
|
||||
caller();
|
||||
when(auth.changeAdminPassword(9L, "old", "new")).thenReturn("CURRENT_PASSWORD_WRONG");
|
||||
assertCoded(change("old", "new", "new"), HttpStatus.BAD_REQUEST, "CURRENT_PASSWORD_WRONG",
|
||||
"Current password is incorrect");
|
||||
verify(auth).record("admin.user", "LOGIN_FAIL", "change-password");
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordSame_is400() throws Exception {
|
||||
caller();
|
||||
when(auth.changeAdminPassword(9L, "old", "old")).thenReturn("PASSWORD_SAME");
|
||||
assertCoded(change("old", "old", "old"), HttpStatus.BAD_REQUEST, "PASSWORD_SAME",
|
||||
"The new password must differ from the current one");
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordPolicy_is400() throws Exception {
|
||||
caller();
|
||||
when(auth.changeAdminPassword(9L, "old", "weak")).thenReturn("PASSWORD_POLICY");
|
||||
assertCoded(change("old", "weak", "weak"), HttpStatus.BAD_REQUEST, "PASSWORD_POLICY",
|
||||
"Password does not meet the password policy");
|
||||
}
|
||||
|
||||
@Test
|
||||
void notFoundOrUnknown_is500SaveFailed() throws Exception {
|
||||
caller();
|
||||
when(auth.changeAdminPassword(9L, "old", "new")).thenReturn("NOT_FOUND");
|
||||
assertCoded(change("old", "new", "new"), HttpStatus.INTERNAL_SERVER_ERROR, "SAVE_FAILED",
|
||||
"The password was not changed");
|
||||
when(auth.changeAdminPassword(9L, "old", "new2")).thenReturn("???");
|
||||
assertCoded(change("old", "new2", "new2"), HttpStatus.INTERNAL_SERVER_ERROR, "SAVE_FAILED",
|
||||
"The password was not changed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ok_recordsPasswordChanged_204_andKeepsSession() throws Exception {
|
||||
caller();
|
||||
when(auth.changeAdminPassword(9L, "old", "new")).thenReturn("OK");
|
||||
change("old", "new", "new").andExpect(status().isNoContent());
|
||||
verify(auth).record("admin.user", "PASSWORD_CHANGED", null);
|
||||
verifyNoInteractions(authenticationService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestToString_hidesPasswords() {
|
||||
String s = new AdminChangePasswordRequest("curSecret1", "newSecret2", "confSecret3").toString();
|
||||
assertThat(s).doesNotContain("curSecret1").doesNotContain("newSecret2").doesNotContain("confSecret3");
|
||||
}
|
||||
|
||||
@Test
|
||||
void handler_refusesPendingFirstLogin() throws Exception {
|
||||
AdminModule m = AdminAuthController.class
|
||||
.getMethod("changePassword", AdminChangePasswordRequest.class).getAnnotation(AdminModule.class);
|
||||
assertThat(m.value()).containsExactly(AdminModule.ANY_ADMIN);
|
||||
assertThat(m.allowPendingReset()).isFalse();
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.Role;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.service.AdminAuthenticationService;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.ResultActions;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdminAuthControllerLoginSecurityTest {
|
||||
|
||||
@Mock private AdminAuthenticationService auth;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@InjectMocks private AdminAuthController controller;
|
||||
|
||||
private MockMvc mvc;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.standaloneSetup(controller).build();
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private User user(boolean enabled) {
|
||||
User u = new User();
|
||||
u.setId(9L);
|
||||
u.setName("Admin User");
|
||||
u.setUsername("admin");
|
||||
u.setEnabled(enabled);
|
||||
u.setLogin(GeneralEnum.LoginStatus.Y);
|
||||
u.setRoles(List.of(new Role("ROLE_ADMIN")));
|
||||
return u;
|
||||
}
|
||||
|
||||
private ResultActions login(String username, String password) throws Exception {
|
||||
return mvc.perform(post("/api/admin/auth/login").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankFields_recordNothing_andSkipLockCheck() throws Exception {
|
||||
login("admin", "").andExpect(status().isUnauthorized());
|
||||
login(" ", "pw").andExpect(status().isUnauthorized());
|
||||
verify(auth, never()).isLocked(anyString());
|
||||
verify(auth, never()).record(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void locked_is401AccountLocked_recordsLocked_andSkipsServicesAuth() throws Exception {
|
||||
when(auth.isLocked("admin")).thenReturn(true);
|
||||
|
||||
login("admin", "pw").andExpect(status().isUnauthorized())
|
||||
.andExpect(content().json("{\"result\":\"false\",\"code\":\"ACCOUNT_LOCKED\",\"message\":"
|
||||
+ "\"Too many failed sign-ins. Try again later or ask an administrator to unlock your account.\"}"));
|
||||
verify(auth).record("admin", "LOGIN_LOCKED", null);
|
||||
verify(auth, never()).getToken(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrongPassword_recordsFail() throws Exception {
|
||||
when(auth.getToken(any())).thenReturn("");
|
||||
|
||||
login("admin", "pw").andExpect(status().isUnauthorized())
|
||||
.andExpect(jsonPath("$.message").value("Invalid username or password"));
|
||||
verify(auth).record("admin", "LOGIN_FAIL", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownUser_noToken_recordsFail() throws Exception {
|
||||
when(auth.getToken(any())).thenReturn(null);
|
||||
|
||||
login("ghost", "pw").andExpect(status().isUnauthorized());
|
||||
verify(auth).record("ghost", "LOGIN_FAIL", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void userNull_recordsFail() throws Exception {
|
||||
when(auth.getToken(any())).thenReturn("t");
|
||||
when(auth.loadUserByToken("t")).thenReturn(null);
|
||||
|
||||
login("admin", "pw").andExpect(status().isUnauthorized());
|
||||
verify(auth).record("admin", "LOGIN_FAIL", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledUser_recordsFail() throws Exception {
|
||||
when(auth.getToken(any())).thenReturn("t");
|
||||
when(auth.loadUserByToken("t")).thenReturn(user(false));
|
||||
|
||||
login("admin", "pw").andExpect(status().isUnauthorized());
|
||||
verify(auth).record("admin", "LOGIN_FAIL", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void restClientException_recordsFail() throws Exception {
|
||||
when(auth.getToken(any())).thenThrow(new org.springframework.web.client.ResourceAccessException("down"));
|
||||
|
||||
login("admin", "pw").andExpect(status().isUnauthorized());
|
||||
verify(auth).record("admin", "LOGIN_FAIL", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void success_recordsSuccess() throws Exception {
|
||||
when(auth.getToken(any())).thenReturn("t");
|
||||
when(auth.loadUserByToken("t")).thenReturn(user(true));
|
||||
|
||||
login("admin", "pw").andExpect(status().isOk()).andExpect(jsonPath("$.token").value("t"));
|
||||
verify(auth).record("admin", "LOGIN_SUCCESS", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void username_isTrimmedForLockCheckAndRecord() throws Exception {
|
||||
when(auth.getToken(any())).thenReturn("t");
|
||||
when(auth.loadUserByToken("t")).thenReturn(user(true));
|
||||
|
||||
login(" admin ", "pw").andExpect(status().isOk());
|
||||
verify(auth).isLocked("admin");
|
||||
verify(auth).record("admin", "LOGIN_SUCCESS", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void logout_recordsLogoutForTokenUser_beforeRevoking() throws Exception {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(true));
|
||||
|
||||
mvc.perform(post("/api/admin/auth/logout")).andExpect(status().isOk())
|
||||
.andExpect(content().json("{\"result\":\"true\"}"));
|
||||
verify(auth).record("admin", "LOGOUT", null);
|
||||
verify(authenticationService).logoutToken("tok");
|
||||
}
|
||||
|
||||
@Test
|
||||
void logout_nullUser_recordsNothing() throws Exception {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(null);
|
||||
|
||||
mvc.perform(post("/api/admin/auth/logout")).andExpect(status().isOk());
|
||||
verify(auth, never()).record(any(), any(), any());
|
||||
verify(authenticationService).logoutToken("tok");
|
||||
}
|
||||
|
||||
@Test
|
||||
void logout_loadUserThrows_stillReturns200() throws Exception {
|
||||
when(auth.loadUserByToken("tok")).thenThrow(new IllegalStateException("down"));
|
||||
|
||||
mvc.perform(post("/api/admin/auth/logout")).andExpect(status().isOk())
|
||||
.andExpect(content().json("{\"result\":\"true\"}"));
|
||||
verify(authenticationService).logoutToken("tok");
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.mobile.api.service.AdminLoginSecurityService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdminLoginSecurityControllerTest {
|
||||
|
||||
@Mock private AdminLoginSecurityService security;
|
||||
@InjectMocks private AdminLoginSecurityController controller;
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.standaloneSetup(controller).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void guardedByLoginSecurityModule() {
|
||||
assertThat(AdminLoginSecurityController.class.getAnnotation(AdminModule.class).value()).containsExactly("BO_LOGIN_SECURITY");
|
||||
}
|
||||
|
||||
@Test
|
||||
void audit_passesFiltersAndPaging() throws Exception {
|
||||
when(security.audit("sales1", "LOCKED", "2026-11-01", "2026-11-30", 1, 5))
|
||||
.thenReturn(Map.of("content", List.of(Map.of("id", 7)), "totalElements", 6));
|
||||
mvc.perform(get("/api/admin/login-security/audit").param("username", "sales1").param("event", "LOCKED")
|
||||
.param("from", "2026-11-01").param("to", "2026-11-30").param("page", "1").param("size", "5"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.content[0].id").value(7));
|
||||
}
|
||||
|
||||
@Test
|
||||
void audit_defaultsToFirstPageOfTwenty() throws Exception {
|
||||
when(security.audit(null, null, null, null, 0, 20)).thenReturn(Map.of("content", List.of()));
|
||||
mvc.perform(get("/api/admin/login-security/audit")).andExpect(status().isOk());
|
||||
verify(security).audit(null, null, null, null, 0, 20);
|
||||
}
|
||||
|
||||
@Test
|
||||
void locked_returnsList() throws Exception {
|
||||
when(security.locked()).thenReturn(List.of(Map.of("username", "sales1", "failures", 5)));
|
||||
mvc.perform(get("/api/admin/login-security/locked")).andExpect(status().isOk()).andExpect(jsonPath("$[0].username").value("sales1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unlock_returns204() throws Exception {
|
||||
mvc.perform(post("/api/admin/login-security/locked/sales1/unlock")).andExpect(status().isNoContent());
|
||||
verify(security).unlock("sales1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void config_getAndPut() throws Exception {
|
||||
when(security.config()).thenReturn(Map.of("maxAttempts", 5));
|
||||
mvc.perform(get("/api/admin/login-security/config")).andExpect(status().isOk()).andExpect(jsonPath("$.maxAttempts").value(5));
|
||||
Map<String, Object> body = Map.of("enabled", true, "maxAttempts", 3, "period", 15, "unit", "MINUTES");
|
||||
when(security.saveConfig(body)).thenReturn(body);
|
||||
mvc.perform(put("/api/admin/login-security/config").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"enabled\":true,\"maxAttempts\":3,\"period\":15,\"unit\":\"MINUTES\"}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.maxAttempts").value(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordRules_getAndPut() throws Exception {
|
||||
when(security.passwordRules()).thenReturn(List.of(Map.of("id", 1)));
|
||||
mvc.perform(get("/api/admin/login-security/password-rules")).andExpect(status().isOk()).andExpect(jsonPath("$[0].id").value(1));
|
||||
List<Map<String, Object>> body = List.of(Map.of("id", 1, "status", "Y", "value", "8"));
|
||||
when(security.savePasswordRules(body)).thenReturn(body);
|
||||
mvc.perform(put("/api/admin/login-security/password-rules").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("[{\"id\":1,\"status\":\"Y\",\"value\":\"8\"}]"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$[0].value").value("8"));
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.Role;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminAclServiceAuditChangesTest {
|
||||
|
||||
private static final long ROOT = 40000000L, USERS = 40700000L, ROLES = 40800000L, LEADS = 40900000L;
|
||||
|
||||
private AdminAclService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AuditChanges.clear();
|
||||
RestTemplateCustomUtil rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
AdminRoleService roles = mock(AdminRoleService.class);
|
||||
service = new AdminAclService(rest, auth, roles);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(roles.find(4L)).thenReturn(Map.of("id", 4L, "name", "ROLE_SALES"));
|
||||
// role 4 holds BO_USERS and BO_ROLES
|
||||
when(rest.getForEntity(eq("/module/findAllByArea/{area}"), any(ParameterizedTypeReference.class), eq("BO"))).thenReturn(ResponseEntity.ok(List.of(
|
||||
module(ROOT, "BO_ROOT", "R"),
|
||||
module(USERS, "BO_USERS", "M", 4),
|
||||
module(ROLES, "BO_ROLES", "M", 4),
|
||||
module(LEADS, "BO_LEADS", "M"))));
|
||||
User u = new User();
|
||||
u.setId(50L);
|
||||
Role r = new Role();
|
||||
r.setId(1L);
|
||||
u.setRoles(List.of(r));
|
||||
when(auth.loadUserByToken("tok")).thenReturn(u);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
http.close();
|
||||
AuditChanges.clear();
|
||||
}
|
||||
|
||||
private static Map<String, Object> module(long id, String name, String type, long... roleIds) {
|
||||
Map<String, Object> m = new HashMap<>();
|
||||
m.put("id", id);
|
||||
m.put("name", name);
|
||||
m.put("type", type);
|
||||
m.put("parent", "R".equals(type) ? null : ROOT);
|
||||
m.put("roles", java.util.Arrays.stream(roleIds).mapToObj(x -> (Object) Map.of("id", x, "name", "R" + x)).toList());
|
||||
return m;
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateGrants_recordsAddedAndRemovedModuleCodes() {
|
||||
service.updateGrants(4L, List.of(USERS, LEADS));
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("modulesAdded", "modulesRemoved");
|
||||
assertThat((Map<String, Object>) AuditChanges.current().get("modulesAdded")).containsEntry("after", List.of("BO_LEADS")).containsEntry("before", null);
|
||||
assertThat((Map<String, Object>) AuditChanges.current().get("modulesRemoved")).containsEntry("after", List.of("BO_ROLES")).containsEntry("before", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateGrants_recordsOnlyTheNonEmptySide() {
|
||||
service.updateGrants(4L, List.of(USERS, ROLES, LEADS));
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("modulesAdded");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateGrants_sameSetRecordsNothing() {
|
||||
service.updateGrants(4L, List.of(USERS, ROLES));
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
}
|
||||
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user