Compare commits
9 Commits
phase-32.1
...
v0.1.21
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc5f4f7260 | ||
|
|
6ec4c85c48 | ||
|
|
b179e6b2e5 | ||
|
|
97f83cc2cf | ||
|
|
6bf219f50a | ||
|
|
91af10b572 | ||
|
|
8446a77605 | ||
| 66fc107eb9 | |||
| bd2cc0c245 |
26
README.md
26
README.md
@@ -16,9 +16,9 @@ It owns the `users` table extensions, `user_throttle`, `jwt_blacklist`, `user_ap
|
||||
|
||||
## Features
|
||||
|
||||
- **Registration and activation.** `POST /register`, `POST /activate`, `POST /activate-by-code`. Registration can be switched off and throttled; `activate_mode` is `auto`, `user` (a mailed code) or `admin`, with codes from `IssueActivationCode` and `VerifyActivationCode`. A `/register` body sets only the `User.RegisterFillable` columns: `name`, `surname`, `email`, `password` (stored as its hash), `preferred_locale` and `marketing_consent`. It cannot set `organisation_id` or `organisation_role` (membership is the administrator's or the application's), `is_onboarded`, `must_change_password`, or the activation, reset, address proof, handle and permission columns; other keys are ignored (they still reach `RegisterEvent.Payload`). `created_ip_address` and `last_ip_address` are server-set from the client address only. With `require_activation` on (the default), `POST /login` refuses an account that is not activated with the same 401 invalid-login answer as a wrong password and counts the attempt for the login throttle. Such an account is activated by the mailed code (`POST /activate-by-code` answers with a token), by the invitation link or by an administrator. `POST /activate` serves the sessions of not-activated accounts, which exist when `require_activation` is off. `Login` checks in this order: a ban or an active suspension (`RejectIfThrottled`), the password, the activation, then the deactivation restore.
|
||||
- **JWT sessions.** `POST /login`, `GET /fetch`, `POST /refresh`, `POST /logout`. Boot registers the `jwt` guard with the framework's `bouncer.Registry` and exposes it as the `jwt.auth` middleware for other plugins. The guard reads the session cookies `classes.SessionCookieNames()` lists and resolves the published `bouncer.BlacklistStore` on every request. Boot installs the plugin's GORM hooks (`classes.RegisterHooks`), publishes the Postgres `jwt_blacklist` store (`bouncer.NewPostgresBlacklist`) and starts its background sweep, which prunes the blacklist, through `lagoon.OnDatabase`. Under `summer serve`, which publishes the database after Boot, they take effect when `lagoon.Publish` runs, before the router is built; when the database is already published they take effect at once. While no store is published, no token counts as blacklisted. `POST /logout` ends the session however the token travels: the bearer header, or only the `token` or `auth_token` cookie the guard also reads. Every session token the request carries goes to the Postgres `jwt_blacklist` until its refresh window closes (the later of `exp` and `iat` plus `refresh_ttl`, plus a minute), so the guard refuses it on the next request and `POST /refresh` cannot revive it after the access token expired; a token whose access lifetime passed is revoked too while it could still be refreshed. The answer, a 401 included, expires the `auth.cookie.*` token cookie (the one `golem15.sociallogin`'s `token_cookie` sets), and any other session cookie the request carries, with that cookie's path, domain, SameSite and Secure. `POST /refresh` loads the token's user and refuses (401, `Could not refresh token`, `User not found`) a deactivated or banned user and a token issued before the user's `tokens_valid_after`; a suspension alone does not stop a refresh. `GET /fetch`, `POST /refresh`, `POST /update` and `POST /change-password`, like the plugin's other signed-in routes, read the session token as the `jwt` guard does: the bearer header first, then the `token` and `auth_token` cookies, so a cookie-only session works on them and a bearer header wins when both are sent. A `POST /refresh` whose token came from the `auth.cookie.*` cookie (`auth.cookie.name`, default `token`) with no bearer header gets that cookie back with the rotated token: the cookie has the `bouncer.LoadCookieConfig` attributes, HttpOnly and Max-Age `refresh_ttl`, and the answer is `{}`, so the token never reaches JavaScript. This holds whoever wrote the cookie (this plugin's `golem15.user.jwt.token_cookie`, `golem15.sociallogin`'s `token_cookie` or the application); a frontend that writes the `token` cookie itself and refreshes through it gets it back HttpOnly, without a body token, so such a frontend sends the bearer header to keep rotating in the body. A refresh carried by the bearer header (a cookie sent with it included) or by the other session cookie answers `{"token": …}` and writes no cookie; the old token is blacklisted after `golem15.user.jwt.blacklist_grace`, so that caller stores the new token itself. A refused refresh writes and forgets no cookie. When `bouncer.LoadCookieConfig` refuses the `auth.cookie` block, a cookie-carried refresh answers the opaque 500 before anything is rotated; a bearer refresh never reads that block. Keep `auth.cookie.name` at `token` or `auth_token`, the cookies the guard reads. With `golem15.user.jwt.token_cookie` on, `POST /login`, `POST /register` (when it signs the new account in) and `POST /activate-by-code` set that HttpOnly session cookie (`bouncer.LoadCookieConfig` attributes, Max-Age `refresh_ttl`) and leave `token` out of the body; `user`, and `message` on activate-by-code, stay. With it off (the default) the token is in the body and no cookie is set. SameSite stays the `auth.cookie` setting (`lax` by default) and there is no CSRF token, so do not set `same_site: none` for this cookie. With the key on, a broken `auth.cookie` block answers those three routes with the opaque 500 before they sign in, create or activate anything. Personal API tokens (`POST /tokens`) are not sessions and are unaffected. A cookie-carried session relies on the cookie's SameSite attribute against cross-site requests (the `auth.cookie` default is `lax`), as on the `jwt.auth` routes.
|
||||
- **Login gates.** Register publishes a `*classes.LoginGates` registry. Another plugin (a two-factor plugin, for example) looks it up with `app.Lookup[*classes.LoginGates]()` and adds a `classes.LoginGate` in its Boot. `POST /login` consults the gates through `controllers.CheckLoginGates` after the password, activation and throttle checks (and the bcrypt rehash) and before it restores a deactivated account, sends the reactivate mail, stamps `last_seen` and mints the token. A gate sees a `classes.LoginAttempt` (`User`, `Source`, the already-read login body as `Fields`, `Request`). A nil result allows the sign-in; a `classes.LoginGateResult` replaces the token response with its `Status` (0 means 200) and `Body`, for example `{"two_factor_required":true,"challenge_token":…,"available_methods":[…],"expires_at":…}`, and no token is issued, no account is restored and no login event fires. A gate error fails closed with the opaque 500. Without a gate, `/login` answers exactly as before. `POST /refresh` never consults the gates.
|
||||
- **Registration and activation.** `POST /register`, `POST /activate`, `POST /activate-by-code`. Registration can be switched off and throttled; `activate_mode` is `auto`, `user` (a mailed code) or `admin`, with codes from `IssueActivationCode` and `VerifyActivationCode`. A `/register` body sets only the `User.RegisterFillable` columns: `name`, `surname`, `email`, `password` (stored as its hash), `preferred_locale` and `marketing_consent`. It cannot set `organisation_id` or `organisation_role` (membership is the administrator's or the application's), `is_onboarded`, `must_change_password`, or the activation, reset, address proof, handle and permission columns; other keys are ignored (they still reach `RegisterEvent.Payload`). `created_ip_address` and `last_ip_address` are server-set from the client address only. With `require_activation` on (the default), `POST /login` refuses an account that is not activated with the same 401 invalid-login answer as a wrong password and counts the attempt for the login throttle. Such an account is activated by the mailed code (`POST /activate-by-code` answers with a token unless a login gate holds the sign-in back, for example a second-factor challenge the user completes through the gate's plugin; the account is activated either way), by the invitation link or by an administrator. `POST /activate` serves the sessions of not-activated accounts, which exist when `require_activation` is off. `Login` checks in this order: a ban or an active suspension (`RejectIfThrottled`), the password, the activation, then the deactivation restore.
|
||||
- **JWT sessions.** `POST /login`, `GET /fetch`, `POST /refresh`, `POST /logout`. Boot registers the `jwt` guard with the framework's `bouncer.Registry` and exposes it as the `jwt.auth` middleware for other plugins. The guard reads the session cookies `classes.SessionCookieNames()` lists and resolves the published `bouncer.BlacklistStore` on every request. Boot installs the plugin's GORM hooks (`classes.RegisterHooks`) and publishes the Postgres `jwt_blacklist` store (`bouncer.NewPostgresBlacklist`) through `lagoon.OnDatabase`; the expired rows are deleted by the scheduled `user:jwt-blacklist-sweep` command (see Configuration). Under `summer serve`, which publishes the database after Boot, they take effect when `lagoon.Publish` runs, before the router is built; when the database is already published they take effect at once. While no store is published, no token counts as blacklisted. `POST /logout` ends the session however the token travels: the bearer header, or only the `token` or `auth_token` cookie the guard also reads. Every session token the request carries goes to the Postgres `jwt_blacklist` until its refresh window closes (the later of `exp` and `iat` plus `refresh_ttl`, plus a minute), so the guard refuses it on the next request and `POST /refresh` cannot revive it after the access token expired; a token whose access lifetime passed is revoked too while it could still be refreshed. The answer, a 401 included, expires the `auth.cookie.*` token cookie (the one `golem15.sociallogin`'s `token_cookie` sets), and any other session cookie the request carries, with that cookie's path, domain, SameSite and Secure. `POST /refresh` loads the token's user and refuses (401, `Could not refresh token`, `User not found`) a deactivated or banned user and a token issued before the user's `tokens_valid_after`; a suspension alone does not stop a refresh. `GET /fetch`, `POST /refresh`, `POST /update` and `POST /change-password`, like the plugin's other signed-in routes, read the session token as the `jwt` guard does: the bearer header first, then the `token` and `auth_token` cookies, so a cookie-only session works on them and a bearer header wins when both are sent. A `POST /refresh` whose token came from the `auth.cookie.*` cookie (`auth.cookie.name`, default `token`) with no bearer header gets that cookie back with the rotated token: the cookie has the `bouncer.LoadCookieConfig` attributes, HttpOnly and Max-Age `refresh_ttl`, and the answer is `{}`, so the token never reaches JavaScript. This holds whoever wrote the cookie (this plugin's `golem15.user.jwt.token_cookie`, `golem15.sociallogin`'s `token_cookie` or the application); a frontend that writes the `token` cookie itself and refreshes through it gets it back HttpOnly, without a body token, so such a frontend sends the bearer header to keep rotating in the body. A refresh carried by the bearer header (a cookie sent with it included) or by the other session cookie answers `{"token": …}` and writes no cookie; the old token is blacklisted after `golem15.user.jwt.blacklist_grace`, so that caller stores the new token itself. A refused refresh writes and forgets no cookie. When `bouncer.LoadCookieConfig` refuses the `auth.cookie` block, a cookie-carried refresh answers the opaque 500 before anything is rotated; a bearer refresh never reads that block. Keep `auth.cookie.name` at `token` or `auth_token`, the cookies the guard reads. With `golem15.user.jwt.token_cookie` on, `POST /login`, `POST /register` (when it signs the new account in) and `POST /activate-by-code` set that HttpOnly session cookie (`bouncer.LoadCookieConfig` attributes, Max-Age `refresh_ttl`) and leave `token` out of the body; `user`, and `message` on activate-by-code, stay. With it off (the default) the token is in the body and no cookie is set. SameSite stays the `auth.cookie` setting (`lax` by default) and there is no CSRF token, so do not set `same_site: none` for this cookie. With the key on, a broken `auth.cookie` block answers those three routes with the opaque 500 before they sign in, create or activate anything. Personal API tokens (`POST /tokens`) are not sessions and are unaffected. A cookie-carried session relies on the cookie's SameSite attribute against cross-site requests (the `auth.cookie` default is `lax`), as on the `jwt.auth` routes.
|
||||
- **Login gates.** Register publishes a `*classes.LoginGates` registry. Another plugin (a two-factor plugin, for example) looks it up with `app.Lookup[*classes.LoginGates]()` and adds a `classes.LoginGate` in its Boot. `POST /login` consults the gates through `controllers.CheckLoginGates` after the password, activation and throttle checks (and the bcrypt rehash) and before it restores a deactivated account, sends the reactivate mail, stamps `last_seen` and mints the token. `POST /activate-by-code` consults them after the mailed code verified and before it mints the token, with source `password`: with `require_activation` off an account can enable a second factor before it activates, so the mailed code must not stand in for that factor. A gate sees a `classes.LoginAttempt` (`User`, `Source`, the already-read login or activation body as `Fields`, `Request`). A nil result allows the sign-in; a `classes.LoginGateResult` replaces the token response with its `Status` (0 means 200) and `Body`, for example `{"two_factor_required":true,"challenge_token":…,"available_methods":[…],"expires_at":…}`, and no token is issued, no session cookie is set, no account is restored and no login event fires. A gate error fails closed with the opaque 500. An activation a gate held back or failed stays committed. Without a gate, `/login` and `/activate-by-code` answer exactly as before. `POST /refresh` never consults the gates.
|
||||
- **Login event.** Every sign-in that issued a session token fires `classes.LoginEvent` (`classes.LoginEventName`, `golem15.user.login`, PHP's name) with `User` and `Source` (`LoginSourcePassword`, `LoginSourceSocial`, `LoginSourcePasskey`, `LoginSourceTwoFactor`, `LoginSourceDevice`), after the token was minted. `POST /login` fires it with `password`; another plugin that completes a sign-in fires it through `controllers.FireLoginEvent`. A listener error is logged and never fails the sign-in. Refresh and `/register` fire none.
|
||||
- **Password-change hook.** A password reset, the user's own `POST /change-password` and an administrator setting a password on the Users screen fire `classes.AccessRevokedEvent` inside the write's transaction (see Access revocation); `(*AccessRevokedEvent).PasswordChanged()` reports these three reasons. A two-factor plugin listens to it to revoke trusted devices, and this plugin revokes the users' pending and confirmed device sessions (see Device authorization); a listener error rolls the password write back. The bcrypt rehash on login and a new account fire nothing.
|
||||
- **Password reset and change.** `POST /forgot-password` answers the same body for known and unknown addresses; `POST /reset-password` consumes a code from `IssueResetCode`. `POST /change-password` requires the current password. With `golem15.user.password.public_routes` false, `POST /login`, `POST /forgot-password` and `POST /reset-password` are not registered, so they answer the router's own 404 like any unknown path (any method, so no 405 shows they exist), while the `controllers` handlers stay exported.
|
||||
@@ -40,7 +40,7 @@ It owns the `users` table extensions, `user_throttle`, `jwt_blacklist`, `user_ap
|
||||
- **Address proof.** `users.email_verified_at` records when the account's owner proved control of the address (`User.EmailVerifiedAt`). Exactly two flows write it: the mailed activation code (`POST /activate`, `POST /activate-by-code` and the invitation link, through `VerifyActivationCode`) and a completed reset-code password reset (`POST /reset-password`). `POST /register` in `auto` or `admin` mode, `RegisterUser`, an administrator's create and the admin Activate action, `POST /change-password` and social sign-ins record none. The proof follows the address: an email change through `POST /update` or the admin Users form clears it, while a change of letter case only keeps it. The column is never mass-assigned and is in no user API payload, admin form or list. No migration or code path backfills it: accounts from before v0.1.5 have no proof. An application that trusts its imported addresses may set the column in its own data migration; this plugin does not. A social-login plugin links a verified provider's identity onto an existing account only when it is set.
|
||||
- **Handle.** `users.handle` is a unique nullable `VARCHAR(255)` generated on create (`classes.HandleGenerator`, charset `[a-z0-9._-]`, length 2–255). It is omitted from the user JSON payload (`json:"-"`). `user:backfill-handles` fills existing rows that still have none.
|
||||
- **User lighthouse authorizer.** Boot calls `classes.RegisterUserAuthorizer`: `lighthouse.From` then `Registry.Register("user", …)` if the namespace is free. `classes.AuthorizeUser` allows only `user:{id}` for that user (`lighthouse.ChannelID` on the two-segment name).
|
||||
- **Shared API tokens.** `user_api_tokens` stores one hashed personal/OAuth credential per user for the whole application. The `user.api_token` guard authenticates it for any plugin; `user.scope:<scope>` limits delegated access and `user.permission:<code>` checks the user's current group permissions. `POST/GET/DELETE /tokens` manage personal tokens, and `user:token:create`, `user:token:list` and `user:token:revoke` provide the CLI equivalent. A raw secret is shown only when created.
|
||||
- **Shared API tokens.** `user_api_tokens` stores one hashed personal/OAuth credential per user for the whole application. The `user.api_token` guard authenticates it for any plugin; `user.scope:<scope>` limits delegated access and `user.permission:<code>` checks the user's current group permissions. `POST/GET/DELETE /tokens` manage personal tokens, and `user:token:create`, `user:token:list` and `user:token:revoke` provide the CLI equivalent. A raw secret is shown only when created. A refusal by `user.scope:<scope>` or `user.permission:<code>` answers 403 with the existing `error` and `message` plus `missing_scope` or `missing_permission` naming what is missing.
|
||||
- **Member token scopes.** A member personal token (`usr_`) carries the built-in scopes `read`, `write` and `ai`, plus any scope another plugin declares with `pact.HasFrontendTokenScopes`:
|
||||
|
||||
```go
|
||||
@@ -53,7 +53,7 @@ It owns the `users` table extensions, `user_throttle`, `jwt_blacklist`, `user_ap
|
||||
```
|
||||
|
||||
Boot compiles the catalog from the activated plugins (`classes.CompileAPITokenScopes`, published as `*classes.APITokenScopeCatalog` and as `pact.MemberTokenScopeCatalog`) and fails on a name that does not pass `pact.ValidTokenScopeName`, a built-in redeclared, a reserved name `backend` or `offline_access`, a name two plugins declare (the error names both), an empty label or description, an `Implies` other than empty, `read` or `write` (the error names the plugin and that value), or a label or description phrase key (containing `::`) that the translator does not have. `Implies` is only those three values: empty means the declared scope is not implied, and the built-ins `read`, `write` and `ai` keep it empty. Implied names are not stored on a token row or a fingerprint. `POST /tokens` and `classes.MintAPITokenFor(app, …)` accept the scopes of the application's own catalog (`classes.APITokenScopesFor(app)`) and answer an undeclared one with the usual 422 `The selected scope is invalid.`; the console's `user:token:create` uses `MintAPITokenFor` too. Applications mint with `MintAPITokenFor`. The older `classes.MintAPIToken` is deprecated; it keeps its signature and accepts the built-ins plus every scope a catalog compiled in the same process declared, a fallback for existing callers; production runs one application per process, so that is the application's own catalog, while a test binary that boots several applications shares it (`classes.ResetDeclaredAPITokenScopes` clears it, for tests only). `user.scope:<name>`, `middleware.Scope` and `APIToken.HasScope` check a declared scope like a built-in, and `GET /tokens` lists it in `scopes`. `GET /tokens/scopes` (`jwt.auth`) answers `{"data":[{"name","label","description","built_in"}]}`, the built-ins first, then the declared scopes in activation order, with phrase-key labels and descriptions translated for the request locale. The admin `g15_` token catalog never shows these scopes (it reads `pact.HasTokenScopes` only). `classes.AllowedAPITokenScopes` stays the built-in list.
|
||||
- **Mail templates.** Activation, reset, reactivation and invitation mails in Polish and English (`golem15.user::mail.*`, layout `golem15.user::mail.layouts.user`); the locale follows the user (`ResolveMailLocale`). The invitation (`golem15.user::mail.invite`) is sent when an administrator creates a user with "Send invitation by email" set; it carries the user's login and an activation link, never the password.
|
||||
- **Mail templates.** Activation, reset, reactivation and invitation mails in Polish and English (`golem15.user::mail.*`, layout `golem15.user::mail.layouts.user`); the Polish templates have Polish subjects. The language follows the user's `preferred_locale`, then the request locale (the translate plugin's, else the raw `Accept-Language` header), each normalised to `pl` or `en` by `NormalizeMailLocale` (comma lists, q-weights, region subtags such as `en-GB`, case), then `golem15.user.mail.fallback_locale` (`ResolveMailLocaleFor`). The invitation (`golem15.user::mail.invite`) is sent when an administrator creates a user with "Send invitation by email" set; it carries the user's login and an activation link, never the password.
|
||||
- **Extension events.** `RegisterEvent` fires after a user row is created; its `Payload` is a copy of the register input (extra keys a client sent included, `password` and `password_confirmation` never), so it is untrusted client input. `CreatedEvent` (`classes.CreatedEventName` `user.Created`) fires from API register and admin create. `/register` logs a failing `RegisterEvent` or `CreatedEvent` listener at Error level and continues: a committed registration is never undone or failed by a listener. `DeletingEvent` (`classes.DeletingEventName` `user.Deleting`) fires from `FormAfterDelete` before `ForceDeleteCleanup` / unscoped delete, inside the same transaction. `GetApiArrayEvent` lets other plugins merge keys into the user payload.
|
||||
- **Registration for other plugins.** `RegisterUser`, `FireRegisterEvent`, `IssueToken` and `APIArray` are the steps `POST /register` runs, exported so another plugin (a first-run setup endpoint, for example) creates a user with the same validation, hashing, event, token and payload.
|
||||
- **OAuth providers.** `GET /oauth-providers` lists the social sign-in providers a social-login plugin has enabled, read on every request from its published `classes.OAuthProviderSource`. Without one it answers the empty list, as before.
|
||||
@@ -233,7 +233,7 @@ Packages:
|
||||
- `BackendLinkShow`, `BackendLinkShowPost`, `BackendLinkConfirm` and `TokenMe`, the handlers of the account link and `/token/me` routes.
|
||||
- `APIArray(ctx, app, user)` builds the user payload, extended by `GetApiArrayEvent` listeners.
|
||||
- `FinishLogin(ctx, app, db, user, ip)` runs the steps `POST /login` takes after authentication, for a caller that authenticated the user another way (a social sign-in): it restores a soft-deleted account and sends the reactivate mail, records `ip` as `last_ip_address` and touches `last_seen` (a failure there is only logged). It checks no password, throttle, activation or ban and fires no event; the caller does those checks, consults the login gates before it and fires the login event after it minted the token.
|
||||
- `CheckLoginGates(ctx, app, attempt)` consults the published `*classes.LoginGates` (none published allows the sign-in) and returns its answer: nil allows, a `*classes.LoginGateResult` replaces the token response, an error must fail the sign-in closed. A social-login plugin calls it before it issues a token.
|
||||
- `CheckLoginGates(ctx, app, attempt)` consults the published `*classes.LoginGates` (none published allows the sign-in) and returns its answer: nil allows, a `*classes.LoginGateResult` replaces the token response, an error must fail the sign-in closed. `Login` and `ActivateByCode` call it before they mint; a social-login plugin calls it before it issues a token.
|
||||
- `FireLoginEvent(ctx, app, user, source)` fires `classes.LoginEvent` and returns the listeners' error; call it after the token was minted and log the error.
|
||||
- `DeviceInitiate`, `DeviceStatus`, `DeviceAuthorize`, `DeviceIndex` and `DeviceDestroy`, the device authorization handlers (see Device authorization).
|
||||
- `RegistrationSettings(app)` returns `allow_registration`, `use_register_throttle`, `activate_mode` and `require_activation` with their defaults (`true`, `true`, `auto`, `true`), and `RegistrationsFromIP(ctx, db, ip)` counts the accounts created from an IP in the last 60 minutes (`/register` refuses at 3 with the throttle on).
|
||||
@@ -251,17 +251,19 @@ Packages:
|
||||
- `OrganisationLogoURL(ctx, app, org, size)`, `OrganisationLogoFields(ctx, app, org)` and `OrganisationLogoSize`, the organisation logo for an application's organisation payloads (see Organisations).
|
||||
- `AvatarURL(ctx, app, user, size)`, the display picture rule of the user payload at any size: the avatar thumbnail (size by size, mode auto) when the user has an avatar and a file bucket is published, the original file's public URL (`attach.File.URL`, which follows `storage.uploads.public_path_prefix` and `public_url`) when the thumbnail fails, otherwise the gravatar URL. The URL may be protocol-relative or relative. The payload's `avatar_url` comes from it at 128.
|
||||
- `BackendLinks` (`CreateLinkRequest`, `LinkRequestByCode`, `ConfirmLinkRequest`, `SetLink`, `RemoveLink`, `LinkFor`, `LinkOf`, `LinkedBackendUser`, `RegisterBackendLinkListeners`), its errors `ErrLinkRequestNotFound`, `ErrLinkRequestUsed`, `ErrLinkRequestExpired`, `ErrStaleSession`, `ErrAlreadyLinked`, `ErrBackendUserUnavailable` and `ErrFrontendUserUnavailable`, the events `BackendLinkedEvent` / `BackendLinkedEventName` and `BackendUnlinkedEvent` / `BackendUnlinkedEventName`, `BackendLinkRequestTTL(app)`, `DefaultBackendLinkRequestTTL`, `FrontendURL(app)`, `BackendLinkPagePath(app)`, `DefaultBackendLinkPagePath`, `BackendLinksFor(app)` (the published service, or one over the app) and `BackendDisplayName(admin)`.
|
||||
- `BlacklistSweepInterval(app)` reads `golem15.user.jwt.blacklist_sweep_interval` (`DefaultBlacklistSweepInterval` when unset, 0 for no sweep, an error for an interval the scheduler cannot run); `JWTBlacklistTable` is the blacklist store's table.
|
||||
- `PermissionManageBackendLinks`, `FrontendPermissionCatalog(ctx, app, db)`, `MCPUserGuard`, `FireSubjectChanged(ctx, app, guard, userID, kind)` and `FireSubjectChangedAfterCommit(ctx, app, tx, guard, userID, kind)` with the guard names `SubjectGuardUser` and `SubjectGuardBackend`, and `FireSubjectEvent(ctx, app, ev)` and `FireSubjectEventAfterCommit(ctx, app, tx, ev)`, which fire a whole `pact.MCPSubjectChanged` (with `TokenID` or `ClientID` to end only one token's or one client's sessions).
|
||||
- `AccessRevokedEvent` / `AccessRevokedEventName` and `FireAccessRevoked(ctx, app, tx, userIDs, before, reason)` (see Access revocation).
|
||||
- `LoginAttempt`, `LoginGateResult`, `LoginGate` (`CheckLogin(ctx, attempt)`), `LoginGates` with `NewLoginGates()`, `Add(gate)` and `Check(ctx, attempt)`, the login-gate seam (see Login gates), and the sources `LoginSourcePassword`, `LoginSourceSocial`, `LoginSourcePasskey`, `LoginSourceTwoFactor` and `LoginSourceDevice`.
|
||||
- `LoginEvent` / `LoginEventName` (see Login event).
|
||||
- `DeviceShortCodeAlphabet`, `NewDeviceToken()`, `NewDeviceShortCode()`, `NormalizeDeviceShortCode(s)`, `DeviceAuthTTL(app)`, `DeviceAuthURLFor(app, token, shortCode)`, `DeviceAuthURL(app, token)` (the same with the token in place of the short code), `DeviceDisplayName(stored, userAgent)`, `RevokeDeviceSessions(ctx, db, userIDs...)` (revokes the users' pending and confirmed sessions; the plugin calls it for every `AccessRevokedEvent`), `FollowDeviceJTI(ctx, db, oldJTI, newJTI)` (moves a used session to a refreshed token's jti and reports a session revoked meanwhile; `POST /refresh` calls it and refuses the refresh then) and `HandOverDeviceJTI(ctx, db, oldJTI, newJTI)` (the same move without the report), the device authorization helpers; device tokens are hashed with `HashAPIToken`.
|
||||
- `TwoFactorAdmin` (`HasTwoFactor(ctx, tx, userID)`, `Reset(ctx, tx, user)`) and `PermissionResetTwoFactor`, the Reset 2FA slot (see Admin: Reset 2FA), and `(*AccessRevokedEvent).PasswordChanged()` (see Password-change hook).
|
||||
- `MailTemplate(base, locale)`, `ResolveMailLocale(ctx, user)`, `ResolveMailLocaleFor(ctx, app, user)`, `NormalizeMailLocale(raw)` and `MailFallbackLocale(app)`, the mail language helpers. `ResolveMailLocale` returns `pl`, `en` or `""` (neither the user nor the request names a supported language); a plugin that mails in the user's language calls `ResolveMailLocaleFor`, which adds the application's fallback and always returns `pl` or `en`, and passes its result to `MailTemplate`.
|
||||
- `HandleGenerator`, `AssignHandle(ctx, db, user)`, `CreatedEvent` / `CreatedEventName`, `DeletingEvent` / `DeletingEventName`, `DeactivatingEvent` / `DeactivatingEventName`, `AuthorizeUser` and `RegisterUserAuthorizer`.
|
||||
- `middleware`: `APITokenGuard`, `Scope`, `Permission` and `BearerToken`.
|
||||
- `models`: `User`, `Throttle`, `Organisation`, `UserGroup`, `UsersGroup` (the `users_groups` pivot), `APIToken`, `OAuthIdentity`, `FrontendPermission`, `BackendLink`, `BackendLinkRequest`, `DeviceAuthSession` (with `DeviceStatusPending`, `DeviceStatusConfirmed`, `DeviceStatusUsed`, `DeviceStatusExpired` and `DeviceStatusRevoked`) and `PermissionSet`. `PermissionSet` reads a stored permission column tolerantly (NULL, an empty string, `[]`, numeric strings) and writes a JSON object of integers; `ParsePermissionSet` and `PermissionSet.Text` do the same for a column that is a plain string on its model. `UserGroup.UsersCount` is filled only by a query that selects `users_count` (the admin list does). `Organisation.Members` is the relation behind the members manager, `Organisation.AttachRelations` declares its avatar (`OrganisationAvatarField`) and its logo (`OrganisationLogoField`), and `Slugify` is the slug rule. `User.FilterScope` answers the admin list scope `FilterByGroup`, and `User.AttachRelations` declares the avatar (`AvatarField`). `User.RegisterFillable` is the registration allow-list; `User.Fillable` is the wider mass-assignment backstop of the admin Users form (cabana intersects it with the form's fields) and of trusted application code.
|
||||
- `updates`: the gormigrate migrations, returned by `updates.All()`.
|
||||
- `console`: `RequirePasswordChange`, `BackfillHandles` and `APITokenCommands`.
|
||||
- `console`: `RequirePasswordChange`, `BackfillHandles`, `JWTBlacklistSweep` and `APITokenCommands`.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -274,12 +276,13 @@ Defaults live in `config/config.yaml` and are merged under `golem15.user.*`. Any
|
||||
| `golem15.user.jwt.refresh_ttl` | `20160` | Refresh window in minutes. |
|
||||
| `golem15.user.jwt.blacklist_grace` | `0` | Grace period in seconds for a blacklisted token. |
|
||||
| `golem15.user.jwt.leeway` | `0` | Clock leeway in seconds (declared for parity, not read yet). |
|
||||
| `golem15.user.jwt.blacklist_sweep_interval` | `10m` | How often expired blacklist rows are deleted (a Go duration). |
|
||||
| `golem15.user.jwt.blacklist_sweep_interval` | `10m` | How often the scheduler runs `user:jwt-blacklist-sweep`, which deletes the `jwt_blacklist` rows whose `expires_at` has passed (a Go duration). It must be at least 1s and divide 24h evenly (`1m`, `10m`, `1h`); `0` schedules no sweep. A value that does not parse, is negative, is shorter than a second or does not divide 24h fails boot. The sweep runs on the job worker's scheduled queue: the in-process worker of `summer serve` while `queue.work_in_serve` is on, `queue:work`, or `schedule:run`; with no worker on that queue, run `schedule:run --once` from cron or the command by hand. The schedule runs once per period across instances. |
|
||||
| `golem15.user.jwt.token_cookie` | `false` | When on, `POST /login`, `POST /register` (when it signs the new account in) and `POST /activate-by-code` set the HttpOnly session cookie with the `auth.cookie.*` attributes (`bouncer.LoadCookieConfig`; Max-Age `refresh_ttl`) and leave `token` out of the body (`user`, and `message` on activate-by-code, stay). When off, the token is in the body and no cookie is set. The twin of `golem15.sociallogin.token_cookie`. |
|
||||
| `golem15.user.activation.require_activation` | `true` | Whether an account must be activated before login. When `true`, `POST /login` refuses a not-activated account (the opaque invalid-login answer, counted as a failed attempt) and `/register` in `admin` mode returns no token; when `false`, both sign such an account in. |
|
||||
| `golem15.user.activation.activate_mode` | `auto` | `auto`, `user` (mailed code) or `admin`. |
|
||||
| `golem15.user.activation.reset_ttl_minutes` | `60` | Password reset code lifetime. |
|
||||
| `golem15.user.activation.activation_ttl_hours` | `72` | Activation code lifetime. |
|
||||
| `golem15.user.mail.fallback_locale` | `pl` | The mail language when the user's `preferred_locale` and the request locale name neither `pl` nor `en`. `pl` keeps the unsuffixed templates; `en` (`SUMMER_GOLEM15__USER__MAIL__FALLBACK_LOCALE=en`) suits English-only sites. Region forms such as `en-GB` are accepted; any other value fails boot. Read on every send. The user and the request still come first, so a browser that asks for Polish first gets Polish mail on an application whose fallback is `en`. |
|
||||
| `golem15.user.registration.allow_registration` | `true` | Whether `POST /register` accepts new accounts. |
|
||||
| `golem15.user.registration.use_register_throttle` | `true` | Whether registration is limited to three accounts per IP an hour. |
|
||||
| `golem15.user.throttle.attempt_limit` | `5` | Failed logins before suspension. |
|
||||
@@ -303,6 +306,7 @@ Defaults live in `config/config.yaml` and are merged under `golem15.user.*`. Any
|
||||
|---------|---------|---------|
|
||||
| `user:require-password-change <email>` | Flag an account so its next session must set a new password. Ends with `Password change required for <email>`. | `bin/<app> user:require-password-change jane@example.com` |
|
||||
| `user:backfill-handles` | Assign a unique handle to every user row that still has none, with a progress bar. Ends with `Assigned handles to N user(s)`. | `bin/<app> user:backfill-handles` |
|
||||
| `user:jwt-blacklist-sweep` | Delete the `jwt_blacklist` rows whose `expires_at` has passed; the scheduler runs it every `golem15.user.jwt.blacklist_sweep_interval`. Ends with `Deleted the expired JWT blacklist rows.` | `bin/<app> user:jwt-blacklist-sweep` |
|
||||
| `user:token:create <email> [--name api] [--scopes read,write] [--expires RFC3339] [--json]` | Create an application-wide API token and print its secret once (also under `-q`); `--json` prints the token and its details as one object. | `bin/<app> user:token:create jane@example.com --scopes read --json` |
|
||||
| `user:token:list` | List token metadata without secrets or hashes; `--json` prints a JSON array with the expiry, revocation and last-use times. | `bin/<app> user:token:list --json` |
|
||||
| `user:token:revoke <id>` | Revoke a shared API token immediately. | `bin/<app> user:token:revoke 12` |
|
||||
@@ -325,6 +329,8 @@ go test ./... # full run, starts Postgres with testcontainers (needs D
|
||||
|
||||
`TestRegisterCORSPath` reads the host application's `config/http.yaml`, so run the tests inside an application checkout where the plugin is mounted at `plugins/golem15/user`.
|
||||
|
||||
The mail language is pinned by `TestNormalizeMailLocale`, `TestResolveMailLocale`, `TestResolveMailLocaleFor` and `TestMailFallbackLocale` (in `classes`, `-short`), `TestMailFallbackLocaleConfig`, `TestMailFallbackLocaleBoot` and `TestPolishMailSubjects` (root, `-short`; the last renders each Polish template next to its `-en` twin and requires a different subject) and `TestMailLocaleFromRequest` (Postgres, skipped under `-short`: `POST /forgot-password` with a raw `Accept-Language` request locale, the default and an `en` fallback, and a saved `en-GB`).
|
||||
|
||||
`TestCommandsDocumented` (in `-short`) logs, without failing, each command whose help lacks a description, long help, examples or an option description (`bonfire.CheckDocs`).
|
||||
|
||||
`TestRegisterIgnoresProtectedFields` posts organisation, IP and account-flag keys to `/register` and `RegisterUser` and checks that only the allow-listed columns and the server-side IP are stored; `TestRegisterListenerErrors` checks that failing register and created listeners do not fail the registration.
|
||||
@@ -333,6 +339,8 @@ go test ./... # full run, starts Postgres with testcontainers (needs D
|
||||
|
||||
`TestLogoutEndsTheSession` signs in through `POST /login` and logs out with the bearer header, with only the `token` or `auth_token` cookie, and with both a bearer and a different cookie token, then checks that the token is refused on a `jwt.auth` route, at `/fetch` and at `/refresh`, each through every carrier (bearer header, `token` cookie, `auth_token` cookie), that the forget cookies match the token cookie's attributes (also with a configured domain and SameSite), that the blacklist row lasts for the refresh window so `/refresh` stays refused after the sweep that follows the access token's expiry, that an expired but refreshable token is revoked, and which tokens a logout refuses with 401.
|
||||
|
||||
The blacklist sweep is pinned by `TestBlacklistSweepInterval` (in `classes`, `-short`: the default, valid intervals, `0` as a string, a duration, an int and a `SUMMER_` variable, and the values that must fail), `TestBlacklistSweepSchedule` (root, `-short`: the default and custom `Schedule()` entries, none for `0` or a bad value, every scheduled command registered), `TestBlacklistSweepBoot` (root, `-short`: Boot fails naming the key for each bad value and accepts `10m`, `0` and an unset key), `TestJWTBlacklistSweepCommand` (root, `-short`: one `Sweep` through the published store with the result line, a failing store, a nil app) and `TestJWTBlacklistSweepPostgres` (Postgres, skipped under `-short`: the command deletes the expired row and keeps the valid one, through the published store and through a database opened from `database.dsn`).
|
||||
|
||||
`TestBootBeforeDatabase` boots in the serve order (`party.Activate` with no database, then `lagoon.Publish`, through `newServeOrderEnv` in `admin_harness_test.go`). It checks that the blacklist store and the GORM hooks are installed on Publish and not before, and that a token ended by `POST /logout` is refused on a `jwt.auth` route through every carrier, at `/fetch` and at `/refresh`, with its `jwt_blacklist` row. `TestAppBlacklist` (in `-short`) covers the guard's per-request store lookup: no store, delegation and a failing store.
|
||||
|
||||
`TestSessionRoutesAcceptCookies` checks that a session `jwt.auth` accepts through only the `token` or `auth_token` cookie is served by `GET /fetch`, `POST /refresh` (through `token`, the `auth.cookie` default, the rotated token comes back in a rewritten cookie with a `{}` body; through `auth_token` it comes in the body with no cookie; the old token is refused afterwards), `POST /update`, `POST /change-password` (the calling token stays valid) and `POST /marketing-consent`; that a request without credentials still gets the old 401 bodies; that the bearer header wins over a cookie exactly as on `jwt.auth`, an invalid bearer included; and that a cut-off token and a banned user are refused through the cookie.
|
||||
@@ -353,7 +361,7 @@ go test ./... # full run, starts Postgres with testcontainers (needs D
|
||||
|
||||
`TestMemberTokenScopesBoot` (no Docker) checks that the scope Boot step fails for a name two plugins declare (naming both), for a redeclared `read`, `write` or `ai`, for a bad name, an empty label and a missing phrase key. With Docker: `TestMemberTokenScopes` walks the member token scope acceptance list item by item (mint and `middleware.Scope`, the 403 message, the 422 for an undeclared scope, the list, discovery in en and pl, the per-application catalog and the legacy fallback); `TestBackendLinkAuthTime` checks the link proof against login, request, refresh and re-login orders, a token without `auth_time` and another user's session token; `TestBackendLinkShowPost` checks that `POST /backend-link/show` answers like the GET route with `Cache-Control: no-store, private`, the fragment URL and `backend_links.page_path`; `TestAccessRevocation` checks `AccessRevokedEvent` from the ban action, the password reset, the password change and an administrator setting a password (ids, `Before`, reason, the transaction, the subject event after commit, the rollback on a failing listener) and that a banned user loses the backend link until unbanned; `TestUserMCPGuardClientIP` checks `last_used_ip` on the MCP personal-token path; `TestAPITokenRevokeEvent` checks the token-specific revoked event of `DELETE /tokens/{id}`; `TestOrganisationLogo` checks the logo field, the upload, `OrganisationLogoFields` with and without a logo, the URL fallback when the thumbnail fails, and that deleting an organisation removes its avatar and logo attachments, the rows and, once the delete commits, the blobs and thumbnails.
|
||||
|
||||
The login-gate seam, the password-change hook and the Reset 2FA slot have their own tests. `TestLoginGates` (in `-short`, clean under `-race`) pins the registry: a nil or empty registry allows, gates run in the order they were added, the first result or error wins and stops the chain, nil gates are ignored, and `controllers.CheckLoginGates` allows when no registry is published. `TestLoginGateOrder` pins where `POST /login` asks the gates: refused first factors (wrong password, unknown email, not activated, banned) never reach them; the gate sees the attempt with the body already read; the bcrypt rehash happens before a challenge and fires no password-change event; a challenged deactivated account stays deactivated with no mail and no login event, while an allowed one is restored with one reactivate mail and one login event; a gate's status and body pass through; `/refresh` never asks a gate. `TestPasswordChangedSources` checks that the reset, the user's own change and an administrator setting a password each fire one `AccessRevokedEvent` with `PasswordChanged()` true inside the write's transaction (a listener's write through `ev.Tx` commits with it, a listener error rolls both back), and that the rehash and a registration fire none. `TestResetTwoFactorAction` covers the `reset_two_factor` record action: not offered without a published `classes.TwoFactorAdmin`, offered with the danger confirmation when one reports a second factor, hidden when it reports none, refused without `golem15.users.reset_two_factor`, `Run` refused outside the action's transaction, `Reset` committed with the action and rolled back by its error, and a privileged-group member refused with 403 before `Reset` without `golem15.users.manage_privileged_groups`. The plan 01 smoke tests (`TestLoginGatesSmoke`, `TestLoginGateSmoke`, `TestPasswordChangedEventSmoke`, `TestResetTwoFactorSlotSmoke`) stay. The Postgres tests need Docker.
|
||||
The login-gate seam, the password-change hook and the Reset 2FA slot have their own tests. `TestLoginGates` (in `-short`, clean under `-race`) pins the registry: a nil or empty registry allows, gates run in the order they were added, the first result or error wins and stops the chain, nil gates are ignored, and `controllers.CheckLoginGates` allows when no registry is published. `TestLoginGateOrder` pins where `POST /login` asks the gates: refused first factors (wrong password, unknown email, not activated, banned) never reach them; the gate sees the attempt with the body already read; the bcrypt rehash happens before a challenge and fires no password-change event; a challenged deactivated account stays deactivated with no mail and no login event, while an allowed one is restored with one reactivate mail and one login event; a gate's status and body pass through; `/refresh` never asks a gate. `TestActivateByCodeGates` pins `POST /activate-by-code`: a challenge or a refusal replaces the token with the gate's status and body and sets no cookie, the gate sees source `password` and the code in `Fields`, an allowing gate gets the usual token answer, a gate error answers the opaque 500, an invalid code never reaches a gate, and the account is activated whatever the gate answers. `TestPasswordChangedSources` checks that the reset, the user's own change and an administrator setting a password each fire one `AccessRevokedEvent` with `PasswordChanged()` true inside the write's transaction (a listener's write through `ev.Tx` commits with it, a listener error rolls both back), and that the rehash and a registration fire none. `TestResetTwoFactorAction` covers the `reset_two_factor` record action: not offered without a published `classes.TwoFactorAdmin`, offered with the danger confirmation when one reports a second factor, hidden when it reports none, refused without `golem15.users.reset_two_factor`, `Run` refused outside the action's transaction, `Reset` committed with the action and rolled back by its error, and a privileged-group member refused with 403 before `Reset` without `golem15.users.manage_privileged_groups`. The plan 01 smoke tests (`TestLoginGatesSmoke`, `TestLoginGateSmoke`, `TestPasswordChangedEventSmoke`, `TestResetTwoFactorSlotSmoke`) stay. The Postgres tests need Docker.
|
||||
|
||||
The device authorization flow is pinned by `TestDeviceCodes` (in `classes`, `-short`: 10,000 tokens and short codes, the alphabet in every position, no modulo bias, the normalization table), `TestDeviceAuthURL` and `TestDeviceDisplayName` (both `-short`: the `auth_url` template with `{short_code}` as the default, the TTL setting and PHP's user-agent order), and on Postgres through the assembled routes: `TestDeviceInitiate` (PHP's answer with an `auth_url` that carries the short code and not the token, the stored pending row, the TTL, the 255-character `device_name` bound, the cleanup of at most 500 stale pending or expired sessions per call, the retry of an insert whose short code collides with a stored one); `TestDeviceStatus` (unknown, pending, PHP's flat expired body for a pending or confirmed session past `expires_at`, used and revoked sessions that never expire); `TestDeviceAuthorize` (short-code forms, the 422 and 400 refusals, the token path, the short code in the token field, body-only fields, sessions bound to another user, a repeated authorize, expired, used and revoked sessions, concurrent authorizes by two users binding one, and the 401 for a missing, invalid, foreign-signed or ended session); `TestDeviceHandOverConcurrent` (50 concurrent polls hand one token over with one login event of source `device`; a poll with another `User-Agent` than the initiating device's takes nothing and the device still collects its token; a deactivated or banned user's session becomes revoked); `TestDeviceAccessRevocation` (a password change revokes the user's confirmed sessions and keeps used ones and other users' sessions, and a session authorized before `tokens_valid_after` hands nothing over without the event); `TestDeviceListAndRevoke` (only confirmed and used sessions, newest activity first, `is_current`, the display name, an empty list as `[]`, 404 for foreign and unknown ids, a repeated revoke, a revoked device signed out); `TestDeviceRevokeAfterRefresh` (the row follows one and two refreshes, a revoke ends the whole token lineage and the blacklist entry outlives the refresh window, a failed refresh leaves the row); `TestDeviceRevokeRacesRefresh` (a refresh of a session revoked after the blacklist check is refused without a token, and a device refreshing in a tight loop while it is revoked ends with its last token refused); `TestDeviceTokensAtRest` (the token column is the SHA-256 hex, no column holds the token or the session JWT). `TestDeviceAuthSessionsMigration` (in `updates`) checks the table's PHP column names plus `jwt_jti`, the types, the unique `token` and `short_code`, the status CHECK, the indexes, the cascade on user delete, the rollback and a second up. The plan 01 smoke tests `TestDeviceCodesSmoke`, `TestDeviceFlowSmoke` and `TestDeviceRevokeSmoke` stay.
|
||||
|
||||
|
||||
283
blacklist_sweep_test.go
Normal file
283
blacklist_sweep_test.go
Normal file
@@ -0,0 +1,283 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
sweepCommand = "user:jwt-blacklist-sweep"
|
||||
sweepIntervalKey = "golem15.user.jwt.blacklist_sweep_interval"
|
||||
)
|
||||
|
||||
// badSweepIntervals are values the scheduler cannot run, so Boot rejects them.
|
||||
var badSweepIntervals = []string{"soon", "3", "-1m", "500ms", "7m", "48h"}
|
||||
|
||||
// fakeBlacklist is a bouncer.BlacklistStore that records the Sweep calls.
|
||||
type fakeBlacklist struct {
|
||||
mu sync.Mutex
|
||||
sweeps []time.Time
|
||||
sweepErr error
|
||||
}
|
||||
|
||||
func (f *fakeBlacklist) Add(context.Context, string, time.Time, time.Time) error { return nil }
|
||||
|
||||
func (f *fakeBlacklist) IsBlacklisted(context.Context, string) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (f *fakeBlacklist) Sweep(_ context.Context, now time.Time) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.sweeps = append(f.sweeps, now)
|
||||
return f.sweepErr
|
||||
}
|
||||
|
||||
func (f *fakeBlacklist) calls() []time.Time {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([]time.Time(nil), f.sweeps...)
|
||||
}
|
||||
|
||||
// TestBlacklistSweepSchedule schedules user:jwt-blacklist-sweep every 10m
|
||||
// by default, before Register (nil app) too, at a custom interval, not at
|
||||
// all for 0 or a bad value, and every scheduled command is a registered
|
||||
// command.
|
||||
func TestBlacklistSweepSchedule(t *testing.T) {
|
||||
want := pact.ScheduledCommand{Command: sweepCommand, Cadence: pact.Every(10 * time.Minute)}
|
||||
app := bareApp(t)
|
||||
for name, p := range map[string]*Plugin{"unset": {app: app}, "nil app": {}} {
|
||||
s := p.Schedule()
|
||||
if len(s) != 1 || s[0].Command != want.Command || s[0].Cadence != want.Cadence || len(s[0].Args) != 0 {
|
||||
t.Fatalf("%s: schedule = %+v", name, s)
|
||||
}
|
||||
}
|
||||
names := map[string]bool{}
|
||||
for _, c := range (&Plugin{app: app}).Commands() {
|
||||
names[c.Name] = true
|
||||
}
|
||||
for _, s := range (&Plugin{app: app}).Schedule() {
|
||||
if !names[s.Command] {
|
||||
t.Fatalf("scheduled %s is not registered: %v", s.Command, names)
|
||||
}
|
||||
}
|
||||
|
||||
for value, every := range map[string]time.Duration{"1h": time.Hour, "30s": 30 * time.Second} {
|
||||
app := bareApp(t)
|
||||
if err := app.Config.Set(sweepIntervalKey, value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := (&Plugin{app: app}).Schedule()
|
||||
if len(s) != 1 || s[0].Command != sweepCommand || s[0].Cadence != pact.Every(every) {
|
||||
t.Fatalf("%s: schedule = %+v", value, s)
|
||||
}
|
||||
}
|
||||
for _, off := range []string{"0", "0s"} {
|
||||
app := bareApp(t)
|
||||
if err := app.Config.Set(sweepIntervalKey, off); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s := (&Plugin{app: app}).Schedule(); len(s) != 0 {
|
||||
t.Fatalf("%s: schedule = %+v, want none", off, s)
|
||||
}
|
||||
}
|
||||
if s := (&Plugin{app: envApp(t, "SUMMER_GOLEM15__USER__JWT__BLACKLIST_SWEEP_INTERVAL=0")}).Schedule(); len(s) != 0 {
|
||||
t.Fatalf("SUMMER_ 0: schedule = %+v, want none", s)
|
||||
}
|
||||
for _, bad := range badSweepIntervals {
|
||||
app := bareApp(t)
|
||||
if err := app.Config.Set(sweepIntervalKey, bad); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s := (&Plugin{app: app}).Schedule(); s != nil {
|
||||
t.Fatalf("%s: schedule = %+v, want nil", bad, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// envApp is a bare application whose config also reads environ.
|
||||
func envApp(t *testing.T, environ ...string) *backpack.App {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: user-env\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: append([]string{"SUMMER_ENV=development"}, environ...)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return backpack.New(cfg)
|
||||
}
|
||||
|
||||
// TestBlacklistSweepBoot fails Boot on an interval the scheduler cannot run,
|
||||
// naming the key, and accepts 10m, 0 and an unset key.
|
||||
func TestBlacklistSweepBoot(t *testing.T) {
|
||||
withSecret := func(t *testing.T) *backpack.App {
|
||||
app := bareApp(t)
|
||||
if err := app.Config.Set("golem15.user.jwt.secret", "blacklist-sweep-boot-secret"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return app
|
||||
}
|
||||
for _, bad := range badSweepIntervals {
|
||||
app := withSecret(t)
|
||||
if err := app.Config.Set(sweepIntervalKey, bad); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := (&Plugin{}).Boot(app); err == nil || !strings.Contains(err.Error(), sweepIntervalKey) {
|
||||
t.Fatalf("Boot with %q: %v", bad, err)
|
||||
}
|
||||
}
|
||||
for _, good := range []string{"10m", "0", ""} {
|
||||
app := withSecret(t)
|
||||
if good != "" {
|
||||
if err := app.Config.Set(sweepIntervalKey, good); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := (&Plugin{}).Boot(app); err != nil && strings.Contains(err.Error(), sweepIntervalKey) {
|
||||
t.Fatalf("Boot with %q: %v", good, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestJWTBlacklistSweepCommand runs the command over a published store: one
|
||||
// Sweep with the current time and the result line; a failing store is an
|
||||
// error and no result line; a nil app is an error.
|
||||
func TestJWTBlacklistSweepCommand(t *testing.T) {
|
||||
run := func(t *testing.T, p *Plugin) (string, error) {
|
||||
t.Helper()
|
||||
cmd := commandNamed(t, p.Commands(), sweepCommand)
|
||||
var buf bytes.Buffer
|
||||
err := cmd.Run(context.Background(), emailArg{}, bonfire.NewOutput(nil, &buf, &buf))
|
||||
return buf.String(), err
|
||||
}
|
||||
|
||||
t.Run("published store", func(t *testing.T) {
|
||||
app := bareApp(t)
|
||||
fake := &fakeBlacklist{}
|
||||
if err := app.Publish[bouncer.BlacklistStore](fake); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := time.Now()
|
||||
out, err := run(t, &Plugin{app: app})
|
||||
after := time.Now()
|
||||
if err != nil {
|
||||
t.Fatalf("run: %v (output %q)", err, out)
|
||||
}
|
||||
calls := fake.calls()
|
||||
if len(calls) != 1 || calls[0].Before(before) || calls[0].After(after) {
|
||||
t.Fatalf("sweeps = %v, want one between %v and %v", calls, before, after)
|
||||
}
|
||||
if !strings.Contains(out, "Deleted the expired JWT blacklist rows.") {
|
||||
t.Fatalf("output = %q", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("failing store", func(t *testing.T) {
|
||||
app := bareApp(t)
|
||||
down := errors.New("blacklist down")
|
||||
if err := app.Publish[bouncer.BlacklistStore](&fakeBlacklist{sweepErr: down}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err := run(t, &Plugin{app: app})
|
||||
if !errors.Is(err, down) {
|
||||
t.Fatalf("run error = %v, want it to wrap %v", err, down)
|
||||
}
|
||||
if strings.Contains(out, "Deleted") {
|
||||
t.Fatalf("output after a failure = %q", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("nil app", func(t *testing.T) {
|
||||
if _, err := run(t, &Plugin{}); err == nil {
|
||||
t.Fatal("run with a nil app: no error")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestJWTBlacklistSweepPostgres runs user:jwt-blacklist-sweep against
|
||||
// Postgres: through the store Boot published it deletes the expired row and
|
||||
// keeps the one still valid; as a console command with no published
|
||||
// database it opens one from database.dsn.
|
||||
func TestJWTBlacklistSweepPostgres(t *testing.T) {
|
||||
skipShortPostgres(t)
|
||||
gdb, sqlDB := sessionDB(t)
|
||||
insert := func(t *testing.T, jti string, at time.Time) {
|
||||
t.Helper()
|
||||
if err := gdb.Exec(`INSERT INTO jwt_blacklist (jti, expires_at, valid_until) VALUES (?, ?, ?)`, jti, at, at).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { gdb.Exec(`DELETE FROM jwt_blacklist WHERE jti = ?`, jti) })
|
||||
}
|
||||
count := func(t *testing.T, jti string) int64 {
|
||||
t.Helper()
|
||||
var n int64
|
||||
if err := gdb.Raw(`SELECT COUNT(*) FROM jwt_blacklist WHERE jti = ?`, jti).Scan(&n).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
run := func(t *testing.T, p *Plugin) string {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
if err := commandNamed(t, p.Commands(), sweepCommand).Run(context.Background(), emailArg{}, bonfire.NewOutput(nil, &buf, &buf)); err != nil {
|
||||
t.Fatalf("run: %v (output %q)", err, buf.String())
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
t.Run("published store", func(t *testing.T) {
|
||||
p := bootPlugin(t, newSessionApp(t, gdb, sqlDB), "0s")
|
||||
insert(t, "sweep-me-published", time.Now().Add(-time.Minute))
|
||||
insert(t, "sweep-keep-published", time.Now().Add(time.Hour))
|
||||
out := run(t, p)
|
||||
if count(t, "sweep-me-published") != 0 {
|
||||
t.Fatal("the expired row was not deleted")
|
||||
}
|
||||
if count(t, "sweep-keep-published") != 1 {
|
||||
t.Fatal("the unexpired row was deleted")
|
||||
}
|
||||
if !strings.Contains(out, "Deleted the expired JWT blacklist rows.") {
|
||||
t.Fatalf("output = %q", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("database from config", func(t *testing.T) {
|
||||
app := backpack.New(sessionConfig(t))
|
||||
if err := app.Config.Set("database.dsn", sessionDSN); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Opening a database also loads the encryption keys from app.key.
|
||||
if err := app.Config.Set("app.key", base64.StdEncoding.EncodeToString([]byte("0123456789abcdef0123456789abcdef"))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := app.Lookup[*gorm.DB](); ok {
|
||||
t.Fatal("setup: a database is published")
|
||||
}
|
||||
insert(t, "sweep-me-console", time.Now().Add(-time.Minute))
|
||||
insert(t, "sweep-keep-console", time.Now().Add(time.Hour))
|
||||
run(t, &Plugin{app: app})
|
||||
if count(t, "sweep-me-console") != 0 {
|
||||
t.Fatal("the expired row was not deleted")
|
||||
}
|
||||
if count(t, "sweep-keep-console") != 1 {
|
||||
t.Fatal("the unexpired row was deleted")
|
||||
}
|
||||
})
|
||||
}
|
||||
52
classes/blacklist_sweep.go
Normal file
52
classes/blacklist_sweep.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
)
|
||||
|
||||
// JWTBlacklistTable is the table of migration
|
||||
// 202609220007_create_jwt_blacklist that the plugin's blacklist store uses.
|
||||
const JWTBlacklistTable = "jwt_blacklist"
|
||||
|
||||
// DefaultBlacklistSweepInterval is how often the scheduler runs
|
||||
// user:jwt-blacklist-sweep when golem15.user.jwt.blacklist_sweep_interval is
|
||||
// not set.
|
||||
const DefaultBlacklistSweepInterval = 10 * time.Minute
|
||||
|
||||
const blacklistSweepIntervalKey = "golem15.user.jwt.blacklist_sweep_interval"
|
||||
|
||||
// BlacklistSweepInterval reads golem15.user.jwt.blacklist_sweep_interval, a
|
||||
// Go duration (10m by default). 0 means no sweep is scheduled. Any other
|
||||
// value must be at least 1s and divide 24h evenly: the scheduler's Every
|
||||
// cadence is aligned to local midnight, so a period that does not divide the
|
||||
// day cannot be scheduled. A value that does not parse, is negative, is
|
||||
// shorter than a second or does not divide 24h is an error, so a typo fails
|
||||
// the boot instead of silently stopping the sweep.
|
||||
func BlacklistSweepInterval(app *backpack.App) (time.Duration, error) {
|
||||
if app == nil || app.Config == nil {
|
||||
return DefaultBlacklistSweepInterval, nil
|
||||
}
|
||||
raw := strings.TrimSpace(app.Config.String(blacklistSweepIntervalKey))
|
||||
if raw == "" {
|
||||
// A non-string value (an unquoted YAML 0) may read as "".
|
||||
if v, ok := app.Config.Lookup(blacklistSweepIntervalKey); ok && v != nil {
|
||||
raw = strings.TrimSpace(fmt.Sprint(v))
|
||||
}
|
||||
}
|
||||
if raw == "" {
|
||||
return DefaultBlacklistSweepInterval, nil
|
||||
}
|
||||
d, err := time.ParseDuration(raw)
|
||||
switch {
|
||||
case err != nil:
|
||||
case d == 0:
|
||||
return 0, nil
|
||||
case d >= time.Second && (24*time.Hour)%d == 0:
|
||||
return d, nil
|
||||
}
|
||||
return 0, fmt.Errorf("golem15.user: %s must be 0 (no sweep) or a duration of at least 1s that divides 24h evenly, such as 10m, got %q", blacklistSweepIntervalKey, raw)
|
||||
}
|
||||
59
classes/blacklist_sweep_test.go
Normal file
59
classes/blacklist_sweep_test.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
)
|
||||
|
||||
// TestBlacklistSweepInterval reads golem15.user.jwt.blacklist_sweep_interval:
|
||||
// 10m by default, 0 for no sweep (string, duration or unquoted YAML int, and
|
||||
// from a SUMMER_ variable), and an error naming the key for a value the
|
||||
// scheduler cannot run.
|
||||
func TestBlacklistSweepInterval(t *testing.T) {
|
||||
const key = "golem15.user.jwt.blacklist_sweep_interval"
|
||||
if got, err := BlacklistSweepInterval(nil); got != DefaultBlacklistSweepInterval || err != nil {
|
||||
t.Errorf("nil app: %v %v", got, err)
|
||||
}
|
||||
if got, err := BlacklistSweepInterval(&backpack.App{}); got != DefaultBlacklistSweepInterval || err != nil {
|
||||
t.Errorf("nil config: %v %v", got, err)
|
||||
}
|
||||
if got, err := BlacklistSweepInterval(mailTestApp(t)); got != 10*time.Minute || err != nil {
|
||||
t.Errorf("unset: %v %v", got, err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
value any
|
||||
want time.Duration
|
||||
}{
|
||||
{"10m", 10 * time.Minute},
|
||||
{"1h", time.Hour},
|
||||
{"30s", 30 * time.Second},
|
||||
{"24h", 24 * time.Hour},
|
||||
{" 1m ", time.Minute},
|
||||
{"0", 0},
|
||||
{"0s", 0},
|
||||
{0, 0},
|
||||
} {
|
||||
app := mailTestApp(t)
|
||||
if err := app.Config.Set(key, tc.value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := BlacklistSweepInterval(app); got != tc.want || err != nil {
|
||||
t.Errorf("%#v: %v %v, want %v", tc.value, got, err, tc.want)
|
||||
}
|
||||
}
|
||||
if got, err := BlacklistSweepInterval(mailTestApp(t, "SUMMER_GOLEM15__USER__JWT__BLACKLIST_SWEEP_INTERVAL=0")); got != 0 || err != nil {
|
||||
t.Errorf("SUMMER_ 0: %v %v", got, err)
|
||||
}
|
||||
for _, bad := range []any{"soon", "3", "-1m", "500ms", "7m", "48h", -5} {
|
||||
app := mailTestApp(t)
|
||||
if err := app.Config.Set(key, bad); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := BlacklistSweepInterval(app); err == nil || got != 0 || !strings.Contains(err.Error(), key) {
|
||||
t.Errorf("%#v: %v %v, want an error naming %s", bad, got, err, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,9 @@ import (
|
||||
// Login sources name the first factor a LoginAttempt or a LoginEvent comes
|
||||
// from.
|
||||
const (
|
||||
// LoginSourcePassword is POST /_user/api/v1/login (email and password).
|
||||
// LoginSourcePassword is POST /_user/api/v1/login (email and password)
|
||||
// and POST /_user/api/v1/activate-by-code (the mailed activation code,
|
||||
// the first factor of that sign-in).
|
||||
LoginSourcePassword = "password"
|
||||
// LoginSourceSocial is a social sign-in completed by a social-login
|
||||
// plugin.
|
||||
@@ -42,7 +44,7 @@ type LoginAttempt struct {
|
||||
// request body again, it is consumed). It carries keys a gate needs,
|
||||
// such as trusted_device_token. It is nil on a social sign-in. Treat it
|
||||
// as read-only, untrusted input; it holds the password on a password
|
||||
// login.
|
||||
// login and the activation code on an activation.
|
||||
Fields map[string]any
|
||||
// Request is the sign-in request, for the client address and the user
|
||||
// agent.
|
||||
@@ -78,8 +80,9 @@ type LoginGate interface {
|
||||
// looks it up with app.Lookup[*classes.LoginGates]() and adds its gate in
|
||||
// its Boot: every Register runs before every Boot. Password Login consults
|
||||
// it after the password, activation and throttle checks and before it
|
||||
// restores a deactivated account and mints the token; JWT refresh never
|
||||
// consults it. It is safe for concurrent use.
|
||||
// restores a deactivated account and mints the token; activate-by-code
|
||||
// consults it after the code verified and before it mints the token; JWT
|
||||
// refresh never consults it. It is safe for concurrent use.
|
||||
type LoginGates struct {
|
||||
mu sync.RWMutex
|
||||
gates []LoginGate
|
||||
|
||||
117
classes/mail.go
117
classes/mail.go
@@ -2,27 +2,128 @@ package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/towel"
|
||||
)
|
||||
|
||||
// MailTemplate appends -en for English and leaves every other locale,
|
||||
// including empty and pl, on the unsuffixed Polish template name.
|
||||
const (
|
||||
// mailFallbackLocaleKey names the mail language used when neither the
|
||||
// user nor the request names one the plugin has mail for.
|
||||
mailFallbackLocaleKey = "golem15.user.mail.fallback_locale"
|
||||
// mailLocalePL is the unsuffixed (Polish) template set and the default
|
||||
// fallback.
|
||||
mailLocalePL = "pl"
|
||||
// mailLocaleEN is the -en template set.
|
||||
mailLocaleEN = "en"
|
||||
)
|
||||
|
||||
// supportedMailLocale reports whether the plugin has mail in lang.
|
||||
func supportedMailLocale(lang string) bool {
|
||||
return lang == mailLocalePL || lang == mailLocaleEN
|
||||
}
|
||||
|
||||
// NormalizeMailLocale reduces a locale value to the language the plugin has
|
||||
// mail for: pl, en or "". It accepts a plain code (en, PL), a region form
|
||||
// (en-GB, pl_PL) and an Accept-Language list with q-weights
|
||||
// (en-GB,en;q=0.9). Entries whose q does not parse, lies outside 0..1 or is
|
||||
// 0 are dropped, as are languages other than pl and en (the wildcard
|
||||
// included); of the rest the one with the highest q wins, ties going to the
|
||||
// earliest. The result never holds anything but pl, en or "".
|
||||
func NormalizeMailLocale(raw string) string {
|
||||
best, bestQ := "", -1.0
|
||||
for _, entry := range strings.Split(raw, ",") {
|
||||
parts := strings.Split(entry, ";")
|
||||
tag := strings.ToLower(strings.TrimSpace(parts[0]))
|
||||
if i := strings.IndexAny(tag, "-_"); i >= 0 {
|
||||
tag = tag[:i]
|
||||
}
|
||||
if !supportedMailLocale(tag) {
|
||||
continue
|
||||
}
|
||||
q, ok := 1.0, true
|
||||
for _, param := range parts[1:] {
|
||||
param = strings.TrimSpace(param)
|
||||
if len(param) < 2 || !strings.EqualFold(param[:2], "q=") {
|
||||
continue
|
||||
}
|
||||
v, err := strconv.ParseFloat(strings.TrimSpace(param[2:]), 64)
|
||||
if err != nil || v < 0 || v > 1 {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
q = v
|
||||
}
|
||||
if !ok || q == 0 {
|
||||
continue
|
||||
}
|
||||
if q > bestQ {
|
||||
best, bestQ = tag, q
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
// MailTemplate appends -en when locale normalises to English
|
||||
// (NormalizeMailLocale) and leaves every other value, empty included, on the
|
||||
// unsuffixed Polish template name. Callers that want the application's
|
||||
// configured fallback resolve the locale with ResolveMailLocaleFor first.
|
||||
func MailTemplate(base, locale string) string {
|
||||
if locale == "en" {
|
||||
if NormalizeMailLocale(locale) == mailLocaleEN {
|
||||
return base + "-en"
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
// ResolveMailLocale prefers the user's saved locale, then the request locale.
|
||||
// ResolveMailLocale prefers the user's saved locale, then the request locale,
|
||||
// each normalised by NormalizeMailLocale; a value naming neither pl nor en is
|
||||
// skipped. It returns pl, en or "" (neither names a supported language).
|
||||
func ResolveMailLocale(ctx context.Context, user *models.User) string {
|
||||
if user != nil && user.PreferredLocale != nil && *user.PreferredLocale != "" {
|
||||
return *user.PreferredLocale
|
||||
if user != nil && user.PreferredLocale != nil {
|
||||
if loc := NormalizeMailLocale(*user.PreferredLocale); loc != "" {
|
||||
return loc
|
||||
}
|
||||
}
|
||||
if loc, ok := towel.Locale(ctx); ok {
|
||||
return loc
|
||||
if ctx != nil {
|
||||
if raw, ok := towel.Locale(ctx); ok {
|
||||
return NormalizeMailLocale(raw)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// MailFallbackLocale returns golem15.user.mail.fallback_locale normalised to
|
||||
// pl or en: the mail language when neither the user nor the request names
|
||||
// one the plugin has mail for. The default is pl (the unsuffixed
|
||||
// templates); an English-only site sets en, for example through
|
||||
// SUMMER_GOLEM15__USER__MAIL__FALLBACK_LOCALE=en. A missing app, config or
|
||||
// blank value gives pl; any other value gives pl and an error naming the key.
|
||||
func MailFallbackLocale(app *backpack.App) (string, error) {
|
||||
if app == nil || app.Config == nil {
|
||||
return mailLocalePL, nil
|
||||
}
|
||||
raw := strings.TrimSpace(app.Config.String(mailFallbackLocaleKey))
|
||||
if raw == "" {
|
||||
return mailLocalePL, nil
|
||||
}
|
||||
if loc := NormalizeMailLocale(raw); loc != "" {
|
||||
return loc, nil
|
||||
}
|
||||
return mailLocalePL, fmt.Errorf("golem15.user: %s must be pl or en, got %q", mailFallbackLocaleKey, raw)
|
||||
}
|
||||
|
||||
// ResolveMailLocaleFor returns the language to mail user in, always pl or
|
||||
// en: ResolveMailLocale, then the application's MailFallbackLocale. It is the
|
||||
// helper other plugins use to mail in the user's language with the
|
||||
// application's fallback; an invalid fallback (rejected at boot) counts as pl.
|
||||
func ResolveMailLocaleFor(ctx context.Context, app *backpack.App, user *models.User) string {
|
||||
if loc := ResolveMailLocale(ctx, user); loc != "" {
|
||||
return loc
|
||||
}
|
||||
loc, _ := MailFallbackLocale(app)
|
||||
return loc
|
||||
}
|
||||
|
||||
@@ -1,16 +1,187 @@
|
||||
package classes
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/towel"
|
||||
)
|
||||
|
||||
func TestMailTemplate(t *testing.T) {
|
||||
base := "golem15.user::mail.reactivate"
|
||||
if got := MailTemplate(base, "pl"); got != base {
|
||||
t.Fatalf("pl = %s", got)
|
||||
}
|
||||
if got := MailTemplate(base, ""); got != base {
|
||||
t.Fatalf("empty = %s", got)
|
||||
}
|
||||
if got := MailTemplate(base, "en"); got != base+"-en" {
|
||||
t.Fatalf("en = %s", got)
|
||||
for _, tc := range []struct {
|
||||
locale, want string
|
||||
}{
|
||||
{"pl", base},
|
||||
{"", base},
|
||||
{"en", base + "-en"},
|
||||
{"en-GB", base + "-en"},
|
||||
{"en-GB,en;q=0.9", base + "-en"},
|
||||
{"de", base},
|
||||
{"pl-PL,en;q=0.5", base},
|
||||
} {
|
||||
if got := MailTemplate(base, tc.locale); got != tc.want {
|
||||
t.Errorf("MailTemplate(%q) = %s, want %s", tc.locale, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeMailLocale(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
raw, want string
|
||||
}{
|
||||
{"en", "en"},
|
||||
{"pl", "pl"},
|
||||
{"EN", "en"},
|
||||
{"en-GB", "en"},
|
||||
{"en_US", "en"},
|
||||
{"pl-PL", "pl"},
|
||||
{" en-gb ; q=0.9 ", "en"},
|
||||
{"en-GB,en;q=0.9", "en"},
|
||||
{"pl-PL,pl;q=0.9,en-US;q=0.8,en;q=0.7", "pl"},
|
||||
{"de-DE,de;q=0.9,en;q=0.8", "en"},
|
||||
{"de-DE,en;q=0.5,pl;q=0.7", "pl"},
|
||||
{"en;q=0.5,pl;q=0.5", "en"},
|
||||
{"en;q=0,pl", "pl"},
|
||||
{"en;q=0", ""},
|
||||
{"en;q=abc,pl;q=0.1", "pl"},
|
||||
{"en;q=1.5", ""},
|
||||
{"english", ""},
|
||||
{"de", ""},
|
||||
{"*", ""},
|
||||
{"", ""},
|
||||
{" ", ""},
|
||||
} {
|
||||
if got := NormalizeMailLocale(tc.raw); got != tc.want {
|
||||
t.Errorf("NormalizeMailLocale(%q) = %q, want %q", tc.raw, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveMailLocale(t *testing.T) {
|
||||
str := func(s string) *string { return &s }
|
||||
header := "en-GB,en;q=0.9"
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
saved *string
|
||||
nilUser bool
|
||||
request string
|
||||
want string
|
||||
}{
|
||||
{"saved region form wins", str("en-GB"), false, "pl", "en"},
|
||||
{"saved upper case", str("PL"), false, "", "pl"},
|
||||
{"unsupported saved falls through", str("de"), false, header, "en"},
|
||||
{"nil user, raw header", nil, true, header, "en"},
|
||||
{"nil user, no request locale", nil, true, "", ""},
|
||||
{"empty saved, unsupported request", str(""), false, "fr", ""},
|
||||
} {
|
||||
ctx := context.Background()
|
||||
if tc.request != "" {
|
||||
ctx = towel.WithLocale(ctx, tc.request)
|
||||
}
|
||||
var user *models.User
|
||||
if !tc.nilUser {
|
||||
user = &models.User{PreferredLocale: tc.saved}
|
||||
}
|
||||
if got := ResolveMailLocale(ctx, user); got != tc.want {
|
||||
t.Errorf("%s: got %q, want %q", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mailTestApp(t *testing.T, environ ...string) *backpack.App {
|
||||
t.Helper()
|
||||
cfg, err := compass.Open(compass.Options{Dir: t.TempDir(), Env: "development", Environ: append([]string{"SUMMER_ENV=development"}, environ...)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return backpack.New(cfg)
|
||||
}
|
||||
|
||||
func TestMailFallbackLocale(t *testing.T) {
|
||||
if got, err := MailFallbackLocale(nil); got != "pl" || err != nil {
|
||||
t.Errorf("nil app: %q %v", got, err)
|
||||
}
|
||||
if got, err := MailFallbackLocale(&backpack.App{}); got != "pl" || err != nil {
|
||||
t.Errorf("nil config: %q %v", got, err)
|
||||
}
|
||||
if got, err := MailFallbackLocale(mailTestApp(t)); got != "pl" || err != nil {
|
||||
t.Errorf("no key: %q %v", got, err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
value, want string
|
||||
bad bool
|
||||
}{
|
||||
{"", "pl", false},
|
||||
{" ", "pl", false},
|
||||
{"en", "en", false},
|
||||
{"EN-gb", "en", false},
|
||||
{"pl", "pl", false},
|
||||
{"de", "pl", true},
|
||||
} {
|
||||
app := mailTestApp(t)
|
||||
if err := app.Config.Set("golem15.user.mail.fallback_locale", tc.value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := MailFallbackLocale(app)
|
||||
if got != tc.want {
|
||||
t.Errorf("%q: got %q, want %q", tc.value, got, tc.want)
|
||||
}
|
||||
if tc.bad {
|
||||
if err == nil || !strings.Contains(err.Error(), "golem15.user.mail.fallback_locale") || !strings.Contains(err.Error(), `"de"`) {
|
||||
t.Errorf("%q: error %v", tc.value, err)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Errorf("%q: unexpected error %v", tc.value, err)
|
||||
}
|
||||
}
|
||||
app := mailTestApp(t, "SUMMER_GOLEM15__USER__MAIL__FALLBACK_LOCALE=en")
|
||||
if got, err := MailFallbackLocale(app); got != "en" || err != nil {
|
||||
t.Errorf("env override: %q %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveMailLocaleFor(t *testing.T) {
|
||||
const restore = "golem15.user::mail.restore"
|
||||
user := &models.User{}
|
||||
headerCtx := towel.WithLocale(context.Background(), "en-GB,en;q=0.9")
|
||||
|
||||
// The reported bug: raw Accept-Language, no preferred_locale, default config.
|
||||
if got := MailTemplate(restore, ResolveMailLocaleFor(headerCtx, mailTestApp(t), user)); got != restore+"-en" {
|
||||
t.Errorf("raw header: %s", got)
|
||||
}
|
||||
if got := MailTemplate(restore, ResolveMailLocaleFor(context.Background(), mailTestApp(t), user)); got != restore {
|
||||
t.Errorf("default fallback: %s", got)
|
||||
}
|
||||
if got := ResolveMailLocaleFor(context.Background(), nil, nil); got != "pl" {
|
||||
t.Errorf("nil app and user: %q", got)
|
||||
}
|
||||
|
||||
set := mailTestApp(t)
|
||||
if err := set.Config.Set("golem15.user.mail.fallback_locale", "en"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := MailTemplate(restore, ResolveMailLocaleFor(context.Background(), set, user)); got != restore+"-en" {
|
||||
t.Errorf("fallback en via Set: %s", got)
|
||||
}
|
||||
env := mailTestApp(t, "SUMMER_GOLEM15__USER__MAIL__FALLBACK_LOCALE=en")
|
||||
if got := MailTemplate(restore, ResolveMailLocaleFor(context.Background(), env, user)); got != restore+"-en" {
|
||||
t.Errorf("fallback en via env: %s", got)
|
||||
}
|
||||
// The user and the request still come first.
|
||||
if got := ResolveMailLocaleFor(towel.WithLocale(context.Background(), "pl-PL,en;q=0.5"), set, user); got != "pl" {
|
||||
t.Errorf("Polish-first browser on an en fallback: %q", got)
|
||||
}
|
||||
|
||||
bad := mailTestApp(t)
|
||||
if err := bad.Config.Set("golem15.user.mail.fallback_locale", "de"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := ResolveMailLocaleFor(context.Background(), bad, user); got != "pl" {
|
||||
t.Errorf("invalid fallback: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ jwt:
|
||||
refresh_ttl: 20160
|
||||
blacklist_grace: 0
|
||||
leeway: 0
|
||||
# 0 schedules no sweep; any other value must divide 24h (1m, 10m, 1h).
|
||||
blacklist_sweep_interval: 10m
|
||||
# On: POST /login, /register (when it signs the account in) and
|
||||
# /activate-by-code set the HttpOnly session cookie from auth.cookie.* and
|
||||
@@ -15,6 +16,14 @@ activation:
|
||||
activate_mode: auto
|
||||
reset_ttl_minutes: 60
|
||||
activation_ttl_hours: 72
|
||||
mail:
|
||||
# The language of this plugin's mails when neither the user's
|
||||
# preferred_locale nor the request locale (the translate plugin's locale,
|
||||
# else the Accept-Language header) names one the plugin has mail for (pl or
|
||||
# en). pl keeps the unsuffixed Polish templates; an English-only site sets
|
||||
# en (SUMMER_GOLEM15__USER__MAIL__FALLBACK_LOCALE=en). Any other value
|
||||
# fails boot.
|
||||
fallback_locale: pl
|
||||
registration:
|
||||
allow_registration: true
|
||||
use_register_throttle: true
|
||||
|
||||
55
console/jwt_blacklist_sweep.go
Normal file
55
console/jwt_blacklist_sweep.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package console
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
)
|
||||
|
||||
// JWTBlacklistSweep deletes the expired rows of the JWT blacklist. It uses
|
||||
// the blacklist store the plugin published or, when it runs as a console
|
||||
// command without a published database, a store over a database opened from
|
||||
// the config for the duration of the run.
|
||||
func JWTBlacklistSweep(app *backpack.App) bonfire.Command {
|
||||
return bonfire.Command{
|
||||
Name: "user:jwt-blacklist-sweep",
|
||||
Description: "Delete the expired JWT blacklist rows",
|
||||
Long: `Deletes the jwt_blacklist rows whose expires_at has passed. A row that
|
||||
still blocks a token or its refresh is not touched, so running it twice
|
||||
changes nothing.
|
||||
|
||||
The scheduler runs it every golem15.user.jwt.blacklist_sweep_interval on
|
||||
the job worker's scheduled queue. Run it by hand or from cron when no
|
||||
worker runs that queue. It ends with "Deleted the expired JWT blacklist
|
||||
rows."`,
|
||||
Examples: []bonfire.Example{
|
||||
{Command: "user:jwt-blacklist-sweep", Description: "Delete the expired JWT blacklist rows"},
|
||||
{Command: "user:jwt-blacklist-sweep -q", Description: "Run it quietly, printing only the result line"},
|
||||
},
|
||||
Run: func(ctx context.Context, _ bonfire.Input, out bonfire.Output) error {
|
||||
if app == nil {
|
||||
return fmt.Errorf("user:jwt-blacklist-sweep: app is nil")
|
||||
}
|
||||
store, ok := app.Lookup[bouncer.BlacklistStore]()
|
||||
if !ok || store == nil {
|
||||
sqlDB, _, err := lagoon.OpenFromApp(ctx, app)
|
||||
if err != nil {
|
||||
return fmt.Errorf("user:jwt-blacklist-sweep: %w", err)
|
||||
}
|
||||
defer sqlDB.Close()
|
||||
store = bouncer.NewPostgresBlacklist(sqlDB, classes.JWTBlacklistTable)
|
||||
}
|
||||
if err := store.Sweep(ctx, time.Now()); err != nil {
|
||||
return fmt.Errorf("user:jwt-blacklist-sweep: %w", err)
|
||||
}
|
||||
out.Success("Deleted the expired JWT blacklist rows.")
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -160,7 +160,7 @@ func Login(app *backpack.App) http.HandlerFunc {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
sendTemplateVars(ctx, app, mailName(ctx, user, "golem15.user::mail.reactivate"), user.Email, mailVars(displayName(user), "", ""))
|
||||
sendTemplateVars(ctx, app, mailName(ctx, app, user, "golem15.user::mail.reactivate"), user.Email, mailVars(displayName(user), "", ""))
|
||||
}
|
||||
// A failed last_seen write is logged and never fails the login.
|
||||
if err := classes.TouchLastSeen(ctx, gdb, user.ID); err != nil {
|
||||
@@ -476,7 +476,7 @@ func ForgotPassword(app *backpack.App) http.HandlerFunc {
|
||||
pluginLog.Error("golem15.user: issue reset code", "err", err)
|
||||
} else {
|
||||
packed := strconv.FormatUint(uint64(user.ID), 10) + "!" + code
|
||||
sendTemplateVars(ctx, app, mailName(ctx, user, "golem15.user::mail.restore"), user.Email, mailVars(displayName(user), resetLink(app, user.ID, code), packed))
|
||||
sendTemplateVars(ctx, app, mailName(ctx, app, user, "golem15.user::mail.restore"), user.Email, mailVars(displayName(user), resetLink(app, user.ID, code), packed))
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"message": forgotPasswordBody})
|
||||
@@ -588,8 +588,15 @@ func Activate(app *backpack.App) http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// ActivateByCode activates from a public "{id}!{code}" value and mints a token.
|
||||
// With golem15.user.jwt.token_cookie on, the token goes into the auth.cookie
|
||||
// ActivateByCode activates from a public "{id}!{code}" value, consults the
|
||||
// login gates and mints a token. The gates run as on password Login, with
|
||||
// source password, because the mailed code is the first factor here: with
|
||||
// golem15.user.activation.require_activation off an account can enable a
|
||||
// second factor before it activates, and the code must not stand in for it.
|
||||
// A gate answer replaces the token response with its status and body and a
|
||||
// gate error answers the opaque 500; neither mints a token or sets a
|
||||
// session cookie, and the account stays activated either way. With
|
||||
// golem15.user.jwt.token_cookie on, the token goes into the auth.cookie
|
||||
// session cookie instead of the body.
|
||||
func ActivateByCode(app *backpack.App) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -638,6 +645,28 @@ func ActivateByCode(app *backpack.App) http.HandlerFunc {
|
||||
writeJSON(w, http.StatusUnprocessableEntity, map[string]any{"error": "This activation link is invalid or has expired"})
|
||||
return
|
||||
}
|
||||
// The activation above is committed whatever the gates answer. A
|
||||
// gate answer replaces the token response; a gate error fails
|
||||
// closed.
|
||||
gate, err := CheckLoginGates(r.Context(), app, classes.LoginAttempt{
|
||||
User: user,
|
||||
Source: classes.LoginSourcePassword,
|
||||
Fields: fields,
|
||||
Request: r,
|
||||
})
|
||||
if err != nil {
|
||||
pluginLog.Error("golem15.user: login gate", "user_id", user.ID, "err", err)
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
if gate != nil {
|
||||
status := gate.Status
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
writeJSON(w, status, gate.Body)
|
||||
return
|
||||
}
|
||||
token, err := mintFor(app, secret, user, requestURL(r))
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
@@ -937,7 +966,7 @@ func Register(app *backpack.App) http.HandlerFunc {
|
||||
packed := strconv.FormatUint(uint64(user.ID), 10) + "!" + code
|
||||
vars = mailVars(displayName(user), activationLink(app, user.ID, code), packed)
|
||||
}
|
||||
sendTemplateVars(ctx, app, mailName(ctx, user, "golem15.user::mail.activate"), user.Email, vars)
|
||||
sendTemplateVars(ctx, app, mailName(ctx, app, user, "golem15.user::mail.activate"), user.Email, vars)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"message": "Activation email sent"})
|
||||
return
|
||||
}
|
||||
@@ -1157,8 +1186,8 @@ func blacklistGrace(app *backpack.App) time.Duration {
|
||||
return time.Duration(secs) * time.Second
|
||||
}
|
||||
|
||||
func mailName(ctx context.Context, user *models.User, base string) string {
|
||||
return classes.MailTemplate(base, classes.ResolveMailLocale(ctx, user))
|
||||
func mailName(ctx context.Context, app *backpack.App, user *models.User, base string) string {
|
||||
return classes.MailTemplate(base, classes.ResolveMailLocaleFor(ctx, app, user))
|
||||
}
|
||||
|
||||
func sendTemplate(ctx context.Context, app *backpack.App, template, to string) {
|
||||
|
||||
@@ -12,8 +12,9 @@ import (
|
||||
// nil allows the sign-in, a result replaces the token response, and an error
|
||||
// must fail the sign-in closed (answer the opaque 500, issue no token). It
|
||||
// looks the registry up on every call and allows the sign-in when none is
|
||||
// published. Password Login calls it; a social-login plugin calls it before
|
||||
// it issues a token.
|
||||
// published. Password Login calls it, activate-by-code calls it after the
|
||||
// mailed code verified (source password), and a social-login plugin calls
|
||||
// it before it issues a token.
|
||||
func CheckLoginGates(ctx context.Context, app *backpack.App, a classes.LoginAttempt) (*classes.LoginGateResult, error) {
|
||||
if app == nil {
|
||||
return nil, nil
|
||||
|
||||
@@ -118,7 +118,7 @@ func FinishLogin(ctx context.Context, app *backpack.App, db *gorm.DB, user *mode
|
||||
return err
|
||||
}
|
||||
user.DeletedAt = gorm.DeletedAt{}
|
||||
sendTemplateVars(ctx, app, mailName(ctx, user, "golem15.user::mail.reactivate"), user.Email, mailVars(displayName(user), "", ""))
|
||||
sendTemplateVars(ctx, app, mailName(ctx, app, user, "golem15.user::mail.reactivate"), user.Email, mailVars(displayName(user), "", ""))
|
||||
}
|
||||
if ip != "" {
|
||||
if err := db.WithContext(ctx).Unscoped().Model(user).Update("last_ip_address", ip).Error; err != nil {
|
||||
|
||||
@@ -378,7 +378,7 @@ func (c usersAdminController) FormAfterCreate(ctx context.Context, model any) er
|
||||
vars["login"], vars["Login"] = email, email
|
||||
hours := c.configInt("golem15.user.activation.activation_ttl_hours", 72)
|
||||
vars["hours"], vars["Hours"] = hours, hours
|
||||
template := mailName(ctx, user, "golem15.user::mail.invite")
|
||||
template := mailName(ctx, app, user, "golem15.user::mail.invite")
|
||||
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, _ *gorm.DB) {
|
||||
sendTemplateVars(ctx, app, template, email, vars)
|
||||
})
|
||||
|
||||
10
go.mod
10
go.mod
@@ -3,20 +3,20 @@ module git.golem15.com/golem15/sm-user-plugin
|
||||
go 1.27.0
|
||||
|
||||
require (
|
||||
git.golem15.com/golem15/summercms v0.5.0
|
||||
git.golem15.com/golem15/summercms v0.6.0
|
||||
github.com/go-gormigrate/gormigrate/v2 v2.1.7
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/jackc/pgx/v5 v5.10.0
|
||||
github.com/testcontainers/testcontainers-go v0.44.0
|
||||
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0
|
||||
gocloud.dev v0.46.0
|
||||
gorm.io/driver/postgres v1.6.3
|
||||
gorm.io/gorm v1.31.2
|
||||
)
|
||||
|
||||
require (
|
||||
charm.land/bubbles/v2 v2.2.1 // indirect
|
||||
charm.land/bubbletea/v2 v2.1.0 // indirect
|
||||
charm.land/fang/v2 v2.0.1 // indirect
|
||||
charm.land/huh/v2 v2.0.3 // indirect
|
||||
charm.land/lipgloss/v2 v2.0.6 // indirect
|
||||
dario.cat/mergo v1.0.2 // indirect
|
||||
@@ -50,7 +50,6 @@ require (
|
||||
github.com/charmbracelet/harmonica v0.2.0 // indirect
|
||||
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 // indirect
|
||||
github.com/charmbracelet/x/ansi v0.11.9 // indirect
|
||||
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250603201427-c31516f43444 // indirect
|
||||
github.com/charmbracelet/x/exp/ordered v0.1.0 // indirect
|
||||
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect
|
||||
github.com/charmbracelet/x/term v0.2.2 // indirect
|
||||
@@ -120,10 +119,6 @@ require (
|
||||
github.com/moby/term v0.5.2 // indirect
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0 // indirect
|
||||
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||
github.com/muesli/mango v0.1.0 // indirect
|
||||
github.com/muesli/mango-cobra v1.2.0 // indirect
|
||||
github.com/muesli/mango-pflag v0.1.0 // indirect
|
||||
github.com/muesli/roff v0.1.0 // indirect
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.1 // indirect
|
||||
github.com/opencontainers/go-digest v1.0.0 // indirect
|
||||
github.com/opencontainers/image-spec v1.1.1 // indirect
|
||||
@@ -177,7 +172,6 @@ require (
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5 // indirect
|
||||
google.golang.org/grpc v1.79.3 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gorm.io/driver/postgres v1.6.3 // indirect
|
||||
)
|
||||
|
||||
replace git.golem15.com/golem15/summercms => ../summercms.go
|
||||
|
||||
12
go.sum
12
go.sum
@@ -4,8 +4,6 @@ charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU=
|
||||
charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc=
|
||||
charm.land/bubbletea/v2 v2.1.0 h1:A9fj9h5LFrvQhQHFNggp8K8rvY6CUfgn9dMbb6p2HIw=
|
||||
charm.land/bubbletea/v2 v2.1.0/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU=
|
||||
charm.land/fang/v2 v2.0.1 h1:zQCM8JQJ1JnQX/66B5jlCYBUxL2as5JXQZ2KJ6EL0mY=
|
||||
charm.land/fang/v2 v2.0.1/go.mod h1:S1GmkpcvK+OB5w9caywUnJcsMew45Ot8FXqoz8ALrII=
|
||||
charm.land/huh/v2 v2.0.3 h1:2cJsMqEPwSywGHvdlKsJyQKPtSJLVnFKyFbsYZTlLkU=
|
||||
charm.land/huh/v2 v2.0.3/go.mod h1:93eEveeeqn47MwiC3tf+2atZ2l7Is88rAtmZNZ8x9Wc=
|
||||
charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=
|
||||
@@ -110,8 +108,6 @@ github.com/charmbracelet/x/conpty v0.1.1 h1:s1bUxjoi7EpqiXysVtC+a8RrvPPNcNvAjfi4
|
||||
github.com/charmbracelet/x/conpty v0.1.1/go.mod h1:OmtR77VODEFbiTzGE9G1XiRJAga6011PIm4u5fTNZpk=
|
||||
github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86 h1:JSt3B+U9iqk37QUU2Rvb6DSBYRLtWqFqfxf8l5hOZUA=
|
||||
github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86/go.mod h1:2P0UgXMEa6TsToMSuFqKFQR+fZTO9CNGUNokkPatT/0=
|
||||
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250603201427-c31516f43444 h1:IJDiTgVE56gkAGfq0lBEloWgkXMk4hl/bmuPoicI4R0=
|
||||
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250603201427-c31516f43444/go.mod h1:T9jr8CzFpjhFVHjNjKwbAD7KwBNyFnj2pntAO7F2zw0=
|
||||
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA=
|
||||
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f/go.mod h1:IfZAMTHB6XkZSeXUqriemErjAWCCzT0LwjKFYCZyw0I=
|
||||
github.com/charmbracelet/x/exp/ordered v0.1.0 h1:55/qLwjIh0gL0Vni+QAWk7T/qRVP6sBf+2agPBgnOFE=
|
||||
@@ -299,14 +295,6 @@ github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtw
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
|
||||
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
|
||||
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
|
||||
github.com/muesli/mango v0.1.0 h1:DZQK45d2gGbql1arsYA4vfg4d7I9Hfx5rX/GCmzsAvI=
|
||||
github.com/muesli/mango v0.1.0/go.mod h1:5XFpbC8jY5UUv89YQciiXNlbi+iJgt29VDC5xbzrLL4=
|
||||
github.com/muesli/mango-cobra v1.2.0 h1:DQvjzAM0PMZr85Iv9LIMaYISpTOliMEg+uMFtNbYvWg=
|
||||
github.com/muesli/mango-cobra v1.2.0/go.mod h1:vMJL54QytZAJhCT13LPVDfkvCUJ5/4jNUKF/8NC2UjA=
|
||||
github.com/muesli/mango-pflag v0.1.0 h1:UADqbYgpUyRoBja3g6LUL+3LErjpsOwaC9ywvBWe7Sg=
|
||||
github.com/muesli/mango-pflag v0.1.0/go.mod h1:YEQomTxaCUp8PrbhFh10UfbhbQrM/xJ4i2PB8VTLLW0=
|
||||
github.com/muesli/roff v0.1.0 h1:YD0lalCotmYuF5HhZliKWlIx7IEhiXeSfq7hNjFqGF8=
|
||||
github.com/muesli/roff v0.1.0/go.mod h1:pjAHQM9hdUUwm/krAfrLGgJkXJ+YuhtsfZ42kieB2Ig=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.1 h1:JDEJraFsQE17Dut9HFDHzCoAWGEQJom5s0TRd17NIEQ=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.1/go.mod h1:Vee0/9RD3Quc/NmwEjzzD7VTZ+Ir7QbXocrkhOzmUKA=
|
||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
package user
|
||||
|
||||
import "git.golem15.com/golem15/summercms/modules/diary"
|
||||
|
||||
// pluginLog is the plugin's logger: its records carry component=user, so
|
||||
// config/log.yaml can raise or lower them (log.components.user).
|
||||
var pluginLog = diary.For("user")
|
||||
@@ -6,6 +6,9 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -399,3 +402,136 @@ func TestLoginGateOrder(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestActivateByCodeGates pins where POST /activate-by-code consults the
|
||||
// login gates: after the mailed code verifies, with source password (the
|
||||
// code is the first factor here), and before the mint. A gate answer
|
||||
// replaces the token response with its status and body and sets no session
|
||||
// cookie, a gate error answers the opaque 500, and the account is activated
|
||||
// whatever the gate answers. An invalid code never reaches a gate.
|
||||
func TestActivateByCodeGates(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Postgres")
|
||||
}
|
||||
challenge := &classes.LoginGateResult{Body: map[string]any{
|
||||
"two_factor_required": true,
|
||||
"challenge_token": "c",
|
||||
"available_methods": []string{"totp"},
|
||||
"expires_at": "2026-10-26T12:00:00+00:00",
|
||||
}}
|
||||
inactive := func(t *testing.T, env *adminEnv, label string) (*models.User, string) {
|
||||
t.Helper()
|
||||
user := env.seedUser(t, label, func(u *models.User) { u.IsActivated = false })
|
||||
code, err := classes.IssueActivationCode(t.Context(), env.gdb, user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return user, strconv.FormatUint(uint64(user.ID), 10) + "!" + code
|
||||
}
|
||||
activate := func(t *testing.T, env *adminEnv, packed string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return env.call(t, http.MethodPost, "/_user/api/v1/activate-by-code", "", map[string]string{"code": packed})
|
||||
}
|
||||
noSession := func(t *testing.T, rec *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
if cookies := rec.Header().Values("Set-Cookie"); len(cookies) != 0 {
|
||||
t.Fatalf("a held-back activation set cookies %v", cookies)
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), `"token"`) {
|
||||
t.Fatalf("a held-back activation answered a token: %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("challenge_replaces_the_token", func(t *testing.T) {
|
||||
env, gate := gatedEnv(t, challenge)
|
||||
user, packed := inactive(t, env, "abc-challenge")
|
||||
rec := activate(t, env, packed)
|
||||
want := `{"available_methods":["totp"],"challenge_token":"c","expires_at":"2026-10-26T12:00:00+00:00","two_factor_required":true}`
|
||||
if rec.Code != http.StatusOK || rec.Body.String() != want {
|
||||
t.Fatalf("challenged activation = %d %s, want 200 %s", rec.Code, rec.Body.String(), want)
|
||||
}
|
||||
noSession(t, rec)
|
||||
if gate.count() != 1 {
|
||||
t.Fatalf("gate calls = %d, want 1", gate.count())
|
||||
}
|
||||
seen := gate.seen[0]
|
||||
if seen.Source != classes.LoginSourcePassword || seen.User == nil || seen.User.ID != user.ID || seen.Request == nil {
|
||||
t.Fatalf("attempt = %+v", seen)
|
||||
}
|
||||
if seen.Fields["code"] != packed {
|
||||
t.Fatalf("attempt fields = %#v", seen.Fields)
|
||||
}
|
||||
if !env.reload(t, user.ID).IsActivated {
|
||||
t.Fatal("a challenged activation left the account not activated")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("refusal_passes_through", func(t *testing.T) {
|
||||
env, _ := gatedEnv(t, &classes.LoginGateResult{Status: http.StatusUnauthorized, Body: map[string]any{"error": "Invalid or expired challenge."}})
|
||||
user, packed := inactive(t, env, "abc-refusal")
|
||||
rec := activate(t, env, packed)
|
||||
if rec.Code != http.StatusUnauthorized || rec.Body.String() != `{"error":"Invalid or expired challenge."}` {
|
||||
t.Fatalf("refused activation = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
noSession(t, rec)
|
||||
if !env.reload(t, user.ID).IsActivated {
|
||||
t.Fatal("a refused activation left the account not activated")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("allowing_gate_mints_as_before", func(t *testing.T) {
|
||||
env, gate := gatedEnv(t, nil)
|
||||
user, packed := inactive(t, env, "abc-allow")
|
||||
rec := activate(t, env, packed)
|
||||
body := decodeBody(t, rec.Body.Bytes())
|
||||
userBody, _ := body["user"].(map[string]any)
|
||||
token, _ := body["token"].(string)
|
||||
if rec.Code != http.StatusOK || token == "" || body["message"] != "Account activated" || userBody["is_activated"] != true {
|
||||
t.Fatalf("allowed activation = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if gate.count() != 1 {
|
||||
t.Fatalf("gate calls = %d, want 1", gate.count())
|
||||
}
|
||||
if !env.reload(t, user.ID).IsActivated {
|
||||
t.Fatal("an allowed activation left the account not activated")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("gate_error_fails_closed", func(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
gates, ok := env.app.Lookup[*classes.LoginGates]()
|
||||
if !ok || gates == nil {
|
||||
t.Fatal("the plugin's Register published no *classes.LoginGates")
|
||||
}
|
||||
gates.Add(gateFunc(func(context.Context, classes.LoginAttempt) (*classes.LoginGateResult, error) {
|
||||
return nil, errors.New("challenge store down")
|
||||
}))
|
||||
user, packed := inactive(t, env, "abc-error")
|
||||
rec := activate(t, env, packed)
|
||||
if rec.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("erroring gate = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
noSession(t, rec)
|
||||
if !env.reload(t, user.ID).IsActivated {
|
||||
t.Fatal("an erroring gate left the account not activated")
|
||||
}
|
||||
// The code was spent: the account is activated, so a second try
|
||||
// answers the Winter error page as before.
|
||||
assertWinterErrorPage(t, activate(t, env, packed))
|
||||
})
|
||||
|
||||
t.Run("bad_code_never_reaches_the_gate", func(t *testing.T) {
|
||||
env, gate := gatedEnv(t, challenge)
|
||||
user, _ := inactive(t, env, "abc-bad")
|
||||
rec := activate(t, env, strconv.FormatUint(uint64(user.ID), 10)+"!nope")
|
||||
if rec.Code != http.StatusUnprocessableEntity || rec.Body.String() != `{"error":"This activation link is invalid or has expired"}` {
|
||||
t.Fatalf("bad code = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if gate.count() != 0 {
|
||||
t.Fatalf("the gate ran %d times for a bad code", gate.count())
|
||||
}
|
||||
if env.reload(t, user.ID).IsActivated {
|
||||
t.Fatal("a bad code activated the account")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
114
mail_locale_test.go
Normal file
114
mail_locale_test.go
Normal file
@@ -0,0 +1,114 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/controllers"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/towel"
|
||||
)
|
||||
|
||||
const mailFallbackKey = "golem15.user.mail.fallback_locale"
|
||||
|
||||
// TestMailFallbackLocaleConfig reads golem15.user.mail.fallback_locale from
|
||||
// the plugin's config.yaml default and from overrides.
|
||||
func TestMailFallbackLocaleConfig(t *testing.T) {
|
||||
app := bareApp(t)
|
||||
if err := app.Config.MergePlugin("golem15.user", configFS); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v, ok := app.Config.Lookup(mailFallbackKey); !ok || v != "pl" {
|
||||
t.Fatalf("config.yaml default = %#v (set %v), want pl", v, ok)
|
||||
}
|
||||
if got, err := classes.MailFallbackLocale(app); got != "pl" || err != nil {
|
||||
t.Fatalf("default: %q %v", got, err)
|
||||
}
|
||||
for _, tc := range []struct{ value, want string }{{"en", "en"}, {"EN-gb", "en"}} {
|
||||
if err := app.Config.Set(mailFallbackKey, tc.value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := classes.MailFallbackLocale(app); got != tc.want || err != nil {
|
||||
t.Errorf("%q: %q %v", tc.value, got, err)
|
||||
}
|
||||
}
|
||||
if err := app.Config.Set(mailFallbackKey, "de"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := classes.MailFallbackLocale(app); err == nil || !strings.Contains(err.Error(), mailFallbackKey) {
|
||||
t.Errorf("de: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMailFallbackLocaleBoot fails Boot on an unsupported fallback before
|
||||
// anything is started, and leaves an unset key alone.
|
||||
func TestMailFallbackLocaleBoot(t *testing.T) {
|
||||
withSecret := func(t *testing.T) *backpack.App {
|
||||
app := bareApp(t)
|
||||
if err := app.Config.Set("golem15.user.jwt.secret", "mail-locale-boot-secret"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return app
|
||||
}
|
||||
app := withSecret(t)
|
||||
if err := app.Config.Set(mailFallbackKey, "de"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := (&Plugin{}).Boot(app); err == nil || !strings.Contains(err.Error(), mailFallbackKey) {
|
||||
t.Fatalf("Boot with fallback de: %v", err)
|
||||
}
|
||||
if err := (&Plugin{}).Boot(withSecret(t)); err != nil && strings.Contains(err.Error(), mailFallbackKey) {
|
||||
t.Fatalf("Boot with the key unset: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMailLocaleFromRequest sends the reset mail through POST
|
||||
// /forgot-password with the request locale the router stores when no
|
||||
// translate plugin is installed: the raw Accept-Language header.
|
||||
func TestMailLocaleFromRequest(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Postgres (testcontainers)")
|
||||
}
|
||||
app, gdb := sessionApp(t, "0s")
|
||||
rec, _ := publishMemoryMail(t, app)
|
||||
|
||||
forgot := func(t *testing.T, email, locale string) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, "/_user/api/v1/forgot-password", strings.NewReader(`{"email":"`+email+`"}`))
|
||||
req.Host = "example.com"
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if locale != "" {
|
||||
req = req.WithContext(towel.WithLocale(req.Context(), locale))
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
controllers.ForgotPassword(app)(w, req)
|
||||
if w.Code >= 300 {
|
||||
t.Fatalf("forgot-password %s: %d %s", email, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
insertUser(t, gdb, "locale-header@example.test", "correct-horse")
|
||||
forgot(t, "locale-header@example.test", "en-GB,en;q=0.9")
|
||||
assertTemplate(t, rec, "golem15.user::mail.restore-en", "locale-header@example.test")
|
||||
|
||||
insertUser(t, gdb, "locale-none@example.test", "correct-horse")
|
||||
forgot(t, "locale-none@example.test", "")
|
||||
assertTemplate(t, rec, "golem15.user::mail.restore", "locale-none@example.test")
|
||||
|
||||
if err := app.Config.Set(mailFallbackKey, "en"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
insertUser(t, gdb, "locale-fallback@example.test", "correct-horse")
|
||||
forgot(t, "locale-fallback@example.test", "")
|
||||
assertTemplate(t, rec, "golem15.user::mail.restore-en", "locale-fallback@example.test")
|
||||
|
||||
saved := insertUser(t, gdb, "locale-saved@example.test", "correct-horse")
|
||||
if err := gdb.Model(saved).Update("preferred_locale", "en-GB").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
forgot(t, "locale-saved@example.test", "pl")
|
||||
assertTemplate(t, rec, "golem15.user::mail.restore-en", "locale-saved@example.test")
|
||||
}
|
||||
58
mail_subjects_test.go
Normal file
58
mail_subjects_test.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/postcard"
|
||||
)
|
||||
|
||||
// TestPolishMailSubjects renders every Polish template next to its -en twin
|
||||
// and requires a subject of its own, so a Polish template with a copied
|
||||
// English subject does not slip through.
|
||||
func TestPolishMailSubjects(t *testing.T) {
|
||||
p := &Plugin{}
|
||||
cat := postcard.NewCatalog()
|
||||
if err := cat.Register(p.ID(), p.MailTemplatesFS(), p.MailTemplates(), p.MailLayouts()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
names := map[string]bool{}
|
||||
for _, name := range p.MailTemplates() {
|
||||
names[name] = true
|
||||
}
|
||||
vars := map[string]any{
|
||||
"name": "Ada", "Name": "Ada",
|
||||
"link": "https://example.com/link", "Link": "https://example.com/link",
|
||||
"code": "1!abc", "Code": "1!abc",
|
||||
"hours": 72, "Hours": 72,
|
||||
"login": "ada@example.test", "Login": "ada@example.test",
|
||||
}
|
||||
subject := func(t *testing.T, template string) string {
|
||||
t.Helper()
|
||||
mem := postcard.NewMemoryDriver()
|
||||
mailer := postcard.NewMailer(cat, mem, postcard.Options{From: "noreply@example.test"})
|
||||
if err := mailer.Send(context.Background(), postcard.Message{Template: template, To: []string{"ada@example.test"}, Vars: vars}); err != nil {
|
||||
t.Fatalf("%s: %v", template, err)
|
||||
}
|
||||
msgs := mem.Messages()
|
||||
if len(msgs) != 1 {
|
||||
t.Fatalf("%s: %d messages", template, len(msgs))
|
||||
}
|
||||
return msgs[0].Subject
|
||||
}
|
||||
pairs := 0
|
||||
for _, name := range p.MailTemplates() {
|
||||
if strings.HasSuffix(name, "-en") || !names[name+"-en"] {
|
||||
continue
|
||||
}
|
||||
pairs++
|
||||
pl, en := subject(t, name), subject(t, name+"-en")
|
||||
if pl == "" || pl == en {
|
||||
t.Errorf("%s: Polish subject %q, English subject %q", name, pl, en)
|
||||
}
|
||||
}
|
||||
if pairs == 0 {
|
||||
t.Fatal("no Polish/English template pairs")
|
||||
}
|
||||
}
|
||||
13
manifest_test.go
Normal file
13
manifest_test.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/kiosk"
|
||||
)
|
||||
|
||||
// TestPluginManifest fails when plugin.yaml is missing or no longer matches
|
||||
// what `summer plugin:manifest` derives from this repository.
|
||||
func TestPluginManifest(t *testing.T) {
|
||||
kiosk.CheckT(t, ".")
|
||||
}
|
||||
2
mcp.go
2
mcp.go
@@ -15,7 +15,7 @@ func (p *Plugin) MCP() pact.MCP {
|
||||
return pact.MCP{Tools: []pact.MCPTool{{
|
||||
Name: "me",
|
||||
Title: "Current user",
|
||||
Description: "Returns the profile of the signed-in frontend user.",
|
||||
Description: "Returns the profile of the signed-in frontend user. Needs scope read.",
|
||||
Guard: "user",
|
||||
Method: http.MethodGet,
|
||||
Path: "/_user/api/v1/token/me",
|
||||
|
||||
@@ -86,14 +86,15 @@ func (g *APITokenGuard) WriteUnauthorized(w http.ResponseWriter, _ error) {
|
||||
wire.WriteJSON(w, http.StatusUnauthorized, map[string]any{"error": true, "message": "Invalid token."})
|
||||
}
|
||||
|
||||
// Scope requires one delegated scope from the shared token credential.
|
||||
// Scope requires one delegated scope from the shared token credential. A
|
||||
// refusal answers 403 with error, message and missing_scope naming the scope.
|
||||
func Scope(scope string) pact.Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
credential, _ := bouncer.Credential(r.Context())
|
||||
token, ok := credential.(*models.APIToken)
|
||||
if !ok || token == nil || !token.HasScope(scope) {
|
||||
wire.WriteJSON(w, http.StatusForbidden, map[string]any{"error": true, "message": "Missing required scope: " + scope})
|
||||
wire.WriteJSON(w, http.StatusForbidden, map[string]any{"error": true, "message": "Missing required scope: " + scope, "missing_scope": scope})
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
@@ -103,12 +104,14 @@ func Scope(scope string) pact.Middleware {
|
||||
|
||||
// Permission requires one current user-group permission. Tokens never carry
|
||||
// a permission snapshot: revoking the user's grant takes effect immediately.
|
||||
// A refusal answers 403 with error, message and missing_permission naming the
|
||||
// code.
|
||||
func Permission(code string) pact.Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
principal, _ := bouncer.User(r.Context())
|
||||
if !cabana.Allows(principal, []string{code}) {
|
||||
wire.WriteJSON(w, http.StatusForbidden, map[string]any{"error": true, "message": "Forbidden."})
|
||||
wire.WriteJSON(w, http.StatusForbidden, map[string]any{"error": true, "message": "Forbidden.", "missing_permission": code})
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
|
||||
88
middleware/api_token_test.go
Normal file
88
middleware/api_token_test.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
)
|
||||
|
||||
// forbiddenBody is the 403 body of Scope and Permission.
|
||||
type forbiddenBody struct {
|
||||
Error bool `json:"error"`
|
||||
Message string `json:"message"`
|
||||
MissingScope string `json:"missing_scope"`
|
||||
MissingPermission string `json:"missing_permission"`
|
||||
}
|
||||
|
||||
// tokenWith is an in-memory credential holding scopes, built the way
|
||||
// MCPDispatch builds it.
|
||||
func tokenWith(scopes ...string) *models.APIToken {
|
||||
return &models.APIToken{Scopes: lagoon.Jsonable[[]string]{Data: scopes, Valid: true}}
|
||||
}
|
||||
|
||||
// serve runs mw over a handler answering 200, with ctx on the request.
|
||||
func serve(t *testing.T, mw func(http.Handler) http.Handler, ctx context.Context) (int, forbiddenBody) {
|
||||
t.Helper()
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx)
|
||||
mw(next).ServeHTTP(rec, req)
|
||||
var body forbiddenBody
|
||||
if rec.Code == http.StatusForbidden {
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("403 body %q: %v", rec.Body.String(), err)
|
||||
}
|
||||
}
|
||||
return rec.Code, body
|
||||
}
|
||||
|
||||
// TestForbiddenBodiesNameWhatIsMissing (D-15, D-20): a refusal by Scope or
|
||||
// Permission keeps error true and the message, and adds missing_scope or
|
||||
// missing_permission naming what is missing. No database.
|
||||
func TestForbiddenBodiesNameWhatIsMissing(t *testing.T) {
|
||||
scopeRefused := forbiddenBody{Error: true, Message: "Missing required scope: write", MissingScope: "write"}
|
||||
|
||||
t.Run("scope missing from the credential", func(t *testing.T) {
|
||||
ctx := bouncer.WithCredential(context.Background(), tokenWith("read"))
|
||||
code, body := serve(t, Scope("write"), ctx)
|
||||
if code != http.StatusForbidden || body != scopeRefused {
|
||||
t.Fatalf("Scope(write) with read = %d %+v, want 403 %+v", code, body, scopeRefused)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("no credential", func(t *testing.T) {
|
||||
code, body := serve(t, Scope("write"), context.Background())
|
||||
if code != http.StatusForbidden || body != scopeRefused {
|
||||
t.Fatalf("Scope(write) without a credential = %d %+v, want 403 %+v", code, body, scopeRefused)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("scope held", func(t *testing.T) {
|
||||
ctx := bouncer.WithCredential(context.Background(), tokenWith("read"))
|
||||
if code, _ := serve(t, Scope("read"), ctx); code != http.StatusOK {
|
||||
t.Fatalf("Scope(read) with read = %d, want 200", code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("permission missing", func(t *testing.T) {
|
||||
ctx := bouncer.WithUser(context.Background(), &bouncer.Principal{ID: 1, PermissionGrants: map[string]bool{"jz.bm.access_schedule": true}})
|
||||
want := forbiddenBody{Error: true, Message: "Forbidden.", MissingPermission: "jz.bm.access_courses"}
|
||||
code, body := serve(t, Permission("jz.bm.access_courses"), ctx)
|
||||
if code != http.StatusForbidden || body != want {
|
||||
t.Fatalf("Permission without the grant = %d %+v, want 403 %+v", code, body, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("permission granted", func(t *testing.T) {
|
||||
ctx := bouncer.WithUser(context.Background(), &bouncer.Principal{ID: 1, PermissionGrants: map[string]bool{"jz.bm.access_courses": true}})
|
||||
if code, _ := serve(t, Permission("jz.bm.access_courses"), ctx); code != http.StatusOK {
|
||||
t.Fatalf("Permission with the grant = %d, want 200", code)
|
||||
}
|
||||
})
|
||||
}
|
||||
72
plugin.go
72
plugin.go
@@ -38,6 +38,7 @@ var (
|
||||
_ pact.HasMailTemplates = (*Plugin)(nil)
|
||||
_ pact.HasLang = (*Plugin)(nil)
|
||||
_ pact.HasCommands = (*Plugin)(nil)
|
||||
_ pact.HasSchedule = (*Plugin)(nil)
|
||||
_ surf.BucketProvider = (*Plugin)(nil)
|
||||
_ bouncer.UserProvider = classes.GormUsers{}
|
||||
)
|
||||
@@ -53,8 +54,7 @@ var langFS embed.FS
|
||||
|
||||
// Plugin is the golem15.user plugin.
|
||||
type Plugin struct {
|
||||
app *backpack.App
|
||||
sweepStop chan struct{}
|
||||
app *backpack.App
|
||||
}
|
||||
|
||||
func (p *Plugin) ID() string { return "golem15.user" }
|
||||
@@ -76,19 +76,22 @@ func (p *Plugin) Boot(app *backpack.App) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Serve publishes the database after Boot, so the GORM hooks, the
|
||||
// blacklist store and its sweep are installed on lagoon.Publish, or at
|
||||
// once when the database is already published.
|
||||
if _, err := classes.MailFallbackLocale(app); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := classes.BlacklistSweepInterval(app); err != nil {
|
||||
return err
|
||||
}
|
||||
// Serve publishes the database after Boot, so the GORM hooks and the
|
||||
// blacklist store are installed on lagoon.Publish, or at once when the
|
||||
// database is already published. Expired blacklist rows are deleted by
|
||||
// the scheduled user:jwt-blacklist-sweep command (Schedule).
|
||||
if err := lagoon.OnDatabase(app, func(sqlDB *sql.DB, gdb *gorm.DB) error {
|
||||
if err := classes.RegisterHooks(gdb); err != nil {
|
||||
return err
|
||||
}
|
||||
store := bouncer.NewPostgresBlacklist(sqlDB, "jwt_blacklist")
|
||||
if err := app.Publish[bouncer.BlacklistStore](store); err != nil {
|
||||
return err
|
||||
}
|
||||
p.startBlacklistSweep(store)
|
||||
return nil
|
||||
store := bouncer.NewPostgresBlacklist(sqlDB, classes.JWTBlacklistTable)
|
||||
return app.Publish[bouncer.BlacklistStore](store)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -218,37 +221,16 @@ func (p *Plugin) bootBackendLinks(app *backpack.App) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) startBlacklistSweep(bl bouncer.BlacklistStore) {
|
||||
interval := 10 * time.Minute
|
||||
if p.app != nil && p.app.Config != nil {
|
||||
raw := p.app.Config.String("golem15.user.jwt.blacklist_sweep_interval")
|
||||
if raw != "" {
|
||||
parsed, err := time.ParseDuration(raw)
|
||||
if err != nil || parsed <= 0 {
|
||||
return
|
||||
}
|
||||
interval = parsed
|
||||
}
|
||||
// Schedule returns the scheduled commands: user:jwt-blacklist-sweep every
|
||||
// golem15.user.jwt.blacklist_sweep_interval (10m by default), none when the
|
||||
// interval is 0. p.app is nil before Register, which yields the default. A
|
||||
// bad interval schedules nothing; Boot reports it.
|
||||
func (p *Plugin) Schedule() []pact.ScheduledCommand {
|
||||
interval, err := classes.BlacklistSweepInterval(p.app)
|
||||
if err != nil || interval == 0 {
|
||||
return nil
|
||||
}
|
||||
if p.sweepStop != nil {
|
||||
return
|
||||
}
|
||||
p.sweepStop = make(chan struct{})
|
||||
stop := p.sweepStop
|
||||
go func() {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if err := bl.Sweep(context.Background(), time.Now()); err != nil {
|
||||
pluginLog.Error("golem15.user: jwt blacklist sweep", "err", err)
|
||||
}
|
||||
case <-stop:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
return []pact.ScheduledCommand{{Command: "user:jwt-blacklist-sweep", Cadence: pact.Every(interval)}}
|
||||
}
|
||||
|
||||
func (p *Plugin) Buckets() map[string]surf.Bucket {
|
||||
@@ -309,8 +291,14 @@ func (p *Plugin) MailLayouts() map[string]string {
|
||||
}
|
||||
}
|
||||
|
||||
// Commands returns the console commands, among them
|
||||
// user:jwt-blacklist-sweep, which Schedule runs.
|
||||
func (p *Plugin) Commands() []bonfire.Command {
|
||||
return append([]bonfire.Command{console.RequirePasswordChange(p.withDB), console.BackfillHandles(p.app)}, console.APITokenCommands(p.app, p.withDB)...)
|
||||
return append([]bonfire.Command{
|
||||
console.RequirePasswordChange(p.withDB),
|
||||
console.BackfillHandles(p.app),
|
||||
console.JWTBlacklistSweep(p.app),
|
||||
}, console.APITokenCommands(p.app, p.withDB)...)
|
||||
}
|
||||
|
||||
// withDB runs fn with the application's database: the one the serve command
|
||||
|
||||
10
plugin.yaml
Normal file
10
plugin.yaml
Normal file
@@ -0,0 +1,10 @@
|
||||
# Generated by summer plugin:manifest. Do not edit; rerun the command.
|
||||
schema: 1
|
||||
id: golem15.user
|
||||
module: git.golem15.com/golem15/sm-user-plugin
|
||||
package: git.golem15.com/golem15/sm-user-plugin
|
||||
name: User
|
||||
description: "The shared front-end user plugin for SummerCMS applications: registration, login with JWT sessions, activation and password reset, profile and avatar endpoints."
|
||||
framework: v0.6.0
|
||||
overrides:
|
||||
name: User
|
||||
@@ -506,47 +506,6 @@ func TestLoginRouteGroup(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginBlacklistSweep(t *testing.T) {
|
||||
gdb, sqlDB := sessionDB(t)
|
||||
app := newSessionApp(t, gdb, sqlDB)
|
||||
_, stop := bootPlugin(t, app, "50ms")
|
||||
past := time.Now().Add(-time.Minute)
|
||||
if err := gdb.Exec(`INSERT INTO jwt_blacklist (jti, expires_at, valid_until) VALUES (?, ?, ?)`, "sweep-me", past, past).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for {
|
||||
var n int64
|
||||
if err := gdb.Raw(`SELECT COUNT(*) FROM jwt_blacklist WHERE jti = ?`, "sweep-me").Scan(&n).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n == 0 {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("expired jwt_blacklist row was not swept")
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
stop()
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
|
||||
quiet := newSessionApp(t, gdb, sqlDB)
|
||||
bootPlugin(t, quiet, "0s")
|
||||
later := time.Now().Add(-time.Minute)
|
||||
if err := gdb.Exec(`INSERT INTO jwt_blacklist (jti, expires_at, valid_until) VALUES (?, ?, ?)`, "sweep-keep", later, later).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
var n int64
|
||||
if err := gdb.Raw(`SELECT COUNT(*) FROM jwt_blacklist WHERE jti = ?`, "sweep-keep").Scan(&n).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 1 {
|
||||
t.Fatal("non-positive sweep interval removed a row")
|
||||
}
|
||||
}
|
||||
|
||||
type captureMail struct {
|
||||
got []string
|
||||
}
|
||||
@@ -707,7 +666,7 @@ func newSessionApp(t *testing.T, gdb *gorm.DB, sqlDB *sql.DB) *backpack.App {
|
||||
return app
|
||||
}
|
||||
|
||||
func bootPlugin(t *testing.T, app *backpack.App, sweep string) (*Plugin, func()) {
|
||||
func bootPlugin(t *testing.T, app *backpack.App, sweep string) *Plugin {
|
||||
t.Helper()
|
||||
if sweep != "" {
|
||||
if err := app.Config.Set("golem15.user.jwt.blacklist_sweep_interval", sweep); err != nil {
|
||||
@@ -718,14 +677,7 @@ func bootPlugin(t *testing.T, app *backpack.App, sweep string) (*Plugin, func())
|
||||
if err := p.Boot(app); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stop := func() {}
|
||||
if p.sweepStop != nil {
|
||||
ch := p.sweepStop
|
||||
var once sync.Once
|
||||
stop = func() { once.Do(func() { close(ch) }) }
|
||||
t.Cleanup(stop)
|
||||
}
|
||||
return p, stop
|
||||
return p
|
||||
}
|
||||
|
||||
func sessionConfig(t *testing.T) *compass.Config {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
subject = "Activate your account"
|
||||
subject = "Aktywuj konto"
|
||||
description = "Aktywacja konta"
|
||||
layout = "user"
|
||||
==
|
||||
|
||||
@@ -5,10 +5,252 @@ name = "User"
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
<style type="text/css">{{ .brandCss }}{{ .css }}</style>
|
||||
<style type="text/css">
|
||||
/* Base */
|
||||
body, body *:not(html):not(style):not(br):not(tr):not(code) {
|
||||
font-family: Avenir, Helvetica, sans-serif;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
body {
|
||||
background-color: #f5f8fa;
|
||||
color: #74787e;
|
||||
height: 100%;
|
||||
line-height: 1.4;
|
||||
margin: 0;
|
||||
width: 100% !important;
|
||||
word-break: break-word;
|
||||
-webkit-text-size-adjust: none;
|
||||
}
|
||||
p, ul, ol, blockquote {
|
||||
line-height: 1.4;
|
||||
text-align: left;
|
||||
}
|
||||
a {
|
||||
color: #2da7c7;
|
||||
}
|
||||
a img {
|
||||
border: none;
|
||||
}
|
||||
/* Typography */
|
||||
h1 {
|
||||
color: #2f3133;
|
||||
font-size: 19px;
|
||||
font-weight: bold;
|
||||
margin-top: 0;
|
||||
text-align: left;
|
||||
}
|
||||
h2 {
|
||||
color: #2f3133;
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
margin-top: 0;
|
||||
text-align: left;
|
||||
}
|
||||
h3 {
|
||||
color: #2f3133;
|
||||
font-size: 14px;
|
||||
font-weight: bold;
|
||||
margin-top: 0;
|
||||
text-align: left;
|
||||
}
|
||||
p {
|
||||
color: #74787e;
|
||||
font-size: 16px;
|
||||
line-height: 1.5em;
|
||||
margin-top: 0;
|
||||
text-align: left;
|
||||
}
|
||||
code {
|
||||
color: #74787e;
|
||||
font-size: 16px;
|
||||
line-height: 1.5em;
|
||||
word-break: break-all;
|
||||
}
|
||||
p.sub {
|
||||
font-size: 12px;
|
||||
}
|
||||
img {
|
||||
max-width: 100%;
|
||||
}
|
||||
.break-all, .break-all * {
|
||||
word-break: break-all;
|
||||
}
|
||||
/* Layout */
|
||||
.wrapper {
|
||||
background-color: #f5f8fa;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
width: 100%;
|
||||
}
|
||||
.content {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
width: 100%;
|
||||
}
|
||||
/* Header */
|
||||
.header {
|
||||
padding: 25px 0;
|
||||
text-align: center;
|
||||
}
|
||||
.header a, .header span {
|
||||
color: #bbbfc3;
|
||||
font-size: 19px;
|
||||
font-weight: bold;
|
||||
text-decoration: none;
|
||||
}
|
||||
img.logo {
|
||||
border: 0;
|
||||
display: inline-block;
|
||||
height: auto;
|
||||
max-height: 60px;
|
||||
max-width: 200px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
/* Body */
|
||||
.body {
|
||||
background-color: #ffffff;
|
||||
border-bottom: 1px solid #edeff2;
|
||||
border-top: 1px solid #edeff2;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
width: 100%;
|
||||
}
|
||||
.inner-body {
|
||||
background-color: #ffffff;
|
||||
margin: 0 auto;
|
||||
padding: 0;
|
||||
width: 570px;
|
||||
}
|
||||
.content-cell {
|
||||
padding: 35px;
|
||||
}
|
||||
/* Subcopy */
|
||||
.subcopy {
|
||||
border-top: 1px solid #edeff2;
|
||||
margin-top: 25px;
|
||||
padding-top: 25px;
|
||||
}
|
||||
.subcopy p {
|
||||
font-size: 12px;
|
||||
}
|
||||
/* Footer */
|
||||
.footer {
|
||||
margin: 0 auto;
|
||||
padding: 0;
|
||||
text-align: center;
|
||||
width: 570px;
|
||||
}
|
||||
.footer p {
|
||||
color: #aeaeae;
|
||||
font-size: 12px;
|
||||
text-align: center;
|
||||
}
|
||||
/* Tables */
|
||||
.table table {
|
||||
border-collapse: collapse;
|
||||
margin: 30px auto;
|
||||
width: 100%;
|
||||
}
|
||||
.table th {
|
||||
border-bottom: 1px solid #edeff2;
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
.table td {
|
||||
color: #74787e;
|
||||
font-size: 15px;
|
||||
line-height: 18px;
|
||||
padding: 10px 0;
|
||||
}
|
||||
/* Buttons */
|
||||
.action {
|
||||
margin: 30px auto;
|
||||
padding: 0;
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
}
|
||||
.button {
|
||||
border-radius: 3px;
|
||||
box-shadow: 0 2px 3px rgba(0, 0, 0, 0.16);
|
||||
color: #ffffff;
|
||||
display: inline-block;
|
||||
text-decoration: none;
|
||||
-webkit-text-size-adjust: none;
|
||||
}
|
||||
.button-primary {
|
||||
background-color: #d66829;
|
||||
border-top: 10px solid #d66829;
|
||||
border-right: 18px solid #d66829;
|
||||
border-bottom: 10px solid #d66829;
|
||||
border-left: 18px solid #d66829;
|
||||
}
|
||||
.button-positive {
|
||||
background-color: #52a838;
|
||||
border-top: 10px solid #52a838;
|
||||
border-right: 18px solid #52a838;
|
||||
border-bottom: 10px solid #52a838;
|
||||
border-left: 18px solid #52a838;
|
||||
}
|
||||
.button-negative {
|
||||
background-color: #e01346;
|
||||
border-top: 10px solid #e01346;
|
||||
border-right: 18px solid #e01346;
|
||||
border-bottom: 10px solid #e01346;
|
||||
border-left: 18px solid #e01346;
|
||||
}
|
||||
/* Panels */
|
||||
.panel {
|
||||
margin: 0 0 21px;
|
||||
}
|
||||
.panel-content {
|
||||
background-color: #edeff2;
|
||||
padding: 16px;
|
||||
}
|
||||
.panel-item {
|
||||
padding: 0;
|
||||
}
|
||||
.panel-item p:last-of-type {
|
||||
margin-bottom: 0;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
{{ .brandCss }}{{ .css }}</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="layout-user">{{ .Content }}</div>
|
||||
<table class="wrapper layout-user" width="100%" cellpadding="0" cellspacing="0">
|
||||
{{ if or .logoUrl .siteName }}<tr>
|
||||
<td class="header">
|
||||
{{ if .logoUrl }}<img src="{{ .logoUrl }}" class="logo" alt="{{ .siteName }}" />{{ else }}<span>{{ .siteName }}</span>{{ end }}
|
||||
</td>
|
||||
</tr>{{ end }}
|
||||
<tr>
|
||||
<td align="center">
|
||||
<table class="content" width="100%" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td class="body" width="100%" cellpadding="0" cellspacing="0">
|
||||
<table class="inner-body" align="center" width="570" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td class="content-cell">
|
||||
{{ .Content }}
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
{{ with .year }}<tr>
|
||||
<td>
|
||||
<table class="footer" align="center" width="570" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td class="content-cell" align="center">
|
||||
<p>© {{ . }}{{ with $.siteName }} {{ . }}{{ end }}</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>{{ end }}
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
subject = "Welcome back"
|
||||
subject = "Witaj ponownie"
|
||||
description = "Konto zostało ponownie aktywowane"
|
||||
layout = "user"
|
||||
==
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
subject = "Reset your password"
|
||||
subject = "Ustaw nowe hasło"
|
||||
description = "Reset hasła"
|
||||
layout = "user"
|
||||
==
|
||||
|
||||
Reference in New Issue
Block a user