Compare commits

...
Author SHA1 Message Date
ngqileandClaude Opus 5.5 059107fbaa fix: harden the lockout after the branch review
Settings get upper limits (a huge period made every lock check fail
open), the lock check uses the same 191-character key the history
stores, login_audit.username compares like user.username, and the
module gets its own icon. Docs and design notes follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 14:59:06 +08:00
ngqileandClaude Opus 5.5 e240a9c37f docs: login security SQL and lockout notes in the deployment guide
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 14:52:15 +08:00
ngqileandClaude Opus 5.5 dd9bbbe036 fix: browser context on password-change history, plain settings errors, New password label
Found in the browser check: change-password history rows had no browser
or IP, settings errors named internal fields, and the dialog's new
password field read just "Password".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 14:52:15 +08:00
ngqileandClaude Opus 5.5 091503a820 feat: Login security screen with history, locked accounts and settings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 14:33:53 +08:00
ngqileandClaude Opus 5.5 6598b58cb8 feat: locked sign-in message and Change password dialog in the portal
mobile-api now records the browser user agent the portal forwards as
X-Client-User-Agent instead of the portal server's own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 14:16:11 +08:00
ngqileandClaude Opus 5.5 5ce684168a feat: admin API for login history, locked accounts, unlock and settings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 14:01:04 +08:00
ngqileandClaude Opus 5.5 6c6734baa3 feat: admin change-password endpoint with lockout on wrong current password
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 13:51:57 +08:00
ngqileandClaude Opus 5.5 39708224ad feat: lock check and login history on admin sign-in and sign-out
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 13:43:42 +08:00
ngqileandClaude Opus 5.5 f6fe246ad0 feat: services-system endpoint for an admin changing their own password
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 13:34:26 +08:00
ngqileandClaude Opus 5.5 f7ec74c7f0 feat: login history and lockout rule in services-system
LoginSecurityService derives the admin lock from login_audit and the
ADMIN_LOGIN_BLOCK settings; /loginSecurity exposes lock check, record,
history, locked list, unlock, lockout settings and password rules. The
gateway routes /loginSecurity/** and lets the lock check and record
through without a user token for the sign-in path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 13:26:20 +08:00
ngqileandClaude Opus 5.5 a0146be325 feat: login_audit table, lockout settings and Login security module SQL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 12:29:09 +08:00
ngqileandClaude Opus 5.5 bbf268e00a docs(openspec): propose add-admin-login-security
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 12:27:14 +08:00
ngqileandClaude Opus 5.5 c82498e5d8 docs: admin login security and own password change design
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 12:23:34 +08:00
ngqile 8f301e0ce5 Merge pull request 'docs(openspec): archive add-admin-email-listing' (#18) from archive-add-admin-email-listing into main
CI / build-and-publish (push) Failing after 0s
2026-11-30 04:15:01 +00:00
59 changed files with 4338 additions and 9 deletions

No files matched your search

+6
View File
@@ -76,6 +76,11 @@ After running `04`, `SELECT LENGTH(password) FROM \`service-system\`.\`user\` WH
| File | What it does | | 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-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.
**Database user:** **Database user:**
- Create one user with `SELECT, INSERT, UPDATE, DELETE, EXECUTE` on the five schemas. EXECUTE is needed: service-member calls a stored function. - Create one user with `SELECT, INSERT, UPDATE, DELETE, EXECUTE` on the five schemas. EXECUTE is needed: service-member calls a stored function.
@@ -264,6 +269,7 @@ data:
## 10. Known gaps at go-live ## 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. - **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. - **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. - **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. - **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.
@@ -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.
+27
View File
@@ -124,3 +124,30 @@ INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `ic
-- add-admin-email-listing/sql/01-email-module.sql -- add-admin-email-listing/sql/01-email-module.sql
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
(40900000, 'BO_EMAILS', 'Emails', 'BO', 'M', 40000000, '/emails', 'Mail'); (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');
@@ -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.
@@ -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
@@ -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;
@@ -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';
@@ -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,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) { if (!result.ok) {
// The mobile-api answers bad credentials with HTTP 401 directly (not the // 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. // 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 // A locked account is also a 401, but carries code ACCOUNT_LOCKED, which the
// errorResponse forwards as-is (4xx passthrough). // login page needs to show its own message; errorResponse keeps the code.
if (result.status === 401) return unauthorized(result.error); if (result.status === 401 && result.code !== "ACCOUNT_LOCKED") return unauthorized(result.error);
return errorResponse(result); 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,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"; "use client";
import { useState } from "react"; 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 { useRouter } from "next/navigation";
import { useAdminAuth } from "@/app/lib/AdminAuthContext"; import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { useTheme } from "@/app/lib/theme"; import { useTheme } from "@/app/lib/theme";
@@ -20,6 +20,7 @@ import { Sheet, SheetContent, SheetTitle } from "@/app/components/ui/sheet";
import Breadcrumbs from "./Breadcrumbs"; import Breadcrumbs from "./Breadcrumbs";
import { BrandLink, SidebarNav } from "./Sidebar"; import { BrandLink, SidebarNav } from "./Sidebar";
import LocaleSwitcher from "./LocaleSwitcher"; import LocaleSwitcher from "./LocaleSwitcher";
import ChangePasswordDialog from "./ChangePasswordDialog";
// The authenticated shell's header: user menu reads the signed-in name from // The authenticated shell's header: user menu reads the signed-in name from
// AdminAuthContext (session hydration, Task 5), and logout calls the // AdminAuthContext (session hydration, Task 5), and logout calls the
@@ -31,6 +32,8 @@ export default function Header() {
const t = useT(); const t = useT();
const router = useRouter(); const router = useRouter();
const [menuOpen, setMenuOpen] = useState(false); const [menuOpen, setMenuOpen] = useState(false);
const [changingPassword, setChangingPassword] = useState(false);
const [changed, setChanged] = useState(false);
async function handleLogout() { async function handleLogout() {
// Best-effort: /api/auth/logout clears the httpOnly cookie regardless of // 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> <span className="block text-sm font-medium">{name}</span>
</DropdownMenuLabel> </DropdownMenuLabel>
<DropdownMenuSeparator /> <DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setChangingPassword(true)}>
<KeyRound aria-hidden="true" className="size-4" />
{t("PwdChangeMenu")}
</DropdownMenuItem>
<DropdownMenuItem onClick={handleLogout}> <DropdownMenuItem onClick={handleLogout}>
<LogOut aria-hidden="true" className="size-4" /> <LogOut aria-hidden="true" className="size-4" />
{t("Logout")} {t("Logout")}
@@ -107,6 +114,20 @@ export default function Header() {
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
</div> </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> </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; disabled?: boolean;
passwordError?: string; passwordError?: string;
confirmError?: string; confirmError?: string;
/** i18n key for the first field's label; "Password" by default. */
passwordLabel?: string;
}) { }) {
const t = useT(); const t = useT();
return ( return (
<> <>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label htmlFor="user-password">{t("Password")}</Label> <Label htmlFor="user-password">{t(props.passwordLabel ?? "Password")}</Label>
<Input <Input
id="user-password" id="user-password"
type="password" type="password"
@@ -77,6 +77,12 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
NotFoundBody: "That route does not exist in the back office.", NotFoundBody: "That route does not exist in the back office.",
LayoutMetaDescription: "Co-Lite admin back office", LayoutMetaDescription: "Co-Lite admin back office",
LoginInvalidCredentials: "Invalid username or password", 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", LoginHidePassword: "Hide password",
LoginShowPassword: "Show password", LoginShowPassword: "Show password",
ResetAllRequired: "All fields are required.", ResetAllRequired: "All fields are required.",
@@ -318,4 +324,67 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
LeadsSameEmailAs: "Same email as", LeadsSameEmailAs: "Same email as",
LeadsSameMobileEmailAs: "Same mobile and email as", LeadsSameMobileEmailAs: "Same mobile and email as",
LeadsViewLead: "View lead", 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",
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", () => { it("leaves other routes ungated", () => {
expect(requiredModuleFor("/")).toBeUndefined(); expect(requiredModuleFor("/")).toBeUndefined();
expect(requiredModulesFor("/members")).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(["/emails", "/event-leads", "/events", "/interests", "/leads", "/login-security", "/roles", "/users"]);
expect(requiredModuleFor("/emails")).toBe("BO_EMAILS"); expect(requiredModuleFor("/emails")).toBe("BO_EMAILS");
expect(requiredModuleFor("/leads")).toBe("BO_LEADS"); expect(requiredModuleFor("/leads")).toBe("BO_LEADS");
}); });
@@ -10,6 +10,7 @@ export const ROUTE_MODULES: Record<string, string> = {
"/event-leads": "BO_EVENT_LEADS", "/event-leads": "BO_EVENT_LEADS",
"/leads": "BO_LEADS", "/leads": "BO_LEADS",
"/emails": "BO_EMAILS", "/emails": "BO_EMAILS",
"/login-security": "BO_LOGIN_SECURITY",
}; };
export function requiredModuleFor(pathname: string): string | undefined { export function requiredModuleFor(pathname: string): string | undefined {
@@ -63,6 +63,11 @@ export async function saveAdminUser(payload: AdminUser): Promise<AdminUser> {
: apiPost<AdminUser>("/api/users", payload); : 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. */ /** 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> { export async function setAdminUserPassword(id: number, password: string, confirmPassword: string): Promise<void> {
await apiPost<void>(`/api/users/${id}/password`, { password, confirmPassword }); await apiPost<void>(`/api/users/${id}/password`, { password, confirmPassword });
@@ -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();
});
});
+3 -2
View File
@@ -8,7 +8,7 @@ import { Button } from "@/app/components/ui/button";
import { Input } from "@/app/components/ui/input"; import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label"; import { Label } from "@/app/components/ui/label";
import { ErrorState } from "@/app/components/ui/states"; 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 { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { useT } from "@/app/lib/i18n/MessagesProvider"; import { useT } from "@/app/lib/i18n/MessagesProvider";
import PoweredBy from "@/app/components/app/PoweredBy"; 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. // replace keeps the root layout, whose locale list was loaded without a token; re-run it.
router.refresh(); router.refresh();
} catch (err) { } 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 { } finally {
setSubmitting(false); setSubmitting(false);
} }
@@ -133,6 +133,9 @@ public class JWTAuthFilter implements GlobalFilter, Ordered {
|| url.contains("/member/forgetPassword") || url.contains("/member/forgetPassword")
// Co-Lite admin forgot password (public; answers the same whether or not details match) // Co-Lite admin forgot password (public; answers the same whether or not details match)
|| url.equals("/user/resetAdminPassword") || 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/findByFirstLevelLocation")
|| url.contains("/geoLocationHierarchy/findAllByParentId") || url.contains("/geoLocationHierarchy/findAllByParentId")
// public content - no JWT required // public content - no JWT required
@@ -148,6 +148,10 @@ spring:
uri: http://${app.services.name.system} uri: http://${app.services.name.system}
predicates: predicates:
- Path=/blockLoginPeriod/** - Path=/blockLoginPeriod/**
- id: loginSecurity
uri: http://${app.services.name.system}
predicates:
- Path=/loginSecurity/**
- id: passwordAging - id: passwordAging
uri: http://${app.services.name.system} uri: http://${app.services.name.system}
predicates: predicates:
@@ -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);
}
}
}
@@ -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_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_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_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_FIRST_TIME_LOGIN="/user/memberFirstTimeLogin";
public static final String API_REST_SYSTEM_USER_VALIDATE_PASSWORD_RULES="/user/validatePasswordFromRulesForMember"; 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_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}"; 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 //Message
public static final String API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE = "/message/findByCodeAndLocale/{code}/{locale}"; public static final String API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE = "/message/findByCodeAndLocale/{code}/{locale}";
} }
@@ -4,10 +4,12 @@ import com.solvway.core.annotation.AppAuth;
import com.solvway.core.enums.GeneralEnum; import com.solvway.core.enums.GeneralEnum;
import com.solvway.core.model.User; import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils; 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.AdminFirstLoginRequest;
import com.solvway.mobile.api.dto.admin.AdminForgotPasswordRequest; import com.solvway.mobile.api.dto.admin.AdminForgotPasswordRequest;
import com.solvway.mobile.api.dto.admin.AdminLoginResponse; import com.solvway.mobile.api.dto.admin.AdminLoginResponse;
import com.solvway.mobile.api.dto.admin.AdminMeResponse; 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.model.AuthRequest;
import com.solvway.mobile.api.service.AdminAuthenticationService; import com.solvway.mobile.api.service.AdminAuthenticationService;
import com.solvway.mobile.api.service.AuthenticationService; import com.solvway.mobile.api.service.AuthenticationService;
@@ -34,6 +36,8 @@ import java.util.Map;
public class AdminAuthController { public class AdminAuthController {
private static final Map<String, String> BAD_LOGIN = private static final Map<String, String> BAD_LOGIN =
Map.of("result", "false", "message", "Invalid username or password"); 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 AdminAuthenticationService adminAuthenticationService;
private final AuthenticationService authenticationService; private final AuthenticationService authenticationService;
@@ -44,6 +48,11 @@ public class AdminAuthController {
if (!StringUtils.hasText(request.getUsername()) || !StringUtils.hasText(request.getPassword())) { if (!StringUtils.hasText(request.getUsername()) || !StringUtils.hasText(request.getPassword())) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(BAD_LOGIN); 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; String token;
User u; User u;
try { try {
@@ -60,8 +69,10 @@ public class AdminAuthController {
token = null; token = null;
} }
if (u == null) { if (u == null) {
adminAuthenticationService.record(username, "LOGIN_FAIL", null);
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(BAD_LOGIN); 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(), return ResponseEntity.ok(new AdminLoginResponse(token, u.getName(), u.getRoles(), u.getAclMenu(),
GeneralEnum.LoginStatus.N.equals(u.getLogin()) ? "true" : "false")); GeneralEnum.LoginStatus.N.equals(u.getLogin()) ? "true" : "false"));
} }
@@ -87,6 +98,46 @@ public class AdminAuthController {
return ResponseEntity.ok(Map.of("result", "true")); 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. */ /** Always 200 with the same body: the answer must not reveal whether username and email matched. */
@AppAuth(skipValidate = true) @AppAuth(skipValidate = true)
@PostMapping("/auth/forgot-password") @PostMapping("/auth/forgot-password")
@@ -105,7 +156,16 @@ public class AdminAuthController {
@AppAuth @AppAuth
@PostMapping("/auth/logout") @PostMapping("/auth/logout")
public ResponseEntity<Map<String, String>> 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")); return ResponseEntity.ok(Map.of("result", "true"));
} }
@@ -0,0 +1,77 @@
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 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());
}
@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));
}
}
@@ -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[]";
}
}
@@ -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.constant.api.RestApiSystemServiceConstants;
import com.solvway.mobile.api.model.AuthRequest; import com.solvway.mobile.api.model.AuthRequest;
import com.solvway.mobile.api.util.RestTemplateCustomUtil; import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service; 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.List;
import java.util.Map; import java.util.Map;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@Slf4j
public class AdminAuthenticationService { public class AdminAuthenticationService {
private final RestTemplateCustomUtil restTemplateUtil; private final RestTemplateCustomUtil restTemplateUtil;
@@ -58,6 +64,14 @@ public class AdminAuthenticationService {
return ent.getBody() == null ? 0 : ent.getBody(); 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). */ /** Emails a temporary password when username and email match an admin; returns rows updated (0 = no match). */
public int resetAdminPassword(String username, String email) { public int resetAdminPassword(String username, String email) {
ResponseEntity<Integer> ent = restTemplateUtil.postForEntity( ResponseEntity<Integer> ent = restTemplateUtil.postForEntity(
@@ -65,4 +79,37 @@ public class AdminAuthenticationService {
Integer.class, Map.of("username", username, "email", email)); Integer.class, Map.of("username", username, "email", email));
return ent.getBody() == null ? 0 : ent.getBody(); 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());
}
}
} }
@@ -0,0 +1,108 @@
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.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.LinkedHashMap;
import java.util.List;
import java.util.Map;
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> saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_CONFIG, MAP, config);
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>> saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_PASSWORD_RULES, LIST, rules);
log.info("password rules changed by {}", callerName());
return saved;
}
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);
}
}
@@ -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();
}
}
@@ -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");
}
}
@@ -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"));
}
}
@@ -0,0 +1,43 @@
package com.solvway.mobile.api.service;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.when;
class AdminAuthenticationServiceChangePasswordTest {
private RestTemplateCustomUtil rest;
private AdminAuthenticationService service;
@BeforeEach
void setUp() {
rest = mock(RestTemplateCustomUtil.class);
service = new AdminAuthenticationService(rest);
when(rest.getURLforApiService("/user/changeAdminPassword")).thenReturn("http://sys/user/changeAdminPassword");
}
@Test
void postsIdCurrentAndNewPassword_returnsBody() {
Map<String, Object> body = Map.of("id", 9L, "currentPassword", "old", "newPassword", "new");
when(rest.postForEntity(eq("http://sys/user/changeAdminPassword"), eq(String.class), eq(body)))
.thenReturn(ResponseEntity.ok("OK"));
assertThat(service.changeAdminPassword(9L, "old", "new")).isEqualTo("OK");
}
@Test
void nullBody_isNotFound() {
when(rest.postForEntity(any(String.class), eq(String.class), any(Object.class)))
.thenReturn(new ResponseEntity<>(HttpStatus.OK));
assertThat(service.changeAdminPassword(9L, "old", "new")).isEqualTo("NOT_FOUND");
}
}
@@ -0,0 +1,107 @@
package com.solvway.mobile.api.service;
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.ArgumentCaptor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@SuppressWarnings({"unchecked", "rawtypes"})
class AdminAuthenticationServiceLoginSecurityTest {
private RestTemplateCustomUtil rest;
private AdminAuthenticationService service;
@BeforeEach
void setUp() {
rest = mock(RestTemplateCustomUtil.class);
service = new AdminAuthenticationService(rest);
when(rest.getURLforApiService(any())).thenReturn("http://gw/loginSecurity/x");
}
@AfterEach
void clear() { RequestContextHolder.resetRequestAttributes(); }
@Test
void isLocked_true() {
when(rest.getForEntity(any(String.class), eq(Map.class), eq("sales1")))
.thenReturn(ResponseEntity.ok(Map.of("locked", true)));
assertThat(service.isLocked("sales1")).isTrue();
}
@Test
void isLocked_false() {
when(rest.getForEntity(any(String.class), eq(Map.class), eq("sales1")))
.thenReturn(ResponseEntity.ok(Map.of("locked", false)));
assertThat(service.isLocked("sales1")).isFalse();
}
@Test
void isLocked_exception_failsOpen() {
when(rest.getForEntity(any(String.class), eq(Map.class), eq("sales1")))
.thenThrow(new IllegalStateException("down"));
assertThat(service.isLocked("sales1")).isFalse();
}
@Test
void isLocked_non200_failsOpen() {
when(rest.getForEntity(any(String.class), eq(Map.class), eq("sales1")))
.thenReturn(new ResponseEntity<>(HttpStatus.NO_CONTENT));
assertThat(service.isLocked("sales1")).isFalse();
}
@Test
void record_swallowsExceptions() {
when(rest.postForEntity(any(String.class), eq(String.class), any()))
.thenThrow(new IllegalStateException("down"));
assertThatCode(() -> service.record("sales1", "LOGIN_FAIL", null)).doesNotThrowAnyException();
}
@Test
void record_sendsClientIpAndUserAgentFromRequest() {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Client-IP", "203.0.113.7");
req.addHeader("X-Client-User-Agent", "JUnit");
req.addHeader("User-Agent", "node");
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(req));
when(rest.postForEntity(any(String.class), eq(String.class), any())).thenReturn(ResponseEntity.ok(""));
service.record("sales1", "LOGIN_FAIL", "why");
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(any(String.class), eq(String.class), body.capture());
assertThat((Map<String, Object>) body.getValue()).containsOnly(
Map.entry("username", "sales1"), Map.entry("event", "LOGIN_FAIL"), Map.entry("ip", "203.0.113.7"),
Map.entry("userAgent", "JUnit"), Map.entry("message", "why"));
}
@Test
void record_noHeaders_sendsNullIpAndUserAgent() {
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest()));
when(rest.postForEntity(any(String.class), eq(String.class), any())).thenReturn(ResponseEntity.ok(""));
service.record("sales1", "LOGOUT", null);
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(any(String.class), eq(String.class), body.capture());
Map<String, Object> m = (Map<String, Object>) body.getValue();
assertThat(m.get("ip")).isNull();
assertThat(m.get("userAgent")).isNull();
assertThat(m).containsEntry("event", "LOGOUT");
}
}
@@ -0,0 +1,137 @@
package com.solvway.mobile.api.service;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
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.ArgumentCaptor;
import org.mockito.MockedStatic;
import org.slf4j.LoggerFactory;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
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.verify;
import static org.mockito.Mockito.when;
@SuppressWarnings({"unchecked", "rawtypes"})
class AdminLoginSecurityServiceTest {
private static final String AUDIT = "/loginSecurity/audit";
private static final String UNLOCK = "/loginSecurity/unlock";
private static final String CONFIG = "/loginSecurity/config";
private static final String RULES = "/loginSecurity/passwordRules";
private RestTemplateCustomUtil rest;
private AdminLoginSecurityService service;
private MockedStatic<HttpReqRespUtils> http;
@BeforeEach
void setUp() {
rest = mock(RestTemplateCustomUtil.class);
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
service = new AdminLoginSecurityService(rest, auth);
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
http = mockStatic(HttpReqRespUtils.class);
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
User caller = new User();
caller.setUsername("boss");
when(auth.loadUserByToken("tok")).thenReturn(caller);
}
@AfterEach
void close() { http.close(); }
private static HttpClientErrorException badRequest(String body) {
return HttpClientErrorException.create(HttpStatus.BAD_REQUEST, "Bad Request", new HttpHeaders(), body.getBytes(StandardCharsets.UTF_8), null);
}
private Object postedBody(String url) {
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(url), any(ParameterizedTypeReference.class), body.capture());
return body.getValue();
}
private List<String> captureLogs(Runnable action) {
Logger logger = (Logger) LoggerFactory.getLogger(AdminLoginSecurityService.class);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
try {
action.run();
} finally {
logger.detachAppender(appender);
}
return appender.list.stream().map(ILoggingEvent::getFormattedMessage).toList();
}
@Test
void audit_forwardsOnlyGivenFiltersWithDefaultPaging() {
when(rest.postForEntity(eq(AUDIT), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("content", List.of())));
service.audit("sales1", null, " ", "2026-11-30", 0, 20);
Map<String, Object> sent = (Map<String, Object>) postedBody(AUDIT);
assertThat(sent).containsOnlyKeys("username", "to", "page", "size");
assertThat(sent).containsEntry("username", "sales1").containsEntry("page", 0).containsEntry("size", 20);
}
@Test
void unlock_sendsCallerAsBy_andLogs() {
when(rest.postForEntity(eq(UNLOCK), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok().build());
List<String> logs = captureLogs(() -> service.unlock("sales1"));
assertThat((Map<String, Object>) postedBody(UNLOCK)).containsEntry("username", "sales1").containsEntry("by", "boss");
assertThat(logs).containsExactly("login lock for sales1 cleared by boss");
}
@Test
void saveConfig_returnsBody_andLogsCaller() {
Map<String, Object> cfg = Map.of("enabled", true, "maxAttempts", 3, "period", 15, "unit", "MINUTES");
when(rest.postForEntity(eq(CONFIG), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(cfg));
List<String> logs = captureLogs(() -> assertThat(service.saveConfig(cfg)).isEqualTo(cfg));
assertThat(logs).containsExactly("lockout settings changed by boss");
}
@Test
void savePasswordRules_returnsBody_andLogsCaller() {
List<Map<String, Object>> rules = List.of(Map.of("id", 1, "status", "Y", "value", "8"));
when(rest.postForEntity(eq(RULES), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(rules));
List<String> logs = captureLogs(() -> assertThat(service.savePasswordRules(rules)).isEqualTo(rules));
assertThat(logs).containsExactly("password rules changed by boss");
}
@Test
void upstreamBadRequest_becomesInvalidSettingWithUpstreamMessage() {
when(rest.postForEntity(eq(CONFIG), any(ParameterizedTypeReference.class), any()))
.thenThrow(badRequest("{\"message\":\"maxAttempts must be at least 1\"}"));
assertThatThrownBy(() -> service.saveConfig(Map.of("maxAttempts", 0)))
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(e.getCode()).isEqualTo("INVALID_SETTING");
assertThat(e.getReason()).isEqualTo("maxAttempts must be at least 1");
});
}
@Test
void upstreamBadRequestWithoutBody_fallsBackToGenericReason() {
when(rest.postForEntity(eq(AUDIT), any(ParameterizedTypeReference.class), any())).thenThrow(badRequest(""));
assertThatThrownBy(() -> service.audit(null, null, "nope", null, 0, 20))
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getReason()).isEqualTo("Invalid request"));
}
}
@@ -0,0 +1,90 @@
package com.solvway.services.system.controller;
import com.solvway.services.system.service.LoginSecurityService;
import com.solvway.services.system.service.LoginSecurityService.Config;
import com.solvway.services.system.service.LoginSecurityService.Locked;
import com.solvway.services.system.service.LoginSecurityService.Rule;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/loginSecurity")
public class LoginSecurityController {
record RecordBody(String username, String event, String ip, String userAgent, String message) {}
record AuditBody(String username, String event, String from, String to, Integer page, Integer size) {}
record UnlockBody(String username, String by) {}
private final LoginSecurityService service;
public LoginSecurityController(LoginSecurityService service) {
this.service = service;
}
@GetMapping("/isLocked/{username}")
public Map<String, Boolean> isLocked(@PathVariable String username) {
return Map.of("locked", service.isLocked(username));
}
@PostMapping("/record")
public void record(@RequestBody RecordBody b) {
body(b);
service.record(b.username(), b.event(), b.ip(), b.userAgent(), b.message());
}
@PostMapping("/audit")
public Map<String, Object> audit(@RequestBody AuditBody b) {
body(b);
return service.audit(b.username(), b.event(), date(b.from()), date(b.to()), b.page(), b.size());
}
@GetMapping("/locked")
public List<Locked> locked() {
return service.lockedUsers();
}
@PostMapping("/unlock")
public void unlock(@RequestBody UnlockBody b) {
body(b);
service.unlock(b.username(), b.by());
}
@GetMapping("/config")
public Config config() {
return service.config();
}
@PostMapping("/config")
public Config saveConfig(@RequestBody Config c) {
return service.saveConfig(c);
}
@GetMapping("/passwordRules")
public List<Rule> passwordRules() {
return service.passwordRules();
}
@PostMapping("/passwordRules")
public List<Rule> savePasswordRules(@RequestBody List<Rule> rules) {
return service.savePasswordRules(rules);
}
@ExceptionHandler({IllegalArgumentException.class, DateTimeParseException.class, HttpMessageNotReadableException.class})
public ResponseEntity<Map<String, String>> badRequest(RuntimeException e) {
return ResponseEntity.badRequest().body(Map.of("message", String.valueOf(e.getMessage())));
}
private static void body(Object b) {
if (b == null) throw new IllegalArgumentException("body is required");
}
private static LocalDate date(String s) {
return s == null || s.isBlank() ? null : LocalDate.parse(s);
}
}
@@ -401,6 +401,24 @@ public class UserController {
return userService.resetPassword(id, bCryptPasswordEncoder.encode(password), LoginStatus.N); return userService.resetPassword(id, bCryptPasswordEncoder.encode(password), LoginStatus.N);
} }
/** An enabled admin changes their own password; returns OK, NOT_FOUND, CURRENT_PASSWORD_WRONG, PASSWORD_SAME or PASSWORD_POLICY. Stores login = Y. Never logs passwords. */
@RequestMapping("/changeAdminPassword")
public String changeAdminPassword(@RequestBody HashMap<String, Object> param) {
Object idParam = param.get("id");
String current = param.get("currentPassword") == null ? "" : param.get("currentPassword").toString();
String next = param.get("newPassword") == null ? "" : param.get("newPassword").toString();
if (idParam == null || current.isBlank() || next.isBlank()) return "NOT_FOUND";
Long id = Long.parseLong(idParam.toString());
User user = userService.findById(id).orElse(null);
if (user == null || user.getType() != UserType.A || !user.isEnabled()) return "NOT_FOUND";
user.setShowPassword(true); // getPassword() is masked unless this is set
if (!bCryptPasswordEncoder.matches(current, user.getPassword())) return "CURRENT_PASSWORD_WRONG";
if (next.equals(current)) return "PASSWORD_SAME";
if (!adminPasswordRuleFailures(next).isEmpty()) return "PASSWORD_POLICY";
userService.resetPassword(id, bCryptPasswordEncoder.encode(next), LoginStatus.Y);
return "OK";
}
@RequestMapping("/validateSecondaryPasswordFromRulesForMember") @RequestMapping("/validateSecondaryPasswordFromRulesForMember")
public List<PasswordRuleProperty> validateSecondaryPasswordFromRulesForMember(@RequestBody HashMap<String, Object> param) { public List<PasswordRuleProperty> validateSecondaryPasswordFromRulesForMember(@RequestBody HashMap<String, Object> param) {
String password = param.get("secondPassword").toString(); String password = param.get("secondPassword").toString();
@@ -0,0 +1,34 @@
package com.solvway.services.system.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
@Entity
@Table(name = "login_audit")
@Getter
@Setter
public class LoginAudit {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonIgnore
private Long companyId;
private String username;
private LocalDateTime datetime;
private String event;
private String ipAddress;
private String userAgent;
private String message;
}
@@ -0,0 +1,34 @@
package com.solvway.services.system.repo;
import com.solvway.services.system.model.LoginAudit;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
@Repository
public interface LoginAuditRepository extends JpaRepository<LoginAudit, Long> {
Optional<LoginAudit> findFirstByUsernameAndEventInOrderByDatetimeDescIdDesc(String username, Collection<String> events);
List<LoginAudit> findByUsernameAndEventAndDatetimeAfterOrderByDatetimeAscIdAsc(String username, String event, LocalDateTime since);
@Query("SELECT DISTINCT a.username FROM LoginAudit a WHERE a.event = 'LOGIN_FAIL' AND a.datetime > :since")
List<String> findUsernamesWithFailuresAfter(@Param("since") LocalDateTime since);
/** Null arguments are ignored; {@code pattern} is a LIKE pattern, {@code toExclusive} an exclusive upper bound. */
@Query("SELECT a FROM LoginAudit a WHERE (:pattern IS NULL OR a.username LIKE :pattern) "
+ "AND (:event IS NULL OR a.event = :event) "
+ "AND (:from IS NULL OR a.datetime >= :from) "
+ "AND (:toExclusive IS NULL OR a.datetime < :toExclusive)")
Page<LoginAudit> search(@Param("pattern") String pattern, @Param("event") String event,
@Param("from") LocalDateTime from, @Param("toExclusive") LocalDateTime toExclusive,
Pageable pageable);
}
@@ -0,0 +1,218 @@
package com.solvway.services.system.service;
import com.solvway.services.system.model.LoginAudit;
import com.solvway.services.system.model.PasswordRuleProperty;
import com.solvway.services.system.model.User;
import com.solvway.services.system.repo.LoginAuditRepository;
import com.solvway.services.system.repo.PasswordRuleRepository;
import com.solvway.services.system.repo.UserRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Clock;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/** Admin login history, lock rule, unlock, and lockout / password-rule settings. */
@Service
public class LoginSecurityService {
private static final List<String> EVENTS = List.of(
"LOGIN_SUCCESS", "LOGIN_FAIL", "LOGIN_LOCKED", "LOGOUT", "UNLOCK_RESET", "PASSWORD_CHANGED");
private static final List<String> RESETS = List.of("LOGIN_SUCCESS", "UNLOCK_RESET", "PASSWORD_CHANGED");
private static final String BLOCK = "ADMIN_LOGIN_BLOCK";
private static final String UNIT = "ADMIN_LOGIN_BLOCK_TIME_UNIT";
private static final String PWD = "ADMIN_PWD_FORMAT";
private static final String PERIOD_PARAM = "ADMIN_LOGIN_BLOCK_PERIOD";
private static final String MAX_PARAM = "ADMIN_LOGIN_MAX_ATTEMPT";
public record Config(boolean enabled, int maxAttempts, int period, String unit) {
ChronoUnit chronoUnit() {
return switch (unit == null ? "" : unit) {
case "S" -> ChronoUnit.SECONDS;
case "M" -> ChronoUnit.MINUTES;
case "H" -> ChronoUnit.HOURS;
case "D" -> ChronoUnit.DAYS;
default -> null;
};
}
boolean valid() {
return maxAttempts >= 1 && period >= 1 && chronoUnit() != null;
}
Duration length() {
return Duration.of(period, chronoUnit());
}
}
public record Locked(String username, int failures, LocalDateTime lastFailure, LocalDateTime lockedUntil) {}
/** Input and output shape of a password rule; {@code param} is ignored on input. */
public record Rule(Long id, String param, String status, String value) {}
private final LoginAuditRepository audits;
private final UserRepository users;
private final PasswordRuleRepository properties; // same system_property table, any type
Clock clock = Clock.systemDefaultZone(); // overridden by tests
public LoginSecurityService(LoginAuditRepository audits, UserRepository users, PasswordRuleRepository properties) {
this.audits = audits;
this.users = users;
this.properties = properties;
}
public boolean isLocked(String username) {
Config c = config();
// Same key the history stores (trimmed, cut to the column size).
return c.enabled() && c.valid() && evaluate(cut(username.trim(), 191), c, LocalDateTime.now(clock)) != null;
}
public List<Locked> lockedUsers() {
Config c = config();
if (!c.enabled() || !c.valid()) return List.of();
LocalDateTime now = LocalDateTime.now(clock);
return audits.findUsernamesWithFailuresAfter(now.minus(c.length())).stream()
.map(u -> evaluate(u, c, now)).filter(l -> l != null).toList();
}
public void record(String username, String event, String ip, String userAgent, String message) {
if (!EVENTS.contains(event) || "UNLOCK_RESET".equals(event)) throw new IllegalArgumentException("unknown event");
write(username, event, cut(ip, 64), cut(userAgent, 512), cut(message, 255));
}
public void unlock(String username, String by) {
write(username, "UNLOCK_RESET", null, null, cut("unlocked by " + by, 255));
}
public Map<String, Object> audit(String username, String event, LocalDate from, LocalDate to, Integer page, Integer size) {
int p = page == null || page < 0 ? 0 : page;
int s = size == null || size < 1 ? 20 : Math.min(size, 100);
String name = username == null ? "" : username.trim();
// ponytail: % and _ in the username filter are not escaped (admin-only filter); escape in the query if it matters
Page<LoginAudit> r = audits.search(name.isEmpty() ? null : "%" + name + "%",
event == null || event.isBlank() ? null : event,
from == null ? null : from.atStartOfDay(),
to == null ? null : to.plusDays(1).atStartOfDay(),
PageRequest.of(p, s, Sort.by(Sort.Direction.DESC, "datetime", "id")));
return Map.of("content", r.getContent(), "totalElements", r.getTotalElements(), "number", p, "size", s);
}
/** Missing or unparsable rows read as 0 / disabled, so bad config never locks anyone. */
public Config config() {
PasswordRuleProperty period = row(BLOCK, PERIOD_PARAM);
PasswordRuleProperty max = row(BLOCK, MAX_PARAM);
PasswordRuleProperty unit = row(UNIT, "ADMIN_LOGIN_BLOCK_TIME_UNIT");
return new Config(period != null && "Y".equals(period.getStatus()), number(max), number(period),
unit == null || unit.getValue() == null ? "" : unit.getValue().trim()); // missing unit = invalid = lockout off
}
@Transactional
public Config saveConfig(Config c) {
if (c == null) throw new IllegalArgumentException("body is required");
if (c.maxAttempts() < 1) throw new IllegalArgumentException("Max attempts must be at least 1");
if (c.period() < 1) throw new IllegalArgumentException("Period must be at least 1");
// Upper limits keep the window computable; a huge period would make every lock check fail open.
if (c.maxAttempts() > 1000) throw new IllegalArgumentException("Max attempts must be at most 1000");
if (c.period() > 10000) throw new IllegalArgumentException("Period must be at most 10000");
if (c.chronoUnit() == null) throw new IllegalArgumentException("Unit must be seconds, minutes, hours or days");
put(BLOCK, PERIOD_PARAM, c.enabled() ? "Y" : "N", String.valueOf(c.period()));
put(BLOCK, MAX_PARAM, null, String.valueOf(c.maxAttempts()));
put(UNIT, "ADMIN_LOGIN_BLOCK_TIME_UNIT", null, c.unit());
return config();
}
public List<Rule> passwordRules() {
return properties.findByType(PWD).stream().sorted(Comparator.comparing(r -> r.getId()))
.map(r -> new Rule(r.getId(), r.getParam(), r.getStatus(), r.getValue())).toList();
}
@Transactional
public List<Rule> savePasswordRules(List<Rule> input) {
if (input == null) throw new IllegalArgumentException("body is required");
List<PasswordRuleProperty> rows = new ArrayList<>();
for (Rule in : input) { // validate everything before saving anything
if (in == null) throw new IllegalArgumentException("rule is required");
if (!"Y".equals(in.status()) && !"N".equals(in.status())) throw new IllegalArgumentException("Each rule must be on or off");
if (in.id() == null) throw new IllegalArgumentException("id is required");
PasswordRuleProperty row = properties.findById(in.id()).filter(r -> PWD.equals(r.getType()))
.orElseThrow(() -> new IllegalArgumentException("unknown password rule " + in.id()));
String p = row.getParam();
if (in.value() != null && p != null && (p.endsWith("_MIN") || p.endsWith("_MAX")) && !in.value().matches("\\d{1,9}"))
throw new IllegalArgumentException("Rule values must be whole numbers");
rows.add(row);
}
for (int i = 0; i < rows.size(); i++) {
rows.get(i).setStatus(input.get(i).status());
if (input.get(i).value() != null) rows.get(i).setValue(input.get(i).value());
}
properties.saveAll(rows);
return passwordRules();
}
/** failures: LOGIN_FAIL rows after max(now - period, newest reset); locked once there are maxAttempts of them. */
private Locked evaluate(String username, Config c, LocalDateTime now) {
Duration period = c.length();
LocalDateTime since = now.minus(period);
LocalDateTime reset = audits.findFirstByUsernameAndEventInOrderByDatetimeDescIdDesc(username, RESETS)
.map(LoginAudit::getDatetime).orElse(null);
if (reset != null && reset.isAfter(since)) since = reset;
List<LoginAudit> f = audits.findByUsernameAndEventAndDatetimeAfterOrderByDatetimeAscIdAsc(username, "LOGIN_FAIL", since);
if (f.size() < c.maxAttempts()) return null;
return new Locked(username, f.size(), f.get(f.size() - 1).getDatetime(),
f.get(f.size() - c.maxAttempts()).getDatetime().plus(period));
}
private void write(String username, String event, String ip, String userAgent, String message) {
String name = username == null ? "" : username.trim();
if (name.isEmpty()) throw new IllegalArgumentException("username is required");
LoginAudit a = new LoginAudit();
a.setUsername(cut(name, 191));
a.setEvent(event);
a.setIpAddress(ip);
a.setUserAgent(userAgent);
a.setMessage(message);
a.setDatetime(LocalDateTime.now(clock));
User user = users.findByUsername(name);
if (user != null) a.setCompanyId(user.getCompanyId());
audits.save(a);
}
private PasswordRuleProperty row(String type, String param) {
return properties.findByType(type).stream().filter(r -> param.equals(r.getParam())).findFirst().orElse(null);
}
private void put(String type, String param, String status, String value) {
PasswordRuleProperty r = row(type, param);
if (r == null) {
r = new PasswordRuleProperty();
r.setType(type);
r.setParam(param);
r.setStatus("Y");
}
if (status != null) r.setStatus(status);
r.setValue(value);
properties.save(r);
}
private static int number(PasswordRuleProperty r) {
try {
return r == null ? 0 : Integer.parseInt(r.getValue().trim());
} catch (RuntimeException e) { // null or non-numeric value
return 0;
}
}
private static String cut(String s, int max) {
return s == null || s.length() <= max ? s : s.substring(0, max);
}
}
@@ -0,0 +1,161 @@
package com.solvway.services.system.controller;
import com.solvway.services.system.service.LoginSecurityService;
import com.solvway.services.system.service.LoginSecurityService.Config;
import com.solvway.services.system.service.LoginSecurityService.Rule;
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.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
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.get;
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 LoginSecurityControllerTest {
@Mock private LoginSecurityService service;
@InjectMocks private LoginSecurityController controller;
private MockMvc mvc;
@BeforeEach
void setUp() {
mvc = MockMvcBuilders.standaloneSetup(controller).build();
}
private org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder json(String url, String body) {
return post(url).contentType(MediaType.APPLICATION_JSON).content(body);
}
@Test
void isLockedReturnsFlag() throws Exception {
when(service.isLocked("admin")).thenReturn(true);
mvc.perform(get("/loginSecurity/isLocked/admin")).andExpect(status().isOk()).andExpect(jsonPath("$.locked").value(true));
}
@Test
void recordPassesFieldsAndReturnsEmpty200() throws Exception {
mvc.perform(json("/loginSecurity/record",
"{\"username\":\"bob\",\"event\":\"LOGIN_FAIL\",\"ip\":\"1.2.3.4\",\"userAgent\":\"ua\",\"message\":\"m\"}"))
.andExpect(status().isOk()).andExpect(content().string(""));
verify(service).record("bob", "LOGIN_FAIL", "1.2.3.4", "ua", "m");
}
@Test
void recordRefusalIsA400WithMessage() throws Exception {
doThrow(new IllegalArgumentException("username is required")).when(service).record(any(), any(), any(), any(), any());
mvc.perform(json("/loginSecurity/record", "{\"username\":\" \",\"event\":\"LOGIN_FAIL\"}"))
.andExpect(status().isBadRequest()).andExpect(jsonPath("$.message").value("username is required"));
}
@Test
void auditParsesDatesAndPassesFilters() throws Exception {
when(service.audit(any(), any(), any(), any(), any(), any())).thenReturn(Map.of("content", List.of(), "totalElements", 0L, "number", 1, "size", 100));
mvc.perform(json("/loginSecurity/audit",
"{\"username\":\"bo\",\"event\":\"LOGOUT\",\"from\":\"2025-06-01\",\"to\":\"2025-06-02\",\"page\":1,\"size\":500}"))
.andExpect(status().isOk()).andExpect(jsonPath("$.size").value(100)).andExpect(jsonPath("$.totalElements").value(0));
verify(service).audit("bo", "LOGOUT", LocalDate.of(2025, 6, 1), LocalDate.of(2025, 6, 2), 1, 500);
}
@Test
void auditWithBadDateIs400() throws Exception {
mvc.perform(json("/loginSecurity/audit", "{\"from\":\"01/06/2025\"}")).andExpect(status().isBadRequest())
.andExpect(jsonPath("$.message").exists());
verify(service, never()).audit(any(), any(), any(), any(), any(), any());
}
@Test
void lockedListIsReturned() throws Exception {
when(service.lockedUsers()).thenReturn(List.of(new LoginSecurityService.Locked("a", 3,
LocalDateTime.of(2025, 6, 15, 11, 59), LocalDateTime.of(2025, 6, 15, 12, 5))));
mvc.perform(get("/loginSecurity/locked")).andExpect(status().isOk())
.andExpect(jsonPath("$[0].username").value("a")).andExpect(jsonPath("$[0].failures").value(3))
.andExpect(jsonPath("$[0].lastFailure").exists()).andExpect(jsonPath("$[0].lockedUntil").exists());
}
@Test
void unlockPassesUsernameAndBy() throws Exception {
mvc.perform(json("/loginSecurity/unlock", "{\"username\":\"bob\",\"by\":\"admin\"}")).andExpect(status().isOk());
verify(service).unlock("bob", "admin");
}
@Test
void unlockBlankIs400() throws Exception {
doThrow(new IllegalArgumentException("username is required")).when(service).unlock(any(), any());
mvc.perform(json("/loginSecurity/unlock", "{\"username\":\"\",\"by\":\"admin\"}")).andExpect(status().isBadRequest());
}
@Test
void configIsReadAndSaved() throws Exception {
when(service.config()).thenReturn(new Config(true, 5, 10, "M"));
when(service.saveConfig(new Config(false, 3, 2, "H"))).thenReturn(new Config(false, 3, 2, "H"));
mvc.perform(get("/loginSecurity/config")).andExpect(jsonPath("$.enabled").value(true))
.andExpect(jsonPath("$.maxAttempts").value(5)).andExpect(jsonPath("$.period").value(10)).andExpect(jsonPath("$.unit").value("M"));
mvc.perform(json("/loginSecurity/config", "{\"enabled\":false,\"maxAttempts\":3,\"period\":2,\"unit\":\"H\"}"))
.andExpect(status().isOk()).andExpect(jsonPath("$.unit").value("H"));
}
@Test
void invalidConfigIs400WithMessage() throws Exception {
when(service.saveConfig(any())).thenThrow(new IllegalArgumentException("unit must be S, M, H or D"));
mvc.perform(json("/loginSecurity/config", "{\"enabled\":true,\"maxAttempts\":3,\"period\":2,\"unit\":\"X\"}"))
.andExpect(status().isBadRequest()).andExpect(jsonPath("$.message").value("unit must be S, M, H or D"));
}
@Test
void passwordRulesAreReadAndSaved() throws Exception {
when(service.passwordRules()).thenReturn(List.of(new Rule(2L, "INPUT_LENGTH_MIN", "Y", "8")));
when(service.savePasswordRules(eq(List.of(new Rule(2L, null, "N", "12"))))).thenReturn(List.of(new Rule(2L, "INPUT_LENGTH_MIN", "N", "12")));
mvc.perform(get("/loginSecurity/passwordRules")).andExpect(jsonPath("$[0].param").value("INPUT_LENGTH_MIN"));
mvc.perform(json("/loginSecurity/passwordRules", "[{\"id\":2,\"status\":\"N\",\"value\":\"12\"}]"))
.andExpect(status().isOk()).andExpect(jsonPath("$[0].status").value("N"));
}
@Test
void invalidPasswordRulesAre400() throws Exception {
when(service.savePasswordRules(any())).thenThrow(new IllegalArgumentException("status must be Y or N"));
mvc.perform(json("/loginSecurity/passwordRules", "[{\"id\":2,\"status\":\"X\"}]")).andExpect(status().isBadRequest());
}
@Test
void nullOrMissingBodyIs400WithMessage() throws Exception {
for (String url : List.of("/loginSecurity/record", "/loginSecurity/audit", "/loginSecurity/unlock",
"/loginSecurity/config", "/loginSecurity/passwordRules")) {
mvc.perform(json(url, "null")).andExpect(status().isBadRequest()).andExpect(jsonPath("$.message").exists());
mvc.perform(post(url).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest())
.andExpect(jsonPath("$.message").exists());
}
}
}
@@ -0,0 +1,130 @@
package com.solvway.services.system.controller;
import com.solvway.services.system.constant.SystemConstants.LoginStatus;
import com.solvway.core.enums.UserEnum.UserType;
import com.solvway.services.system.model.PasswordRuleProperty;
import com.solvway.services.system.model.User;
import com.solvway.services.system.repo.PasswordRuleRepository;
import com.solvway.services.system.service.UserService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** Admin changing their own password: result codes checked in a fixed order; OK stores bcrypt with login = Y. */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class UserControllerChangeAdminPasswordTest {
@Mock private UserService userService;
@Mock private PasswordRuleRepository passwordRuleRepository;
@Spy private BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(4);
@InjectMocks private UserController controller;
@BeforeEach
void minLengthEightRule() {
PasswordRuleProperty rule = new PasswordRuleProperty();
rule.setParam("INPUT_LENGTH_MIN");
rule.setValue("8");
rule.setStatus("Y");
when(passwordRuleRepository.findByType("ADMIN_PWD_FORMAT")).thenReturn(List.of(rule));
when(userService.resetPassword(anyLong(), anyString(), any())).thenReturn(1);
}
private void admin(boolean enabled, UserType type) {
User u = new User();
u.setId(5L);
u.setType(type);
u.setEnabled(enabled);
u.setPassword(bCryptPasswordEncoder.encode("OldPassw0rd"));
when(userService.findById(5L)).thenReturn(Optional.of(u));
}
private static HashMap<String, Object> body(String current, String next) {
HashMap<String, Object> m = new HashMap<>();
m.put("id", 5);
m.put("currentPassword", current);
m.put("newPassword", next);
return m;
}
@Test
void okStoresBcryptHashWithLoginY() {
admin(true, UserType.A);
assertThat(controller.changeAdminPassword(body("OldPassw0rd", "NewPassw0rd"))).isEqualTo("OK");
ArgumentCaptor<String> hash = ArgumentCaptor.forClass(String.class);
verify(userService).resetPassword(eq(5L), hash.capture(), eq(LoginStatus.Y));
assertThat(bCryptPasswordEncoder.matches("NewPassw0rd", hash.getValue())).isTrue();
}
@Test
void notFoundForUnknownNonAdminOrDisabled() {
when(userService.findById(9L)).thenReturn(Optional.empty());
HashMap<String, Object> unknown = body("OldPassw0rd", "NewPassw0rd");
unknown.put("id", 9);
assertThat(controller.changeAdminPassword(unknown)).isEqualTo("NOT_FOUND");
admin(true, UserType.M);
assertThat(controller.changeAdminPassword(body("OldPassw0rd", "NewPassw0rd"))).isEqualTo("NOT_FOUND");
admin(false, UserType.A);
assertThat(controller.changeAdminPassword(body("OldPassw0rd", "NewPassw0rd"))).isEqualTo("NOT_FOUND");
verify(userService, never()).resetPassword(anyLong(), anyString(), any());
}
@Test
void missingOrBlankFieldIsNotFound() {
admin(true, UserType.A);
assertThat(controller.changeAdminPassword(body(null, "NewPassw0rd"))).isEqualTo("NOT_FOUND");
assertThat(controller.changeAdminPassword(body("OldPassw0rd", " "))).isEqualTo("NOT_FOUND");
HashMap<String, Object> noId = body("OldPassw0rd", "NewPassw0rd");
noId.remove("id");
assertThat(controller.changeAdminPassword(noId)).isEqualTo("NOT_FOUND");
verify(userService, never()).resetPassword(anyLong(), anyString(), any());
}
@Test
void currentPasswordWrong() {
admin(true, UserType.A);
assertThat(controller.changeAdminPassword(body("Wrong12345", "NewPassw0rd"))).isEqualTo("CURRENT_PASSWORD_WRONG");
verify(userService, never()).resetPassword(anyLong(), anyString(), any());
}
@Test
void passwordSame() {
admin(true, UserType.A);
assertThat(controller.changeAdminPassword(body("OldPassw0rd", "OldPassw0rd"))).isEqualTo("PASSWORD_SAME");
verify(userService, never()).resetPassword(anyLong(), anyString(), any());
}
@Test
void passwordPolicy() {
admin(true, UserType.A);
assertThat(controller.changeAdminPassword(body("OldPassw0rd", "short"))).isEqualTo("PASSWORD_POLICY");
verify(userService, never()).resetPassword(anyLong(), anyString(), any());
}
}
@@ -0,0 +1,473 @@
package com.solvway.services.system.service;
import com.solvway.services.system.model.LoginAudit;
import com.solvway.services.system.model.PasswordRuleProperty;
import com.solvway.services.system.model.User;
import com.solvway.services.system.repo.LoginAuditRepository;
import com.solvway.services.system.repo.PasswordRuleRepository;
import com.solvway.services.system.repo.UserRepository;
import com.solvway.services.system.service.LoginSecurityService.Config;
import com.solvway.services.system.service.LoginSecurityService.Locked;
import com.solvway.services.system.service.LoginSecurityService.Rule;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class LoginSecurityServiceTest {
private static final LocalDateTime NOW = LocalDateTime.of(2025, 6, 15, 12, 0);
@Mock private LoginAuditRepository audits;
@Mock private UserRepository users;
@Mock private PasswordRuleRepository properties;
private LoginSecurityService service;
@BeforeEach
void setUp() {
service = new LoginSecurityService(audits, users, properties);
service.clock = Clock.fixed(NOW.toInstant(ZoneOffset.UTC), ZoneOffset.UTC);
}
private static PasswordRuleProperty prop(Long id, String param, String type, String status, String value) {
PasswordRuleProperty p = new PasswordRuleProperty();
p.setId(id);
p.setParam(param);
p.setType(type);
p.setStatus(status);
p.setValue(value);
return p;
}
private void settings(String status, String period, String max, String unit) {
when(properties.findByType("ADMIN_LOGIN_BLOCK")).thenReturn(List.of(
prop(1L, "ADMIN_LOGIN_BLOCK_PERIOD", "ADMIN_LOGIN_BLOCK", status, period),
prop(2L, "ADMIN_LOGIN_MAX_ATTEMPT", "ADMIN_LOGIN_BLOCK", "Y", max)));
when(properties.findByType("ADMIN_LOGIN_BLOCK_TIME_UNIT")).thenReturn(List.of(
prop(3L, "ADMIN_LOGIN_BLOCK_TIME_UNIT", "ADMIN_LOGIN_BLOCK_TIME_UNIT", "Y", unit)));
}
private static LoginAudit row(String event, LocalDateTime at) {
LoginAudit a = new LoginAudit();
a.setUsername("admin");
a.setEvent(event);
a.setDatetime(at);
return a;
}
/** Behaves like the DB query: only rows strictly after {@code since}, in the given (oldest first) order. */
private void failures(String username, LocalDateTime... times) {
when(audits.findByUsernameAndEventAndDatetimeAfterOrderByDatetimeAscIdAsc(eq(username), eq("LOGIN_FAIL"), any()))
.thenAnswer(i -> java.util.Arrays.stream(times)
.filter(t -> t.isAfter(i.getArgument(2))).map(t -> row("LOGIN_FAIL", t)).toList());
}
private LocalDateTime sinceUsed() {
ArgumentCaptor<LocalDateTime> c = ArgumentCaptor.forClass(LocalDateTime.class);
verify(audits).findByUsernameAndEventAndDatetimeAfterOrderByDatetimeAscIdAsc(anyString(), eq("LOGIN_FAIL"), c.capture());
return c.getValue();
}
@Test
void lockedAtMaxFailuresInsidePeriod() {
settings("Y", "10", "3", "M");
failures("admin", NOW.minusMinutes(5), NOW.minusMinutes(3), NOW.minusMinutes(1));
assertThat(service.isLocked("admin")).isTrue();
}
@Test
void notLockedWhenOlderFailuresFallOutsidePeriod() {
settings("Y", "10", "3", "M");
failures("admin", NOW.minusMinutes(30), NOW.minusMinutes(20), NOW.minusMinutes(1));
assertThat(service.isLocked("admin")).isFalse();
}
@Test
void lockCheckUsesTheSame191CharacterKeyTheHistoryStores() {
String stored = "a".repeat(191);
settings("Y", "10", "1", "M");
failures(stored, NOW.minusMinutes(1));
assertThat(service.isLocked(stored + "bbbb")).isTrue();
}
@Test
void settingsHaveUpperLimits() {
assertThatThrownBy(() -> service.saveConfig(new Config(true, 1001, 15, "M"))).hasMessage("Max attempts must be at most 1000");
assertThatThrownBy(() -> service.saveConfig(new Config(true, 5, 10001, "M"))).hasMessage("Period must be at most 10000");
verify(properties, never()).save(any());
}
@Test
void usernameIsTrimmed() {
settings("Y", "10", "1", "M");
failures("admin", NOW.minusMinutes(1));
assertThat(service.isLocked(" admin ")).isTrue();
}
@ParameterizedTest
@ValueSource(strings = {"LOGIN_SUCCESS", "UNLOCK_RESET", "PASSWORD_CHANGED"})
void resetEventsRestartTheCount(String event) {
settings("Y", "10", "3", "M");
failures("admin", NOW.minusMinutes(5), NOW.minusMinutes(4), NOW.minusMinutes(3), NOW.minusMinutes(1));
LocalDateTime resetAt = NOW.minusMinutes(2);
when(audits.findFirstByUsernameAndEventInOrderByDatetimeDescIdDesc(eq("admin"), anyList()))
.thenAnswer(i -> ((java.util.Collection<?>) i.getArgument(1)).contains(event)
? Optional.of(row(event, resetAt)) : Optional.empty());
assertThat(service.isLocked("admin")).isFalse();
assertThat(sinceUsed()).isEqualTo(resetAt);
}
@Test
void logoutAndLoginLockedDoNotResetTheCount() {
settings("Y", "10", "3", "M");
failures("admin", NOW.minusMinutes(5), NOW.minusMinutes(4), NOW.minusMinutes(3));
when(audits.findFirstByUsernameAndEventInOrderByDatetimeDescIdDesc(eq("admin"), anyList()))
.thenAnswer(i -> ((java.util.Collection<?>) i.getArgument(1)).stream()
.anyMatch(e -> e.equals("LOGOUT") || e.equals("LOGIN_LOCKED"))
? Optional.of(row("LOGOUT", NOW.minusMinutes(2))) : Optional.empty());
assertThat(service.isLocked("admin")).isTrue();
}
@Test
void resetOlderThanThePeriodDoesNotMoveTheWindow() {
settings("Y", "10", "1", "M");
failures("admin", NOW.minusMinutes(1));
when(audits.findFirstByUsernameAndEventInOrderByDatetimeDescIdDesc(eq("admin"), anyList()))
.thenReturn(Optional.of(row("LOGIN_SUCCESS", NOW.minusHours(5))));
assertThat(service.isLocked("admin")).isTrue();
assertThat(sinceUsed()).isEqualTo(NOW.minusMinutes(10));
}
@Test
void lockoutOffNeverLocks() {
settings("N", "10", "1", "M");
failures("admin", NOW.minusMinutes(1), NOW.minusMinutes(2));
assertThat(service.isLocked("admin")).isFalse();
}
@ParameterizedTest
@CsvSource({"abc,3,M", "10,,M", "10,3,X", "0,3,M", "10,0,M"})
void badSettingsMeanLockoutOff(String period, String max, String unit) {
settings("Y", period, max, unit);
failures("admin", NOW.minusSeconds(1), NOW.minusSeconds(2), NOW.minusSeconds(3));
assertThat(service.isLocked("admin")).isFalse();
}
@Test
void missingSettingsMeanLockoutOff() {
failures("admin", NOW.minusSeconds(1));
assertThat(service.isLocked("admin")).isFalse();
assertThat(service.lockedUsers()).isEmpty();
}
@ParameterizedTest
@CsvSource({"S,PT2S", "M,PT2M", "H,PT2H", "D,PT48H"})
void unitIsConvertedToThePeriod(String unit, Duration expected) {
settings("Y", "2", "1", unit);
failures("admin", NOW.minusSeconds(1));
assertThat(service.isLocked("admin")).isTrue();
assertThat(sinceUsed()).isEqualTo(NOW.minus(expected));
}
@Test
void lockedUntilIsOldestFailureKeepingTheCountPlusPeriod() {
settings("Y", "10", "2", "M");
failures("admin", NOW.minusMinutes(9), NOW.minusMinutes(5), NOW.minusMinutes(1));
assertThat(service.lockedUsers().size()).isZero(); // no candidates yet
when(audits.findUsernamesWithFailuresAfter(NOW.minusMinutes(10))).thenReturn(List.of("admin"));
List<Locked> locked = service.lockedUsers();
assertThat(locked).containsExactly(new Locked("admin", 3, NOW.minusMinutes(1), NOW.plusMinutes(5)));
}
@Test
void lockedListReturnsOnlyLockedUsernames() {
settings("Y", "10", "2", "M");
when(audits.findUsernamesWithFailuresAfter(NOW.minusMinutes(10))).thenReturn(List.of("a", "b"));
failures("a", NOW.minusMinutes(2), NOW.minusMinutes(1));
failures("b", NOW.minusMinutes(1));
assertThat(service.lockedUsers()).extracting(Locked::username).containsExactly("a");
}
@Test
void lockedListIsEmptyWhenLockoutOff() {
settings("N", "10", "2", "M");
assertThat(service.lockedUsers()).isEmpty();
verify(audits, never()).findUsernamesWithFailuresAfter(any());
}
private LoginAudit saved() {
ArgumentCaptor<LoginAudit> c = ArgumentCaptor.forClass(LoginAudit.class);
verify(audits).save(c.capture());
return c.getValue();
}
@Test
void unlockWritesUnlockResetRowWithCompany() {
User u = new User();
u.setCompanyId(7L);
when(users.findByUsername("admin")).thenReturn(u);
service.unlock(" admin ", "boss");
LoginAudit a = saved();
assertThat(a.getUsername()).isEqualTo("admin");
assertThat(a.getEvent()).isEqualTo("UNLOCK_RESET");
assertThat(a.getMessage()).isEqualTo("unlocked by boss");
assertThat(a.getCompanyId()).isEqualTo(7L);
assertThat(a.getDatetime()).isEqualTo(NOW);
}
@Test
void unlockRefusesBlankUsername() {
assertThatThrownBy(() -> service.unlock(" ", "boss")).isInstanceOf(IllegalArgumentException.class);
verify(audits, never()).save(any());
}
@Test
void recordCutsLongValuesAndFillsCompanyForKnownUser() {
User u = new User();
u.setCompanyId(9L);
when(users.findByUsername("bob")).thenReturn(u);
service.record(" bob ", "LOGIN_FAIL", "i".repeat(80), "u".repeat(600), "m".repeat(300));
LoginAudit a = saved();
assertThat(a.getUsername()).isEqualTo("bob");
assertThat(a.getIpAddress()).hasSize(64);
assertThat(a.getUserAgent()).hasSize(512);
assertThat(a.getMessage()).hasSize(255);
assertThat(a.getCompanyId()).isEqualTo(9L);
assertThat(a.getDatetime()).isEqualTo(NOW);
}
@Test
void recordCutsUsernameTo191AndLeavesCompanyNullForUnknownUser() {
service.record("n".repeat(250), "LOGOUT", null, null, null);
LoginAudit a = saved();
assertThat(a.getUsername()).hasSize(191);
assertThat(a.getCompanyId()).isNull();
}
@Test
void recordRefusesBlankUsernameAndUnknownEvent() {
assertThatThrownBy(() -> service.record(" ", "LOGIN_FAIL", null, null, null))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> service.record(null, "LOGIN_FAIL", null, null, null))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> service.record("bob", "NOPE", null, null, null))
.isInstanceOf(IllegalArgumentException.class);
verify(audits, never()).save(any());
}
@Test
void auditMapsFiltersAndCapsSizeAt100() {
when(audits.search(any(), any(), any(), any(), any())).thenReturn(new PageImpl<>(List.of(row("LOGIN_FAIL", NOW))));
Map<String, Object> r = service.audit(" bo ", "LOGIN_FAIL", LocalDate.of(2025, 6, 1), LocalDate.of(2025, 6, 2), 2, 500);
ArgumentCaptor<Pageable> p = ArgumentCaptor.forClass(Pageable.class);
verify(audits).search(eq("%bo%"), eq("LOGIN_FAIL"), eq(LocalDateTime.of(2025, 6, 1, 0, 0)),
eq(LocalDateTime.of(2025, 6, 3, 0, 0)), p.capture());
assertThat(p.getValue().getPageSize()).isEqualTo(100);
assertThat(p.getValue().getPageNumber()).isEqualTo(2);
assertThat(p.getValue().getSort().toString()).isEqualTo("datetime: DESC,id: DESC");
assertThat(r).containsEntry("totalElements", 1L).containsEntry("number", 2).containsEntry("size", 100);
assertThat((List<?>) r.get("content")).hasSize(1);
}
@Test
void auditDefaultsToPageZeroSize20AndNoFilters() {
when(audits.search(any(), any(), any(), any(), any())).thenReturn(Page.empty());
Map<String, Object> r = service.audit(null, " ", null, null, null, null);
verify(audits).search(eq(null), eq(null), eq(null), eq(null), any(Pageable.class));
assertThat(r).containsEntry("number", 0).containsEntry("size", 20);
}
@Test
void configIsReadFromTheRows() {
settings("Y", "15", "4", "H");
assertThat(service.config()).isEqualTo(new Config(true, 4, 15, "H"));
}
@ParameterizedTest
@CsvSource({"0,5,M", "3,0,M", "3,5,X"})
void invalidConfigIsRejectedAndNothingSaved(int max, int period, String unit) {
assertThatThrownBy(() -> service.saveConfig(new Config(true, max, period, unit)))
.isInstanceOf(IllegalArgumentException.class);
verify(properties, never()).save(any());
}
@Test
void settingsErrorsReadAsPlainText() {
assertThatThrownBy(() -> service.saveConfig(new Config(true, 0, 15, "M"))).hasMessage("Max attempts must be at least 1");
assertThatThrownBy(() -> service.saveConfig(new Config(true, 5, 0, "M"))).hasMessage("Period must be at least 1");
assertThatThrownBy(() -> service.saveConfig(new Config(true, 5, 15, "X"))).hasMessage("Unit must be seconds, minutes, hours or days");
}
@Test
void validConfigUpdatesThreeRowsAndEnabledSetsPeriodStatus() {
settings("Y", "15", "4", "H");
service.saveConfig(new Config(false, 6, 20, "D"));
ArgumentCaptor<PasswordRuleProperty> c = ArgumentCaptor.forClass(PasswordRuleProperty.class);
verify(properties, org.mockito.Mockito.times(3)).save(c.capture());
assertThat(c.getAllValues()).extracting("param", "status", "value").containsExactlyInAnyOrder(
org.assertj.core.groups.Tuple.tuple("ADMIN_LOGIN_BLOCK_PERIOD", "N", "20"),
org.assertj.core.groups.Tuple.tuple("ADMIN_LOGIN_MAX_ATTEMPT", "Y", "6"),
org.assertj.core.groups.Tuple.tuple("ADMIN_LOGIN_BLOCK_TIME_UNIT", "Y", "D"));
}
@Test
void passwordRulesAreOrderedById() {
when(properties.findByType("ADMIN_PWD_FORMAT")).thenReturn(List.of(
prop(5L, "B", "ADMIN_PWD_FORMAT", "Y", "2"), prop(2L, "A", "ADMIN_PWD_FORMAT", "N", "1")));
assertThat(service.passwordRules()).extracting(Rule::id).containsExactly(2L, 5L);
}
@Test
void passwordRulesUpdateOnlyStatusAndValue() {
PasswordRuleProperty r = prop(2L, "INPUT_LENGTH_MIN", "ADMIN_PWD_FORMAT", "Y", "8");
when(properties.findById(2L)).thenReturn(Optional.of(r));
when(properties.findByType("ADMIN_PWD_FORMAT")).thenReturn(List.of(r));
service.savePasswordRules(List.of(new Rule(2L, "HACKED", "N", "12")));
assertThat(r.getStatus()).isEqualTo("N");
assertThat(r.getValue()).isEqualTo("12");
assertThat(r.getParam()).isEqualTo("INPUT_LENGTH_MIN");
verify(properties).saveAll(List.of(r));
}
@Test
void passwordRulesRefuseAnIdOfAnotherTypeAndSaveNothing() {
PasswordRuleProperty good = prop(2L, "A", "ADMIN_PWD_FORMAT", "Y", "1");
when(properties.findById(2L)).thenReturn(Optional.of(good));
when(properties.findById(9L)).thenReturn(Optional.of(prop(9L, "X", "USER_PWD_FORMAT", "Y", "1")));
assertThatThrownBy(() -> service.savePasswordRules(List.of(new Rule(2L, null, "N", "5"), new Rule(9L, null, "Y", "5"))))
.isInstanceOf(IllegalArgumentException.class);
assertThat(good.getStatus()).isEqualTo("Y");
verify(properties, never()).saveAll(any());
}
@Test
void passwordRulesRefuseUnknownIdAndBadStatusAndSaveNothing() {
PasswordRuleProperty good = prop(2L, "A", "ADMIN_PWD_FORMAT", "Y", "1");
when(properties.findById(2L)).thenReturn(Optional.of(good));
assertThatThrownBy(() -> service.savePasswordRules(List.of(new Rule(404L, null, "Y", null))))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> service.savePasswordRules(List.of(new Rule(2L, null, "X", "5"))))
.isInstanceOf(IllegalArgumentException.class);
assertThat(good.getValue()).isEqualTo("1");
verify(properties, never()).saveAll(any());
}
@Test
void missingUnitRowMeansLockoutOff() {
when(properties.findByType("ADMIN_LOGIN_BLOCK")).thenReturn(List.of(
prop(1L, "ADMIN_LOGIN_BLOCK_PERIOD", "ADMIN_LOGIN_BLOCK", "Y", "10"),
prop(2L, "ADMIN_LOGIN_MAX_ATTEMPT", "ADMIN_LOGIN_BLOCK", "Y", "1")));
failures("admin", NOW.minusSeconds(1));
assertThat(service.isLocked("admin")).isFalse();
assertThat(service.lockedUsers()).isEmpty();
}
@Test
void recordRefusesUnlockResetButAcceptsTheOtherEvents() {
assertThatThrownBy(() -> service.record("bob", "UNLOCK_RESET", null, null, null))
.isInstanceOf(IllegalArgumentException.class);
verify(audits, never()).save(any());
for (String e : List.of("LOGIN_SUCCESS", "LOGIN_FAIL", "LOGIN_LOCKED", "LOGOUT", "PASSWORD_CHANGED")) {
service.record("bob", e, null, null, null);
}
verify(audits, org.mockito.Mockito.times(5)).save(any());
}
@ParameterizedTest
@CsvSource({"INPUT_LENGTH_MIN,abc", "INPUT_LENGTH_MIN,-1", "INPUT_LENGTH_MIN,''", "UPPER_CASE_MAX,1.5"})
void minMaxRulesRefuseNonIntegerValuesAndSaveNothing(String param, String value) {
when(properties.findById(2L)).thenReturn(Optional.of(prop(2L, param, "ADMIN_PWD_FORMAT", "Y", "1")));
assertThatThrownBy(() -> service.savePasswordRules(List.of(new Rule(2L, null, "Y", value))))
.isInstanceOf(IllegalArgumentException.class);
verify(properties, never()).saveAll(any());
}
@Test
void otherRulesAllowEmptyValue() {
PasswordRuleProperty r = prop(3L, "SPACE_NOT_ALLOWED", "ADMIN_PWD_FORMAT", "Y", "x");
when(properties.findById(3L)).thenReturn(Optional.of(r));
when(properties.findByType("ADMIN_PWD_FORMAT")).thenReturn(List.of(r));
service.savePasswordRules(List.of(new Rule(3L, null, "Y", "")));
verify(properties).saveAll(List.of(r));
}
@Test
void nullInputsAreRefusedAsIllegalArgument() {
assertThatThrownBy(() -> service.savePasswordRules(null)).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> service.savePasswordRules(java.util.Arrays.asList((Rule) null))).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> service.savePasswordRules(List.of(new Rule(null, null, "Y", "1")))).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> service.saveConfig(null)).isInstanceOf(IllegalArgumentException.class);
verify(properties, never()).saveAll(any());
}
}