Compare commits
42 Commits
0fe5b91b63
...
v0.1.4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c43ba87371 | ||
|
|
174161895e | ||
|
|
78a867bccb | ||
|
|
1fc0ce7ed0 | ||
|
|
7b9faa3419 | ||
| 4c5d3b8935 | |||
| 9335e80342 | |||
| 80b436d3d9 | |||
| ee474401cb | |||
| b82d85f440 | |||
|
|
c0770294a5 | ||
|
|
15b19c7021 | ||
| 569768e657 | |||
|
|
24b16b1f10 | ||
|
|
7a6fa0e8b6 | ||
|
|
cf5c6b9d44 | ||
|
|
f0d3b8b21d | ||
|
|
026848fc02 | ||
|
|
ac8aa16217 | ||
|
|
8e172c5087 | ||
|
|
63ac504c42 | ||
|
|
2b04cda3ff | ||
|
|
7991b53979 | ||
|
|
a848aa17d6 | ||
|
|
493a3ff47c | ||
|
|
43fabfa6c3 | ||
|
|
f4969591e2 | ||
|
|
ba43ad9c03 | ||
|
|
4693155108 | ||
|
|
58595fef27 | ||
|
|
a3992879db | ||
|
|
9611708792 | ||
|
|
5805c6347f | ||
|
|
c7d9d7d25d | ||
|
|
f7ca3c4f59 | ||
|
|
cdea47a178 | ||
|
|
970eba7734 | ||
|
|
ebaf3a0817 | ||
|
|
f3f33b809a | ||
|
|
4e17c0d35b | ||
|
|
b410a7fea9 | ||
|
|
e22f7660f3 |
106
README.md
106
README.md
@@ -12,7 +12,7 @@ Module `git.golem15.com/golem15/sm-user-plugin`, package `user`, plugin ID `gole
|
||||
|
||||
The plugin is a compiled SummerCMS plugin. Its `init` registers it with the framework, so an application loads it by listing it in `summer.yaml`; `summer build` then emits the blank import above into the application's `plugins.gen.go`.
|
||||
|
||||
It owns the `users` table extensions, `user_throttle`, `jwt_blacklist`, `user_api_tokens`, `golem15_user_organisations`, `user_groups` and `users_groups`, and the JSON API under `/_user/api/v1`. It is a core plugin shared by several applications, so its routes, payloads, table names, migration IDs and config keys are a contract: change them only in a backwards-compatible way.
|
||||
It owns the `users` table extensions, `user_throttle`, `jwt_blacklist`, `user_api_tokens`, `golem15_user_oauth_identities`, `golem15_user_organisations`, `user_groups`, `users_groups` and `golem15_user_frontend_permissions`, the JSON API under `/_user/api/v1`, and the Users, User Groups and Organisations screens of the admin. It is a core plugin shared by several applications, so its routes, payloads, table names, migration IDs, permission codes and config keys are a contract: change them only in a backwards-compatible way.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -23,13 +23,22 @@ It owns the `users` table extensions, `user_throttle`, `jwt_blacklist`, `user_ap
|
||||
- **Login throttling.** Failed logins are counted per user and IP in `user_throttle` (`CheckAndRecordLogin`, `RejectIfThrottled`) and suspend the account for a configured time.
|
||||
- **Rate limiting.** Every route runs behind the `user-api` bucket: 120 requests a minute per authenticated user, or per client IP for anonymous calls.
|
||||
- **Profile.** `POST /update`, `POST /marketing-consent`, `POST /avatar` and `POST /avatar/remove` (the avatar is stored through the framework's attachment storage).
|
||||
- **Organisations.** The `Organisation` model and the `organisation_id` and `organisation_role` user columns, as a foreign-key target for other plugins.
|
||||
- **User groups.** The `user_groups` table (seeded with the `guest` and `registered` groups, as in PHP) and the `users_groups` membership pivot, the `UserGroup` model and the `User.Groups` relation, which is never serialized. `UserGroupCodes` and `HasGroupCode` let other plugins check membership server-side, for example a site-admin check on the group code `admin`. No route of this plugin reads or writes groups, and the user payload still answers `"groups":[]`.
|
||||
- **Organisations.** The `Organisation` model and the `organisation_id` and `organisation_role` user columns, as a foreign-key target for other plugins. An organisation has a name, a slug (filled from the name by `Slugify` when it is left empty), a description, an avatar and its members: the users whose `organisation_id` points at it.
|
||||
- **User groups.** The `user_groups` table (seeded with the `guest` and `registered` groups, as in PHP) and the `users_groups` membership pivot, the `UserGroup` model and the `User.Groups` relation, which is never serialized. `UserGroupCodes` and `HasGroupCode` let other plugins check membership server-side, for example a site-admin check on the group code `admin`. No user API route reads or writes groups, and the user payload still answers `"groups":[]`. Membership is written in one place only: the `groups` field of the admin user form. Apart from that, rows leave `users_groups` only when a user or a group is deleted for good. The admin Users list can filter by group.
|
||||
- **Admin screens.** The plugin registers the Users screen with the framework's admin (`pact.HasAdminControllers`, controller ID `golem15.user.users`), the port of the WinterCMS `Users` controller: a list with search, the group, registration date and activated filters and row states (deactivated, banned, not activated); a read-only preview with a status hint; and a form with name, email, a password with confirmation, an optional invitation mail, the user's groups, the organisation, the avatar and the user's frontend permissions. Bulk actions activate, deactivate, restore, ban and unban users; the preview offers activate, unban and unsuspend while they apply. Deactivating is the soft delete; the delete button and the bulk delete remove a user for good, together with the throttle rows, group memberships and attachments. A user created in the admin starts not activated. There is no impersonation and no guest account.
|
||||
- **User Groups screen.** Controller ID `golem15.user.usergroups`, the port of the WinterCMS `UserGroups` controller, behind `golem15.users.access_groups`: a list with the name, code, creation date and number of members, and a form with the name, the code (letters, digits, underscore and hyphen; unique), a description and the group's frontend permissions as checkboxes, stored in `user_groups.permissions` as a JSON object of code to `1`. A group can be deleted from its form; its memberships go with it and its members stay. The screen never changes who is in a group.
|
||||
- **Organisations screen.** Controller ID `golem15.user.organisations`, the port of the WinterCMS `Organisations` controller, behind `golem15.users.access_users`: a list and a form with the name, slug, description and avatar, and on an existing organisation the Members tab. Adding a member sets that user's `organisation_id` and removing one clears it; a user is never deleted. Only users without an organisation can be added, so a user moves by being removed from one organisation and added to the other (or through the organisation field of the user form). Deleting an organisation clears `organisation_id` and `organisation_role` of its members first.
|
||||
- **Privileged groups.** The groups whose code is listed in `golem15.user.privileged_groups` (default `admin`) are privileged: an application may treat their members as site administrators. Three things therefore need the backend permission `golem15.users.manage_privileged_groups` on top of the screen's own permission, and answer 403 without it, saving nothing. First, membership: adding a privileged group to a user or removing it, on create and on update of the user form. An administrator without the permission sees those groups locked in the field and can still change the user's other groups. Second, the code: creating a group with a privileged code, changing a group's code to or from a privileged one, and deleting a privileged group. Its name, description and frontend permissions need only `golem15.users.access_groups`. Codes compare case-sensitively, and a group without a code is never privileged. Third, the member's account, which is protected against takeover: changing that user's email or password, and deleting them for good, needs the backend permission `golem15.users.manage_privileged_groups` on top of `golem15.users.access_users`. Without it the request answers 403 and nothing is saved; a bulk delete that contains such a user deletes none of the selected users. Everything else on such a user (name, organisation, avatar, frontend permissions, activate, deactivate, restore, ban, unban, unsuspend) needs only `golem15.users.access_users`. `PrivilegedGroupCodes`, `IsPrivilegedCode`, `PrivilegedGroupIDs` and `IsPrivilegedMember` expose the rule to other code.
|
||||
- **Frontend permissions.** `golem15_user_frontend_permissions` is the catalogue of permissions a site defines for its users (rows come from the application's migrations or seeds). A user's own choices are stored in `users.permissions` and a group's in `user_groups.permissions`, as a JSON object of code to `1` (allow) or `-1` (deny). `MergedPermissions` combines them as PHP `getMergedPermissions` does: among a user's groups the most positive value wins, then the user's own value replaces the groups'. `HasPermission` and `UserHasPermission` answer whether a code is held: only at exactly `1`, with Winter's `*` wildcards. Neither value appears in the user payload, whose `permissions` key stays `null`.
|
||||
- **Last seen.** `users.last_seen` is stamped by `POST /login` and `POST /refresh` through `TouchLastSeen`, at most once per five minutes per user. A failed write is logged and never fails authentication. It is shown in the admin list and is not part of any user payload.
|
||||
- **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.
|
||||
- **Mail templates.** Activation, reset and reactivation mails in Polish and English (`golem15.user::mail.*`, layout `golem15.user::mail.layouts.user`); the locale follows the user (`ResolveMailLocale`).
|
||||
- **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). `GetApiArrayEvent` lets other plugins merge keys into the user payload.
|
||||
- **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.
|
||||
- **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). `CreatedEvent` (`classes.CreatedEventName` `user.Created`) fires from API register and admin create. `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 configured social login providers (none yet: it returns an empty list).
|
||||
- **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.
|
||||
- **Sign-in helpers for social login.** `RegisterOptions.PasswordLess`, `FinishLogin`, `RegistrationSettings`, `RegistrationsFromIP`, `RefreshTTL` and `RemoteIP` let a social-login plugin create accounts and finish logins with the user plugin's own rules instead of copies.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -68,6 +77,8 @@ plugins:
|
||||
|
||||
The plugin's own `go.mod` replaces the framework with `../../../../summercms.go`, so it expects the framework checkout next to the application checkout (`<dir>/summercms.go` and `<dir>/acme/plugins/golem15/user`).
|
||||
|
||||
Because the plugin registers an admin screen, an application that loads it mounts the framework's admin API and must set `admin.jwt.secret` (`SUMMER_ADMIN__JWT__SECRET`); start-up fails while it is empty. The admin screens need framework release v0.1.3 or later.
|
||||
|
||||
Another plugin that needs the signed-in user puts its routes behind `jwt.auth`. A machine API uses `user.api_token`, optionally followed by `user.scope:read`, `user.scope:write`, or `user.permission:vendor.plugin.code`. Both guards resolve the same user and current group permissions. Import `git.golem15.com/golem15/sm-user-plugin/models`, `.../classes`, or `.../middleware` for the shared types and helpers.
|
||||
|
||||
## API reference
|
||||
@@ -95,18 +106,84 @@ All routes are mounted under `/_user/api/v1` with the `throttle:user-api` middle
|
||||
| `GET /tokens` | `controllers.APITokenIndex` (`jwt.auth`) |
|
||||
| `DELETE /tokens/{id}` | `controllers.APITokenDestroy` (`jwt.auth`) |
|
||||
|
||||
### Host-mounted OAuth identities
|
||||
|
||||
The host application mounts these constructors on a path it chooses. They are not registered under `/_user/api/v1`. `OAuthIdentitiesOptions.WriteNotFound` is the host's 404 writer so missing, foreign and unknown providers share one body. `OAuthIdentitiesOptions.Providers` is the unlink allow-list; when empty it is read on every request from a published `classes.OAuthProviderSource` (its `KnownOAuthProviders`), else it is `google`, `facebook`, `github` and `microsoft`. Unlinking follows the PHP rule: it succeeds when the user has a self-set password (`has_self_set_password`) or another identity remains, and otherwise answers 409 with the phrase `golem15.user::lang.oauth.last_method_blocked` (body unchanged). The guarded delete runs in a transaction that first locks the user's `users` row, so two concurrent unlinks never remove the last sign-in method.
|
||||
|
||||
| Constructor | Role |
|
||||
|-------------|------|
|
||||
| `controllers.OAuthIdentitiesIndex` | Lists the caller's linked providers as `{provider, linked_at}` only. |
|
||||
| `controllers.OAuthIdentitiesDestroy` | Unlinks one provider for the caller (204), or answers 409 when it is the last sign-in method of a user without a self-set password. |
|
||||
| `controllers.OAuthIdentitiesOptions` | Host injects `Providers` and `WriteNotFound`. |
|
||||
|
||||
### Admin
|
||||
|
||||
The three screens are served by the framework's generic admin API under `<admin prefix>/api/v1/golem15/user/users`, `.../usergroups` and `.../organisations`; the plugin adds no admin route of its own.
|
||||
|
||||
| Item | Value |
|
||||
|------|-------|
|
||||
| Admin controllers | `golem15.user.users`, `golem15.user.usergroups` and `golem15.user.organisations`, from `controllers.AdminControllers` |
|
||||
| Navigation | main item `user` (order 555) with the side items `users`, `usergroups` and `organisations`, each shown to an administrator who holds its permission |
|
||||
| Relation manager | `members` on `golem15.user.organisations` (link and unlink) |
|
||||
| Bulk actions (Users) | `activate`, `deactivate`, `restore`, `ban`, `unban`, and the built-in delete |
|
||||
| Record actions (Users) | `activate`, `unban`, `unsuspend` |
|
||||
|
||||
Backend permissions, all on the tab `golem15.user::lang.plugin.tab`:
|
||||
|
||||
| Code | Default role | Grants |
|
||||
|------|--------------|--------|
|
||||
| `golem15.users.access_users` | `developer` | The Users screen and every action on it, including a user's membership of ordinary groups, and the Organisations screen with its members. |
|
||||
| `golem15.users.access_groups` | `developer` | The User Groups screen. |
|
||||
| `golem15.users.access_settings` | `developer` | Registered for roles that already name it; no screen uses it yet. |
|
||||
| `golem15.users.impersonate_user` | `developer` | Registered for roles that already name it; impersonation is not available. |
|
||||
| `golem15.users.manage_privileged_groups` | none | Adding a privileged group to a user or removing it; creating, re-coding or deleting a privileged group; changing the email or password of a privileged-group member, and deleting one for good. Only a superuser or a role that was granted it holds it. |
|
||||
|
||||
Migrations added for the admin, all additive:
|
||||
|
||||
| ID | Adds |
|
||||
|----|------|
|
||||
| `202610040001_add_users_permissions` | `users.permissions` (text, nullable) |
|
||||
| `202610040002_add_users_last_seen` | `users.last_seen` (timestamp, nullable) |
|
||||
| `202610040003_create_frontend_permissions` | the table `golem15_user_frontend_permissions` (`code` unique, `label`, `tab`, `comment`) |
|
||||
|
||||
Migrations added for linked OAuth identities, all additive:
|
||||
|
||||
| ID | Adds |
|
||||
|----|------|
|
||||
| `202610050001_create_oauth_identities` | the table `golem15_user_oauth_identities` (`user_id` cascade FK to `users`, unique `(user_id, provider)` and `(provider, provider_id)`, jsonb `profile_data`) |
|
||||
|
||||
Migrations added for @mention handles, all additive:
|
||||
|
||||
| ID | Adds |
|
||||
|----|------|
|
||||
| `202610160002_add_handle_to_users` | `users.handle` (`VARCHAR(255)` NULL, unique index `users_handle_unique`, `ADD COLUMN IF NOT EXISTS`; rollback is a no-op) |
|
||||
|
||||
Packages:
|
||||
|
||||
- `controllers`: the route handlers above, plus the registration steps `POST /register` runs, for other plugins:
|
||||
- `RegisterUser(ctx, app, db, fields, RegisterOptions)` validates `fields` against the user model's rules, hashes the password with `golem15.user.password.bcrypt_cost` and creates the user on `db` (which may be a transaction). It returns the validation errors instead of writing a response and never modifies `fields`. `RegisterOptions.Activate` creates the account activated; `RegisterOptions.IP` records the client IP.
|
||||
- `controllers`: the route handlers above, `AdminControllers` (the admin controller list), `PermissionAccessUsers` and `PermissionAccessGroups`, plus the registration steps `POST /register` runs, for other plugins:
|
||||
- `RegisterUser(ctx, app, db, fields, RegisterOptions)` validates `fields` against the user model's rules, hashes the password with `golem15.user.password.bcrypt_cost` and creates the user on `db` (which may be a transaction). It returns the validation errors instead of writing a response and never modifies `fields`. `RegisterOptions.Activate` creates the account activated; `RegisterOptions.IP` records the client IP; `RegisterOptions.PasswordLess` stores `has_self_set_password=false` for an account whose random password the user never knew (a social sign-in), while the zero value keeps `true`.
|
||||
- `FireRegisterEvent(ctx, app, user, fields)` fires `RegisterEvent` with `Payload` set to a copy of `fields` without `password` and `password_confirmation`, and returns the listeners' error (`/register` ignores it). Fire it after the user row is committed.
|
||||
- `FireCreatedEvent(ctx, app, user)` fires `CreatedEvent` (`user.Created`). `/register` ignores that error.
|
||||
- `FireDeletingEvent(ctx, app, user, tx)` fires `DeletingEvent` (`user.Deleting`) inside the delete transaction.
|
||||
- `FireDeactivatingEvent(ctx, app, user, tx)` fires `DeactivatingEvent` (`user.Deactivating`) inside the deactivation transaction. The admin deactivate bulk action fires it after `DeactivateUsers` for every selected user that was not deactivated yet; a listener error rolls the action back.
|
||||
- `IssueToken(app, user, r)` mints the session JWT as `/register` and `/login` do.
|
||||
- `APIArray(ctx, app, user)` builds the user payload, extended by `GetApiArrayEvent` listeners.
|
||||
- `classes`: `JWTSecret`, `GormUsers` (the `bouncer.UserProvider`), `LookupByEmail`, `UserPermissionGrants`, `UserGroupCodes`, `HasGroupCode`, `APITokenPrefix`, `MintAPIToken`, `HashAPIToken` and `RevokeAPIToken`, plus the activation/reset, throttle, mail locale and event helpers. `RegisterEvent` carries `User` and `Payload map[string]any`, a read-only copy of the register input without the password keys.
|
||||
- `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.
|
||||
- `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).
|
||||
- `RefreshTTL(app)` is the refresh window, `golem15.user.jwt.refresh_ttl` minutes (default 20160), and `RemoteIP(r)` the host part of `r.RemoteAddr` that `/login` uses for its throttle.
|
||||
- `classes`: `JWTSecret`, `GormUsers` (the `bouncer.UserProvider`), `LookupByEmail`, `UserPermissionGrants`, `UserGroupCodes`, `HasGroupCode`, `APITokenPrefix`, `MintAPIToken`, `HashAPIToken` and `RevokeAPIToken`, plus the activation/reset, throttle, mail locale and event helpers. `RegisterEvent` carries `User` and `Payload map[string]any`, a read-only copy of the register input without the password keys. For the admin and for other plugins it also has:
|
||||
- `MergedPermissions(ctx, db, userID)`, `HasPermission(merged, code)` and `UserHasPermission(ctx, db, userID, code)`, the frontend permission resolver, and `FrontendPermissionOptions(ctx, db)`, the catalogue by tab and code.
|
||||
- `PermissionManagePrivilegedGroups`, `PrivilegedGroupCodes(cfg)`, `IsPrivilegedCode(codes, code)`, `PrivilegedGroupIDs(ctx, db, codes)` and `IsPrivilegedMember(ctx, db, codes, userID)`, the privileged-group rule.
|
||||
- `ActivateUsers`, `DeactivateUsers`, `RestoreUsers`, `BanUsers`, `UnbanUsers`, `UnsuspendUser`, `ThrottleStates` and `ForceDeleteCleanup`, the user actions the admin runs. Each takes the handle of the caller's transaction.
|
||||
- `TouchLastSeen(ctx, db, userID)`.
|
||||
- `OAuthProvider` (`Name`, `Label`) and `OAuthProviderSource` (`EnabledOAuthProviders(ctx)`, `KnownOAuthProviders()`), the seam a social-login plugin publishes with an explicit type argument, `app.Publish[classes.OAuthProviderSource](src)`, so the lookup finds it. `GET /oauth-providers` lists its enabled providers in order; the unlink routes accept its known names.
|
||||
- `RequestUser(ctx, app, r)` and `EndRequestSession(ctx, app, w, r)`, for handlers that serve signed-in and anonymous browsers on one route (an OAuth provider's authorize page). `RequestUser` reads and checks the session JWT exactly as the `jwt` guard does (bearer header, then the `token` and `auth_token` cookies, the blacklist, `tokens_valid_after`) and returns the user, or `nil` for an anonymous, invalid, expired or blacklisted request and for a soft-deleted user; only an infrastructure failure is an error. `EndRequestSession` blacklists the request's JWT until it expires (as `POST /logout` does) and writes the forget cookie of `bouncer.LoadCookieConfig`, best effort: a blacklist failure is logged, never returned.
|
||||
- `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 file path 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.
|
||||
- `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`, `APIToken`.
|
||||
- `models`: `User`, `Throttle`, `Organisation`, `UserGroup`, `UsersGroup` (the `users_groups` pivot), `APIToken`, `OAuthIdentity`, `FrontendPermission` 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 `Slugify` is the slug rule. `User.FilterScope` answers the admin list scope `FilterByGroup`, and `User.AttachRelations` declares the avatar (`AvatarField`).
|
||||
- `updates`: the gormigrate migrations, returned by `updates.All()`.
|
||||
- `console`: `RequirePasswordChange` and `APITokenCommands`.
|
||||
- `console`: `RequirePasswordChange`, `BackfillHandles` and `APITokenCommands`.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -132,16 +209,21 @@ Defaults live in `config/config.yaml` and are merged under `golem15.user.*`. Any
|
||||
| `golem15.user.password.bcrypt_cost` | `10` | bcrypt cost for new password hashes. |
|
||||
| `golem15.user.password.min_length` | `8` | Minimum password length. |
|
||||
| `golem15.user.api_tokens.prefix` | `usr_` | Prefix for newly minted and accepted shared API-token secrets. Override an existing application's legacy prefix without creating a plugin-specific token table. |
|
||||
| `golem15.user.privileged_groups` | `[admin]` | Codes of the privileged user groups. Membership of such a group, the group's code and its delete, and the email, password and permanent delete of its members need `golem15.users.manage_privileged_groups`. Read on every request. An empty list protects no group. |
|
||||
| `golem15.user.turnstile` | `""` | Cloudflare Turnstile on `POST /login` and `POST /register`. Empty adds nothing; `open` or `closed` appends the framework's `turnstile:open` or `turnstile:closed` middleware to those two routes only (summercms v0.3.0 and later; secret in `turnstile.secret`, token in the `turnstile_token` field). `open` lets requests pass when Cloudflare is unreachable, `closed` refuses them. Any other value fails boot. |
|
||||
|
||||
## CLI commands
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `user:require-password-change <email>` | Flag an account so its next session must set a new password. |
|
||||
| `user:backfill-handles` | Assign a unique handle to every user row that still has none. |
|
||||
| `user:token:create <email> [--name api] [--scopes read,write] [--expires RFC3339]` | Create an application-wide API token and print its secret once. |
|
||||
| `user:token:list` | List token metadata without secrets or hashes. |
|
||||
| `user:token:revoke <id>` | Revoke a shared API token immediately. |
|
||||
|
||||
Each command uses the database the serve command published or, run from the console, opens one from `database.dsn` (and loads the encryption keys from `app.key`) for its duration.
|
||||
|
||||
## Dependencies
|
||||
|
||||
- The SummerCMS framework, `git.golem15.com/golem15/summercms` (modules `backpack`, `bonfire`, `bouncer`, `pact`, `party`, `surf` and others).
|
||||
@@ -156,3 +238,5 @@ 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 admin tests (`TestAdmin*`) boot the plugin with the admin API mounted on a database of their own and sign in backend administrators with a chosen permission set; the helpers are in `admin_harness_test.go`.
|
||||
|
||||
38
admin.go
Normal file
38
admin.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"io/fs"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/controllers"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
// adminFS holds the admin YAML and partials, file by file: the controllers
|
||||
// directory also holds files that are not admin assets.
|
||||
//
|
||||
//go:embed controllers/users/config_list.yaml controllers/users/config_form.yaml controllers/users/config_filter.yaml controllers/users/_hint.htm models/user/fields.yaml models/user/columns.yaml
|
||||
//go:embed controllers/usergroups/config_list.yaml controllers/usergroups/config_form.yaml models/usergroup/fields.yaml models/usergroup/columns.yaml
|
||||
//go:embed controllers/organisations/config_list.yaml controllers/organisations/config_form.yaml controllers/organisations/config_relation.yaml models/organisation/fields.yaml models/organisation/columns.yaml
|
||||
var adminFS embed.FS
|
||||
|
||||
func (p *Plugin) AdminFS() fs.FS { return adminFS }
|
||||
|
||||
// AdminControllers hands the controllers a lazy accessor of the booted app,
|
||||
// so they read the database handle and the config at request time.
|
||||
func (p *Plugin) AdminControllers() []pact.AdminController {
|
||||
return controllers.AdminControllers(func() *backpack.App {
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
return p.app
|
||||
})
|
||||
}
|
||||
|
||||
var (
|
||||
_ pact.AdminAssets = (*Plugin)(nil)
|
||||
_ pact.HasAdminControllers = (*Plugin)(nil)
|
||||
_ pact.HasPermissions = (*Plugin)(nil)
|
||||
_ pact.HasNavigation = (*Plugin)(nil)
|
||||
)
|
||||
259
admin_groups_edge_test.go
Normal file
259
admin_groups_edge_test.go
Normal file
@@ -0,0 +1,259 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
// TestAdminGroupsControllerGuards drives the User Groups controller directly
|
||||
// on the inputs the HTTP tests cannot produce. A guard that cannot read what
|
||||
// it needs answers a plain error (the opaque 500), never a pass.
|
||||
func TestAdminGroupsControllerGuards(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
const id = "golem15.user.usergroups"
|
||||
notGroup := &models.User{}
|
||||
var nilGroup *models.UserGroup
|
||||
admin, plain := "admin", "plain-code"
|
||||
damaged := "{not json"
|
||||
|
||||
broken, _ := brokenApp(t)
|
||||
env := newAdminEnv(t)
|
||||
sets := map[string]adminControllerSet{
|
||||
"no accessor": adminControllersOn(nil),
|
||||
"not booted": adminControllersOn(func() *backpack.App { return nil }),
|
||||
"no database": adminControllersOn(func() *backpack.App { return bareApp(t) }),
|
||||
"a failing handle": adminControllersOn(func() *backpack.App { return broken }),
|
||||
"the live database": adminControllersOn(func() *backpack.App { return env.app }),
|
||||
}
|
||||
for name, set := range sets {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ctl := set[id]
|
||||
for _, record := range []any{notGroup, nilGroup, nil} {
|
||||
wantPlainError(t, "FormBeforeCreate", ctl.(pact.FormBeforeCreate).FormBeforeCreate(ctx, record))
|
||||
wantPlainError(t, "FormBeforeUpdate", ctl.(pact.FormBeforeUpdate).FormBeforeUpdate(ctx, record))
|
||||
wantPlainError(t, "FormBeforeDelete", ctl.(pact.FormBeforeDelete).FormBeforeDelete(ctx, record))
|
||||
wantPlainError(t, "FormAfterDelete", ctl.(pact.FormAfterDelete).FormAfterDelete(ctx, record))
|
||||
editor := ctl.(cabana.PermissionEditorProvider)
|
||||
_, err := editor.AdminPermissionValues(ctx, "permissions", record)
|
||||
wantPlainError(t, "AdminPermissionValues", err)
|
||||
wantPlainError(t, "AdminSetPermissionValues", editor.AdminSetPermissionValues(ctx, "permissions", record, nil))
|
||||
}
|
||||
editor := ctl.(cabana.PermissionEditorProvider)
|
||||
if _, err := editor.AdminPermissionOptions(ctx, "name"); err == nil {
|
||||
t.Fatal("permission options for another field")
|
||||
}
|
||||
if _, err := editor.AdminPermissionValues(ctx, "name", &models.UserGroup{}); err == nil {
|
||||
t.Fatal("permission values for another field")
|
||||
}
|
||||
if err := editor.AdminSetPermissionValues(ctx, "name", &models.UserGroup{}, nil); err == nil {
|
||||
t.Fatal("permission write for another field")
|
||||
}
|
||||
// A stored value that is not a JSON object is an error, never an
|
||||
// empty set an edit would then save over it.
|
||||
_, err := editor.AdminPermissionValues(ctx, "permissions", &models.UserGroup{Permissions: &damaged})
|
||||
wantPlainError(t, "damaged stored permissions", err)
|
||||
if values, err := editor.AdminPermissionValues(ctx, "permissions", &models.UserGroup{}); err != nil || len(values) != 0 {
|
||||
t.Fatalf("no stored permissions = %v %v", values, err)
|
||||
}
|
||||
if ctl.(pact.ListExtendQuery).ListExtendQuery(ctx, nil) != nil {
|
||||
t.Fatal("ListExtendQuery invented a handle")
|
||||
}
|
||||
wantPlainError(t, "FormAfterDelete without a transaction", ctl.(pact.FormAfterDelete).FormAfterDelete(ctx, &models.UserGroup{ID: 1}))
|
||||
|
||||
// Without a principal the privileged code is refused on every
|
||||
// path, with the screen's 403 (D-06).
|
||||
for what, err := range map[string]error{
|
||||
"create": ctl.(pact.FormBeforeCreate).FormBeforeCreate(ctx, &models.UserGroup{Name: "Admins", Code: &admin}),
|
||||
"delete": ctl.(pact.FormBeforeDelete).FormBeforeDelete(ctx, &models.UserGroup{ID: 1, Name: "Admins", Code: &admin}),
|
||||
} {
|
||||
forbidden, ok := err.(*cabana.ForbiddenError)
|
||||
if !ok || forbidden.Message != "golem15.user::lang.groups.privileged_forbidden" || forbidden.Details["code"] == nil {
|
||||
t.Fatalf("%s of a privileged group without a principal: %v", what, err)
|
||||
}
|
||||
}
|
||||
// With the extra permission, and for a superuser, it passes.
|
||||
for _, principal := range []*bouncer.Principal{
|
||||
{PermissionGrants: map[string]bool{permManagePrivileged: true}},
|
||||
{IsSuperuser: true},
|
||||
} {
|
||||
as := bouncer.WithUser(ctx, principal)
|
||||
if err := ctl.(pact.FormBeforeCreate).FormBeforeCreate(as, &models.UserGroup{Name: "Admins", Code: &admin}); err != nil {
|
||||
t.Fatalf("create for %+v: %v", principal, err)
|
||||
}
|
||||
if err := ctl.(pact.FormBeforeDelete).FormBeforeDelete(as, &models.UserGroup{ID: 1, Code: &admin}); err != nil {
|
||||
t.Fatalf("delete for %+v: %v", principal, err)
|
||||
}
|
||||
}
|
||||
// An ordinary code and a group without a code need nothing extra.
|
||||
if err := ctl.(pact.FormBeforeCreate).FormBeforeCreate(ctx, &models.UserGroup{Name: "Plain", Code: &plain}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ctl.(pact.FormBeforeDelete).FormBeforeDelete(ctx, &models.UserGroup{ID: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// An update reads the stored code first: with no database, a
|
||||
// failing one or an unknown group it is an error, not a pass.
|
||||
wantPlainError(t, "update of an unreadable group", ctl.(pact.FormBeforeUpdate).FormBeforeUpdate(ctx, &models.UserGroup{ID: 987654321, Name: "Gone", Code: &plain}))
|
||||
if name != "the live database" {
|
||||
_, err := editor.AdminPermissionOptions(ctx, "permissions")
|
||||
wantPlainError(t, "AdminPermissionOptions", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminGroupsEdge covers the remaining branches of the User Groups
|
||||
// screen through the admin API.
|
||||
func TestAdminGroupsEdge(t *testing.T) {
|
||||
stamp := adminStamp()
|
||||
privilegedCode := "edgepriv-" + stamp
|
||||
env := newAdminEnv(t, func(cfg *compass.Config) {
|
||||
if err := cfg.Set("golem15.user.privileged_groups", []string{"admin", "guest", privilegedCode}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
token := env.admin(t, permAccessGroups)
|
||||
manager := env.admin(t, permAccessGroups, permManagePrivileged)
|
||||
|
||||
// A group update that keeps a privileged code needs nothing extra: the
|
||||
// name and description change, the code stays.
|
||||
privileged := env.seedGroup(t, "Edge privileged "+stamp, privilegedCode)
|
||||
env.expect(t, http.StatusOK, http.MethodPut, groupPath(privileged.ID), token, map[string]any{"name": "Edge renamed " + stamp, "code": privilegedCode, "description": "kept"})
|
||||
if got := env.group(t, privileged.ID); got.Name != "Edge renamed "+stamp || got.Code == nil || *got.Code != privilegedCode || got.Description == nil || *got.Description != "kept" {
|
||||
t.Fatalf("group after a name-only update = %+v", got)
|
||||
}
|
||||
// The same administrator may not move the code away from, or onto, a
|
||||
// privileged one; the manager may.
|
||||
ordinary := env.seedGroup(t, "Edge ordinary "+stamp, "edgeord-"+stamp)
|
||||
rec := env.expect(t, http.StatusForbidden, http.MethodPut, groupPath(privileged.ID), token, map[string]any{"code": "edgefree-" + stamp})
|
||||
if message := adminDecode(t, rec).Error.Message; message != privilegedGroupCodeForbidden {
|
||||
t.Fatalf("403 message = %q", message)
|
||||
}
|
||||
if got := env.group(t, privileged.ID); *got.Code != privilegedCode {
|
||||
t.Fatalf("a refused re-code changed the code to %q", *got.Code)
|
||||
}
|
||||
env.expect(t, http.StatusOK, http.MethodPut, groupPath(ordinary.ID), manager, map[string]any{"name": "Edge ordinary " + stamp + " b"})
|
||||
|
||||
// Validation answers before the guard: a create that would be refused
|
||||
// with 403 answers 422 when its body is also invalid, and saves nothing.
|
||||
rec = env.expect(t, http.StatusUnprocessableEntity, http.MethodPost, adminAPI(adminGroupsPath), token, map[string]any{"name": "Edge duplicate " + stamp, "code": privilegedCode})
|
||||
if details := adminDecode(t, rec).Error.Details; len(details["code"]) == 0 {
|
||||
t.Fatalf("422 details = %v", details)
|
||||
}
|
||||
var count int64
|
||||
if err := env.gdb.Raw(`SELECT COUNT(*) FROM user_groups WHERE code = ?`, privilegedCode).Scan(&count).Error; err != nil || count != 1 {
|
||||
t.Fatalf("groups with the privileged code = %d err = %v", count, err)
|
||||
}
|
||||
|
||||
// A code with characters outside letters, digits, dash and underscore is
|
||||
// a 422 on the field, in the request's language.
|
||||
for _, code := range []string{"with space", "dot.ted", "sl/ash", "ąę"} {
|
||||
rec := env.expect(t, http.StatusUnprocessableEntity, http.MethodPost, adminAPI(adminGroupsPath), token, map[string]any{"name": "Edge bad code " + stamp, "code": code})
|
||||
details := adminDecode(t, rec).Error.Details
|
||||
if got := details["code"]; len(got) != 1 || got[0] != "The code may only contain letters, numbers, dashes and underscores." {
|
||||
t.Fatalf("code %q: details = %v", code, details)
|
||||
}
|
||||
}
|
||||
|
||||
// An application protects a seeded group by naming its code in
|
||||
// golem15.user.privileged_groups: the guest group then cannot be deleted
|
||||
// or re-coded with golem15.users.access_groups alone.
|
||||
var guestID uint
|
||||
if err := env.gdb.Raw(`SELECT id FROM user_groups WHERE code = 'guest' ORDER BY id LIMIT 1`).Scan(&guestID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if guestID == 0 {
|
||||
guestID = env.seedGroup(t, "Guest", "guest").ID
|
||||
}
|
||||
env.expect(t, http.StatusForbidden, http.MethodDelete, groupPath(guestID), token, nil)
|
||||
env.expect(t, http.StatusForbidden, http.MethodPut, groupPath(guestID), token, map[string]any{"code": "visitor-" + stamp})
|
||||
if got := env.group(t, guestID); got == nil || got.Code == nil || *got.Code != "guest" {
|
||||
t.Fatalf("the protected guest group = %+v", got)
|
||||
}
|
||||
|
||||
// Search and sort on the list.
|
||||
for _, name := range []string{"b", "a", "c"} {
|
||||
env.seedGroup(t, "Sort "+stamp+" "+name, "sort-"+stamp+"-"+name)
|
||||
}
|
||||
order := func(query string) []string {
|
||||
var rows []map[string]any
|
||||
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminGroupsPath)+"?search=Sort%20"+stamp+"&"+query, token, nil), &rows)
|
||||
codes := []string{}
|
||||
for _, row := range rows {
|
||||
code, _ := row["code"].(string)
|
||||
codes = append(codes, code[len(code)-1:])
|
||||
}
|
||||
return codes
|
||||
}
|
||||
if got := order("sort=name&dir=asc"); !reflect.DeepEqual(got, []string{"a", "b", "c"}) {
|
||||
t.Fatalf("name asc = %v", got)
|
||||
}
|
||||
if got := order("sort=code&dir=desc"); !reflect.DeepEqual(got, []string{"c", "b", "a"}) {
|
||||
t.Fatalf("code desc = %v", got)
|
||||
}
|
||||
for _, query := range []string{"sort=permissions", "sort=description", "filter[code]=x"} {
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodGet, adminAPI(adminGroupsPath)+"?"+query, token, nil)
|
||||
}
|
||||
|
||||
// A group whose stored permissions are not a JSON object cannot be
|
||||
// opened: the answer is the opaque 500, and the row is left as it is.
|
||||
broken := env.seedGroup(t, "Edge damaged "+stamp, "edgedmg-"+stamp)
|
||||
if err := env.gdb.Exec(`UPDATE user_groups SET permissions = '{"a":' WHERE id = ?`, broken.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = env.expect(t, http.StatusInternalServerError, http.MethodGet, groupPath(broken.ID), token, nil)
|
||||
if message := adminDecode(t, rec).Error.Message; message != "Server error" {
|
||||
t.Fatalf("500 message = %q", message)
|
||||
}
|
||||
if got := env.group(t, broken.ID); got.Permissions == nil || *got.Permissions != `{"a":` {
|
||||
t.Fatalf("damaged permissions after the read = %v", got.Permissions)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminGroupsLegacyBooleanPermissions pins a known difference between
|
||||
// the two readers of user_groups.permissions (12.1-SECURITY-REVIEW.md, open
|
||||
// item 5): the API-token grants count a stored true as granted, the admin
|
||||
// editor and the merged-permission resolver read only numbers. A group
|
||||
// stored with booleans therefore shows unchecked, and an edit through the
|
||||
// editor does not keep the boolean. The change is towards fewer grants,
|
||||
// never more.
|
||||
func TestAdminGroupsLegacyBooleanPermissions(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
token := env.admin(t, permAccessGroups)
|
||||
stamp := adminStamp()
|
||||
legacy, offered := "legacy.bool."+stamp, "offered.bool."+stamp
|
||||
if err := env.gdb.Exec(`INSERT INTO golem15_user_frontend_permissions (code, label, tab) VALUES (?, 'Legacy', 'Edge'), (?, 'Offered', 'Edge')`, legacy, offered).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
group := env.seedGroup(t, "Edge boolean "+stamp, "edgebool-"+stamp)
|
||||
if err := env.gdb.Exec(`UPDATE user_groups SET permissions = ? WHERE id = ?`, `{"`+legacy+`":true}`, group.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var record struct {
|
||||
Permissions map[string]int `json:"permissions"`
|
||||
}
|
||||
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, groupPath(group.ID), token, nil), &record)
|
||||
if len(record.Permissions) != 0 {
|
||||
t.Fatalf("a boolean value is shown as %v", record.Permissions)
|
||||
}
|
||||
// A save that does not carry the field leaves the stored value alone.
|
||||
env.expect(t, http.StatusOK, http.MethodPut, groupPath(group.ID), token, map[string]any{"description": "untouched"})
|
||||
if got := env.group(t, group.ID); got.Permissions == nil || *got.Permissions != `{"`+legacy+`":true}` {
|
||||
t.Fatalf("permissions after a save without the field = %v", got.Permissions)
|
||||
}
|
||||
// A save that carries the field writes numbers only.
|
||||
env.expect(t, http.StatusOK, http.MethodPut, groupPath(group.ID), token, map[string]any{"permissions": map[string]int{offered: 1}})
|
||||
if got := env.group(t, group.ID); got.Permissions == nil || *got.Permissions != `{"`+offered+`":1}` {
|
||||
t.Fatalf("permissions after an edit = %v", got.Permissions)
|
||||
}
|
||||
}
|
||||
405
admin_groups_test.go
Normal file
405
admin_groups_test.go
Normal file
@@ -0,0 +1,405 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
)
|
||||
|
||||
const (
|
||||
// adminGroupsPath is the User Groups controller under the admin API.
|
||||
adminGroupsPath = "/golem15/user/usergroups"
|
||||
|
||||
permAccessGroups = "golem15.users.access_groups"
|
||||
|
||||
privilegedGroupCodeForbidden = "You do not have permission to create, re-code or delete a privileged group. Nothing was saved."
|
||||
)
|
||||
|
||||
// groupPath is the admin API path of one user group.
|
||||
func groupPath(id uint) string {
|
||||
return adminAPI(adminGroupsPath) + "/" + strconv.FormatUint(uint64(id), 10)
|
||||
}
|
||||
|
||||
// storedGroup is a user_groups row as the database holds it.
|
||||
type storedGroup struct {
|
||||
Name string
|
||||
Code *string
|
||||
Description *string
|
||||
Permissions *string
|
||||
}
|
||||
|
||||
// group reads a user_groups row; nil when it is gone.
|
||||
func (e *adminEnv) group(t *testing.T, id uint) *storedGroup {
|
||||
t.Helper()
|
||||
var rows []storedGroup
|
||||
if err := e.gdb.Raw(`SELECT name, code, description, permissions FROM user_groups WHERE id = ?`, id).Scan(&rows).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
return &rows[0]
|
||||
}
|
||||
|
||||
// sideMenu returns the side item codes of the navigation item `user` as the
|
||||
// administrator sees them; nil when the item is not shown.
|
||||
func (e *adminEnv) sideMenu(t *testing.T, token string) []string {
|
||||
t.Helper()
|
||||
var nav []struct {
|
||||
Code string `json:"code"`
|
||||
SideMenu []struct {
|
||||
Code string `json:"code"`
|
||||
Controller string `json:"controller"`
|
||||
} `json:"sideMenu"`
|
||||
}
|
||||
adminInto(t, e.expect(t, http.StatusOK, http.MethodGet, adminAPI("/navigation"), token, nil), &nav)
|
||||
for _, item := range nav {
|
||||
if item.Code != "user" {
|
||||
continue
|
||||
}
|
||||
codes := []string{}
|
||||
for _, side := range item.SideMenu {
|
||||
codes = append(codes, side.Code+"="+side.Controller)
|
||||
}
|
||||
return codes
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestAdminGroups covers the User Groups screen (D-06 ordinary path, D-15,
|
||||
// D-16, D-24, D-29): its permission, the list with the member count, the
|
||||
// form with the code rules and the checkbox permission editor, and the
|
||||
// delete with its pivot cleanup.
|
||||
func TestAdminGroups(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
usersOnly := env.admin(t, permAccessUsers)
|
||||
token := env.admin(t, permAccessGroups)
|
||||
stamp := adminStamp()
|
||||
|
||||
// The screen needs golem15.users.access_groups: the users permission
|
||||
// alone opens nothing here and does not show the side item.
|
||||
for _, path := range []string{adminAPI(adminGroupsPath), adminAPI(adminGroupsPath + "/schema/list"), adminAPI(adminGroupsPath + "/schema/form")} {
|
||||
rec := env.expect(t, http.StatusForbidden, http.MethodGet, path, usersOnly, nil)
|
||||
if code := adminDecode(t, rec).Error.Code; code != "forbidden" {
|
||||
t.Fatalf("%s code = %q", path, code)
|
||||
}
|
||||
}
|
||||
env.expect(t, http.StatusForbidden, http.MethodPost, adminAPI(adminGroupsPath), usersOnly, map[string]any{"name": "Nope " + stamp, "code": "nope-" + stamp})
|
||||
if got := env.sideMenu(t, usersOnly); !reflect.DeepEqual(got, []string{"users=golem15.user.users", "organisations=golem15.user.organisations"}) {
|
||||
t.Fatalf("side menu with the users permission = %v", got)
|
||||
}
|
||||
if got := env.sideMenu(t, token); !reflect.DeepEqual(got, []string{"usergroups=golem15.user.usergroups"}) {
|
||||
t.Fatalf("side menu with the groups permission = %v", got)
|
||||
}
|
||||
// The users screen stays closed to the groups permission.
|
||||
env.expect(t, http.StatusForbidden, http.MethodGet, adminAPI(adminUsersPath), token, nil)
|
||||
|
||||
// The list schema: Name, Code, Created and Users; rows open the update
|
||||
// form; no checkboxes, no bulk actions, no delete in the toolbar.
|
||||
var schema struct {
|
||||
RecordURL string `json:"recordUrl"`
|
||||
ShowCheckboxes bool `json:"showCheckboxes"`
|
||||
Columns []struct {
|
||||
Key string `json:"key"`
|
||||
Label string `json:"label"`
|
||||
Invisible bool `json:"invisible"`
|
||||
Sortable bool `json:"sortable"`
|
||||
Type string `json:"type"`
|
||||
} `json:"columns"`
|
||||
ToolbarButtons []string `json:"toolbarButtons"`
|
||||
BulkActions []json.RawMessage `json:"bulkActions"`
|
||||
Messages map[string]map[string]string `json:"messages"`
|
||||
}
|
||||
rawSchema := env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminGroupsPath+"/schema/list"), token, nil)
|
||||
adminInto(t, rawSchema, &schema)
|
||||
var visible []string
|
||||
for _, column := range schema.Columns {
|
||||
if column.Invisible {
|
||||
continue
|
||||
}
|
||||
visible = append(visible, column.Key+":"+column.Label)
|
||||
if column.Key == "users_count" && column.Sortable {
|
||||
t.Fatal("users_count is sortable")
|
||||
}
|
||||
}
|
||||
if want := []string{"name:Name", "code:Code", "created_at:Created", "users_count:Users"}; !reflect.DeepEqual(visible, want) {
|
||||
t.Fatalf("visible columns = %v, want %v", visible, want)
|
||||
}
|
||||
if schema.RecordURL != "golem15/user/usergroups/update/:id" || schema.ShowCheckboxes || len(schema.BulkActions) != 0 ||
|
||||
!reflect.DeepEqual(schema.ToolbarButtons, []string{"create"}) {
|
||||
t.Fatalf("list schema = %s", rawSchema.Body.String())
|
||||
}
|
||||
if got := schema.Messages["empty"]["other"]; got != "No user groups yet. Create the first one with New Group." {
|
||||
t.Fatalf("empty message = %q", got)
|
||||
}
|
||||
if got := schema.Messages["create"]["other"]; got != "New Group" {
|
||||
t.Fatalf("create message = %q", got)
|
||||
}
|
||||
// Without checkboxes there is no bulk delete on this screen.
|
||||
if rec := env.call(t, http.MethodPost, adminAPI(adminGroupsPath+"/bulk-delete"), token, map[string]any{"ids": []uint{1}}); rec.Code == http.StatusOK {
|
||||
t.Fatalf("bulk delete of groups = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// The list carries the member count from its own query: 0 for a group
|
||||
// without members (a number, not an absent value), the count otherwise.
|
||||
empty := env.seedGroup(t, "Empty "+stamp, "empty-"+stamp)
|
||||
pair := env.seedGroup(t, "Pair "+stamp, "pair-"+stamp)
|
||||
single := env.seedGroup(t, "Single "+stamp, "single-"+stamp)
|
||||
alice := env.seedUser(t, "alice", nil)
|
||||
bob := env.seedUser(t, "bob", nil)
|
||||
env.join(t, alice, pair, single)
|
||||
env.join(t, bob, pair)
|
||||
list := func(query string) (map[uint]map[string]any, int) {
|
||||
t.Helper()
|
||||
rec := env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminGroupsPath)+"?"+query, token, nil)
|
||||
var rows []map[string]any
|
||||
answer := adminInto(t, rec, &rows)
|
||||
var meta struct {
|
||||
Total int `json:"total"`
|
||||
}
|
||||
if err := json.Unmarshal(answer.Meta, &meta); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := map[uint]map[string]any{}
|
||||
for _, row := range rows {
|
||||
out[uint(row["id"].(float64))] = row
|
||||
}
|
||||
return out, meta.Total
|
||||
}
|
||||
rows, total := list("search=" + stamp)
|
||||
if total != 3 || len(rows) != 3 {
|
||||
t.Fatalf("list total = %d rows = %d", total, len(rows))
|
||||
}
|
||||
for id, want := range map[uint]float64{empty.ID: 0, pair.ID: 2, single.ID: 1} {
|
||||
got, ok := rows[id]["users_count"].(float64)
|
||||
if !ok || got != want {
|
||||
t.Fatalf("users_count of %d = %v, want %v", id, rows[id]["users_count"], want)
|
||||
}
|
||||
}
|
||||
if rows[pair.ID]["name"] != "Pair "+stamp || rows[pair.ID]["code"] != "pair-"+stamp {
|
||||
t.Fatalf("list row = %v", rows[pair.ID])
|
||||
}
|
||||
// Paging counts groups, not memberships.
|
||||
if _, total = list("search=" + stamp + "&per_page=20&page=1&sort=name&dir=asc"); total != 3 {
|
||||
t.Fatalf("sorted list total = %d", total)
|
||||
}
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodGet, adminAPI(adminGroupsPath)+"?sort=users_count", token, nil)
|
||||
|
||||
// The form: name, code (preset from name), description and the checkbox
|
||||
// permission editor on the Permissions tab.
|
||||
read, write := "wiki."+stamp+".read", "wiki."+stamp+".write"
|
||||
if err := env.gdb.Exec(`INSERT INTO golem15_user_frontend_permissions (code, label, tab) VALUES (?, 'Read', ?), (?, 'Write', ?)`,
|
||||
read, "Wiki "+stamp, write, "Wiki "+stamp).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var form struct {
|
||||
Fields []struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Mode string `json:"mode"`
|
||||
Tab string `json:"tab"`
|
||||
Preset *struct {
|
||||
Field string `json:"field"`
|
||||
} `json:"preset"`
|
||||
Options []struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"permissionOptions"`
|
||||
} `json:"fields"`
|
||||
Preview json.RawMessage `json:"preview"`
|
||||
}
|
||||
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminGroupsPath+"/schema/form"), token, nil), &form)
|
||||
var names []string
|
||||
for _, field := range form.Fields {
|
||||
names = append(names, field.Name+":"+field.Type)
|
||||
switch field.Name {
|
||||
case "code":
|
||||
if field.Preset == nil || field.Preset.Field != "name" {
|
||||
t.Fatalf("code preset = %+v", field.Preset)
|
||||
}
|
||||
case "permissions":
|
||||
offered := 0
|
||||
for _, option := range field.Options {
|
||||
if option.Code == read || option.Code == write {
|
||||
offered++
|
||||
}
|
||||
}
|
||||
if field.Mode != "checkbox" || field.Tab != "Permissions" || offered != 2 {
|
||||
t.Fatalf("permissions field = %+v", field)
|
||||
}
|
||||
}
|
||||
}
|
||||
if want := []string{"name:text", "code:text", "description:textarea", "permissions:permissioneditor"}; !reflect.DeepEqual(names, want) {
|
||||
t.Fatalf("form fields = %v, want %v", names, want)
|
||||
}
|
||||
if len(form.Preview) != 0 && string(form.Preview) != "null" {
|
||||
t.Fatalf("the group form has a preview: %s", form.Preview)
|
||||
}
|
||||
|
||||
// Create: the code needs the PHP format and must be unique; the name
|
||||
// needs three characters.
|
||||
create := func(status int, body map[string]any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return env.expect(t, status, http.MethodPost, adminAPI(adminGroupsPath), token, body)
|
||||
}
|
||||
code := "editors-" + stamp
|
||||
for field, body := range map[string]map[string]any{
|
||||
"code": {"name": "Editors " + stamp, "code": "bad code " + stamp},
|
||||
"name": {"name": "ab", "code": "short-" + stamp},
|
||||
} {
|
||||
rec := create(http.StatusUnprocessableEntity, body)
|
||||
if details := adminDecode(t, rec).Error.Details; len(details[field]) == 0 {
|
||||
t.Fatalf("create refusal has no detail on %s: %s", field, rec.Body.String())
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"dot." + stamp, "ąę" + stamp, "semi;" + stamp} {
|
||||
rec := create(http.StatusUnprocessableEntity, map[string]any{"name": "Editors " + stamp, "code": bad})
|
||||
if details := adminDecode(t, rec).Error.Details; len(details["code"]) != 1 || details["code"][0] != "The code may only contain letters, numbers, dashes and underscores." {
|
||||
t.Fatalf("code refusal for %q = %s", bad, rec.Body.String())
|
||||
}
|
||||
}
|
||||
create(http.StatusUnprocessableEntity, map[string]any{"name": "No code " + stamp})
|
||||
var before int64
|
||||
if err := env.gdb.Raw(`SELECT COUNT(*) FROM user_groups WHERE name LIKE ?`, "%"+stamp).Scan(&before).Error; err != nil || before != 3 {
|
||||
t.Fatalf("refused creates left rows: %d (%v)", before, err)
|
||||
}
|
||||
id := createdID(t, create(http.StatusCreated, map[string]any{"name": "Editors " + stamp, "code": code, "description": "May edit"}))
|
||||
if got := env.group(t, id); got == nil || got.Name != "Editors "+stamp || got.Code == nil || *got.Code != code ||
|
||||
got.Description == nil || *got.Description != "May edit" || got.Permissions != nil {
|
||||
t.Fatalf("created group = %+v", got)
|
||||
}
|
||||
rec := create(http.StatusUnprocessableEntity, map[string]any{"name": "Editors again " + stamp, "code": code})
|
||||
if details := adminDecode(t, rec).Error.Details; len(details["code"]) == 0 {
|
||||
t.Fatalf("duplicate code refusal = %s", rec.Body.String())
|
||||
}
|
||||
|
||||
// Update: name and description; the group's own code sent back is not a
|
||||
// duplicate; a bad code is refused and changes nothing.
|
||||
update := func(status int, body map[string]any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return env.expect(t, status, http.MethodPut, groupPath(id), token, body)
|
||||
}
|
||||
update(http.StatusOK, map[string]any{"name": "Editors renamed " + stamp, "code": code, "description": "Edits the wiki"})
|
||||
if got := env.group(t, id); got.Name != "Editors renamed "+stamp || *got.Code != code || *got.Description != "Edits the wiki" {
|
||||
t.Fatalf("updated group = %+v", got)
|
||||
}
|
||||
update(http.StatusUnprocessableEntity, map[string]any{"name": "Broken " + stamp, "code": "bad code"})
|
||||
update(http.StatusUnprocessableEntity, map[string]any{"name": "Broken " + stamp, "code": "pair-" + stamp})
|
||||
if got := env.group(t, id); got.Name != "Editors renamed "+stamp || *got.Code != code {
|
||||
t.Fatalf("a refused update changed the group: %+v", got)
|
||||
}
|
||||
// An ordinary code changes freely.
|
||||
code = "wiki-editors-" + stamp
|
||||
update(http.StatusOK, map[string]any{"name": "Editors renamed " + stamp, "code": code})
|
||||
if got := env.group(t, id); *got.Code != code {
|
||||
t.Fatalf("code after the change = %q", *got.Code)
|
||||
}
|
||||
base := map[string]any{"name": "Editors renamed " + stamp, "code": code}
|
||||
save := func(status int, permissions any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
body := map[string]any{"permissions": permissions}
|
||||
for key, value := range base {
|
||||
body[key] = value
|
||||
}
|
||||
return update(status, body)
|
||||
}
|
||||
storedPermissions := func() map[string]int {
|
||||
t.Helper()
|
||||
got := env.group(t, id)
|
||||
if got.Permissions == nil {
|
||||
return nil
|
||||
}
|
||||
var decoded map[string]int
|
||||
if err := json.Unmarshal([]byte(*got.Permissions), &decoded); err != nil {
|
||||
t.Fatalf("stored permissions %q: %v", *got.Permissions, err)
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
|
||||
// Checkbox mode stores a JSON object of code to 1.
|
||||
save(http.StatusOK, map[string]int{read: 1, write: 1})
|
||||
if got := storedPermissions(); !reflect.DeepEqual(got, map[string]int{read: 1, write: 1}) {
|
||||
t.Fatalf("stored permissions = %v", got)
|
||||
}
|
||||
var record struct {
|
||||
Permissions map[string]int `json:"permissions"`
|
||||
}
|
||||
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, groupPath(id), token, nil), &record)
|
||||
if !reflect.DeepEqual(record.Permissions, map[string]int{read: 1, write: 1}) {
|
||||
t.Fatalf("record permissions = %v", record.Permissions)
|
||||
}
|
||||
// A deny has no place in checkbox mode; neither has an unknown code.
|
||||
for _, bad := range []any{map[string]int{read: -1}, map[string]int{read: 2}, map[string]int{"unknown." + stamp: 1}, "all"} {
|
||||
rec := save(http.StatusUnprocessableEntity, bad)
|
||||
if details := adminDecode(t, rec).Error.Details; len(details["permissions"]) == 0 {
|
||||
t.Fatalf("permission refusal of %v = %s", bad, rec.Body.String())
|
||||
}
|
||||
}
|
||||
if got := storedPermissions(); !reflect.DeepEqual(got, map[string]int{read: 1, write: 1}) {
|
||||
t.Fatalf("a refused save changed the permissions: %v", got)
|
||||
}
|
||||
// A save without the field leaves them alone; unchecking removes the
|
||||
// entry; an empty object stores NULL.
|
||||
update(http.StatusOK, base)
|
||||
if got := storedPermissions(); len(got) != 2 {
|
||||
t.Fatalf("a save without the field changed the permissions: %v", got)
|
||||
}
|
||||
save(http.StatusOK, map[string]int{read: 1, write: 0})
|
||||
if got := storedPermissions(); !reflect.DeepEqual(got, map[string]int{read: 1}) {
|
||||
t.Fatalf("permissions after unchecking = %v", got)
|
||||
}
|
||||
save(http.StatusOK, map[string]int{})
|
||||
if got := env.group(t, id); got.Permissions != nil {
|
||||
t.Fatalf("cleared permissions = %q", *got.Permissions)
|
||||
}
|
||||
// A stored code that is no longer offered survives an edit, and a member
|
||||
// of the group holds what the editor stored.
|
||||
legacy := "legacy." + stamp
|
||||
if err := env.gdb.Exec(`UPDATE user_groups SET permissions = ? WHERE id = ?`, `{"`+legacy+`":1}`, id).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
save(http.StatusOK, map[string]int{write: 1})
|
||||
if got := storedPermissions(); !reflect.DeepEqual(got, map[string]int{legacy: 1, write: 1}) {
|
||||
t.Fatalf("permissions after an edit over a legacy code = %v", got)
|
||||
}
|
||||
|
||||
// The screen cannot write a membership or the count.
|
||||
created := &models.UserGroup{ID: id}
|
||||
env.join(t, alice, created)
|
||||
update(http.StatusOK, map[string]any{"name": base["name"], "code": code, "users_count": 99, "users": []uint{bob.ID}, "Users": []uint{bob.ID}})
|
||||
if got := env.groupIDs(t, bob.ID); !reflect.DeepEqual(got, sortedIDs(pair)) {
|
||||
t.Fatalf("a group save changed bob's memberships: %v", got)
|
||||
}
|
||||
if rows, _ = list("search=" + stamp); rows[id]["users_count"].(float64) != 1 {
|
||||
t.Fatalf("users_count after a save that sent one = %v", rows[id]["users_count"])
|
||||
}
|
||||
|
||||
// Delete (D-29): the standard form delete removes the group and its
|
||||
// memberships in one transaction; the members and their other
|
||||
// memberships stay.
|
||||
rec = env.expect(t, http.StatusOK, http.MethodDelete, groupPath(pair.ID), token, nil)
|
||||
if env.group(t, pair.ID) != nil {
|
||||
t.Fatalf("the group survived its delete: %s", rec.Body.String())
|
||||
}
|
||||
var left int64
|
||||
if err := env.gdb.Raw(`SELECT COUNT(*) FROM users_groups WHERE user_group_id = ?`, pair.ID).Scan(&left).Error; err != nil || left != 0 {
|
||||
t.Fatalf("memberships of the deleted group = %d (%v)", left, err)
|
||||
}
|
||||
if env.reload(t, alice.ID) == nil || env.reload(t, bob.ID) == nil {
|
||||
t.Fatal("a group delete removed a member")
|
||||
}
|
||||
if got := env.groupIDs(t, alice.ID); !reflect.DeepEqual(got, sortedIDs(single, created)) {
|
||||
t.Fatalf("alice's memberships after the delete = %v", got)
|
||||
}
|
||||
if got := env.groupIDs(t, bob.ID); len(got) != 0 {
|
||||
t.Fatalf("bob's memberships after the delete = %v", got)
|
||||
}
|
||||
env.expect(t, http.StatusNotFound, http.MethodGet, groupPath(pair.ID), token, nil)
|
||||
if rows, total = list("search=" + stamp); total != 3 || rows[pair.ID] != nil {
|
||||
t.Fatalf("list after the delete: total %d", total)
|
||||
}
|
||||
}
|
||||
662
admin_harness_test.go
Normal file
662
admin_harness_test.go
Normal file
@@ -0,0 +1,662 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
"gocloud.dev/blob"
|
||||
"gocloud.dev/blob/memblob"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// The admin test harness boots the plugin the way an application does
|
||||
// (party.Activate, lagoon.Migrate, surf.Assemble) with the admin API mounted,
|
||||
// on its own database in the session container, and mints backend
|
||||
// administrators with a chosen permission set.
|
||||
//
|
||||
// env := newAdminEnv(t)
|
||||
// token := env.admin(t, permAccessUsers)
|
||||
// rec := env.call(t, http.MethodGet, adminAPI("/golem15/user/users"), token, nil)
|
||||
|
||||
const (
|
||||
// adminUsersPath is the Users controller under the admin API.
|
||||
adminUsersPath = "/golem15/user/users"
|
||||
|
||||
permAccessUsers = "golem15.users.access_users"
|
||||
permManagePrivileged = "golem15.users.manage_privileged_groups"
|
||||
)
|
||||
|
||||
var (
|
||||
adminHarnessOnce sync.Once
|
||||
adminHarnessGDB *gorm.DB
|
||||
adminHarnessSQL *sql.DB
|
||||
adminHarnessErr error
|
||||
// adminSeq makes logins, emails and codes unique across the tests that
|
||||
// share the harness database.
|
||||
adminSeq atomic.Uint64
|
||||
)
|
||||
|
||||
// adminEnv is one booted application: the assembled handler, its app, the
|
||||
// shared harness database and the in-memory blob bucket.
|
||||
type adminEnv struct {
|
||||
h http.Handler
|
||||
app *backpack.App
|
||||
gdb *gorm.DB
|
||||
bucket *blob.Bucket
|
||||
mail *mailCapture
|
||||
}
|
||||
|
||||
// adminAPI builds a path under the admin API prefix.
|
||||
func adminAPI(rel string) string {
|
||||
return cabana.DefaultAdminPrefix + "/api/v1" + rel
|
||||
}
|
||||
|
||||
// adminStamp returns a token unique within the test binary, for emails,
|
||||
// logins and group codes.
|
||||
func adminStamp() string {
|
||||
return fmt.Sprintf("%d%d", time.Now().UnixNano()%1_000_000_000, adminSeq.Add(1))
|
||||
}
|
||||
|
||||
// adminHarnessDB opens (once) the harness database: a second database in the
|
||||
// session container, migrated by lagoon.Migrate on the first boot.
|
||||
func adminHarnessDB(t *testing.T) (*gorm.DB, *sql.DB) {
|
||||
t.Helper()
|
||||
if testing.Short() {
|
||||
t.Skip("requires testcontainers postgres")
|
||||
}
|
||||
_, admin := sessionDB(t)
|
||||
adminHarnessOnce.Do(func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
const name = "user_admin"
|
||||
if _, err := admin.ExecContext(ctx, `CREATE DATABASE `+name+` TEMPLATE template0 ENCODING 'UTF8' LOCALE_PROVIDER icu ICU_LOCALE 'pl-PL'`); err != nil {
|
||||
adminHarnessErr = err
|
||||
return
|
||||
}
|
||||
u, err := url.Parse(sessionDSN)
|
||||
if err != nil {
|
||||
adminHarnessErr = err
|
||||
return
|
||||
}
|
||||
u.Path = "/" + name
|
||||
db, err := sql.Open("pgx", u.String())
|
||||
if err != nil {
|
||||
adminHarnessErr = err
|
||||
return
|
||||
}
|
||||
gdb, err := lagoon.Use(ctx, db)
|
||||
if err != nil {
|
||||
adminHarnessErr = err
|
||||
return
|
||||
}
|
||||
adminHarnessSQL, adminHarnessGDB = db, gdb
|
||||
})
|
||||
if adminHarnessErr != nil {
|
||||
t.Fatal(adminHarnessErr)
|
||||
}
|
||||
return adminHarnessGDB, adminHarnessSQL
|
||||
}
|
||||
|
||||
// newAdminEnv boots the plugin alone with the admin API mounted. configure
|
||||
// functions adjust the config before the plugin is activated.
|
||||
func newAdminEnv(t *testing.T, configure ...func(*compass.Config)) *adminEnv {
|
||||
t.Helper()
|
||||
gdb, sqlDB := adminHarnessDB(t)
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: user-admin\nlocale: en\nfallback_locale: en\nurl: https://app.example.test\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := compass.Open(compass.Options{
|
||||
Dir: dir,
|
||||
Environ: []string{
|
||||
"SUMMER_ENV=development",
|
||||
"SUMMER_GOLEM15__USER__JWT__SECRET=" + sessionSecret,
|
||||
"SUMMER_ADMIN__JWT__SECRET=" + adminHarnessSecret,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for key, value := range map[string]any{
|
||||
"http.body_limits.default_bytes": 1048576,
|
||||
"http.body_limits.upload_bytes": 8388608,
|
||||
// The log driver renders every mail and hands it to the app logger,
|
||||
// which mailCapture reads.
|
||||
"mail.driver": "log",
|
||||
"mail.from": "noreply@example.test",
|
||||
} {
|
||||
if err := cfg.Set(key, value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
app := backpack.New(cfg)
|
||||
if err := lagoon.Publish(app, sqlDB, gdb); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mail := &mailCapture{next: slog.Default().Handler()}
|
||||
if err := app.Publish(slog.New(mail)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bucket := memblob.OpenBucket(nil)
|
||||
t.Cleanup(func() { _ = bucket.Close() })
|
||||
if err := attach.Publish(app, bucket); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The registered plugin value is shared by every boot in this binary;
|
||||
// its blacklist sweep is started at most once and is harmless here.
|
||||
plugins, err := party.Activate(app, []string{"golem15.user"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Overrides go in after the plugin's own config defaults were merged.
|
||||
for _, fn := range configure {
|
||||
fn(app.Config)
|
||||
}
|
||||
if err := lagoon.Migrate(gdb, plugins); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := surf.Assemble(app, plugins)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &adminEnv{h: h, app: app, gdb: gdb, bucket: bucket, mail: mail}
|
||||
}
|
||||
|
||||
// admin inserts a backend role holding exactly permissions and a backend
|
||||
// user in it, logs the user in and returns the bearer token. No permission
|
||||
// at all gives an administrator who may sign in and open nothing.
|
||||
func (e *adminEnv) admin(t *testing.T, permissions ...string) string {
|
||||
t.Helper()
|
||||
stamp := adminStamp()
|
||||
login := "admin-" + stamp
|
||||
password := "admin-secret-" + stamp
|
||||
hash, err := bouncer.HashPassword(10, password)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
grants := map[string]int{}
|
||||
for _, code := range permissions {
|
||||
grants[code] = 1
|
||||
}
|
||||
raw, err := json.Marshal(grants)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var roleID uint
|
||||
if err := e.gdb.Raw(`INSERT INTO backend_user_roles (name, code, permissions, is_system, created_at, updated_at) VALUES (?, ?, ?, FALSE, NOW(), NOW()) RETURNING id`,
|
||||
"Role "+stamp, "role-"+stamp, string(raw)).Scan(&roleID).Error; err != nil || roleID == 0 {
|
||||
t.Fatalf("backend role: id=%d err=%v", roleID, err)
|
||||
}
|
||||
if err := e.gdb.Exec(`INSERT INTO backend_users (login, email, password, is_activated, is_superuser, role_id, created_at, updated_at) VALUES (?, ?, ?, TRUE, FALSE, ?, NOW(), NOW())`,
|
||||
login, login+"@example.test", hash, roleID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := e.call(t, http.MethodPost, adminAPI("/auth/login"), "", map[string]string{"login": login, "password": password})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("admin login %s: %d %s", login, rec.Code, rec.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
Data struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body.Data.AccessToken == "" {
|
||||
t.Fatalf("admin login body: %s err=%v", rec.Body.String(), err)
|
||||
}
|
||||
return body.Data.AccessToken
|
||||
}
|
||||
|
||||
// call sends one request through the assembled handler. body is JSON-encoded
|
||||
// unless it is nil; token, when set, is sent as a bearer token. The request
|
||||
// locale is English and each call comes from its own address, so the login
|
||||
// throttle never trips inside one test.
|
||||
func (e *adminEnv) call(t *testing.T, method, path, token string, body any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var raw []byte
|
||||
if body != nil {
|
||||
var err error
|
||||
if raw, err = json.Marshal(body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return e.send(t, method, path, token, raw, "application/json", nil)
|
||||
}
|
||||
|
||||
// send is call with a raw body, its content type and extra headers (for
|
||||
// example the form session key of a file upload).
|
||||
func (e *adminEnv) send(t *testing.T, method, path, token string, body []byte, contentType string, headers map[string]string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var reader io.Reader
|
||||
if body != nil {
|
||||
reader = bytes.NewReader(body)
|
||||
}
|
||||
req := httptest.NewRequest(method, path, reader)
|
||||
req.Host = "example.com"
|
||||
req.RemoteAddr = fmt.Sprintf("198.51.100.%d:4000", adminSeq.Add(1)%250+1)
|
||||
req.Header.Set("Accept-Language", "en")
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
for name, value := range headers {
|
||||
req.Header.Set(name, value)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
e.h.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// sentMail is one message the application sent, as the log mail driver
|
||||
// reports it: rendered, with the text part.
|
||||
type sentMail struct {
|
||||
To []string
|
||||
Subject string
|
||||
Text string
|
||||
}
|
||||
|
||||
// mailCapture is the slog handler behind the app logger: it keeps the
|
||||
// records of the log mail driver and passes everything else on.
|
||||
type mailCapture struct {
|
||||
mu sync.Mutex
|
||||
sent []sentMail
|
||||
next slog.Handler
|
||||
}
|
||||
|
||||
func (m *mailCapture) Enabled(context.Context, slog.Level) bool { return true }
|
||||
|
||||
func (m *mailCapture) Handle(ctx context.Context, record slog.Record) error {
|
||||
if record.Message != "postcard mail" {
|
||||
if m.next != nil && m.next.Enabled(ctx, record.Level) {
|
||||
return m.next.Handle(ctx, record)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
var mail sentMail
|
||||
record.Attrs(func(attr slog.Attr) bool {
|
||||
switch attr.Key {
|
||||
case "to":
|
||||
mail.To, _ = attr.Value.Any().([]string)
|
||||
case "subject":
|
||||
mail.Subject = attr.Value.String()
|
||||
case "text":
|
||||
mail.Text = attr.Value.String()
|
||||
}
|
||||
return true
|
||||
})
|
||||
m.mu.Lock()
|
||||
m.sent = append(m.sent, mail)
|
||||
m.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mailCapture) WithAttrs([]slog.Attr) slog.Handler { return m }
|
||||
func (m *mailCapture) WithGroup(string) slog.Handler { return m }
|
||||
|
||||
// mails returns the messages sent to the address since the env booted.
|
||||
func (e *adminEnv) mails(to string) []sentMail {
|
||||
e.mail.mu.Lock()
|
||||
defer e.mail.mu.Unlock()
|
||||
var out []sentMail
|
||||
for _, mail := range e.mail.sent {
|
||||
for _, recipient := range mail.To {
|
||||
if recipient == to {
|
||||
out = append(out, mail)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// adminSessionKey returns a fresh form session key, as the admin SPA makes
|
||||
// one when it opens a form.
|
||||
func adminSessionKey(t *testing.T) string {
|
||||
t.Helper()
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(raw)
|
||||
}
|
||||
|
||||
// upload posts one file to a fileupload field of a user's form under a form
|
||||
// session key; the next save sent with the same key attaches it.
|
||||
func (e *adminEnv) upload(t *testing.T, token string, id uint, field, name string, data []byte, sessionKey string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
part, err := mw.CreateFormFile("file_data", name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := part.Write(data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := mw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return e.send(t, http.MethodPost, userPath(id, "/files/"+field), token, buf.Bytes(), mw.FormDataContentType(),
|
||||
map[string]string{cabana.SessionKeyHeader: sessionKey})
|
||||
}
|
||||
|
||||
// expect is call plus a status assertion.
|
||||
func (e *adminEnv) expect(t *testing.T, status int, method, path, token string, body any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
rec := e.call(t, method, path, token, body)
|
||||
if rec.Code != status {
|
||||
t.Fatalf("%s %s = %d, want %d: %s", method, path, rec.Code, status, rec.Body.String())
|
||||
}
|
||||
return rec
|
||||
}
|
||||
|
||||
// adminEnvelope is the admin API answer: data and meta on success, error
|
||||
// otherwise.
|
||||
type adminEnvelope struct {
|
||||
Data json.RawMessage `json:"data"`
|
||||
Meta json.RawMessage `json:"meta"`
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Details map[string][]string `json:"details"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
// adminDecode parses an admin API answer.
|
||||
func adminDecode(t *testing.T, rec *httptest.ResponseRecorder) adminEnvelope {
|
||||
t.Helper()
|
||||
var env adminEnvelope
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &env); err != nil {
|
||||
t.Fatalf("admin body %q: %v", rec.Body.String(), err)
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
// adminInto decodes the data of an admin API answer into out.
|
||||
func adminInto(t *testing.T, rec *httptest.ResponseRecorder, out any) adminEnvelope {
|
||||
t.Helper()
|
||||
env := adminDecode(t, rec)
|
||||
if err := json.Unmarshal(env.Data, out); err != nil {
|
||||
t.Fatalf("admin data %q: %v", string(env.Data), err)
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
// adminUserList is a decoded Users list page.
|
||||
type adminUserList struct {
|
||||
Rows []map[string]any
|
||||
RowStates map[string][]string
|
||||
Total int
|
||||
Raw string
|
||||
}
|
||||
|
||||
// has reports whether the page holds the user.
|
||||
func (l adminUserList) has(id uint) bool { return l.row(id) != nil }
|
||||
|
||||
// row returns the list row of the user, or nil.
|
||||
func (l adminUserList) row(id uint) map[string]any {
|
||||
for _, row := range l.Rows {
|
||||
if n, ok := row["id"].(float64); ok && uint(n) == id {
|
||||
return row
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// states returns the row states of the user.
|
||||
func (l adminUserList) states(id uint) []string {
|
||||
return l.RowStates[strconv.FormatUint(uint64(id), 10)]
|
||||
}
|
||||
|
||||
// users lists the Users screen with a raw query string (without the leading
|
||||
// question mark) and expects 200.
|
||||
func (e *adminEnv) users(t *testing.T, token, query string) adminUserList {
|
||||
t.Helper()
|
||||
path := adminAPI(adminUsersPath)
|
||||
if query != "" {
|
||||
path += "?" + query
|
||||
}
|
||||
rec := e.expect(t, http.StatusOK, http.MethodGet, path, token, nil)
|
||||
out := adminUserList{Raw: rec.Body.String()}
|
||||
env := adminInto(t, rec, &out.Rows)
|
||||
var meta struct {
|
||||
Total int `json:"total"`
|
||||
RowStates map[string][]string `json:"row_states"`
|
||||
}
|
||||
if err := json.Unmarshal(env.Meta, &meta); err != nil {
|
||||
t.Fatalf("list meta %q: %v", string(env.Meta), err)
|
||||
}
|
||||
out.RowStates, out.Total = meta.RowStates, meta.Total
|
||||
return out
|
||||
}
|
||||
|
||||
// userPath is the admin API path of one user, with an optional suffix such
|
||||
// as "/actions/activate".
|
||||
func userPath(id uint, suffix string) string {
|
||||
return adminAPI(adminUsersPath) + "/" + strconv.FormatUint(uint64(id), 10) + suffix
|
||||
}
|
||||
|
||||
// seedUser stores a frontend user with the password correct-horse. The email
|
||||
// is unique; mutate adjusts the row before it is inserted.
|
||||
func (e *adminEnv) seedUser(t *testing.T, label string, mutate func(*models.User)) *models.User {
|
||||
t.Helper()
|
||||
hash, err := bouncer.HashPassword(10, "correct-horse")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
name := label
|
||||
user := &models.User{Email: label + "-" + adminStamp() + "@example.test", Password: hash, Name: &name, IsActivated: true}
|
||||
if mutate != nil {
|
||||
mutate(user)
|
||||
}
|
||||
if err := e.gdb.Omit("Groups").Create(user).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
// seedGroup stores a user group; an empty code stores a group without one.
|
||||
func (e *adminEnv) seedGroup(t *testing.T, name, code string) *models.UserGroup {
|
||||
t.Helper()
|
||||
group := &models.UserGroup{Name: name}
|
||||
if code != "" {
|
||||
group.Code = &code
|
||||
}
|
||||
if err := e.gdb.Create(group).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return group
|
||||
}
|
||||
|
||||
// join puts the user into the groups by writing users_groups directly.
|
||||
func (e *adminEnv) join(t *testing.T, user *models.User, groups ...*models.UserGroup) {
|
||||
t.Helper()
|
||||
for _, group := range groups {
|
||||
if err := e.gdb.Exec(`INSERT INTO users_groups (user_id, user_group_id) VALUES (?, ?)`, user.ID, group.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// reload reads a user row, deactivated or not; nil when it is gone.
|
||||
func (e *adminEnv) reload(t *testing.T, id uint) *models.User {
|
||||
t.Helper()
|
||||
var users []models.User
|
||||
if err := e.gdb.Unscoped().Where("id = ?", id).Limit(1).Find(&users).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(users) == 0 {
|
||||
return nil
|
||||
}
|
||||
return &users[0]
|
||||
}
|
||||
|
||||
// groupIDs returns the user's users_groups rows, ordered.
|
||||
func (e *adminEnv) groupIDs(t *testing.T, userID uint) []uint {
|
||||
t.Helper()
|
||||
ids := []uint{}
|
||||
if err := e.gdb.Raw(`SELECT user_group_id FROM users_groups WHERE user_id = ? ORDER BY user_group_id`, userID).Scan(&ids).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// seedAvatar stores an avatar for the user the way the user API does: one
|
||||
// system_files row (field avatar) and its blob. It returns the blob key.
|
||||
func (e *adminEnv) seedAvatar(t *testing.T, user *models.User) string {
|
||||
t.Helper()
|
||||
disk := "avatar" + adminStamp() + ".jpg"
|
||||
key := attach.BlobKey(disk)
|
||||
if err := e.bucket.WriteAll(context.Background(), key, []byte("avatar-bytes"), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
row := attach.File{
|
||||
DiskName: disk,
|
||||
FileName: "avatar.jpg",
|
||||
FileSize: 12,
|
||||
ContentType: "image/jpeg",
|
||||
Field: "avatar",
|
||||
AttachmentID: strconv.FormatUint(uint64(user.ID), 10),
|
||||
AttachmentType: user.MorphName(),
|
||||
}
|
||||
if err := e.gdb.Create(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
// blobExists reports whether the bucket still holds key.
|
||||
func (e *adminEnv) blobExists(t *testing.T, key string) bool {
|
||||
t.Helper()
|
||||
ok, err := e.bucket.Exists(context.Background(), key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// seedThrottle stores one user_throttle row. ip may be empty for the row
|
||||
// without an address.
|
||||
func (e *adminEnv) seedThrottle(t *testing.T, user *models.User, ip string, banned bool, suspendedAt *time.Time) {
|
||||
t.Helper()
|
||||
row := models.Throttle{UserID: user.ID, IsBanned: banned}
|
||||
if ip != "" {
|
||||
row.IPAddress = &ip
|
||||
}
|
||||
if suspendedAt != nil {
|
||||
row.IsSuspended, row.SuspendedAt, row.Attempts = true, suspendedAt, 5
|
||||
}
|
||||
if err := e.gdb.Create(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// hangers counts what hangs off a user: throttle rows, group memberships
|
||||
// and attachment rows.
|
||||
type hangers struct{ Throttle, Groups, Files int64 }
|
||||
|
||||
func (e *adminEnv) hangers(t *testing.T, user *models.User) hangers {
|
||||
t.Helper()
|
||||
var out hangers
|
||||
count := func(into *int64, query string, args ...any) {
|
||||
t.Helper()
|
||||
if err := e.gdb.Raw(query, args...).Scan(into).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
count(&out.Throttle, `SELECT COUNT(*) FROM user_throttle WHERE user_id = ?`, user.ID)
|
||||
count(&out.Groups, `SELECT COUNT(*) FROM users_groups WHERE user_id = ?`, user.ID)
|
||||
count(&out.Files, `SELECT COUNT(*) FROM system_files WHERE attachment_type = ? AND attachment_id = ?`,
|
||||
user.MorphName(), strconv.FormatUint(uint64(user.ID), 10))
|
||||
return out
|
||||
}
|
||||
|
||||
// bulk posts a declared bulk action, or the built-in bulk delete when action
|
||||
// is "delete", for the given users.
|
||||
func (e *adminEnv) bulk(t *testing.T, token, action string, users ...*models.User) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
ids := make([]uint, len(users))
|
||||
for i, user := range users {
|
||||
ids[i] = user.ID
|
||||
}
|
||||
path := adminAPI(adminUsersPath + "/bulk/" + action)
|
||||
if action == "delete" {
|
||||
path = adminAPI(adminUsersPath + "/bulk-delete")
|
||||
}
|
||||
return e.call(t, http.MethodPost, path, token, map[string]any{"ids": ids})
|
||||
}
|
||||
|
||||
// offered returns the record actions the show response of the user offers.
|
||||
func (e *adminEnv) offered(t *testing.T, token string, id uint) []string {
|
||||
t.Helper()
|
||||
rec := e.expect(t, http.StatusOK, http.MethodGet, userPath(id, ""), token, nil)
|
||||
var meta struct {
|
||||
Actions []struct {
|
||||
Name string `json:"name"`
|
||||
} `json:"actions"`
|
||||
}
|
||||
if err := json.Unmarshal(adminDecode(t, rec).Meta, &meta); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
names := []string{}
|
||||
for _, action := range meta.Actions {
|
||||
names = append(names, action.Name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// userLogin signs a frontend user in through the user API route and returns
|
||||
// the status and the token.
|
||||
func (e *adminEnv) userLogin(t *testing.T, email, password string) (int, string) {
|
||||
t.Helper()
|
||||
rec := e.call(t, http.MethodPost, "/_user/api/v1/login", "", map[string]string{"email": email, "password": password})
|
||||
var body struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &body)
|
||||
return rec.Code, body.Token
|
||||
}
|
||||
|
||||
// secretKey matches a JSON key that names a password or a one-time code.
|
||||
var secretKey = regexp.MustCompile(`(?i)"[a-z_]*(password|activation_code|reset_password_code)[a-z_]*"\s*:`)
|
||||
|
||||
// assertNoSecret fails when an admin response carries a password key, a
|
||||
// stored hash or the given plain text.
|
||||
func assertNoSecret(t *testing.T, raw string, plain ...string) {
|
||||
t.Helper()
|
||||
if secretKey.MatchString(raw) || strings.Contains(raw, "$2a$") || strings.Contains(raw, "$2y$") {
|
||||
t.Fatalf("admin response carries a password: %s", raw)
|
||||
}
|
||||
for _, secret := range plain {
|
||||
if secret != "" && strings.Contains(raw, secret) {
|
||||
t.Fatalf("admin response carries a secret value: %s", raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
45
admin_navigation.go
Normal file
45
admin_navigation.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"git.golem15.com/golem15/sm-user-plugin/controllers"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
// Navigation is the plugin's Winter registerNavigation() entry: the main item
|
||||
// user (order 555) with its side menu. Controller names an admin controller
|
||||
// id in place of a backend URL, and icons are lucide names.
|
||||
func (*Plugin) Navigation() []pact.NavigationItem {
|
||||
return []pact.NavigationItem{
|
||||
{
|
||||
Code: "user",
|
||||
Label: "golem15.user::lang.users.menu_label",
|
||||
Icon: "user",
|
||||
Permissions: []string{"golem15.users.*"},
|
||||
Order: 555,
|
||||
Controller: "golem15.user.users",
|
||||
SideMenu: []pact.NavigationItem{
|
||||
{
|
||||
Code: "users",
|
||||
Label: "golem15.user::lang.users.menu_label",
|
||||
Icon: "user",
|
||||
Permissions: []string{controllers.PermissionAccessUsers},
|
||||
Controller: "golem15.user.users",
|
||||
},
|
||||
{
|
||||
Code: "usergroups",
|
||||
Label: "golem15.user::lang.groups.all_groups",
|
||||
Icon: "users",
|
||||
Permissions: []string{controllers.PermissionAccessGroups},
|
||||
Controller: "golem15.user.usergroups",
|
||||
},
|
||||
{
|
||||
Code: "organisations",
|
||||
Label: "golem15.user::lang.organisation.menu_label",
|
||||
Icon: "users-round",
|
||||
Permissions: []string{controllers.PermissionAccessUsers},
|
||||
Controller: "golem15.user.organisations",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
202
admin_organisations_edge_test.go
Normal file
202
admin_organisations_edge_test.go
Normal file
@@ -0,0 +1,202 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
// TestAdminOrganisationsControllerGuards drives the Organisations controller
|
||||
// directly on the inputs the HTTP tests cannot produce.
|
||||
func TestAdminOrganisationsControllerGuards(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
const id = "golem15.user.organisations"
|
||||
notOrganisation := &models.User{}
|
||||
var nilOrganisation *models.Organisation
|
||||
|
||||
env := newAdminEnv(t)
|
||||
sets := map[string]adminControllerSet{
|
||||
"no accessor": adminControllersOn(nil),
|
||||
"not booted": adminControllersOn(func() *backpack.App { return nil }),
|
||||
"no database": adminControllersOn(func() *backpack.App { return bareApp(t) }),
|
||||
"the live database": adminControllersOn(func() *backpack.App { return env.app }),
|
||||
}
|
||||
for name, set := range sets {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ctl := set[id]
|
||||
for _, record := range []any{notOrganisation, nilOrganisation, nil} {
|
||||
wantPlainError(t, "FormBeforeCreate", ctl.(pact.FormBeforeCreate).FormBeforeCreate(ctx, record))
|
||||
wantPlainError(t, "FormBeforeUpdate", ctl.(pact.FormBeforeUpdate).FormBeforeUpdate(ctx, record))
|
||||
wantPlainError(t, "FormBeforeDelete", ctl.(pact.FormBeforeDelete).FormBeforeDelete(ctx, record))
|
||||
}
|
||||
wantPlainError(t, "FormBeforeDelete without a transaction", ctl.(pact.FormBeforeDelete).FormBeforeDelete(ctx, &models.Organisation{ID: 1}))
|
||||
|
||||
// The slug check needs no database; without a translator the
|
||||
// refusal is in English.
|
||||
if err := ctl.(pact.FormBeforeCreate).FormBeforeCreate(ctx, &models.Organisation{Name: "Fine", Slug: "fine_slug-1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ctl.(pact.FormBeforeUpdate).FormBeforeUpdate(ctx, &models.Organisation{Name: "Empty"}); err != nil {
|
||||
t.Fatalf("an empty slug is left to the required rule: %v", err)
|
||||
}
|
||||
err := ctl.(pact.FormBeforeCreate).FormBeforeCreate(ctx, &models.Organisation{Name: "Bad", Slug: "bad slug"})
|
||||
invalid, ok := err.(*cabana.ValidationError)
|
||||
if !ok || !reflect.DeepEqual(invalid.Details["slug"], []string{"The slug may only contain letters, numbers, dashes and underscores."}) {
|
||||
t.Fatalf("slug refusal = %v", err)
|
||||
}
|
||||
|
||||
// The members manager is the only relation: any other name has
|
||||
// no candidates.
|
||||
manage := ctl.(pact.RelationExtendManageQuery)
|
||||
if manage.RelationExtendManageQuery(ctx, "members", nil) != nil || manage.RelationExtendManageQuery(ctx, "groups", nil) != nil {
|
||||
t.Fatal("RelationExtendManageQuery invented a handle")
|
||||
}
|
||||
contracts := ctl.(cabana.AdminRelationContractProvider).AdminRelationContracts()
|
||||
if len(contracts) != 1 || contracts[0].Name != "members" || contracts[0].Kind != cabana.RelationHasMany || contracts[0].ForeignKey != "organisation_id" {
|
||||
t.Fatalf("relation contracts = %+v", contracts)
|
||||
}
|
||||
if _, ok := contracts[0].NewRelated().(*models.User); !ok {
|
||||
t.Fatal("the members relation is not on users")
|
||||
}
|
||||
if name == "the live database" {
|
||||
var all, none int64
|
||||
users := env.gdb.Model(&models.User{})
|
||||
if err := manage.RelationExtendManageQuery(ctx, "members", users).Count(&all).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := manage.RelationExtendManageQuery(ctx, "groups", env.gdb.Model(&models.User{})).Count(&none).Error; err != nil || none != 0 {
|
||||
t.Fatalf("candidates of another relation = %d err = %v", none, err)
|
||||
}
|
||||
_ = all
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminOrganisationsEdge covers the remaining branches of the
|
||||
// Organisations screen through the admin API.
|
||||
func TestAdminOrganisationsEdge(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
token := env.admin(t, permAccessUsers)
|
||||
stamp := adminStamp()
|
||||
|
||||
// An organisation without members is deleted and nothing else changes.
|
||||
bystander := env.seedUser(t, "bystander-"+stamp, nil)
|
||||
empty := env.seedOrganisation(t, "Edge empty "+stamp)
|
||||
env.expect(t, http.StatusOK, http.MethodDelete, organisationPath(empty.ID, ""), token, nil)
|
||||
if env.organisation(t, empty.ID) != nil {
|
||||
t.Fatal("the organisation survived its delete")
|
||||
}
|
||||
if env.reload(t, bystander.ID) == nil {
|
||||
t.Fatal("deleting an organisation without members deleted a user")
|
||||
}
|
||||
env.expect(t, http.StatusNotFound, http.MethodGet, organisationPath(empty.ID, ""), token, nil)
|
||||
|
||||
// A slug with other characters is a 422 on the field, on create and on
|
||||
// update; a duplicate slug too.
|
||||
home := env.seedOrganisation(t, "Edge home "+stamp)
|
||||
for _, slug := range []string{"with space", "dot.ted", "sl/ash", "ąę"} {
|
||||
rec := env.expect(t, http.StatusUnprocessableEntity, http.MethodPost, adminAPI(adminOrganisationsPath), token, map[string]any{"name": "Edge bad " + stamp, "slug": slug})
|
||||
if details := adminDecode(t, rec).Error.Details; len(details["slug"]) == 0 {
|
||||
t.Fatalf("slug %q: details = %v", slug, details)
|
||||
}
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, organisationPath(home.ID, ""), token, map[string]any{"slug": slug})
|
||||
}
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodPost, adminAPI(adminOrganisationsPath), token, map[string]any{"name": "Edge twin " + stamp, "slug": home.Slug})
|
||||
if got := env.organisation(t, home.ID); got.Slug != home.Slug {
|
||||
t.Fatalf("a refused update changed the slug to %q", got.Slug)
|
||||
}
|
||||
|
||||
// Search and sort on the list.
|
||||
for _, name := range []string{"b", "a", "c"} {
|
||||
env.seedOrganisation(t, "Orgsort "+stamp+" "+name)
|
||||
}
|
||||
order := func(query string) []string {
|
||||
var rows []map[string]any
|
||||
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminOrganisationsPath)+"?search=Orgsort%20"+stamp+"&"+query, token, nil), &rows)
|
||||
names := []string{}
|
||||
for _, row := range rows {
|
||||
name, _ := row["name"].(string)
|
||||
names = append(names, name[len(name)-1:])
|
||||
}
|
||||
return names
|
||||
}
|
||||
if got := order("sort=name&dir=asc"); !reflect.DeepEqual(got, []string{"a", "b", "c"}) {
|
||||
t.Fatalf("name asc = %v", got)
|
||||
}
|
||||
if got := order("sort=slug&dir=desc"); !reflect.DeepEqual(got, []string{"c", "b", "a"}) {
|
||||
t.Fatalf("slug desc = %v", got)
|
||||
}
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodGet, adminAPI(adminOrganisationsPath)+"?filter[slug]=x", token, nil)
|
||||
|
||||
// A deactivated user is not offered as a member and cannot be linked:
|
||||
// the candidates leave soft-deleted users out.
|
||||
gone := env.seedUser(t, "gone-"+stamp, nil)
|
||||
if err := env.gdb.Exec(`UPDATE users SET deleted_at = NOW() WHERE id = ?`, gone.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var candidates []map[string]any
|
||||
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, organisationPath(home.ID, "/relations/members/candidates?search=gone-"+stamp), token, nil), &candidates)
|
||||
if len(candidates) != 0 {
|
||||
t.Fatalf("a deactivated user is a candidate: %v", candidates)
|
||||
}
|
||||
rec := env.call(t, http.MethodPost, organisationPath(home.ID, "/relations/members/link"), token, map[string]any{"ids": []uint{gone.ID}})
|
||||
if rec.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("link of a deactivated user = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := env.reload(t, gone.ID); got.OrganisationID != nil {
|
||||
t.Fatalf("a deactivated user was linked to %d", *got.OrganisationID)
|
||||
}
|
||||
// Ids that are not users, and an empty list, change nothing.
|
||||
for _, body := range []map[string]any{{"ids": []uint{987654321}}, {"ids": []uint{}}, {}} {
|
||||
rec := env.call(t, http.MethodPost, organisationPath(home.ID, "/relations/members/link"), token, body)
|
||||
if rec.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("link %v = %d %s", body, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminOrganisationRoleOutlivesMembership pins a known gap
|
||||
// (12.1-SECURITY-REVIEW.md, open item 6): removing a member through the
|
||||
// members manager clears organisation_id and nothing else, so the user keeps
|
||||
// organisation_role and carries it into the next organisation they are
|
||||
// added to. Deleting the organisation clears both. When the unlink learns to
|
||||
// clear the role, this test changes with it.
|
||||
func TestAdminOrganisationRoleOutlivesMembership(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
token := env.admin(t, permAccessUsers)
|
||||
stamp := adminStamp()
|
||||
first := env.seedOrganisation(t, "Role first "+stamp)
|
||||
second := env.seedOrganisation(t, "Role second "+stamp)
|
||||
doomed := env.seedOrganisation(t, "Role doomed "+stamp)
|
||||
owner := "owner"
|
||||
member := env.seedUser(t, "role-"+stamp, func(u *models.User) { u.OrganisationID, u.OrganisationRole = &first.ID, &owner })
|
||||
other := env.seedUser(t, "role-other-"+stamp, func(u *models.User) { u.OrganisationID, u.OrganisationRole = &doomed.ID, &owner })
|
||||
ids := map[string]any{"ids": []uint{member.ID}}
|
||||
|
||||
env.expect(t, http.StatusOK, http.MethodPost, organisationPath(first.ID, "/relations/members/unlink"), token, ids)
|
||||
got := env.reload(t, member.ID)
|
||||
if got.OrganisationID != nil {
|
||||
t.Fatalf("organisation_id after the unlink = %d", *got.OrganisationID)
|
||||
}
|
||||
if got.OrganisationRole == nil || *got.OrganisationRole != "owner" {
|
||||
t.Fatalf("organisation_role after the unlink = %v; the known gap is closed, update this test and the review", got.OrganisationRole)
|
||||
}
|
||||
env.expect(t, http.StatusOK, http.MethodPost, organisationPath(second.ID, "/relations/members/link"), token, ids)
|
||||
got = env.reload(t, member.ID)
|
||||
if got.OrganisationID == nil || *got.OrganisationID != second.ID || got.OrganisationRole == nil || *got.OrganisationRole != "owner" {
|
||||
t.Fatalf("after the link elsewhere: organisation %v role %v", got.OrganisationID, got.OrganisationRole)
|
||||
}
|
||||
|
||||
// The delete of an organisation releases its members completely.
|
||||
env.expect(t, http.StatusOK, http.MethodDelete, organisationPath(doomed.ID, ""), token, nil)
|
||||
if got := env.reload(t, other.ID); got == nil || got.OrganisationID != nil || got.OrganisationRole != nil {
|
||||
t.Fatalf("member of a deleted organisation = %+v", got)
|
||||
}
|
||||
}
|
||||
482
admin_organisations_test.go
Normal file
482
admin_organisations_test.go
Normal file
@@ -0,0 +1,482 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
)
|
||||
|
||||
// adminOrganisationsPath is the Organisations controller under the admin API.
|
||||
const adminOrganisationsPath = "/golem15/user/organisations"
|
||||
|
||||
// organisationPath is the admin API path of one organisation, with an
|
||||
// optional suffix such as "/relations/members".
|
||||
func organisationPath(id uint, suffix string) string {
|
||||
return adminAPI(adminOrganisationsPath) + "/" + strconv.FormatUint(uint64(id), 10) + suffix
|
||||
}
|
||||
|
||||
// organisation reads an organisation row; nil when it is gone.
|
||||
func (e *adminEnv) organisation(t *testing.T, id uint) *models.Organisation {
|
||||
t.Helper()
|
||||
var rows []models.Organisation
|
||||
if err := e.gdb.Where("id = ?", id).Limit(1).Find(&rows).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
return &rows[0]
|
||||
}
|
||||
|
||||
// seedOrganisation stores an organisation with a unique slug.
|
||||
func (e *adminEnv) seedOrganisation(t *testing.T, name string) *models.Organisation {
|
||||
t.Helper()
|
||||
organisation := &models.Organisation{Name: name, Slug: models.Slugify(name)}
|
||||
if err := e.gdb.Create(organisation).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return organisation
|
||||
}
|
||||
|
||||
// TestSlugify pins the slug rule the organisation model shares with the
|
||||
// admin form's slug preset.
|
||||
func TestSlugify(t *testing.T) {
|
||||
for text, want := range map[string]string{
|
||||
"Acme Records": "acme-records",
|
||||
" Acme -- Records ": "acme-records",
|
||||
"ACME_Records 2": "acme-records-2",
|
||||
"Zażółć gęślą": "za-g-l",
|
||||
"---": "",
|
||||
"": "",
|
||||
"a": "a",
|
||||
} {
|
||||
if got := models.Slugify(text); got != want {
|
||||
t.Fatalf("Slugify(%q) = %q, want %q", text, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminOrganisations covers the Organisations screen (D-22, D-20): its
|
||||
// permission, the list, the form with the slug rules and the avatar, and the
|
||||
// delete that releases the members.
|
||||
func TestAdminOrganisations(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
token := env.admin(t, permAccessUsers)
|
||||
groupsOnly := env.admin(t, permAccessGroups)
|
||||
both := env.admin(t, permAccessUsers, permAccessGroups)
|
||||
stamp := adminStamp()
|
||||
|
||||
// The screen needs golem15.users.access_users.
|
||||
for _, path := range []string{adminAPI(adminOrganisationsPath), adminAPI(adminOrganisationsPath + "/schema/list"), adminAPI(adminOrganisationsPath + "/schema/form")} {
|
||||
rec := env.expect(t, http.StatusForbidden, http.MethodGet, path, groupsOnly, nil)
|
||||
if code := adminDecode(t, rec).Error.Code; code != "forbidden" {
|
||||
t.Fatalf("%s code = %q", path, code)
|
||||
}
|
||||
}
|
||||
env.expect(t, http.StatusForbidden, http.MethodPost, adminAPI(adminOrganisationsPath), groupsOnly, map[string]any{"name": "Nope " + stamp})
|
||||
// All three screens are side items of `user`, in this order, each shown
|
||||
// only with its permission.
|
||||
if got := env.sideMenu(t, both); !reflect.DeepEqual(got, []string{
|
||||
"users=golem15.user.users", "usergroups=golem15.user.usergroups", "organisations=golem15.user.organisations",
|
||||
}) {
|
||||
t.Fatalf("side menu with both permissions = %v", got)
|
||||
}
|
||||
if got := env.sideMenu(t, groupsOnly); !reflect.DeepEqual(got, []string{"usergroups=golem15.user.usergroups"}) {
|
||||
t.Fatalf("side menu with the groups permission = %v", got)
|
||||
}
|
||||
|
||||
// The list schema: Name, Slug and Created; rows open the update form.
|
||||
var schema struct {
|
||||
RecordURL string `json:"recordUrl"`
|
||||
ShowCheckboxes bool `json:"showCheckboxes"`
|
||||
ToolbarButtons []string `json:"toolbarButtons"`
|
||||
Columns []struct {
|
||||
Key string `json:"key"`
|
||||
Invisible bool `json:"invisible"`
|
||||
Searchable bool `json:"searchable"`
|
||||
Type string `json:"type"`
|
||||
} `json:"columns"`
|
||||
Messages map[string]map[string]string `json:"messages"`
|
||||
}
|
||||
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminOrganisationsPath+"/schema/list"), token, nil), &schema)
|
||||
var visible []string
|
||||
for _, column := range schema.Columns {
|
||||
if !column.Invisible {
|
||||
visible = append(visible, column.Key)
|
||||
}
|
||||
}
|
||||
if !reflect.DeepEqual(visible, []string{"name", "slug", "created_at"}) || schema.RecordURL != "golem15/user/organisations/update/:id" ||
|
||||
schema.ShowCheckboxes || !reflect.DeepEqual(schema.ToolbarButtons, []string{"create"}) {
|
||||
t.Fatalf("list schema = %+v", schema)
|
||||
}
|
||||
if got := schema.Messages["empty"]["other"]; got != "No organisations yet. Create the first one with New Organisation." {
|
||||
t.Fatalf("empty message = %q", got)
|
||||
}
|
||||
if got := schema.Messages["create"]["other"]; got != "New Organisation" {
|
||||
t.Fatalf("create message = %q", got)
|
||||
}
|
||||
|
||||
// The form: name, slug (slug preset from name), description, the avatar
|
||||
// as a 120 by 120 image and the members manager on update only; no
|
||||
// preview.
|
||||
var form struct {
|
||||
Fields []struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Mode string `json:"mode"`
|
||||
Tab string `json:"tab"`
|
||||
Context any `json:"context"`
|
||||
ImageWidth int `json:"imageWidth"`
|
||||
ImageHeight int `json:"imageHeight"`
|
||||
Preset *struct {
|
||||
Field string `json:"field"`
|
||||
Type string `json:"type"`
|
||||
} `json:"preset"`
|
||||
} `json:"fields"`
|
||||
Preview json.RawMessage `json:"preview"`
|
||||
}
|
||||
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminOrganisationsPath+"/schema/form"), token, nil), &form)
|
||||
var names []string
|
||||
for _, field := range form.Fields {
|
||||
names = append(names, field.Name+":"+field.Type)
|
||||
switch field.Name {
|
||||
case "slug":
|
||||
if field.Preset == nil || field.Preset.Field != "name" || field.Preset.Type != "slug" {
|
||||
t.Fatalf("slug preset = %+v", field.Preset)
|
||||
}
|
||||
case "avatar":
|
||||
if field.Mode != "image" || field.ImageWidth != 120 || field.ImageHeight != 120 {
|
||||
t.Fatalf("avatar field = %+v", field)
|
||||
}
|
||||
case "members":
|
||||
if field.Context != "update" || field.Tab != "Members" {
|
||||
t.Fatalf("members field = %+v", field)
|
||||
}
|
||||
}
|
||||
}
|
||||
if want := []string{"name:text", "slug:text", "description:textarea", "avatar:fileupload", "members:relation-manager"}; !reflect.DeepEqual(names, want) {
|
||||
t.Fatalf("form fields = %v, want %v", names, want)
|
||||
}
|
||||
if len(form.Preview) != 0 && string(form.Preview) != "null" {
|
||||
t.Fatalf("the organisation form has a preview: %s", form.Preview)
|
||||
}
|
||||
|
||||
// Create: an empty slug is derived from the name; a given slug is kept.
|
||||
create := func(status int, body map[string]any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return env.expect(t, status, http.MethodPost, adminAPI(adminOrganisationsPath), token, body)
|
||||
}
|
||||
name := "Acme Records " + stamp
|
||||
id := createdID(t, create(http.StatusCreated, map[string]any{"name": name, "slug": "", "description": "A label"}))
|
||||
if got := env.organisation(t, id); got == nil || got.Name != name || got.Slug != "acme-records-"+stamp || got.Description == nil || *got.Description != "A label" {
|
||||
t.Fatalf("created organisation = %+v", got)
|
||||
}
|
||||
omitted := createdID(t, create(http.StatusCreated, map[string]any{"name": "Omitted Slug " + stamp}))
|
||||
if got := env.organisation(t, omitted); got.Slug != "omitted-slug-"+stamp {
|
||||
t.Fatalf("slug of a create without the key = %q", got.Slug)
|
||||
}
|
||||
given := createdID(t, create(http.StatusCreated, map[string]any{"name": "Given " + stamp, "slug": "Given_Slug-" + stamp}))
|
||||
if got := env.organisation(t, given); got.Slug != "Given_Slug-"+stamp {
|
||||
t.Fatalf("given slug = %q", got.Slug)
|
||||
}
|
||||
// A slug with other characters, a duplicate slug and a missing name are
|
||||
// refused on their field and create nothing.
|
||||
for _, bad := range []string{"has space " + stamp, "dot." + stamp, "ślad-" + stamp} {
|
||||
rec := create(http.StatusUnprocessableEntity, map[string]any{"name": "Bad " + stamp, "slug": bad})
|
||||
if details := adminDecode(t, rec).Error.Details; len(details["slug"]) != 1 || details["slug"][0] != "The slug may only contain letters, numbers, dashes and underscores." {
|
||||
t.Fatalf("slug refusal for %q = %s", bad, rec.Body.String())
|
||||
}
|
||||
}
|
||||
rec := create(http.StatusUnprocessableEntity, map[string]any{"name": "Duplicate " + stamp, "slug": "acme-records-" + stamp})
|
||||
if details := adminDecode(t, rec).Error.Details; len(details["slug"]) == 0 {
|
||||
t.Fatalf("duplicate slug refusal = %s", rec.Body.String())
|
||||
}
|
||||
// The derived slug collides as well.
|
||||
rec = create(http.StatusUnprocessableEntity, map[string]any{"name": name})
|
||||
if details := adminDecode(t, rec).Error.Details; len(details["slug"]) == 0 {
|
||||
t.Fatalf("derived duplicate slug refusal = %s", rec.Body.String())
|
||||
}
|
||||
rec = create(http.StatusUnprocessableEntity, map[string]any{"slug": "nameless-" + stamp})
|
||||
if details := adminDecode(t, rec).Error.Details; len(details["name"]) == 0 {
|
||||
t.Fatalf("missing name refusal = %s", rec.Body.String())
|
||||
}
|
||||
var count int64
|
||||
if err := env.gdb.Raw(`SELECT COUNT(*) FROM golem15_user_organisations WHERE name LIKE ?`, "%"+stamp).Scan(&count).Error; err != nil || count != 3 {
|
||||
t.Fatalf("organisations after the refused creates = %d (%v)", count, err)
|
||||
}
|
||||
|
||||
// The list finds it by name and by slug.
|
||||
for _, term := range []string{"Acme+Records+" + stamp, "acme-records-" + stamp} {
|
||||
var rows []map[string]any
|
||||
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminOrganisationsPath)+"?search="+term, token, nil), &rows)
|
||||
if len(rows) != 1 || rows[0]["name"] != name || rows[0]["slug"] != "acme-records-"+stamp {
|
||||
t.Fatalf("list for %q = %v", term, rows)
|
||||
}
|
||||
}
|
||||
|
||||
// Update: the fields change; a bad slug is refused and changes nothing.
|
||||
env.expect(t, http.StatusOK, http.MethodPut, organisationPath(id, ""), token, map[string]any{"name": name, "slug": "acme-" + stamp, "description": "Renamed slug"})
|
||||
if got := env.organisation(t, id); got.Slug != "acme-"+stamp || *got.Description != "Renamed slug" {
|
||||
t.Fatalf("updated organisation = %+v", got)
|
||||
}
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, organisationPath(id, ""), token, map[string]any{"name": name, "slug": "acme " + stamp})
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, organisationPath(id, ""), token, map[string]any{"name": name, "slug": "Given_Slug-" + stamp})
|
||||
if got := env.organisation(t, id); got.Slug != "acme-"+stamp {
|
||||
t.Fatalf("a refused update changed the slug to %q", got.Slug)
|
||||
}
|
||||
|
||||
// Avatar: a file uploaded through the admin file route is attached to
|
||||
// the organisation under its morph name when the form is saved.
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
part, err := mw.CreateFormFile("file_data", "logo.jpg")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := part.Write(jpegBytes(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := mw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sessionKey := adminSessionKey(t)
|
||||
headers := map[string]string{cabana.SessionKeyHeader: sessionKey}
|
||||
if up := env.send(t, http.MethodPost, organisationPath(id, "/files/avatar"), token, buf.Bytes(), mw.FormDataContentType(), headers); up.Code != http.StatusCreated && up.Code != http.StatusOK {
|
||||
t.Fatalf("avatar upload = %d %s", up.Code, up.Body.String())
|
||||
}
|
||||
body, err := json.Marshal(map[string]any{"name": name, "slug": "acme-" + stamp})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if saved := env.send(t, http.MethodPut, organisationPath(id, ""), token, body, "application/json", headers); saved.Code != http.StatusOK {
|
||||
t.Fatalf("save with the avatar = %d %s", saved.Code, saved.Body.String())
|
||||
}
|
||||
files := func() int64 {
|
||||
t.Helper()
|
||||
var n int64
|
||||
if err := env.gdb.Raw(`SELECT COUNT(*) FROM system_files WHERE attachment_type = ? AND attachment_id = ? AND field = 'avatar'`,
|
||||
`Golem15\User\Models\Organisation`, strconv.FormatUint(uint64(id), 10)).Scan(&n).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
if files() != 1 || (models.Organisation{}).MorphName() != `Golem15\User\Models\Organisation` {
|
||||
t.Fatalf("avatar rows of the organisation = %d", files())
|
||||
}
|
||||
|
||||
// Delete: an organisation with members goes; its members stay, active or
|
||||
// deactivated, without an organisation and without a role in it. Users
|
||||
// of another organisation are not touched.
|
||||
role := "owner"
|
||||
owner := env.seedUser(t, "org-owner", func(u *models.User) { u.OrganisationID, u.OrganisationRole = &id, &role })
|
||||
gone := env.seedUser(t, "org-gone", func(u *models.User) { u.OrganisationID = &id })
|
||||
if err := env.gdb.Exec(`UPDATE users SET deleted_at = NOW() WHERE id = ?`, gone.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
other := env.seedUser(t, "org-other", func(u *models.User) { u.OrganisationID, u.OrganisationRole = &given, &role })
|
||||
group := env.seedGroup(t, "Org "+stamp, "org-"+stamp)
|
||||
env.join(t, owner, group)
|
||||
env.expect(t, http.StatusOK, http.MethodDelete, organisationPath(id, ""), token, nil)
|
||||
if env.organisation(t, id) != nil {
|
||||
t.Fatal("the organisation survived its delete")
|
||||
}
|
||||
for _, member := range []*models.User{owner, gone} {
|
||||
got := env.reload(t, member.ID)
|
||||
if got == nil || got.OrganisationID != nil || got.OrganisationRole != nil || got.Email != member.Email {
|
||||
t.Fatalf("member %d after the delete = %+v", member.ID, got)
|
||||
}
|
||||
}
|
||||
if got := env.reload(t, other.ID); got.OrganisationID == nil || *got.OrganisationID != given || got.OrganisationRole == nil {
|
||||
t.Fatalf("a member of another organisation changed: %+v", got)
|
||||
}
|
||||
if got := env.groupIDs(t, owner.ID); !reflect.DeepEqual(got, []uint{group.ID}) {
|
||||
t.Fatalf("the delete changed the owner's groups: %v", got)
|
||||
}
|
||||
env.expect(t, http.StatusNotFound, http.MethodGet, organisationPath(id, ""), token, nil)
|
||||
}
|
||||
|
||||
// TestAdminOrganisationMembers covers the members relation manager: link
|
||||
// sets and unlink clears users.organisation_id, the lists are scoped to the
|
||||
// organisation, and nothing else of a user changes, least of all
|
||||
// users_groups (T-12.1-30).
|
||||
func TestAdminOrganisationMembers(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
token := env.admin(t, permAccessUsers)
|
||||
groupsOnly := env.admin(t, permAccessGroups)
|
||||
stamp := adminStamp()
|
||||
here := env.seedOrganisation(t, "Here "+stamp)
|
||||
there := env.seedOrganisation(t, "There "+stamp)
|
||||
label := "Member" + stamp
|
||||
named := func(suffix string, mutate func(*models.User)) *models.User {
|
||||
return env.seedUser(t, "member-"+suffix, func(u *models.User) {
|
||||
name := label + " " + suffix
|
||||
u.Name = &name
|
||||
if mutate != nil {
|
||||
mutate(u)
|
||||
}
|
||||
})
|
||||
}
|
||||
first, second := named("first", nil), named("second", nil)
|
||||
role := "member"
|
||||
foreign := named("foreign", func(u *models.User) { u.OrganisationID, u.OrganisationRole = &there.ID, &role })
|
||||
group := env.seedGroup(t, "Members "+stamp, "members-"+stamp)
|
||||
adminGroup := env.seedGroup(t, "Admins "+stamp, "admin")
|
||||
env.join(t, first, group, adminGroup)
|
||||
env.join(t, second, group)
|
||||
env.join(t, foreign, adminGroup)
|
||||
everyone := []*models.User{first, second, foreign}
|
||||
memberships := map[uint][]uint{}
|
||||
stored := map[uint]*models.User{}
|
||||
for _, user := range everyone {
|
||||
memberships[user.ID] = env.groupIDs(t, user.ID)
|
||||
stored[user.ID] = env.reload(t, user.ID)
|
||||
}
|
||||
untouched := func() {
|
||||
t.Helper()
|
||||
for _, user := range everyone {
|
||||
if got := env.groupIDs(t, user.ID); !reflect.DeepEqual(got, memberships[user.ID]) {
|
||||
t.Fatalf("users_groups of %d = %v, want %v", user.ID, got, memberships[user.ID])
|
||||
}
|
||||
got, want := env.reload(t, user.ID), stored[user.ID]
|
||||
if got == nil || got.Email != want.Email || got.Password != want.Password || got.IsActivated != want.IsActivated ||
|
||||
!reflect.DeepEqual(got.Name, want.Name) || !reflect.DeepEqual(got.OrganisationRole, want.OrganisationRole) ||
|
||||
!reflect.DeepEqual(got.TokensValidAfter, want.TokensValidAfter) || got.DeletedAt.Valid {
|
||||
t.Fatalf("user %d changed beyond organisation_id: %+v", user.ID, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
organisationOf := func(user *models.User) uint {
|
||||
t.Helper()
|
||||
got := env.reload(t, user.ID)
|
||||
if got == nil || got.OrganisationID == nil {
|
||||
return 0
|
||||
}
|
||||
return *got.OrganisationID
|
||||
}
|
||||
ids := func(path string) []uint {
|
||||
t.Helper()
|
||||
var rows []map[string]any
|
||||
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, path, token, nil), &rows)
|
||||
out := []uint{}
|
||||
for _, row := range rows {
|
||||
out = append(out, uint(row["id"].(float64)))
|
||||
}
|
||||
return out
|
||||
}
|
||||
members := func(organisation *models.Organisation) []uint {
|
||||
t.Helper()
|
||||
return ids(organisationPath(organisation.ID, "/relations/members"))
|
||||
}
|
||||
candidates := func() []uint {
|
||||
t.Helper()
|
||||
return ids(organisationPath(here.ID, "/relations/members/candidates?search="+label))
|
||||
}
|
||||
mutate := func(organisation *models.Organisation, action string, users ...*models.User) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
list := make([]uint, len(users))
|
||||
for i, user := range users {
|
||||
list[i] = user.ID
|
||||
}
|
||||
return env.call(t, http.MethodPost, organisationPath(organisation.ID, "/relations/members/"+action), token, map[string]any{"ids": list})
|
||||
}
|
||||
|
||||
// The relation schema carries the screen's copy: the unlink confirm
|
||||
// counts and says the users are not deleted.
|
||||
var relation struct {
|
||||
Messages map[string]map[string]string `json:"messages"`
|
||||
}
|
||||
rawRelation := env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminOrganisationsPath+"/schema/relation/members"), token, nil)
|
||||
adminInto(t, rawRelation, &relation)
|
||||
for key, want := range map[string]string{
|
||||
"link": "Add member",
|
||||
"unlinkSelected": "Remove selected",
|
||||
"unlinkConfirm": "Remove the selected (:count) from this organisation? The users are not deleted.",
|
||||
"empty": "This organisation has no members yet. Add users with Add member.",
|
||||
} {
|
||||
if got := relation.Messages[key]["other"]; got != want {
|
||||
t.Fatalf("relation message %s = %q, want %q (%s)", key, got, want, rawRelation.Body.String())
|
||||
}
|
||||
}
|
||||
env.expect(t, http.StatusNotFound, http.MethodGet, adminAPI(adminOrganisationsPath+"/schema/relation/groups"), token, nil)
|
||||
|
||||
// The routes need the screen's permission.
|
||||
env.expect(t, http.StatusForbidden, http.MethodGet, organisationPath(here.ID, "/relations/members"), groupsOnly, nil)
|
||||
env.expect(t, http.StatusForbidden, http.MethodPost, organisationPath(here.ID, "/relations/members/link"), groupsOnly, map[string]any{"ids": []uint{first.ID}})
|
||||
if organisationOf(first) != 0 {
|
||||
t.Fatal("a refused link set organisation_id")
|
||||
}
|
||||
|
||||
// An organisation without members lists none; the candidates are the
|
||||
// users without an organisation.
|
||||
if got := members(here); len(got) != 0 {
|
||||
t.Fatalf("members of a new organisation = %v", got)
|
||||
}
|
||||
if got := candidates(); !reflect.DeepEqual(got, []uint{first.ID, second.ID}) {
|
||||
t.Fatalf("candidates = %v, want %v", got, []uint{first.ID, second.ID})
|
||||
}
|
||||
|
||||
// Link sets organisation_id of both users.
|
||||
if rec := mutate(here, "link", first, second); rec.Code != http.StatusOK {
|
||||
t.Fatalf("link = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if organisationOf(first) != here.ID || organisationOf(second) != here.ID {
|
||||
t.Fatalf("organisation_id after the link = %d, %d", organisationOf(first), organisationOf(second))
|
||||
}
|
||||
untouched()
|
||||
// Each list shows only its own organisation's members.
|
||||
if got := members(here); !reflect.DeepEqual(got, []uint{first.ID, second.ID}) {
|
||||
t.Fatalf("members here = %v", got)
|
||||
}
|
||||
if got := members(there); !reflect.DeepEqual(got, []uint{foreign.ID}) {
|
||||
t.Fatalf("members there = %v", got)
|
||||
}
|
||||
if got := candidates(); len(got) != 0 {
|
||||
t.Fatalf("candidates after the link = %v", got)
|
||||
}
|
||||
|
||||
// A member of another organisation is not a candidate and cannot be
|
||||
// taken over by a link: they stay where they are.
|
||||
refused := mutate(here, "link", foreign)
|
||||
if details := adminDecode(t, refused).Error.Details; refused.Code != http.StatusUnprocessableEntity || len(details["ids"]) == 0 {
|
||||
t.Fatalf("link of a foreign member = %d %s", refused.Code, refused.Body.String())
|
||||
}
|
||||
if organisationOf(foreign) != there.ID {
|
||||
t.Fatalf("a foreign member moved to %d", organisationOf(foreign))
|
||||
}
|
||||
// Unlinking through the wrong organisation is ignored.
|
||||
mutate(here, "unlink", foreign)
|
||||
if organisationOf(foreign) != there.ID {
|
||||
t.Fatal("an unlink through another organisation cleared organisation_id")
|
||||
}
|
||||
untouched()
|
||||
|
||||
// Unlink clears organisation_id of the chosen user only; the user stays.
|
||||
if rec := mutate(here, "unlink", first); rec.Code != http.StatusOK {
|
||||
t.Fatalf("unlink = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if organisationOf(first) != 0 || organisationOf(second) != here.ID || env.reload(t, first.ID) == nil {
|
||||
t.Fatalf("organisation_id after the unlink = %d, %d", organisationOf(first), organisationOf(second))
|
||||
}
|
||||
if got := members(here); !reflect.DeepEqual(got, []uint{second.ID}) {
|
||||
t.Fatalf("members after the unlink = %v", got)
|
||||
}
|
||||
untouched()
|
||||
|
||||
// Once released there, the user can be linked here: this is how a user
|
||||
// moves between organisations.
|
||||
if rec := mutate(there, "unlink", foreign); rec.Code != http.StatusOK {
|
||||
t.Fatalf("unlink there = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := mutate(here, "link", foreign); rec.Code != http.StatusOK || organisationOf(foreign) != here.ID {
|
||||
t.Fatalf("link after the release = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
untouched()
|
||||
}
|
||||
46
admin_permissions.go
Normal file
46
admin_permissions.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package user
|
||||
|
||||
import "git.golem15.com/golem15/summercms/modules/pact"
|
||||
|
||||
const userPermissionTab = "golem15.user::lang.plugin.tab"
|
||||
|
||||
// Permissions is the plugin's Winter registerPermissions() catalog plus one
|
||||
// code of its own. The four PHP codes default to the developer role;
|
||||
// impersonate_user is registered so imported backend roles that name it stay
|
||||
// valid, although no screen uses it. The fifth code
|
||||
// (classes.PermissionManagePrivilegedGroups) has no default role: only a
|
||||
// superuser, or a role that was granted it explicitly, may change the email
|
||||
// or password of a privileged-group member or delete one.
|
||||
func (*Plugin) Permissions() []pact.Permission {
|
||||
return []pact.Permission{
|
||||
{
|
||||
Code: "golem15.users.access_users",
|
||||
Tab: userPermissionTab,
|
||||
Label: "golem15.user::lang.plugin.access_users",
|
||||
Roles: []string{"developer"},
|
||||
},
|
||||
{
|
||||
Code: "golem15.users.access_groups",
|
||||
Tab: userPermissionTab,
|
||||
Label: "golem15.user::lang.plugin.access_groups",
|
||||
Roles: []string{"developer"},
|
||||
},
|
||||
{
|
||||
Code: "golem15.users.access_settings",
|
||||
Tab: userPermissionTab,
|
||||
Label: "golem15.user::lang.plugin.access_settings",
|
||||
Roles: []string{"developer"},
|
||||
},
|
||||
{
|
||||
Code: "golem15.users.impersonate_user",
|
||||
Tab: userPermissionTab,
|
||||
Label: "golem15.user::lang.plugin.impersonate_user",
|
||||
Roles: []string{"developer"},
|
||||
},
|
||||
{
|
||||
Code: "golem15.users.manage_privileged_groups",
|
||||
Tab: userPermissionTab,
|
||||
Label: "golem15.user::lang.plugin.manage_privileged_groups",
|
||||
},
|
||||
}
|
||||
}
|
||||
556
admin_privileged_test.go
Normal file
556
admin_privileged_test.go
Normal file
@@ -0,0 +1,556 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
)
|
||||
|
||||
const privilegedGroupForbidden = "You do not have permission to change membership of privileged groups. Nothing was saved."
|
||||
|
||||
// groupOptions returns the choices of the user form's groups field that
|
||||
// match search, as id to locked.
|
||||
func (e *adminEnv) groupOptions(t *testing.T, token, search string) map[uint]bool {
|
||||
t.Helper()
|
||||
var options []struct {
|
||||
Value uint `json:"value"`
|
||||
Locked bool `json:"locked"`
|
||||
}
|
||||
path := adminAPI(adminUsersPath + "/fields/groups/options?per_page=100&search=" + search)
|
||||
adminInto(t, e.expect(t, http.StatusOK, http.MethodGet, path, token, nil), &options)
|
||||
out := map[uint]bool{}
|
||||
for _, option := range options {
|
||||
out[option.Value] = option.Locked
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// recordGroups reads a user through the admin API and returns the ids of
|
||||
// the groups field and, per id, whether its label is flagged locked.
|
||||
func (e *adminEnv) recordGroups(t *testing.T, token string, userID uint) ([]uint, map[uint]bool) {
|
||||
t.Helper()
|
||||
rec := e.expect(t, http.StatusOK, http.MethodGet, userPath(userID, ""), token, nil)
|
||||
var data struct {
|
||||
Groups []uint `json:"groups"`
|
||||
}
|
||||
answer := adminInto(t, rec, &data)
|
||||
var meta struct {
|
||||
Labels map[string][]struct {
|
||||
Value uint `json:"value"`
|
||||
Locked bool `json:"locked"`
|
||||
} `json:"labels"`
|
||||
}
|
||||
if err := json.Unmarshal(answer.Meta, &meta); err != nil {
|
||||
t.Fatalf("record meta %q: %v", string(answer.Meta), err)
|
||||
}
|
||||
locked := map[uint]bool{}
|
||||
for _, label := range meta.Labels["groups"] {
|
||||
locked[label.Value] = label.Locked
|
||||
}
|
||||
return data.Groups, locked
|
||||
}
|
||||
|
||||
// sortedIDs returns the ids of the groups in ascending order, the order
|
||||
// groupIDs reads the pivot in.
|
||||
func sortedIDs(groups ...*models.UserGroup) []uint {
|
||||
ids := make([]uint, 0, len(groups))
|
||||
for _, group := range groups {
|
||||
ids = append(ids, group.ID)
|
||||
}
|
||||
for i := 1; i < len(ids); i++ {
|
||||
for j := i; j > 0 && ids[j-1] > ids[j]; j-- {
|
||||
ids[j-1], ids[j] = ids[j], ids[j-1]
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// TestAdminUserGroupsField covers the groups field of the user form with
|
||||
// ordinary groups: it is the writer of users_groups, it replaces the user's
|
||||
// memberships only when the field is sent, it refuses ids that are not
|
||||
// groups, and none of it reaches a user API payload (D-08).
|
||||
func TestAdminUserGroupsField(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
token := env.admin(t, permAccessUsers)
|
||||
stamp := adminStamp()
|
||||
first := env.seedGroup(t, "First "+stamp, "first-"+stamp)
|
||||
second := env.seedGroup(t, "Second "+stamp, "second-"+stamp)
|
||||
user := env.seedUser(t, "groups", nil)
|
||||
base := map[string]any{"name": "groups", "email": user.Email}
|
||||
save := func(status int, groups any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
body := map[string]any{"groups": groups}
|
||||
for key, value := range base {
|
||||
body[key] = value
|
||||
}
|
||||
return env.expect(t, status, http.MethodPut, userPath(user.ID, ""), token, body)
|
||||
}
|
||||
pivot := func(want ...*models.UserGroup) {
|
||||
t.Helper()
|
||||
if got := env.groupIDs(t, user.ID); !reflect.DeepEqual(got, sortedIDs(want...)) {
|
||||
t.Fatalf("users_groups of %d = %v, want %v", user.ID, got, sortedIDs(want...))
|
||||
}
|
||||
}
|
||||
|
||||
// The field is a multiple relation field on the Account tab, and its
|
||||
// options are the user groups; none is locked for ordinary codes.
|
||||
var form struct {
|
||||
Fields []struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Multiple bool `json:"multiple"`
|
||||
Tab string `json:"tab"`
|
||||
} `json:"fields"`
|
||||
}
|
||||
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminUsersPath+"/schema/form"), token, nil), &form)
|
||||
found := false
|
||||
for _, field := range form.Fields {
|
||||
if field.Name != "groups" {
|
||||
continue
|
||||
}
|
||||
found = true
|
||||
if field.Type != "relation" || !field.Multiple || field.Tab != "Account" {
|
||||
t.Fatalf("groups field = %+v", field)
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("the user form has no groups field")
|
||||
}
|
||||
if options := env.groupOptions(t, token, stamp); len(options) != 2 || options[first.ID] || options[second.ID] {
|
||||
t.Fatalf("group options = %v", options)
|
||||
}
|
||||
|
||||
// Setting the field writes exactly the chosen memberships.
|
||||
saved := save(http.StatusOK, []uint{first.ID, second.ID})
|
||||
pivot(first, second)
|
||||
var record struct {
|
||||
Groups []uint `json:"groups"`
|
||||
}
|
||||
adminInto(t, saved, &record)
|
||||
if !reflect.DeepEqual(record.Groups, sortedIDs(first, second)) {
|
||||
t.Fatalf("record groups = %v", record.Groups)
|
||||
}
|
||||
if ids, locked := env.recordGroups(t, token, user.ID); !reflect.DeepEqual(ids, sortedIDs(first, second)) || locked[first.ID] || locked[second.ID] || len(locked) != 2 {
|
||||
t.Fatalf("shown groups = %v locked %v", ids, locked)
|
||||
}
|
||||
save(http.StatusOK, []uint{second.ID})
|
||||
pivot(second)
|
||||
|
||||
// A save without the field leaves the memberships alone.
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(user.ID, ""), token, map[string]any{"name": "renamed", "email": user.Email})
|
||||
pivot(second)
|
||||
if got := env.reload(t, user.ID); got.Name == nil || *got.Name != "renamed" {
|
||||
t.Fatalf("name after a save without groups = %v", got.Name)
|
||||
}
|
||||
|
||||
// An id that is not a group, a duplicate and a value that is not a list
|
||||
// are refused on the field and change nothing.
|
||||
for _, bad := range []any{[]uint{second.ID, 987654321}, []uint{first.ID, first.ID}, first.ID, []string{"x"}} {
|
||||
rec := save(http.StatusUnprocessableEntity, bad)
|
||||
if details := adminDecode(t, rec).Error.Details; len(details["groups"]) == 0 {
|
||||
t.Fatalf("refusal of %v has no detail on groups: %s", bad, rec.Body.String())
|
||||
}
|
||||
pivot(second)
|
||||
}
|
||||
// The plain relation name of the model is not a way around the field.
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(user.ID, ""), token, map[string]any{
|
||||
"name": "renamed", "email": user.Email, "Groups": []map[string]any{{"id": first.ID}}, "users_groups": []uint{first.ID},
|
||||
})
|
||||
pivot(second)
|
||||
|
||||
// The user API payload still answers an empty list (D-08), although the
|
||||
// user is a member of a group.
|
||||
status, userToken := env.userLogin(t, user.Email, "correct-horse")
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("user login = %d", status)
|
||||
}
|
||||
fetch := env.call(t, http.MethodGet, "/_user/api/v1/fetch", userToken, nil)
|
||||
var body struct {
|
||||
User map[string]any `json:"user"`
|
||||
}
|
||||
if err := json.Unmarshal(fetch.Body.Bytes(), &body); err != nil || fetch.Code != http.StatusOK {
|
||||
t.Fatalf("fetch = %d %s (%v)", fetch.Code, fetch.Body.String(), err)
|
||||
}
|
||||
if groups, ok := body.User["groups"].([]any); !ok || len(groups) != 0 {
|
||||
t.Fatalf("user payload groups = %v", body.User["groups"])
|
||||
}
|
||||
|
||||
// Clearing the field removes every membership.
|
||||
save(http.StatusOK, []uint{})
|
||||
pivot()
|
||||
|
||||
// A create with the field writes the memberships of the new user.
|
||||
const password = "groups-password-1"
|
||||
created := env.expect(t, http.StatusCreated, http.MethodPost, adminAPI(adminUsersPath), token, map[string]any{
|
||||
"name": "Created", "email": "groups-created-" + stamp + "@example.test",
|
||||
"password": password, "password_confirmation": password, "send_invite": false,
|
||||
"groups": []uint{first.ID},
|
||||
})
|
||||
if got := env.groupIDs(t, createdID(t, created)); !reflect.DeepEqual(got, []uint{first.ID}) {
|
||||
t.Fatalf("users_groups of the created user = %v", got)
|
||||
}
|
||||
// A refused create leaves no user behind.
|
||||
refusedEmail := "groups-refused-" + stamp + "@example.test"
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodPost, adminAPI(adminUsersPath), token, map[string]any{
|
||||
"name": "Refused", "email": refusedEmail, "password": password, "password_confirmation": password, "send_invite": false,
|
||||
"groups": []uint{987654321},
|
||||
})
|
||||
var refused int64
|
||||
if err := env.gdb.Raw(`SELECT COUNT(*) FROM users WHERE email = ?`, refusedEmail).Scan(&refused).Error; err != nil || refused != 0 {
|
||||
t.Fatalf("a refused create left %d users (%v)", refused, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminPrivilegedGroups covers threat T-12-18 as revisited by D-04 to
|
||||
// D-07: golem15.users.access_users changes ordinary memberships, and adding
|
||||
// or removing a privileged group additionally needs
|
||||
// golem15.users.manage_privileged_groups, on create and on update. It also
|
||||
// ties the field to the takeover guard (D-30).
|
||||
func TestAdminPrivilegedGroups(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
limited := env.admin(t, permAccessUsers)
|
||||
manager := env.admin(t, permAccessUsers, permManagePrivileged)
|
||||
|
||||
stamp := adminStamp()
|
||||
// The migrations seed only guest and registered; the default privileged
|
||||
// list is [admin].
|
||||
adminGroup := env.seedGroup(t, "Admins "+stamp, "admin")
|
||||
ordinaryCode := "ordinary-" + stamp
|
||||
ordinary := env.seedGroup(t, "Ordinary "+stamp, ordinaryCode)
|
||||
uncoded := env.seedGroup(t, "Uncoded "+stamp, "")
|
||||
// A code that differs from a privileged one only by case is ordinary.
|
||||
upper := env.seedGroup(t, "Upper "+stamp, "ADMIN")
|
||||
|
||||
isAdmin := func(e *adminEnv, userID uint) bool {
|
||||
t.Helper()
|
||||
held, err := classes.HasGroupCode(t.Context(), e.gdb, userID, "admin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return held
|
||||
}
|
||||
put := func(e *adminEnv, status int, token string, user *models.User, extra map[string]any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
body := map[string]any{"name": "kept", "email": user.Email}
|
||||
for key, value := range extra {
|
||||
body[key] = value
|
||||
}
|
||||
return e.expect(t, status, http.MethodPut, userPath(user.ID, ""), token, body)
|
||||
}
|
||||
assertRefused := func(rec *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
answer := adminDecode(t, rec)
|
||||
if answer.Error.Code != "forbidden" || answer.Error.Message != privilegedGroupForbidden {
|
||||
t.Fatalf("refusal = %s", rec.Body.String())
|
||||
}
|
||||
if got := answer.Error.Details["groups"]; len(answer.Error.Details) != 1 || len(got) != 1 || got[0] != privilegedGroupForbidden {
|
||||
t.Fatalf("refusal details = %v", answer.Error.Details)
|
||||
}
|
||||
}
|
||||
pivot := func(e *adminEnv, user *models.User, want ...*models.UserGroup) {
|
||||
t.Helper()
|
||||
if got := e.groupIDs(t, user.ID); !reflect.DeepEqual(got, sortedIDs(want...)) {
|
||||
t.Fatalf("users_groups of %d = %v, want %v", user.ID, got, sortedIDs(want...))
|
||||
}
|
||||
}
|
||||
unchanged := func(original *models.User) {
|
||||
t.Helper()
|
||||
got := env.reload(t, original.ID)
|
||||
if got == nil || got.Email != original.Email || !reflect.DeepEqual(got.Name, original.Name) ||
|
||||
got.Password != original.Password || !reflect.DeepEqual(got.OrganisationID, original.OrganisationID) {
|
||||
t.Fatalf("user %d changed: %+v", original.ID, got)
|
||||
}
|
||||
}
|
||||
|
||||
// Without the permission the privileged group is flagged locked among the
|
||||
// options; a group without a code and one whose code differs by case are
|
||||
// not. With the permission nothing is locked.
|
||||
if options := env.groupOptions(t, limited, stamp); len(options) != 4 || !options[adminGroup.ID] || options[ordinary.ID] || options[uncoded.ID] || options[upper.ID] {
|
||||
t.Fatalf("options without the permission = %v", options)
|
||||
}
|
||||
if options := env.groupOptions(t, manager, stamp); len(options) != 4 || options[adminGroup.ID] || options[ordinary.ID] || options[uncoded.ID] || options[upper.ID] {
|
||||
t.Fatalf("options with the permission = %v", options)
|
||||
}
|
||||
|
||||
// Adding the privileged group on update is refused as a whole: the name
|
||||
// in the same body is not saved and the pivot is unchanged.
|
||||
target := env.seedUser(t, "target", nil)
|
||||
env.join(t, target, ordinary)
|
||||
if isAdmin(env, target.ID) {
|
||||
t.Fatal("the target starts as a site admin")
|
||||
}
|
||||
assertRefused(put(env, http.StatusForbidden, limited, target, map[string]any{"name": "Promoted", "groups": []uint{ordinary.ID, adminGroup.ID}}))
|
||||
pivot(env, target, ordinary)
|
||||
unchanged(target)
|
||||
if isAdmin(env, target.ID) {
|
||||
t.Fatal("a refused save made a site admin")
|
||||
}
|
||||
// The privileged group alone, replacing the ordinary one, is refused too.
|
||||
assertRefused(put(env, http.StatusForbidden, limited, target, map[string]any{"groups": []uint{adminGroup.ID}}))
|
||||
pivot(env, target, ordinary)
|
||||
|
||||
// Removing it from a member is refused: by leaving it out, and by
|
||||
// clearing the field.
|
||||
member := env.seedUser(t, "member", nil)
|
||||
env.join(t, member, adminGroup, ordinary)
|
||||
for _, groups := range [][]uint{{ordinary.ID}, {}} {
|
||||
assertRefused(put(env, http.StatusForbidden, limited, member, map[string]any{"name": "Demoted", "groups": groups}))
|
||||
pivot(env, member, adminGroup, ordinary)
|
||||
unchanged(member)
|
||||
if !isAdmin(env, member.ID) {
|
||||
t.Fatal("a refused save removed a site admin")
|
||||
}
|
||||
}
|
||||
// The member's privileged label is flagged locked for the limited admin
|
||||
// and not for the manager.
|
||||
if ids, locked := env.recordGroups(t, limited, member.ID); !reflect.DeepEqual(ids, sortedIDs(adminGroup, ordinary)) || !locked[adminGroup.ID] || locked[ordinary.ID] {
|
||||
t.Fatalf("member groups for the limited admin = %v locked %v", ids, locked)
|
||||
}
|
||||
if _, locked := env.recordGroups(t, manager, member.ID); locked[adminGroup.ID] || locked[ordinary.ID] {
|
||||
t.Fatalf("member groups for the manager are locked: %v", locked)
|
||||
}
|
||||
|
||||
// Creating a user who is already in the privileged group is refused and
|
||||
// leaves no user row.
|
||||
const password = "privileged-password-1"
|
||||
create := func(token, email string, groups []uint) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return env.call(t, http.MethodPost, adminAPI(adminUsersPath), token, map[string]any{
|
||||
"name": "Created", "email": email, "password": password, "password_confirmation": password, "send_invite": false,
|
||||
"groups": groups,
|
||||
})
|
||||
}
|
||||
refusedEmail := "born-admin-" + stamp + "@example.test"
|
||||
rec := create(limited, refusedEmail, []uint{adminGroup.ID, ordinary.ID})
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("create with a privileged group = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
assertRefused(rec)
|
||||
var born int64
|
||||
if err := env.gdb.Raw(`SELECT COUNT(*) FROM users WHERE email = ?`, refusedEmail).Scan(&born).Error; err != nil || born != 0 {
|
||||
t.Fatalf("a refused create left %d users (%v)", born, err)
|
||||
}
|
||||
|
||||
// Ordinary changes need only the users permission, also on a member of
|
||||
// the privileged group as long as that membership is sent back as it is;
|
||||
// a group without a code and a case variant are ordinary.
|
||||
put(env, http.StatusOK, limited, member, map[string]any{"groups": []uint{adminGroup.ID, uncoded.ID, upper.ID}})
|
||||
pivot(env, member, adminGroup, uncoded, upper)
|
||||
put(env, http.StatusOK, limited, target, map[string]any{"groups": []uint{uncoded.ID}})
|
||||
pivot(env, target, uncoded)
|
||||
put(env, http.StatusOK, limited, target, map[string]any{"groups": []uint{}})
|
||||
pivot(env, target)
|
||||
if isAdmin(env, target.ID) || !isAdmin(env, member.ID) {
|
||||
t.Fatal("ordinary changes moved the site-admin membership")
|
||||
}
|
||||
|
||||
// With the permission every refused request succeeds.
|
||||
put(env, http.StatusOK, manager, target, map[string]any{"groups": []uint{ordinary.ID, adminGroup.ID}})
|
||||
pivot(env, target, ordinary, adminGroup)
|
||||
if !isAdmin(env, target.ID) {
|
||||
t.Fatal("the manager could not add the privileged group")
|
||||
}
|
||||
put(env, http.StatusOK, manager, target, map[string]any{"groups": []uint{ordinary.ID}})
|
||||
pivot(env, target, ordinary)
|
||||
put(env, http.StatusOK, manager, member, map[string]any{"groups": []uint{}})
|
||||
pivot(env, member)
|
||||
if isAdmin(env, target.ID) || isAdmin(env, member.ID) {
|
||||
t.Fatal("the manager could not remove the privileged group")
|
||||
}
|
||||
rec = create(manager, "born-admin-ok-"+stamp+"@example.test", []uint{adminGroup.ID})
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("manager create with a privileged group = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if bornID := createdID(t, rec); !isAdmin(env, bornID) {
|
||||
t.Fatal("the manager's create did not write the privileged membership")
|
||||
}
|
||||
|
||||
// D-30: the takeover guard follows the membership this field writes. No
|
||||
// row is inserted into users_groups directly here.
|
||||
guarded := env.seedUser(t, "guarded", nil)
|
||||
newEmail := "guarded-new-" + stamp + "@example.test"
|
||||
put(env, http.StatusOK, manager, guarded, map[string]any{"groups": []uint{adminGroup.ID}})
|
||||
rec = env.expect(t, http.StatusForbidden, http.MethodPut, userPath(guarded.ID, ""), limited, map[string]any{"name": "kept", "email": newEmail})
|
||||
if answer := adminDecode(t, rec); answer.Error.Message != privilegedMemberForbidden || len(answer.Error.Details["email"]) != 1 {
|
||||
t.Fatalf("takeover refusal = %s", rec.Body.String())
|
||||
}
|
||||
if got := env.reload(t, guarded.ID); got.Email != guarded.Email {
|
||||
t.Fatalf("a refused takeover changed the email to %q", got.Email)
|
||||
}
|
||||
put(env, http.StatusOK, manager, guarded, map[string]any{"groups": []uint{}})
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(guarded.ID, ""), limited, map[string]any{"name": "kept", "email": newEmail})
|
||||
if got := env.reload(t, guarded.ID); got.Email != newEmail {
|
||||
t.Fatalf("email after the membership was removed = %q", got.Email)
|
||||
}
|
||||
|
||||
// The privileged list is config, read per request. With the ordinary
|
||||
// group's code in it, that group is the locked one and admin is not.
|
||||
moved := newAdminEnv(t, func(cfg *compass.Config) {
|
||||
if err := cfg.Set("golem15.user.privileged_groups", []string{ordinaryCode}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
movedLimited := moved.admin(t, permAccessUsers)
|
||||
if options := moved.groupOptions(t, movedLimited, stamp); len(options) != 4 || options[adminGroup.ID] || !options[ordinary.ID] || options[uncoded.ID] {
|
||||
t.Fatalf("options under the moved list = %v", options)
|
||||
}
|
||||
put(moved, http.StatusOK, movedLimited, member, map[string]any{"groups": []uint{adminGroup.ID}})
|
||||
pivot(moved, member, adminGroup)
|
||||
assertRefused(put(moved, http.StatusForbidden, movedLimited, member, map[string]any{"groups": []uint{adminGroup.ID, ordinary.ID}}))
|
||||
pivot(moved, member, adminGroup)
|
||||
// target is in the ordinary group, which is now the privileged one.
|
||||
assertRefused(put(moved, http.StatusForbidden, movedLimited, target, map[string]any{"groups": []uint{}}))
|
||||
pivot(moved, target, ordinary)
|
||||
|
||||
// An empty list means no group is privileged: nothing is locked.
|
||||
open := newAdminEnv(t, func(cfg *compass.Config) {
|
||||
if err := cfg.Set("golem15.user.privileged_groups", []string{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
openLimited := open.admin(t, permAccessUsers)
|
||||
for id, locked := range open.groupOptions(t, openLimited, stamp) {
|
||||
if locked {
|
||||
t.Fatalf("group %s is locked although no code is privileged", strconv.FormatUint(uint64(id), 10))
|
||||
}
|
||||
}
|
||||
|
||||
// D-06: the group's code carries the privilege, so creating a group with
|
||||
// a privileged code, changing a code to or from one, and deleting a
|
||||
// privileged group need the extra permission on the User Groups screen.
|
||||
// The harness database is shared and may hold several groups coded
|
||||
// admin, so the matrix runs on two codes of its own next to admin.
|
||||
priv, second := "priv-"+stamp, "priv2-"+stamp
|
||||
coded := newAdminEnv(t, func(cfg *compass.Config) {
|
||||
if err := cfg.Set("golem15.user.privileged_groups", []string{"admin", priv, second}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
groupsOnly := coded.admin(t, permAccessGroups)
|
||||
groupsManager := coded.admin(t, permAccessGroups, permManagePrivileged)
|
||||
privGroup := coded.seedGroup(t, "Privileged "+stamp, priv)
|
||||
plainCode := "plain-" + stamp
|
||||
plainGroup := coded.seedGroup(t, "Plain "+stamp, plainCode)
|
||||
holder := coded.seedUser(t, "holder", nil)
|
||||
coded.join(t, holder, privGroup, plainGroup)
|
||||
holds := func(code string) bool {
|
||||
t.Helper()
|
||||
held, err := classes.HasGroupCode(t.Context(), coded.gdb, holder.ID, code)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return held
|
||||
}
|
||||
refusedCode := func(rec *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status = %d, want 403: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
answer := adminDecode(t, rec)
|
||||
if answer.Error.Code != "forbidden" || answer.Error.Message != privilegedGroupCodeForbidden {
|
||||
t.Fatalf("refusal = %s", rec.Body.String())
|
||||
}
|
||||
if got := answer.Error.Details["code"]; len(answer.Error.Details) != 1 || len(got) != 1 || got[0] != privilegedGroupCodeForbidden {
|
||||
t.Fatalf("refusal details = %v", answer.Error.Details)
|
||||
}
|
||||
}
|
||||
sameGroup := func(id uint, name, code string) {
|
||||
t.Helper()
|
||||
got := coded.group(t, id)
|
||||
if got == nil || got.Name != name || got.Code == nil || *got.Code != code {
|
||||
t.Fatalf("group %d = %+v, want %s (%s)", id, got, name, code)
|
||||
}
|
||||
}
|
||||
codeCount := func(code string) int64 {
|
||||
t.Helper()
|
||||
var n int64
|
||||
if err := coded.gdb.Raw(`SELECT COUNT(*) FROM user_groups WHERE code = ?`, code).Scan(&n).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
groupPut := func(token string, id uint, body map[string]any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return coded.call(t, http.MethodPut, groupPath(id), token, body)
|
||||
}
|
||||
|
||||
// Without the permission each of the four is refused and changes nothing.
|
||||
refusedCode(coded.call(t, http.MethodPost, adminAPI(adminGroupsPath), groupsOnly, map[string]any{"name": "Second " + stamp, "code": second}))
|
||||
if codeCount(second) != 0 {
|
||||
t.Fatal("a refused create left a privileged group")
|
||||
}
|
||||
refusedCode(groupPut(groupsOnly, plainGroup.ID, map[string]any{"name": "Promoted " + stamp, "code": second}))
|
||||
sameGroup(plainGroup.ID, "Plain "+stamp, plainCode)
|
||||
refusedCode(groupPut(groupsOnly, privGroup.ID, map[string]any{"name": "Demoted " + stamp, "code": "demoted-" + stamp}))
|
||||
sameGroup(privGroup.ID, "Privileged "+stamp, priv)
|
||||
// From one privileged code to another is a change of a privileged code.
|
||||
refusedCode(groupPut(groupsOnly, privGroup.ID, map[string]any{"name": "Privileged " + stamp, "code": second}))
|
||||
sameGroup(privGroup.ID, "Privileged "+stamp, priv)
|
||||
refusedCode(coded.call(t, http.MethodDelete, groupPath(privGroup.ID), groupsOnly, nil))
|
||||
sameGroup(privGroup.ID, "Privileged "+stamp, priv)
|
||||
pivot(coded, holder, privGroup, plainGroup)
|
||||
if !holds(priv) || holds(second) {
|
||||
t.Fatal("a refused group change moved the privilege")
|
||||
}
|
||||
// The default code admin is protected the same way, and a group without
|
||||
// a code cannot be given a privileged one.
|
||||
refusedCode(groupPut(groupsOnly, adminGroup.ID, map[string]any{"name": "Admins " + stamp, "code": "was-admin-" + stamp}))
|
||||
refusedCode(coded.call(t, http.MethodDelete, groupPath(adminGroup.ID), groupsOnly, nil))
|
||||
sameGroup(adminGroup.ID, "Admins "+stamp, "admin")
|
||||
refusedCode(groupPut(groupsOnly, uncoded.ID, map[string]any{"name": "Uncoded " + stamp, "code": second}))
|
||||
if got := coded.group(t, uncoded.ID); got == nil || got.Code != nil {
|
||||
t.Fatalf("the uncoded group after a refused save = %+v", got)
|
||||
}
|
||||
|
||||
// Everything else on a privileged group needs only the groups
|
||||
// permission: its name, description and frontend permissions, with the
|
||||
// code sent back as it is.
|
||||
if rec := groupPut(groupsOnly, privGroup.ID, map[string]any{"name": "Privileged renamed " + stamp, "code": priv, "description": "Kept code", "permissions": map[string]int{}}); rec.Code != http.StatusOK {
|
||||
t.Fatalf("name-only update of a privileged group = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
sameGroup(privGroup.ID, "Privileged renamed "+stamp, priv)
|
||||
// Ordinary groups, a case variant of a privileged code included, are
|
||||
// re-coded and deleted freely.
|
||||
if rec := groupPut(groupsOnly, plainGroup.ID, map[string]any{"name": "Plain " + stamp, "code": "plain2-" + stamp}); rec.Code != http.StatusOK {
|
||||
t.Fatalf("ordinary re-code = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
plainCode = "plain2-" + stamp
|
||||
if rec := groupPut(groupsOnly, uncoded.ID, map[string]any{"name": "Uncoded " + stamp, "code": "coded-" + stamp}); rec.Code != http.StatusOK {
|
||||
t.Fatalf("first code of an uncoded group = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := coded.call(t, http.MethodDelete, groupPath(upper.ID), groupsOnly, nil); rec.Code != http.StatusOK || coded.group(t, upper.ID) != nil {
|
||||
t.Fatalf("delete of the ADMIN group = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// With the permission all four succeed.
|
||||
created := coded.call(t, http.MethodPost, adminAPI(adminGroupsPath), groupsManager, map[string]any{"name": "Second " + stamp, "code": second})
|
||||
if created.Code != http.StatusCreated || codeCount(second) != 1 {
|
||||
t.Fatalf("manager create of a privileged group = %d %s", created.Code, created.Body.String())
|
||||
}
|
||||
if rec := groupPut(groupsManager, privGroup.ID, map[string]any{"name": "Privileged renamed " + stamp, "code": "freed-" + stamp}); rec.Code != http.StatusOK {
|
||||
t.Fatalf("manager re-code from a privileged code = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if holds(priv) {
|
||||
t.Fatal("the holder kept the privilege after the group lost its code")
|
||||
}
|
||||
if rec := groupPut(groupsManager, plainGroup.ID, map[string]any{"name": "Plain " + stamp, "code": priv}); rec.Code != http.StatusOK {
|
||||
t.Fatalf("manager re-code to a privileged code = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if !holds(priv) {
|
||||
t.Fatal("the holder did not gain the privilege with the group's new code")
|
||||
}
|
||||
if rec := coded.call(t, http.MethodDelete, groupPath(plainGroup.ID), groupsManager, nil); rec.Code != http.StatusOK || coded.group(t, plainGroup.ID) != nil {
|
||||
t.Fatalf("manager delete of a privileged group = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
pivot(coded, holder, privGroup)
|
||||
if holds(priv) || coded.reload(t, holder.ID) == nil {
|
||||
t.Fatal("the delete of the privileged group left the privilege or removed the member")
|
||||
}
|
||||
}
|
||||
273
admin_registration_test.go
Normal file
273
admin_registration_test.go
Normal file
@@ -0,0 +1,273 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/controllers"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
)
|
||||
|
||||
// langKey matches one complete phrase key of the plugin.
|
||||
var langKey = regexp.MustCompile(`golem15\.user::lang\.[a-z0-9_]+(\.[a-z0-9_]+)+`)
|
||||
|
||||
// TestAdminRegistration pins what the plugin registers for the admin: the
|
||||
// permission catalog, the navigation tree, the embedded admin files and the
|
||||
// phrase keys they and the controllers name, in English and Polish.
|
||||
func TestAdminRegistration(t *testing.T) {
|
||||
plugin := &Plugin{}
|
||||
|
||||
// The five permission codes, each on the plugin's tab.
|
||||
var codes []string
|
||||
for _, permission := range plugin.Permissions() {
|
||||
codes = append(codes, permission.Code)
|
||||
if permission.Tab != "golem15.user::lang.plugin.tab" || !strings.HasPrefix(permission.Label, "golem15.user::lang.plugin.") {
|
||||
t.Fatalf("permission %+v is not on the plugin tab", permission)
|
||||
}
|
||||
}
|
||||
wantCodes := []string{
|
||||
"golem15.users.access_users", "golem15.users.access_groups", "golem15.users.access_settings",
|
||||
"golem15.users.impersonate_user", "golem15.users.manage_privileged_groups",
|
||||
}
|
||||
if !reflect.DeepEqual(codes, wantCodes) {
|
||||
t.Fatalf("permission codes = %v, want %v", codes, wantCodes)
|
||||
}
|
||||
// The privileged-groups permission has no default role: nobody holds it
|
||||
// until it is granted on purpose.
|
||||
for _, permission := range plugin.Permissions() {
|
||||
if privileged := permission.Code == permManagePrivileged; privileged != (len(permission.Roles) == 0) {
|
||||
t.Fatalf("permission %s has roles %v", permission.Code, permission.Roles)
|
||||
}
|
||||
}
|
||||
|
||||
// The navigation: one main item with three side items, each behind the
|
||||
// permission of its screen.
|
||||
nav := plugin.Navigation()
|
||||
if len(nav) != 1 || nav[0].Code != "user" || nav[0].Order != 555 || nav[0].Controller != "golem15.user.users" ||
|
||||
!reflect.DeepEqual(nav[0].Permissions, []string{"golem15.users.*"}) {
|
||||
t.Fatalf("navigation = %+v", nav)
|
||||
}
|
||||
type side struct{ code, controller, permission string }
|
||||
var sides []side
|
||||
for _, item := range nav[0].SideMenu {
|
||||
if len(item.Permissions) != 1 || item.Icon == "" || len(item.SideMenu) != 0 {
|
||||
t.Fatalf("side item %+v", item)
|
||||
}
|
||||
sides = append(sides, side{item.Code, item.Controller, item.Permissions[0]})
|
||||
}
|
||||
if want := []side{
|
||||
{"users", "golem15.user.users", permAccessUsers},
|
||||
{"usergroups", "golem15.user.usergroups", permAccessGroups},
|
||||
{"organisations", "golem15.user.organisations", permAccessUsers},
|
||||
}; !reflect.DeepEqual(sides, want) {
|
||||
t.Fatalf("side menu = %v, want %v", sides, want)
|
||||
}
|
||||
|
||||
// The controllers: three, each naming a config directory that exists in
|
||||
// the embedded files, each behind the permission its side item names.
|
||||
ctls := controllers.AdminControllers(func() *backpack.App { return nil })
|
||||
if len(ctls) != 3 {
|
||||
t.Fatalf("controllers = %d", len(ctls))
|
||||
}
|
||||
required := map[string]string{}
|
||||
for _, ctl := range ctls {
|
||||
permissioned, ok := ctl.(pact.AdminPermissioned)
|
||||
if !ok || len(permissioned.RequiredPermissions()) != 1 {
|
||||
t.Fatalf("controller %s declares no single permission", ctl.ID())
|
||||
}
|
||||
required[ctl.ID()] = permissioned.RequiredPermissions()[0]
|
||||
if _, err := fs.Stat(plugin.AdminFS(), ctl.ConfigDir()+"/config_list.yaml"); err != nil {
|
||||
t.Fatalf("controller %s: %v", ctl.ID(), err)
|
||||
}
|
||||
}
|
||||
for _, item := range sides {
|
||||
if required[item.controller] != item.permission {
|
||||
t.Fatalf("side item %s asks for %s, its controller for %s", item.code, item.permission, required[item.controller])
|
||||
}
|
||||
}
|
||||
|
||||
// Every embedded admin file is readable and not empty.
|
||||
wantFiles := []string{
|
||||
"controllers/organisations/config_form.yaml", "controllers/organisations/config_list.yaml", "controllers/organisations/config_relation.yaml",
|
||||
"controllers/usergroups/config_form.yaml", "controllers/usergroups/config_list.yaml",
|
||||
"controllers/users/_hint.htm", "controllers/users/config_filter.yaml", "controllers/users/config_form.yaml", "controllers/users/config_list.yaml",
|
||||
"models/organisation/columns.yaml", "models/organisation/fields.yaml",
|
||||
"models/user/columns.yaml", "models/user/fields.yaml",
|
||||
"models/usergroup/columns.yaml", "models/usergroup/fields.yaml",
|
||||
}
|
||||
var files []string
|
||||
keys := map[string]string{}
|
||||
collect := func(source string, text []byte) {
|
||||
for _, key := range langKey.FindAllString(string(text), -1) {
|
||||
if _, seen := keys[key]; !seen {
|
||||
keys[key] = source
|
||||
}
|
||||
}
|
||||
}
|
||||
err := fs.WalkDir(plugin.AdminFS(), ".", func(name string, entry fs.DirEntry, err error) error {
|
||||
if err != nil || entry.IsDir() {
|
||||
return err
|
||||
}
|
||||
data, err := fs.ReadFile(plugin.AdminFS(), name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(data) == 0 {
|
||||
t.Errorf("embedded admin file %s is empty", name)
|
||||
}
|
||||
files = append(files, name)
|
||||
collect(name, data)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sort.Strings(files)
|
||||
if !reflect.DeepEqual(files, wantFiles) {
|
||||
t.Fatalf("embedded admin files = %v, want %v", files, wantFiles)
|
||||
}
|
||||
// Every admin file on disk is embedded: a new YAML file that is not in the
|
||||
// embed list would be missing from the binary.
|
||||
for _, pattern := range []string{"controllers/*/*.yaml", "controllers/*/_*.htm", "models/*/*.yaml"} {
|
||||
onDisk, err := filepath.Glob(pattern)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range onDisk {
|
||||
if _, err := fs.Stat(plugin.AdminFS(), filepath.ToSlash(name)); err != nil {
|
||||
t.Errorf("%s is on disk and not embedded", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The phrase keys of the Go side: literal keys in the sources, and the
|
||||
// labels, confirms and messages the registered actions name.
|
||||
for _, pattern := range []string{"*.go", "controllers/*.go", "classes/*.go"} {
|
||||
sources, err := filepath.Glob(pattern)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range sources {
|
||||
if strings.HasSuffix(name, "_test.go") {
|
||||
continue
|
||||
}
|
||||
data, err := os.ReadFile(name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
collect(name, data)
|
||||
}
|
||||
}
|
||||
for _, permission := range plugin.Permissions() {
|
||||
keys[permission.Label], keys[permission.Tab] = "permissions", "permissions"
|
||||
}
|
||||
keys[nav[0].Label] = "navigation"
|
||||
for _, item := range nav[0].SideMenu {
|
||||
keys[item.Label] = "navigation"
|
||||
}
|
||||
for _, ctl := range ctls {
|
||||
if bulk, ok := ctl.(pact.HasAdminBulkActions); ok {
|
||||
for _, action := range bulk.AdminBulkActions() {
|
||||
keys[action.Label], keys[action.Confirm] = "bulk action "+action.Name, "bulk action "+action.Name
|
||||
keys["golem15.user::lang.users."+action.Name+"_selected_success"] = "bulk action " + action.Name
|
||||
}
|
||||
}
|
||||
if record, ok := ctl.(pact.HasAdminRecordActions); ok {
|
||||
for _, action := range record.AdminRecordActions() {
|
||||
keys[action.Label], keys[action.Confirm] = "record action "+action.Name, "record action "+action.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"activated_success", "unbanned_success", "unsuspend_success"} {
|
||||
keys["golem15.user::lang.users."+key] = "record action messages"
|
||||
}
|
||||
if len(keys) < 80 {
|
||||
t.Fatalf("only %d phrase keys were collected", len(keys))
|
||||
}
|
||||
|
||||
env := newAdminEnv(t)
|
||||
tr, ok := env.app.Lookup[*phrasebook.Translator]()
|
||||
if !ok {
|
||||
t.Fatal("no translator")
|
||||
}
|
||||
var missing []string
|
||||
for key, source := range keys {
|
||||
if !strings.HasPrefix(key, "golem15.user::lang.") {
|
||||
t.Errorf("%s names %q, which is not a phrase key of the plugin", source, key)
|
||||
continue
|
||||
}
|
||||
for _, locale := range []string{"en", "pl"} {
|
||||
if text := tr.GetIn(locale, key, nil); text == "" || text == key || strings.Contains(text, "::lang.") {
|
||||
missing = append(missing, locale+" "+key+" ("+source+")")
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(missing)
|
||||
if len(missing) > 0 {
|
||||
t.Fatalf("%d phrase keys do not resolve:\n%s", len(missing), strings.Join(missing, "\n"))
|
||||
}
|
||||
// The two locales carry the same keys.
|
||||
en, pl := tr.Bundle("en", "golem15.user::lang"), tr.Bundle("pl", "golem15.user::lang")
|
||||
if len(en) == 0 || len(en) != len(pl) {
|
||||
t.Fatalf("en has %d phrases, pl has %d", len(en), len(pl))
|
||||
}
|
||||
for key := range en {
|
||||
if _, ok := pl[key]; !ok {
|
||||
t.Errorf("pl lacks %s", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminNeedsSecret: a host application that loads the plugin mounts the
|
||||
// admin API, so assembling its routes without admin.jwt.secret fails loudly
|
||||
// instead of serving the screens unauthenticated.
|
||||
func TestAdminNeedsSecret(t *testing.T) {
|
||||
gdb, sqlDB := adminHarnessDB(t)
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: user-no-admin-secret\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{
|
||||
"SUMMER_ENV=development",
|
||||
"SUMMER_GOLEM15__USER__JWT__SECRET=" + sessionSecret,
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Everything else the router needs is set, so the secret is the one thing
|
||||
// missing.
|
||||
for key, value := range map[string]any{
|
||||
"http.body_limits.default_bytes": 1048576,
|
||||
"http.body_limits.upload_bytes": 8388608,
|
||||
} {
|
||||
if err := cfg.Set(key, value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
app := backpack.New(cfg)
|
||||
if err := lagoon.Publish(app, sqlDB, gdb); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plugins, err := party.Activate(app, []string{"golem15.user"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := surf.Assemble(app, plugins); err == nil || !strings.Contains(err.Error(), "admin.jwt.secret") {
|
||||
t.Fatalf("assembling without the admin secret: %v, want an error naming admin.jwt.secret", err)
|
||||
}
|
||||
// The registered plugin value now points at this app: boot a working
|
||||
// environment again for whatever runs next.
|
||||
newAdminEnv(t)
|
||||
}
|
||||
429
admin_users_edge_test.go
Normal file
429
admin_users_edge_test.go
Normal file
@@ -0,0 +1,429 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/controllers"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// TestAdminUsersGroupFilterValue (D-23): the groups filter takes a group id.
|
||||
// A value that is not one matches nobody (or is refused with 422 by the
|
||||
// framework); it must not reach the database as it is, where a non-numeric
|
||||
// text fails the whole list with a 500.
|
||||
func TestAdminUsersGroupFilterValue(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
token := env.admin(t, permAccessUsers)
|
||||
marker := "gfilter" + adminStamp()
|
||||
group := env.seedGroup(t, "Filter "+marker, "")
|
||||
member := env.seedUser(t, marker, nil)
|
||||
other := env.seedUser(t, marker, nil)
|
||||
env.join(t, member, group)
|
||||
|
||||
gid := strconv.FormatUint(uint64(group.ID), 10)
|
||||
if page := env.users(t, token, "search="+marker+"&filter[groups]="+gid); page.Total != 1 || !page.has(member.ID) || page.has(other.ID) {
|
||||
t.Fatalf("group filter = %s", page.Raw)
|
||||
}
|
||||
for _, value := range []string{"abc", "1%20OR%201=1", "-1", "0", "1.5", "99999999999999999999", gid + "x"} {
|
||||
rec := env.call(t, http.MethodGet, adminAPI(adminUsersPath)+"?search="+marker+"&filter[groups]="+value, token, nil)
|
||||
// The framework refuses a value it cannot read as a scope argument
|
||||
// with 422; whatever it lets through must list nobody.
|
||||
if rec.Code == http.StatusUnprocessableEntity {
|
||||
continue
|
||||
}
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("filter[groups]=%s answers %d: %s", value, rec.Code, rec.Body.String())
|
||||
}
|
||||
var rows []map[string]any
|
||||
adminInto(t, rec, &rows)
|
||||
if len(rows) != 0 {
|
||||
t.Fatalf("filter[groups]=%s lists %d users, want none", value, len(rows))
|
||||
}
|
||||
}
|
||||
// The list without the filter is unaffected.
|
||||
if page := env.users(t, token, "search="+marker); page.Total != 2 {
|
||||
t.Fatalf("unfiltered list = %s", page.Raw)
|
||||
}
|
||||
}
|
||||
|
||||
// adminControllerSet is the plugin's three admin controllers built on one app
|
||||
// accessor, by controller id.
|
||||
type adminControllerSet map[string]pact.AdminController
|
||||
|
||||
func adminControllersOn(app func() *backpack.App) adminControllerSet {
|
||||
out := adminControllerSet{}
|
||||
for _, ctl := range controllers.AdminControllers(app) {
|
||||
out[ctl.ID()] = ctl
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// bareApp is a booted application value without a database handle, a bucket
|
||||
// or a translator.
|
||||
func bareApp(t *testing.T) *backpack.App {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: user-bare\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{"SUMMER_ENV=development"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return backpack.New(cfg)
|
||||
}
|
||||
|
||||
// brokenApp is an application whose database handle fails every query: its
|
||||
// connection pool is closed.
|
||||
func brokenApp(t *testing.T) (*backpack.App, *gorm.DB) {
|
||||
t.Helper()
|
||||
adminHarnessDB(t)
|
||||
u, err := url.Parse(sessionDSN)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u.Path = "/user_admin"
|
||||
db, err := sql.Open("pgx", u.String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gdb, err := lagoon.Use(t.Context(), db)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
app := bareApp(t)
|
||||
if err := lagoon.Publish(app, db, gdb); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return app, gdb
|
||||
}
|
||||
|
||||
// wantPlainError asserts that err is an ordinary error: the framework answers
|
||||
// it as the opaque 500. A ForbiddenError or a ValidationError would be shown
|
||||
// to the administrator.
|
||||
func wantPlainError(t *testing.T, what string, err error) {
|
||||
t.Helper()
|
||||
var forbidden *cabana.ForbiddenError
|
||||
var invalid *cabana.ValidationError
|
||||
if err == nil || errors.As(err, &forbidden) || errors.As(err, &invalid) {
|
||||
t.Fatalf("%s: err = %v, want a plain error", what, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminUsersControllerGuards drives the Users controller directly, the
|
||||
// way the framework calls it, on the inputs the HTTP tests cannot produce: a
|
||||
// record of another type, an application that is not booted, one without a
|
||||
// database handle and one whose database fails. Each ends in a plain error
|
||||
// (the opaque 500) or the documented empty answer; none passes a guard.
|
||||
func TestAdminUsersControllerGuards(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
notUser := &models.UserGroup{}
|
||||
var nilUser *models.User
|
||||
user := &models.User{ID: 987654001, Email: "guards@example.test"}
|
||||
|
||||
sets := map[string]adminControllerSet{
|
||||
"no accessor": adminControllersOn(nil),
|
||||
"not booted": adminControllersOn(func() *backpack.App { return nil }),
|
||||
"no database": adminControllersOn(func() *backpack.App { return bareApp(t) }),
|
||||
"a failing handle": nil,
|
||||
"the live database": nil,
|
||||
}
|
||||
broken, brokenDB := brokenApp(t)
|
||||
sets["a failing handle"] = adminControllersOn(func() *backpack.App { return broken })
|
||||
env := newAdminEnv(t)
|
||||
sets["the live database"] = adminControllersOn(func() *backpack.App { return env.app })
|
||||
|
||||
for name, set := range sets {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ctl := set["golem15.user.users"]
|
||||
live := name == "the live database"
|
||||
|
||||
// Records of another type and nil records.
|
||||
for _, record := range []any{notUser, nilUser, nil} {
|
||||
wantPlainError(t, "FormBeforeUpdate", ctl.(pact.FormBeforeUpdate).FormBeforeUpdate(ctx, record))
|
||||
wantPlainError(t, "FormBeforeCreate", ctl.(pact.FormBeforeCreate).FormBeforeCreate(ctx, record))
|
||||
wantPlainError(t, "FormAfterCreate", ctl.(pact.FormAfterCreate).FormAfterCreate(ctx, record))
|
||||
wantPlainError(t, "FormBeforeDelete", ctl.(pact.FormBeforeDelete).FormBeforeDelete(ctx, record))
|
||||
wantPlainError(t, "FormAfterDelete", ctl.(pact.FormAfterDelete).FormAfterDelete(ctx, record))
|
||||
_, err := ctl.(pact.ListRowStates).ListRowStates(ctx, env.gdb, []any{record})
|
||||
wantPlainError(t, "ListRowStates", err)
|
||||
editor := ctl.(cabana.PermissionEditorProvider)
|
||||
_, err = editor.AdminPermissionValues(ctx, "permissions", record)
|
||||
wantPlainError(t, "AdminPermissionValues", err)
|
||||
wantPlainError(t, "AdminSetPermissionValues", editor.AdminSetPermissionValues(ctx, "permissions", record, map[string]int{"a": 1}))
|
||||
for _, action := range ctl.(pact.HasAdminBulkActions).AdminBulkActions() {
|
||||
_, err := action.Run(ctx, pact.AdminBulkActionInput{Records: []any{record}})
|
||||
wantPlainError(t, "bulk "+action.Name, err)
|
||||
}
|
||||
for _, action := range ctl.(pact.HasAdminRecordActions).AdminRecordActions() {
|
||||
_, err := action.Applies(ctx, record)
|
||||
wantPlainError(t, "applies "+action.Name, err)
|
||||
_, err = action.Run(ctx, pact.AdminRecordActionInput{Record: record})
|
||||
wantPlainError(t, "record "+action.Name, err)
|
||||
}
|
||||
}
|
||||
// The hint of a record that is not a user is empty, never an error.
|
||||
if data, err := ctl.(pact.AdminPartialData).PartialData(ctx, "hint", notUser); err != nil || !reflect.ValueOf(data).IsZero() {
|
||||
t.Fatalf("hint of another record = %+v %v", data, err)
|
||||
}
|
||||
if _, err := ctl.(pact.AdminPartialData).PartialData(ctx, "other", user); err == nil || !strings.Contains(err.Error(), `unknown partial "other"`) {
|
||||
t.Fatalf("unknown partial: %v", err)
|
||||
}
|
||||
|
||||
// Wrong field names.
|
||||
editor := ctl.(cabana.PermissionEditorProvider)
|
||||
if _, err := editor.AdminPermissionOptions(ctx, "groups"); err == nil {
|
||||
t.Fatal("permission options for another field")
|
||||
}
|
||||
if _, err := editor.AdminPermissionValues(ctx, "groups", user); err == nil {
|
||||
t.Fatal("permission values for another field")
|
||||
}
|
||||
if err := editor.AdminSetPermissionValues(ctx, "groups", user, nil); err == nil {
|
||||
t.Fatal("permission write for another field")
|
||||
}
|
||||
if lock, err := ctl.(cabana.RelationLockProvider).AdminRelationLocks(ctx, "organisation"); err != nil || len(lock.IDs) != 0 || lock.Message != "" {
|
||||
t.Fatalf("locks of another field = %+v %v", lock, err)
|
||||
}
|
||||
if options := ctl.(pact.FilterOptions).FilterOptions("other"); options != nil {
|
||||
t.Fatalf("options of another scope = %v", options)
|
||||
}
|
||||
if ctl.(pact.ListExtendQuery).ListExtendQuery(ctx, nil) != nil || ctl.(pact.FormExtendQuery).FormExtendQuery(ctx, nil) != nil {
|
||||
t.Fatal("an extend query invented a handle")
|
||||
}
|
||||
|
||||
// A bulk or record action outside a transaction never writes.
|
||||
for _, action := range ctl.(pact.HasAdminBulkActions).AdminBulkActions() {
|
||||
_, err := action.Run(ctx, pact.AdminBulkActionInput{Records: []any{user}})
|
||||
wantPlainError(t, "bulk "+action.Name+" without a transaction", err)
|
||||
}
|
||||
for _, action := range ctl.(pact.HasAdminRecordActions).AdminRecordActions() {
|
||||
_, err := action.Run(ctx, pact.AdminRecordActionInput{Record: user})
|
||||
wantPlainError(t, "record "+action.Name+" without a transaction", err)
|
||||
}
|
||||
wantPlainError(t, "FormAfterDelete without a transaction", ctl.(pact.FormAfterDelete).FormAfterDelete(ctx, user))
|
||||
|
||||
if live {
|
||||
// On a working database the same calls answer, and an update
|
||||
// of a user who does not exist is an error, not a pass.
|
||||
wantPlainError(t, "update of an unknown user", ctl.(pact.FormBeforeUpdate).FormBeforeUpdate(ctx, user))
|
||||
if options := ctl.(pact.FilterOptions).FilterOptions(models.FilterByGroup); options == nil {
|
||||
t.Fatal("no group choices on a working database")
|
||||
}
|
||||
if lock, err := ctl.(cabana.RelationLockProvider).AdminRelationLocks(ctx, "groups"); err != nil || lock.Message == "" {
|
||||
t.Fatalf("locks without a principal = %+v %v, want the locks", lock, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Without a working database every read that a guard depends on
|
||||
// is an error: the guard never answers "not privileged".
|
||||
wantPlainError(t, "FormBeforeUpdate", ctl.(pact.FormBeforeUpdate).FormBeforeUpdate(ctx, user))
|
||||
wantPlainError(t, "FormBeforeCreate", ctl.(pact.FormBeforeCreate).FormBeforeCreate(ctx, user))
|
||||
wantPlainError(t, "FormBeforeDelete", ctl.(pact.FormBeforeDelete).FormBeforeDelete(ctx, user))
|
||||
_, err := ctl.(cabana.RelationLockProvider).AdminRelationLocks(ctx, "groups")
|
||||
wantPlainError(t, "AdminRelationLocks", err)
|
||||
_, err = editor.AdminPermissionOptions(ctx, "permissions")
|
||||
wantPlainError(t, "AdminPermissionOptions", err)
|
||||
_, err = ctl.(pact.AdminPartialData).PartialData(ctx, "hint", user)
|
||||
wantPlainError(t, "PartialData", err)
|
||||
for _, action := range ctl.(pact.HasAdminRecordActions).AdminRecordActions() {
|
||||
if action.Name == "activate" {
|
||||
continue // reads the record only
|
||||
}
|
||||
_, err := action.Applies(ctx, user)
|
||||
wantPlainError(t, "applies "+action.Name, err)
|
||||
}
|
||||
if options := ctl.(pact.FilterOptions).FilterOptions(models.FilterByGroup); options != nil {
|
||||
t.Fatalf("group choices without a database = %v", options)
|
||||
}
|
||||
if name == "a failing handle" {
|
||||
_, err := ctl.(pact.ListRowStates).ListRowStates(ctx, brokenDB, []any{user})
|
||||
wantPlainError(t, "ListRowStates on a failing handle", err)
|
||||
}
|
||||
|
||||
// A principal who holds the extra permission, and a superuser,
|
||||
// pass the delete guard before any query is made (D-30).
|
||||
for _, principal := range []*bouncer.Principal{
|
||||
{PermissionGrants: map[string]bool{permManagePrivileged: true}},
|
||||
{IsSuperuser: true},
|
||||
} {
|
||||
if err := ctl.(pact.FormBeforeDelete).FormBeforeDelete(bouncer.WithUser(ctx, principal), user); err != nil {
|
||||
t.Fatalf("delete guard for %+v: %v", principal, err)
|
||||
}
|
||||
if lock, err := ctl.(cabana.RelationLockProvider).AdminRelationLocks(bouncer.WithUser(ctx, principal), "groups"); err != nil || len(lock.IDs) != 0 {
|
||||
t.Fatalf("locks for %+v = %+v %v", principal, lock, err)
|
||||
}
|
||||
}
|
||||
// One who holds only the screen's permission does not.
|
||||
limited := bouncer.WithUser(ctx, &bouncer.Principal{PermissionGrants: map[string]bool{permAccessUsers: true}})
|
||||
wantPlainError(t, "delete guard without the extra permission", ctl.(pact.FormBeforeDelete).FormBeforeDelete(limited, user))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminUsersEdge covers the remaining branches of the Users screen
|
||||
// through the admin API: an unknown partial, an undeclared filter, options
|
||||
// of a field that has none, search and sort, the superuser, and a membership
|
||||
// query that fails while the takeover guard needs it (D-30).
|
||||
func TestAdminUsersEdge(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
token := env.admin(t, permAccessUsers)
|
||||
marker := "edge" + adminStamp()
|
||||
surname := "Sur" + marker
|
||||
first := env.seedUser(t, "a-"+marker, func(u *models.User) { u.Surname = &surname })
|
||||
second := env.seedUser(t, "b-"+marker, nil)
|
||||
third := env.seedUser(t, "c-"+marker, nil)
|
||||
id := strconv.FormatUint(uint64(first.ID), 10)
|
||||
|
||||
// Partials: only the declared hint is served.
|
||||
for _, name := range []string{"nope", "status", "_hint", "hint.htm", "..%2Fhint"} {
|
||||
rec := env.call(t, http.MethodGet, adminAPI(adminUsersPath+"/partials/"+name+"?id="+id), token, nil)
|
||||
if rec.Code != http.StatusNotFound && rec.Code != http.StatusBadRequest && rec.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("partial %s answers %d: %s", name, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertNoSecret(t, rec.Body.String())
|
||||
}
|
||||
env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminUsersPath+"/partials/hint?id="+id), token, nil)
|
||||
env.expect(t, http.StatusNotFound, http.MethodGet, adminAPI(adminUsersPath+"/partials/hint?id=987654321"), token, nil)
|
||||
|
||||
// Filters: an undeclared name and a malformed value are 422, never a
|
||||
// query.
|
||||
for _, query := range []string{
|
||||
"filter[nope]=1", "filter[password]=x", "filter[activated]=maybe",
|
||||
"filter[created_date]=yesterday", "filter[created_date]=2020-06-30..2020-06-01x",
|
||||
} {
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodGet, adminAPI(adminUsersPath)+"?"+query, token, nil)
|
||||
}
|
||||
// Options exist for the groups filter and the two relation fields only.
|
||||
for _, path := range []string{
|
||||
"/filters/activated/options", "/filters/created_date/options", "/filters/nope/options",
|
||||
"/fields/name/options", "/fields/password/options", "/fields/permissions/options", "/fields/nope/options",
|
||||
} {
|
||||
rec := env.call(t, http.MethodGet, adminAPI(adminUsersPath+path), token, nil)
|
||||
if rec.Code != http.StatusNotFound && rec.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("%s answers %d: %s", path, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Search reaches the invisible surname column; sort orders both ways and
|
||||
// refuses a column that is not sortable.
|
||||
if page := env.users(t, token, "search="+surname); page.Total != 1 || !page.has(first.ID) {
|
||||
t.Fatalf("surname search = %s", page.Raw)
|
||||
}
|
||||
order := func(query string) []uint {
|
||||
ids := []uint{}
|
||||
for _, row := range env.users(t, token, "search="+marker+"&"+query).Rows {
|
||||
ids = append(ids, uint(row["id"].(float64)))
|
||||
}
|
||||
return ids
|
||||
}
|
||||
if got, want := order("sort=email&dir=asc"), []uint{first.ID, second.ID, third.ID}; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("email asc = %v, want %v", got, want)
|
||||
}
|
||||
if got, want := order("sort=email&dir=desc"), []uint{third.ID, second.ID, first.ID}; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("email desc = %v, want %v", got, want)
|
||||
}
|
||||
if got, want := order("sort=id&dir=desc"), []uint{third.ID, second.ID, first.ID}; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("id desc = %v, want %v", got, want)
|
||||
}
|
||||
for _, query := range []string{"sort=password", "sort=permissions", "sort=email&dir=sideways", "sort=email%3Bdrop", "per_page=2"} {
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodGet, adminAPI(adminUsersPath)+"?"+query, token, nil)
|
||||
}
|
||||
|
||||
// D-30: a superuser needs no extra permission for a privileged member.
|
||||
code := "edgepriv-" + marker
|
||||
privileged := func(cfg *compass.Config) {
|
||||
if err := cfg.Set("golem15.user.privileged_groups", []string{code}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
env = newAdminEnv(t, privileged)
|
||||
limited := env.admin(t, permAccessUsers)
|
||||
super := env.admin(t)
|
||||
if err := env.gdb.Exec(`UPDATE backend_users SET is_superuser = TRUE WHERE id = (SELECT MAX(id) FROM backend_users)`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
group := env.seedGroup(t, "Edge privileged "+marker, code)
|
||||
member := env.seedUser(t, "member-"+marker, nil)
|
||||
env.join(t, member, group)
|
||||
env.expect(t, http.StatusForbidden, http.MethodPut, userPath(member.ID, ""), limited, map[string]any{"email": "taken-" + marker + "@example.test"})
|
||||
renamed := "super-" + marker + "@example.test"
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(member.ID, ""), super, map[string]any{"email": renamed})
|
||||
if got := env.reload(t, member.ID); got.Email != renamed {
|
||||
t.Fatalf("superuser update: email = %s", got.Email)
|
||||
}
|
||||
|
||||
// D-30: when the membership cannot be read, the guard does not let the
|
||||
// request through. The answer is the opaque 500 and nothing changes.
|
||||
before := env.reload(t, member.ID)
|
||||
victim := env.seedUser(t, "victim-"+marker, nil)
|
||||
rename := func(from, to string) {
|
||||
t.Helper()
|
||||
if err := env.gdb.Exec(`ALTER TABLE ` + from + ` RENAME TO ` + to).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rename("users_groups", "users_groups_away")
|
||||
restored := false
|
||||
restore := func() {
|
||||
if !restored {
|
||||
restored = true
|
||||
rename("users_groups_away", "users_groups")
|
||||
}
|
||||
}
|
||||
t.Cleanup(restore)
|
||||
for what, rec := range map[string]interface {
|
||||
Result() *http.Response
|
||||
}{
|
||||
"email change": env.call(t, http.MethodPut, userPath(member.ID, ""), limited, map[string]any{"email": "stolen-" + marker + "@example.test"}),
|
||||
"password reset": env.call(t, http.MethodPut, userPath(member.ID, ""), limited, map[string]any{"password": "stolen-secret-1", "password_confirmation": "stolen-secret-1"}),
|
||||
"delete": env.call(t, http.MethodDelete, userPath(member.ID, ""), limited, nil),
|
||||
"bulk delete": env.bulk(t, limited, "delete", victim, member),
|
||||
"ordinary delete": env.call(t, http.MethodDelete, userPath(victim.ID, ""), limited, nil),
|
||||
} {
|
||||
res := rec.Result()
|
||||
body := make([]byte, 4096)
|
||||
n, _ := res.Body.Read(body)
|
||||
text := string(body[:n])
|
||||
if res.StatusCode != http.StatusInternalServerError {
|
||||
t.Fatalf("%s with an unreadable membership answers %d: %s", what, res.StatusCode, text)
|
||||
}
|
||||
if strings.Contains(text, "users_groups") || strings.Contains(strings.ToLower(text), "sqlstate") || strings.Contains(text, "relation") {
|
||||
t.Fatalf("%s leaks the database error: %s", what, text)
|
||||
}
|
||||
}
|
||||
restore()
|
||||
after := env.reload(t, member.ID)
|
||||
if after == nil || after.Email != before.Email || after.Password != before.Password || !reflect.DeepEqual(after.TokensValidAfter, before.TokensValidAfter) {
|
||||
t.Fatalf("a failed guard changed the member: %+v", after)
|
||||
}
|
||||
if env.reload(t, victim.ID) == nil {
|
||||
t.Fatal("a failed guard deleted a user")
|
||||
}
|
||||
if got := env.groupIDs(t, member.ID); !reflect.DeepEqual(got, []uint{group.ID}) {
|
||||
t.Fatalf("memberships after the failed guard = %v", got)
|
||||
}
|
||||
if status, _ := env.userLogin(t, before.Email, "correct-horse"); status != http.StatusOK {
|
||||
t.Fatalf("login with the old password = %d", status)
|
||||
}
|
||||
}
|
||||
1501
admin_users_test.go
Normal file
1501
admin_users_test.go
Normal file
File diff suppressed because it is too large
Load Diff
104
api_tokens_edge_test.go
Normal file
104
api_tokens_edge_test.go
Normal file
@@ -0,0 +1,104 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/controllers"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
)
|
||||
|
||||
// TestAPITokenManagementRefusals covers the refusals of the personal API
|
||||
// token routes: no application, no principal, invalid bodies, and a token
|
||||
// that is not the caller's.
|
||||
func TestAPITokenManagementRefusals(t *testing.T) {
|
||||
app, db := sessionApp(t, "0s")
|
||||
if err := app.Config.Set("golem15.user.api_tokens.prefix", "usr_"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner := insertUser(t, db, "token-owner@example.test", "correct-horse")
|
||||
stranger := insertUser(t, db, "token-stranger@example.test", "correct-horse")
|
||||
|
||||
call := func(handler http.Handler, method, body, id string, userID uint) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, "/_user/api/v1/tokens", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if id != "" {
|
||||
req.SetPathValue("id", id)
|
||||
}
|
||||
if userID != 0 {
|
||||
req = req.WithContext(bouncer.WithUser(req.Context(), &bouncer.Principal{ID: userID}))
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// Without an application or a principal nothing is served.
|
||||
for name, handler := range map[string]http.Handler{
|
||||
"store": controllers.APITokenStore(nil), "index": controllers.APITokenIndex(nil), "destroy": controllers.APITokenDestroy(nil),
|
||||
} {
|
||||
if rec := call(handler, http.MethodPost, `{"name":"x"}`, "1", owner.ID); rec.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("%s without an application = %d", name, rec.Code)
|
||||
}
|
||||
}
|
||||
for name, handler := range map[string]http.Handler{
|
||||
"store": controllers.APITokenStore(app), "index": controllers.APITokenIndex(app), "destroy": controllers.APITokenDestroy(app),
|
||||
} {
|
||||
if rec := call(handler, http.MethodPost, `{"name":"x"}`, "1", 0); rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("%s without a principal = %d %s", name, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Invalid bodies are 422 on the field and mint nothing.
|
||||
for body, field := range map[string]string{
|
||||
`{}`: "name",
|
||||
`{"name":" "}`: "name",
|
||||
`{"name":"` + strings.Repeat("n", 256) + `"}`: "name",
|
||||
`{"name":"a","scopes":"read"}`: "scopes",
|
||||
`{"name":"a","scopes":["nope"]}`: "scopes",
|
||||
`{"name":"a","scopes":[1]}`: "scopes",
|
||||
`{"name":"a","expires_at":"tomorrow"}`: "expires_at",
|
||||
} {
|
||||
rec := call(controllers.APITokenStore(app), http.MethodPost, body, "", owner.ID)
|
||||
if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), `"`+field+`"`) {
|
||||
t.Fatalf("store %s = %d %s, want 422 on %s", body, rec.Code, rec.Body.String(), field)
|
||||
}
|
||||
}
|
||||
var minted int64
|
||||
if err := db.Model(&models.APIToken{}).Where("user_id = ?", owner.ID).Count(&minted).Error; err != nil || minted != 0 {
|
||||
t.Fatalf("tokens after refused creates = %d err = %v", minted, err)
|
||||
}
|
||||
|
||||
// A token with an expiry is minted; only its owner can revoke it.
|
||||
created := call(controllers.APITokenStore(app), http.MethodPost, `{"name":"expiring","expires_at":"2099-01-02T03:04:05Z"}`, "", owner.ID)
|
||||
if created.Code != http.StatusCreated {
|
||||
t.Fatalf("create = %d %s", created.Code, created.Body.String())
|
||||
}
|
||||
var token models.APIToken
|
||||
if err := db.Where("user_id = ?", owner.ID).First(&token).Error; err != nil || token.ExpiresAt == nil {
|
||||
t.Fatalf("stored token = %+v err = %v", token, err)
|
||||
}
|
||||
id := strconv.FormatUint(uint64(token.ID), 10)
|
||||
for _, bad := range []string{"", "0", "abc", "-1", "987654321"} {
|
||||
if rec := call(controllers.APITokenDestroy(app), http.MethodDelete, "", bad, owner.ID); rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("destroy %q = %d %s", bad, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
if rec := call(controllers.APITokenDestroy(app), http.MethodDelete, "", id, stranger.ID); rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("destroy by another user = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := call(controllers.APITokenIndex(app), http.MethodGet, "", "", stranger.ID); rec.Code != http.StatusOK || strings.Contains(rec.Body.String(), "expiring") {
|
||||
t.Fatalf("another user's list = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := call(controllers.APITokenDestroy(app), http.MethodDelete, "", id, owner.ID); rec.Code != http.StatusOK {
|
||||
t.Fatalf("destroy = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := call(controllers.APITokenIndex(app), http.MethodGet, "", "", owner.ID); rec.Code != http.StatusOK || strings.Contains(rec.Body.String(), "expiring") {
|
||||
t.Fatalf("list after the revoke = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
136
avatar_url_test.go
Normal file
136
avatar_url_test.go
Normal file
@@ -0,0 +1,136 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/controllers"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"gocloud.dev/blob/memblob"
|
||||
)
|
||||
|
||||
// jpegAvatar stores a real JPEG avatar for user (a system_files row and its
|
||||
// blob) and returns the row.
|
||||
func (e *adminEnv) jpegAvatar(t *testing.T, user *models.User) attach.File {
|
||||
t.Helper()
|
||||
disk := "face" + adminStamp() + ".jpg"
|
||||
data := jpegBytes(t)
|
||||
if err := e.bucket.WriteAll(context.Background(), attach.BlobKey(disk), data, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
row := attach.File{
|
||||
DiskName: disk, FileName: "face.jpg", FileSize: int64(len(data)), ContentType: "image/jpeg",
|
||||
Field: models.AvatarField, AttachmentID: strconv.FormatUint(uint64(user.ID), 10), AttachmentType: user.MorphName(),
|
||||
}
|
||||
if err := e.gdb.Create(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return row
|
||||
}
|
||||
|
||||
func gravatarFor(email string, size int) string {
|
||||
return fmt.Sprintf("//www.gravatar.com/avatar/%x?s=%d&d=mm", md5.Sum([]byte(strings.ToLower(strings.TrimSpace(email)))), size)
|
||||
}
|
||||
|
||||
// TestAvatarURL pins classes.AvatarURL (D-05): the avatar thumbnail at the
|
||||
// asked size, the file path when the thumbnail fails, the gravatar
|
||||
// fallback with the size, errors only for a failing lookup, and the user
|
||||
// API payload (applyAvatar) unchanged: its avatar_url is AvatarURL at 128.
|
||||
func TestAvatarURL(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
ctx := t.Context()
|
||||
|
||||
if _, err := classes.AvatarURL(ctx, env.app, nil, 128); err == nil {
|
||||
t.Fatal("a nil user must be refused")
|
||||
}
|
||||
|
||||
// Gravatar: no app, an unsaved user, no attachment; the email is
|
||||
// trimmed and lower-cased, the size is the one asked for.
|
||||
plain := env.seedUser(t, "plain", func(u *models.User) { u.Email = " Mixed.Case-" + adminStamp() + "@Example.TEST " })
|
||||
for _, size := range []int{32, 128, 256} {
|
||||
for name, call := range map[string]func() (string, error){
|
||||
"no app": func() (string, error) { return classes.AvatarURL(ctx, nil, plain, size) },
|
||||
"unsaved user": func() (string, error) { return classes.AvatarURL(ctx, env.app, &models.User{Email: plain.Email}, size) },
|
||||
"no attachment": func() (string, error) { return classes.AvatarURL(ctx, env.app, plain, size) },
|
||||
} {
|
||||
got, err := call()
|
||||
if err != nil || got != gravatarFor(plain.Email, size) {
|
||||
t.Fatalf("%s at %d = %q %v, want %q", name, size, got, err, gravatarFor(plain.Email, size))
|
||||
}
|
||||
}
|
||||
}
|
||||
if gravatarFor(plain.Email, 1) != gravatarFor(strings.ToLower(strings.TrimSpace(plain.Email)), 1) {
|
||||
t.Fatal("the gravatar hash is not of the normalised email")
|
||||
}
|
||||
|
||||
// A file avatar: the thumbnail at size by size, mode auto.
|
||||
withFile := env.seedUser(t, "withfile", nil)
|
||||
row := env.jpegAvatar(t, withFile)
|
||||
thumb, err := classes.AvatarURL(ctx, env.app, withFile, 64)
|
||||
want := attach.ThumbFilename(row.ID, 64, 64, 0, 0, "auto", "jpg")
|
||||
if err != nil || !strings.HasSuffix(thumb, want) || strings.HasPrefix(thumb, "//") {
|
||||
t.Fatalf("thumbnail = %q %v, want a path ending in %s", thumb, err, want)
|
||||
}
|
||||
// Without a published bucket the gravatar is used even with a file.
|
||||
noBucket := sessionUserApp(t, "SUMMER_GOLEM15__USER__JWT__SECRET="+sessionSecret)
|
||||
if err := noBucket.Publish(env.gdb); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := classes.AvatarURL(ctx, noBucket, withFile, 64); err != nil || got != gravatarFor(withFile.Email, 64) {
|
||||
t.Fatalf("no bucket = %q %v", got, err)
|
||||
}
|
||||
|
||||
// An original that does not decode gets WinterCMS's broken-image
|
||||
// thumbnail, still a thumbnail path.
|
||||
notImage := env.seedUser(t, "notimage", nil)
|
||||
env.seedAvatar(t, notImage) // its blob is not an image
|
||||
if got, err := classes.AvatarURL(ctx, env.app, notImage, 128); err != nil || !strings.Contains(got, "thumb_") {
|
||||
t.Fatalf("non-image avatar = %q %v", got, err)
|
||||
}
|
||||
// A thumbnail that cannot be made (here: the storage fails) falls back
|
||||
// to the file path.
|
||||
closed := memblob.OpenBucket(nil)
|
||||
_ = closed.Close()
|
||||
failing := sessionUserApp(t, "SUMMER_GOLEM15__USER__JWT__SECRET="+sessionSecret)
|
||||
if err := failing.Publish(env.gdb); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := attach.Publish(failing, closed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := classes.AvatarURL(ctx, failing, withFile, 128); err != nil || got != "/"+attach.BlobKey(row.DiskName) {
|
||||
t.Fatalf("failing thumbnail = %q %v, want /%s", got, err, attach.BlobKey(row.DiskName))
|
||||
}
|
||||
|
||||
// A failing lookup is the only error.
|
||||
canceled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
if got, err := classes.AvatarURL(canceled, env.app, withFile, 128); err == nil {
|
||||
t.Fatalf("failing lookup = %q, want an error", got)
|
||||
}
|
||||
|
||||
// The user API payload is unchanged: avatar_url is AvatarURL at 128,
|
||||
// next to has_avatar and the disk name.
|
||||
payload, err := controllers.APIArray(ctx, env.app, withFile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
at128, _ := classes.AvatarURL(ctx, env.app, withFile, 128)
|
||||
if payload["has_avatar"] != true || payload["avatar"] != row.DiskName || payload["avatar_url"] != at128 {
|
||||
t.Fatalf("payload avatar fields = %v %v %v, want true %s %s", payload["has_avatar"], payload["avatar"], payload["avatar_url"], row.DiskName, at128)
|
||||
}
|
||||
without, err := controllers.APIArray(ctx, env.app, plain)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Without one the payload keeps its gravatar default (size 25).
|
||||
if without["has_avatar"] != false || without["avatar"] != gravatarFor(plain.Email, 25) {
|
||||
t.Fatalf("payload without an avatar = %v %v", without["has_avatar"], without["avatar"])
|
||||
}
|
||||
}
|
||||
272
classes/admin_actions.go
Normal file
272
classes/admin_actions.go
Normal file
@@ -0,0 +1,272 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"gocloud.dev/blob"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// The functions in this file are the admin screen's user actions. Each takes
|
||||
// the handle of the transaction the admin write runs in and never opens one
|
||||
// of its own. None of them writes users_groups, except the cleanup of a user
|
||||
// who is being deleted for good.
|
||||
|
||||
// ThrottleStates reads the ban and suspension state of userIDs from
|
||||
// user_throttle in one query. A user is banned when any of their rows is
|
||||
// banned, and suspended when a row is suspended and its suspended_at lies
|
||||
// inside the suspension window (golem15.user.throttle.suspension_minutes,
|
||||
// read from ctx as ContextWithThrottle stores it). It is a pure read: an
|
||||
// expired suspension is not lifted here.
|
||||
func ThrottleStates(ctx context.Context, db *gorm.DB, userIDs []uint) (banned, suspended map[uint]bool, err error) {
|
||||
banned, suspended = map[uint]bool{}, map[uint]bool{}
|
||||
if db == nil {
|
||||
return nil, nil, fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
if len(userIDs) == 0 {
|
||||
return banned, suspended, nil
|
||||
}
|
||||
minutes := throttleFrom(ctx).minutes
|
||||
if minutes <= 0 {
|
||||
minutes = 15
|
||||
}
|
||||
window := time.Duration(minutes) * time.Minute
|
||||
var rows []models.Throttle
|
||||
err = fresh(ctx, db).
|
||||
Where("user_id IN ? AND (is_banned OR is_suspended)", userIDs).
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
now := time.Now()
|
||||
for _, row := range rows {
|
||||
if row.IsBanned {
|
||||
banned[row.UserID] = true
|
||||
}
|
||||
if row.IsSuspended && row.SuspendedAt != nil && now.Before(row.SuspendedAt.Add(window)) {
|
||||
suspended[row.UserID] = true
|
||||
}
|
||||
}
|
||||
return banned, suspended, nil
|
||||
}
|
||||
|
||||
// ActivateUsers activates the users that are not active yet and returns how
|
||||
// many it changed. Like VerifyActivationCode it sets is_activated, stamps
|
||||
// activated_at, clears the activation code and restores a deactivated user.
|
||||
// Users that are already active are skipped.
|
||||
func ActivateUsers(ctx context.Context, db *gorm.DB, users []*models.User) (int, error) {
|
||||
if db == nil {
|
||||
return 0, fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
changed := 0
|
||||
for _, user := range users {
|
||||
if user == nil || user.ID == 0 || user.IsActivated {
|
||||
continue
|
||||
}
|
||||
now := time.Now()
|
||||
err := fresh(ctx, db).Unscoped().Model(&models.User{}).Where("id = ?", user.ID).UpdateColumns(map[string]any{
|
||||
"is_activated": true,
|
||||
"activated_at": now,
|
||||
"activation_code": nil,
|
||||
"activation_code_issued_at": nil,
|
||||
"deleted_at": nil,
|
||||
}).Error
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
user.IsActivated = true
|
||||
user.ActivatedAt = &now
|
||||
user.ActivationCode = nil
|
||||
user.ActivationCodeIssuedAt = nil
|
||||
user.DeletedAt = gorm.DeletedAt{}
|
||||
changed++
|
||||
}
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
// DeactivateUsers soft-deletes the users that are not deactivated yet, the
|
||||
// PHP $user->delete(), and returns how many it changed.
|
||||
func DeactivateUsers(ctx context.Context, db *gorm.DB, users []*models.User) (int, error) {
|
||||
if db == nil {
|
||||
return 0, fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
changed := 0
|
||||
for _, user := range users {
|
||||
if user == nil || user.ID == 0 || user.DeletedAt.Valid {
|
||||
continue
|
||||
}
|
||||
now := time.Now()
|
||||
err := fresh(ctx, db).Unscoped().Model(&models.User{}).Where("id = ?", user.ID).UpdateColumn("deleted_at", now).Error
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
user.DeletedAt = gorm.DeletedAt{Time: now, Valid: true}
|
||||
changed++
|
||||
}
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
// RestoreUsers brings deactivated users back, the PHP $user->restore(), and
|
||||
// returns how many it changed.
|
||||
func RestoreUsers(ctx context.Context, db *gorm.DB, users []*models.User) (int, error) {
|
||||
if db == nil {
|
||||
return 0, fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
changed := 0
|
||||
for _, user := range users {
|
||||
if user == nil || user.ID == 0 || !user.DeletedAt.Valid {
|
||||
continue
|
||||
}
|
||||
err := fresh(ctx, db).Unscoped().Model(&models.User{}).Where("id = ?", user.ID).UpdateColumn("deleted_at", nil).Error
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
user.DeletedAt = gorm.DeletedAt{}
|
||||
changed++
|
||||
}
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
// BanUsers bans the users and returns how many were not banned before. A ban
|
||||
// is set on every user_throttle row of the user, and a row without an IP
|
||||
// address is created when the user has none, so a login from any address is
|
||||
// refused (RejectIfThrottled falls back to that row).
|
||||
func BanUsers(ctx context.Context, db *gorm.DB, users []*models.User) (int, error) {
|
||||
ids, err := userIDs(db, users)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
banned, _, err := ThrottleStates(ctx, db, ids)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
changed := 0
|
||||
for _, id := range ids {
|
||||
if err := fresh(ctx, db).Model(&models.Throttle{}).Where("user_id = ?", id).UpdateColumn("is_banned", true).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var anyAddress int64
|
||||
if err := fresh(ctx, db).Model(&models.Throttle{}).Where("user_id = ? AND ip_address IS NULL", id).Count(&anyAddress).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if anyAddress == 0 {
|
||||
if err := fresh(ctx, db).Create(&models.Throttle{UserID: id, IsBanned: true}).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
if !banned[id] {
|
||||
changed++
|
||||
}
|
||||
}
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
// UnbanUsers clears the ban on every user_throttle row of the users and
|
||||
// returns how many were banned before.
|
||||
func UnbanUsers(ctx context.Context, db *gorm.DB, users []*models.User) (int, error) {
|
||||
ids, err := userIDs(db, users)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
banned, _, err := ThrottleStates(ctx, db, ids)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
changed := 0
|
||||
for _, id := range ids {
|
||||
if !banned[id] {
|
||||
continue
|
||||
}
|
||||
if err := fresh(ctx, db).Model(&models.Throttle{}).Where("user_id = ?", id).UpdateColumn("is_banned", false).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
changed++
|
||||
}
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
// UnsuspendUser lifts a suspension: it clears is_suspended, suspended_at and
|
||||
// the attempt counter on every user_throttle row of the user.
|
||||
func UnsuspendUser(ctx context.Context, db *gorm.DB, userID uint) error {
|
||||
if db == nil {
|
||||
return fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
return fresh(ctx, db).Model(&models.Throttle{}).Where("user_id = ?", userID).UpdateColumns(map[string]any{
|
||||
"is_suspended": false,
|
||||
"suspended_at": nil,
|
||||
"attempts": 0,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// ForceDeleteCleanup removes what hangs off a user who is being deleted for
|
||||
// good: the user_throttle rows (their foreign key has no ON DELETE), the
|
||||
// users_groups rows and the attachments. It runs inside the delete's
|
||||
// transaction and does not delete the user row; the caller does that with
|
||||
// the same handle. The attachments' blobs are removed only after the
|
||||
// transaction commits, so a rollback leaves the files in place. bucket may be
|
||||
// nil: the rows are still deleted.
|
||||
func ForceDeleteCleanup(ctx context.Context, db *gorm.DB, bucket *blob.Bucket, user *models.User) error {
|
||||
if db == nil {
|
||||
return fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
if user == nil || user.ID == 0 {
|
||||
return fmt.Errorf("golem15.user: cannot clean up a user without an id")
|
||||
}
|
||||
if err := fresh(ctx, db).Exec(`DELETE FROM user_throttle WHERE user_id = ?`, user.ID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := fresh(ctx, db).Exec(`DELETE FROM users_groups WHERE user_id = ?`, user.ID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
var keys []string
|
||||
err := attach.DeleteForOwner(fresh(ctx, db), user, strconv.FormatUint(uint64(user.ID), 10), func(blobKeys []string) error {
|
||||
keys = append(keys, blobKeys...)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if bucket == nil || len(keys) == 0 {
|
||||
return nil
|
||||
}
|
||||
userID := user.ID
|
||||
lagoon.AfterCommit(ctx, db, func(ctx context.Context, _ *gorm.DB) {
|
||||
// The rows are gone by now, so a blob that cannot be removed is
|
||||
// orphaned, not lost data: log it and carry on.
|
||||
if err := attach.DeleteKeys(ctx, bucket, keys); err != nil {
|
||||
slog.Default().Warn("golem15.user: remove attachment blobs of a deleted user", "user_id", userID, "err", err)
|
||||
}
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// fresh returns db with an empty statement on ctx, so a query never continues
|
||||
// from conditions the caller's handle already carries. A NewDB session is
|
||||
// lazy: GORM builds the empty statement on the next chain method, and a
|
||||
// WithContext chained directly onto it clones the caller's statement with its
|
||||
// conditions instead. Clauses() makes the empty statement exist first, so the
|
||||
// handle stays clean whatever is chained next.
|
||||
func fresh(ctx context.Context, db *gorm.DB) *gorm.DB {
|
||||
return db.Session(&gorm.Session{NewDB: true, Context: ctx}).Clauses().Session(&gorm.Session{NewDB: true})
|
||||
}
|
||||
|
||||
// userIDs returns the ids of users, skipping nil and unsaved entries.
|
||||
func userIDs(db *gorm.DB, users []*models.User) ([]uint, error) {
|
||||
if db == nil {
|
||||
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
ids := make([]uint, 0, len(users))
|
||||
for _, user := range users {
|
||||
if user != nil && user.ID != 0 {
|
||||
ids = append(ids, user.ID)
|
||||
}
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
439
classes/admin_actions_test.go
Normal file
439
classes/admin_actions_test.go
Normal file
@@ -0,0 +1,439 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"gocloud.dev/blob/memblob"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// actionUser stores an active user for the admin action tests.
|
||||
func actionUser(t *testing.T, db *gorm.DB, label string, mutate func(*models.User)) *models.User {
|
||||
t.Helper()
|
||||
user := &models.User{Email: "action-" + label + "@example.test", IsActivated: true}
|
||||
if mutate != nil {
|
||||
mutate(user)
|
||||
}
|
||||
if err := db.Omit("Groups").Create(user).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
// actionReload reads a user row, deactivated or not.
|
||||
func actionReload(t *testing.T, db *gorm.DB, id uint) models.User {
|
||||
t.Helper()
|
||||
var user models.User
|
||||
if err := db.Unscoped().Take(&user, id).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
// actionThrottle returns the user's throttle rows ordered by id.
|
||||
func actionThrottle(t *testing.T, db *gorm.DB, id uint) []models.Throttle {
|
||||
t.Helper()
|
||||
var rows []models.Throttle
|
||||
if err := db.Where("user_id = ?", id).Order("id").Find(&rows).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// actionPivot is the whole users_groups table, for "nothing changed" checks.
|
||||
func actionPivot(t *testing.T, db *gorm.DB) []models.UsersGroup {
|
||||
t.Helper()
|
||||
var rows []models.UsersGroup
|
||||
if err := db.Order("user_id, user_group_id").Find(&rows).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// TestAdminActions covers the admin screen's user actions against a real
|
||||
// Postgres: the changed-row count of each, its idempotency, and that none of
|
||||
// them writes users_groups (D-13, D-14, D-29).
|
||||
func TestAdminActions(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
db := throttleDB(t)
|
||||
group := models.UserGroup{Name: "Action group"}
|
||||
if err := db.Create(&group).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
join := func(user *models.User) {
|
||||
t.Helper()
|
||||
if err := db.Create(&models.UsersGroup{UserID: user.ID, UserGroupID: group.ID}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("a missing handle is an error", func(t *testing.T) {
|
||||
users := []*models.User{{ID: 1}}
|
||||
if _, err := ActivateUsers(ctx, nil, users); err == nil {
|
||||
t.Error("ActivateUsers")
|
||||
}
|
||||
if _, err := DeactivateUsers(ctx, nil, users); err == nil {
|
||||
t.Error("DeactivateUsers")
|
||||
}
|
||||
if _, err := RestoreUsers(ctx, nil, users); err == nil {
|
||||
t.Error("RestoreUsers")
|
||||
}
|
||||
if _, err := BanUsers(ctx, nil, users); err == nil {
|
||||
t.Error("BanUsers")
|
||||
}
|
||||
if _, err := UnbanUsers(ctx, nil, users); err == nil {
|
||||
t.Error("UnbanUsers")
|
||||
}
|
||||
if err := UnsuspendUser(ctx, nil, 1); err == nil {
|
||||
t.Error("UnsuspendUser")
|
||||
}
|
||||
if _, _, err := ThrottleStates(ctx, nil, []uint{1}); err == nil {
|
||||
t.Error("ThrottleStates")
|
||||
}
|
||||
if err := ForceDeleteCleanup(ctx, nil, nil, &models.User{ID: 1}); err == nil {
|
||||
t.Error("ForceDeleteCleanup")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("activate, deactivate and restore", func(t *testing.T) {
|
||||
code := "pending"
|
||||
issued := time.Now()
|
||||
idle := actionUser(t, db, "idle", func(u *models.User) {
|
||||
u.IsActivated, u.ActivationCode, u.ActivationCodeIssuedAt = false, &code, &issued
|
||||
})
|
||||
gone := actionUser(t, db, "gone-idle", func(u *models.User) {
|
||||
u.IsActivated = false
|
||||
u.DeletedAt = gorm.DeletedAt{Time: time.Now(), Valid: true}
|
||||
})
|
||||
live := actionUser(t, db, "live", nil)
|
||||
join(idle)
|
||||
join(live)
|
||||
before := actionPivot(t, db)
|
||||
everyone := []*models.User{idle, nil, gone, live, {}}
|
||||
|
||||
n, err := ActivateUsers(ctx, db, everyone)
|
||||
if err != nil || n != 2 {
|
||||
t.Fatalf("ActivateUsers = %d %v, want the two users that were not active", n, err)
|
||||
}
|
||||
for _, id := range []uint{idle.ID, gone.ID} {
|
||||
got := actionReload(t, db, id)
|
||||
if !got.IsActivated || got.ActivatedAt == nil || got.ActivationCode != nil || got.ActivationCodeIssuedAt != nil || got.DeletedAt.Valid {
|
||||
t.Fatalf("user %d after activate = %+v", id, got)
|
||||
}
|
||||
}
|
||||
// The passed values are updated too, so the caller's next step sees them.
|
||||
if !idle.IsActivated || idle.ActivationCode != nil || gone.DeletedAt.Valid {
|
||||
t.Fatalf("the passed users were not updated: %+v %+v", idle, gone)
|
||||
}
|
||||
if n, err = ActivateUsers(ctx, db, everyone); err != nil || n != 0 {
|
||||
t.Fatalf("second ActivateUsers = %d %v, want 0", n, err)
|
||||
}
|
||||
|
||||
if n, err = DeactivateUsers(ctx, db, everyone); err != nil || n != 3 {
|
||||
t.Fatalf("DeactivateUsers = %d %v, want 3", n, err)
|
||||
}
|
||||
for _, user := range []*models.User{idle, gone, live} {
|
||||
if got := actionReload(t, db, user.ID); !got.DeletedAt.Valid || !got.IsActivated {
|
||||
t.Fatalf("user %d after deactivate = %+v", user.ID, got)
|
||||
}
|
||||
}
|
||||
if n, err = DeactivateUsers(ctx, db, everyone); err != nil || n != 0 {
|
||||
t.Fatalf("second DeactivateUsers = %d %v, want 0", n, err)
|
||||
}
|
||||
if n, err = RestoreUsers(ctx, db, []*models.User{idle, live}); err != nil || n != 2 {
|
||||
t.Fatalf("RestoreUsers = %d %v, want 2", n, err)
|
||||
}
|
||||
if got := actionReload(t, db, idle.ID); got.DeletedAt.Valid {
|
||||
t.Fatal("restore left deleted_at")
|
||||
}
|
||||
if got := actionReload(t, db, gone.ID); !got.DeletedAt.Valid {
|
||||
t.Fatal("restore touched a user outside its selection")
|
||||
}
|
||||
if n, err = RestoreUsers(ctx, db, []*models.User{idle, live}); err != nil || n != 0 {
|
||||
t.Fatalf("second RestoreUsers = %d %v, want 0", n, err)
|
||||
}
|
||||
if !reflect.DeepEqual(actionPivot(t, db), before) {
|
||||
t.Fatal("an action changed users_groups")
|
||||
}
|
||||
// Conditions on the caller's handle never narrow an action: each one
|
||||
// starts from an empty statement.
|
||||
scoped := db.Where("1 = 0")
|
||||
late := actionUser(t, db, "scoped", func(u *models.User) { u.IsActivated = false })
|
||||
if n, err = ActivateUsers(ctx, scoped, []*models.User{late}); err != nil || n != 1 || !actionReload(t, db, late.ID).IsActivated {
|
||||
t.Fatalf("ActivateUsers through a scoped handle = %d %v", n, err)
|
||||
}
|
||||
if n, err = DeactivateUsers(ctx, scoped, []*models.User{late}); err != nil || n != 1 || !actionReload(t, db, late.ID).DeletedAt.Valid {
|
||||
t.Fatalf("DeactivateUsers through a scoped handle = %d %v", n, err)
|
||||
}
|
||||
if n, err = BanUsers(ctx, scoped, []*models.User{late}); err != nil || n != 1 || len(actionThrottle(t, db, late.ID)) != 1 {
|
||||
t.Fatalf("BanUsers through a scoped handle = %d %v", n, err)
|
||||
}
|
||||
if banned, _, err := ThrottleStates(ctx, scoped, []uint{late.ID}); err != nil || !banned[late.ID] {
|
||||
t.Fatalf("ThrottleStates through a scoped handle = %v %v", banned, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ban and unban", func(t *testing.T) {
|
||||
several := actionUser(t, db, "several", nil)
|
||||
none := actionUser(t, db, "none", nil)
|
||||
anyRow := actionUser(t, db, "any-row", nil)
|
||||
first, second := "203.0.113.1", "203.0.113.2"
|
||||
for _, row := range []models.Throttle{
|
||||
{UserID: several.ID, IPAddress: &first, Attempts: 2},
|
||||
{UserID: several.ID, IPAddress: &second},
|
||||
{UserID: anyRow.ID},
|
||||
} {
|
||||
if err := db.Create(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
join(several)
|
||||
before := actionPivot(t, db)
|
||||
everyone := []*models.User{several, none, anyRow, nil}
|
||||
|
||||
n, err := BanUsers(ctx, db, everyone)
|
||||
if err != nil || n != 3 {
|
||||
t.Fatalf("BanUsers = %d %v, want 3", n, err)
|
||||
}
|
||||
// Every row is banned, and each user has exactly one row without an
|
||||
// address: created for the two who had none, kept for the third.
|
||||
for user, want := range map[*models.User]int{several: 3, none: 1, anyRow: 1} {
|
||||
rows := actionThrottle(t, db, user.ID)
|
||||
nullRows := 0
|
||||
for _, row := range rows {
|
||||
if !row.IsBanned {
|
||||
t.Fatalf("user %d has a row that is not banned: %+v", user.ID, row)
|
||||
}
|
||||
if row.IPAddress == nil {
|
||||
nullRows++
|
||||
}
|
||||
}
|
||||
if len(rows) != want || nullRows != 1 {
|
||||
t.Fatalf("user %d has %d rows (%d without an address), want %d and 1", user.ID, len(rows), nullRows, want)
|
||||
}
|
||||
}
|
||||
if rows := actionThrottle(t, db, several.ID); rows[0].Attempts != 2 {
|
||||
t.Fatalf("a ban changed the attempt counter: %+v", rows[0])
|
||||
}
|
||||
if n, err = BanUsers(ctx, db, everyone); err != nil || n != 0 {
|
||||
t.Fatalf("second BanUsers = %d %v, want 0", n, err)
|
||||
}
|
||||
if rows := actionThrottle(t, db, none.ID); len(rows) != 1 {
|
||||
t.Fatalf("a second ban created another row: %d", len(rows))
|
||||
}
|
||||
banned, suspended, err := ThrottleStates(ctx, db, []uint{several.ID, none.ID, anyRow.ID, 987654})
|
||||
if err != nil || len(banned) != 3 || len(suspended) != 0 {
|
||||
t.Fatalf("ThrottleStates = %v %v %v", banned, suspended, err)
|
||||
}
|
||||
|
||||
// A mixed selection counts only the users who were banned.
|
||||
fresh := actionUser(t, db, "never-banned", nil)
|
||||
if n, err = UnbanUsers(ctx, db, []*models.User{several, fresh, nil}); err != nil || n != 1 {
|
||||
t.Fatalf("UnbanUsers = %d %v, want 1", n, err)
|
||||
}
|
||||
for _, row := range actionThrottle(t, db, several.ID) {
|
||||
if row.IsBanned {
|
||||
t.Fatalf("a row stayed banned: %+v", row)
|
||||
}
|
||||
}
|
||||
if rows := actionThrottle(t, db, fresh.ID); len(rows) != 0 {
|
||||
t.Fatalf("unban created a row for a user who was not banned: %+v", rows)
|
||||
}
|
||||
if rows := actionThrottle(t, db, none.ID); !rows[0].IsBanned {
|
||||
t.Fatal("unban touched a user outside its selection")
|
||||
}
|
||||
if n, err = UnbanUsers(ctx, db, []*models.User{several}); err != nil || n != 0 {
|
||||
t.Fatalf("second UnbanUsers = %d %v, want 0", n, err)
|
||||
}
|
||||
if !reflect.DeepEqual(actionPivot(t, db), before) {
|
||||
t.Fatal("ban or unban changed users_groups")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the suspension window is a pure read", func(t *testing.T) {
|
||||
inside := actionUser(t, db, "inside", nil)
|
||||
expired := actionUser(t, db, "expired", nil)
|
||||
flagged := actionUser(t, db, "flagged", nil)
|
||||
recent, longAgo := time.Now().Add(-14*time.Minute), time.Now().Add(-16*time.Minute)
|
||||
ip := "203.0.113.9"
|
||||
for _, row := range []models.Throttle{
|
||||
{UserID: inside.ID, IPAddress: &ip, IsSuspended: true, SuspendedAt: &recent, Attempts: 5},
|
||||
{UserID: expired.ID, IPAddress: &ip, IsSuspended: true, SuspendedAt: &longAgo, Attempts: 5},
|
||||
// Suspended without a time: not inside any window.
|
||||
{UserID: flagged.ID, IPAddress: &ip, IsSuspended: true, Attempts: 5},
|
||||
} {
|
||||
if err := db.Create(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
ids := []uint{inside.ID, expired.ID, flagged.ID}
|
||||
_, suspended, err := ThrottleStates(ctx, db, ids)
|
||||
if err != nil || !reflect.DeepEqual(suspended, map[uint]bool{inside.ID: true}) {
|
||||
t.Fatalf("suspended = %v %v, want only the user inside the 15 minute window", suspended, err)
|
||||
}
|
||||
// A shorter window from the context moves the boundary.
|
||||
short := withThrottle(ctx, throttleSettings{use: true, limit: 5, minutes: 10})
|
||||
if _, suspended, err = ThrottleStates(short, db, ids); err != nil || len(suspended) != 0 {
|
||||
t.Fatalf("suspended under a 10 minute window = %v %v", suspended, err)
|
||||
}
|
||||
long := withThrottle(ctx, throttleSettings{use: true, limit: 5, minutes: 30})
|
||||
if _, suspended, err = ThrottleStates(long, db, ids); err != nil || len(suspended) != 2 {
|
||||
t.Fatalf("suspended under a 30 minute window = %v %v", suspended, err)
|
||||
}
|
||||
// A window of zero falls back to the default.
|
||||
zero := withThrottle(ctx, throttleSettings{use: true})
|
||||
if _, suspended, err = ThrottleStates(zero, db, ids); err != nil || len(suspended) != 1 {
|
||||
t.Fatalf("suspended under a zero window = %v %v", suspended, err)
|
||||
}
|
||||
// Reading changed nothing: the expired suspension is still flagged.
|
||||
for _, id := range ids {
|
||||
if rows := actionThrottle(t, db, id); len(rows) != 1 || !rows[0].IsSuspended || rows[0].Attempts != 5 {
|
||||
t.Fatalf("reading the state changed the row of %d: %+v", id, rows)
|
||||
}
|
||||
}
|
||||
banned, suspended, err := ThrottleStates(ctx, db, nil)
|
||||
if err != nil || banned == nil || suspended == nil || len(banned)+len(suspended) != 0 {
|
||||
t.Fatalf("ThrottleStates without ids = %v %v %v", banned, suspended, err)
|
||||
}
|
||||
|
||||
if err := UnsuspendUser(ctx, db, inside.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rows := actionThrottle(t, db, inside.ID); rows[0].IsSuspended || rows[0].SuspendedAt != nil || rows[0].Attempts != 0 {
|
||||
t.Fatalf("row after unsuspend = %+v", rows[0])
|
||||
}
|
||||
if rows := actionThrottle(t, db, expired.ID); !rows[0].IsSuspended {
|
||||
t.Fatal("unsuspend touched another user")
|
||||
}
|
||||
// Idempotent, and a user without rows is no error.
|
||||
if err := UnsuspendUser(ctx, db, inside.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := UnsuspendUser(ctx, db, 987654); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the cleanup of a permanent delete", func(t *testing.T) {
|
||||
bucket := memblob.OpenBucket(nil)
|
||||
t.Cleanup(func() { _ = bucket.Close() })
|
||||
// The class harness runs the plugin's migrations only; system_files is
|
||||
// the framework's table.
|
||||
if err := db.AutoMigrate(&attach.File{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded := func(label string) (*models.User, string) {
|
||||
t.Helper()
|
||||
user := actionUser(t, db, label, nil)
|
||||
join(user)
|
||||
ip := "203.0.113.20"
|
||||
for _, row := range []models.Throttle{{UserID: user.ID, IPAddress: &ip}, {UserID: user.ID, IsBanned: true}} {
|
||||
if err := db.Create(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
disk := "cleanup-" + label + ".jpg"
|
||||
key := attach.BlobKey(disk)
|
||||
if err := bucket.WriteAll(ctx, key, []byte("avatar"), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file := attach.File{DiskName: disk, FileName: "a.jpg", FileSize: 6, ContentType: "image/jpeg", Field: models.AvatarField,
|
||||
AttachmentID: strconv.FormatUint(uint64(user.ID), 10), AttachmentType: user.MorphName()}
|
||||
if err := db.Create(&file).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return user, key
|
||||
}
|
||||
left := func(user *models.User) [3]int64 {
|
||||
t.Helper()
|
||||
var out [3]int64
|
||||
for i, query := range []string{
|
||||
`SELECT COUNT(*) FROM user_throttle WHERE user_id = ?`,
|
||||
`SELECT COUNT(*) FROM users_groups WHERE user_id = ?`,
|
||||
} {
|
||||
if err := db.Raw(query, user.ID).Scan(&out[i]).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
err := db.Raw(`SELECT COUNT(*) FROM system_files WHERE attachment_type = ? AND attachment_id = ?`,
|
||||
user.MorphName(), strconv.FormatUint(uint64(user.ID), 10)).Scan(&out[2]).Error
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
exists := func(key string) bool {
|
||||
t.Helper()
|
||||
ok, err := bucket.Exists(ctx, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// A transaction that rolls back keeps the rows and the blob.
|
||||
kept, keptKey := loaded("kept")
|
||||
bystander, bystanderKey := loaded("bystander")
|
||||
rollback := errors.New("rollback")
|
||||
err := lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||
if err := ForceDeleteCleanup(ctx, tx, bucket, kept); err != nil {
|
||||
return err
|
||||
}
|
||||
return rollback
|
||||
})
|
||||
if !errors.Is(err, rollback) || left(kept) != [3]int64{2, 1, 1} || !exists(keptKey) {
|
||||
t.Fatalf("after a rollback: err=%v rows=%v blob=%v", err, left(kept), exists(keptKey))
|
||||
}
|
||||
// A committed one removes the rows, and the blob after the commit.
|
||||
err = lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||
if err := ForceDeleteCleanup(ctx, tx, bucket, kept); err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists(keptKey) {
|
||||
t.Error("the blob was removed before the commit")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil || left(kept) != [3]int64{} || exists(keptKey) {
|
||||
t.Fatalf("after the commit: err=%v rows=%v blob=%v", err, left(kept), exists(keptKey))
|
||||
}
|
||||
// The user row itself is the caller's to delete.
|
||||
if got := actionReload(t, db, kept.ID); got.ID != kept.ID {
|
||||
t.Fatal("the cleanup deleted the user row")
|
||||
}
|
||||
if left(bystander) != [3]int64{2, 1, 1} || !exists(bystanderKey) {
|
||||
t.Fatal("the cleanup touched another user")
|
||||
}
|
||||
// Idempotent: nothing left to remove is no error.
|
||||
if err := lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||
return ForceDeleteCleanup(ctx, tx, bucket, kept)
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Without a bucket the rows still go; the blob is left for the host.
|
||||
err = lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||
return ForceDeleteCleanup(ctx, tx, nil, bystander)
|
||||
})
|
||||
if err != nil || left(bystander) != [3]int64{} || !exists(bystanderKey) {
|
||||
t.Fatalf("without a bucket: err=%v rows=%v blob=%v", err, left(bystander), exists(bystanderKey))
|
||||
}
|
||||
for _, user := range []*models.User{nil, {}} {
|
||||
if err := ForceDeleteCleanup(ctx, db, bucket, user); err == nil {
|
||||
t.Fatalf("cleanup of %+v was accepted", user)
|
||||
}
|
||||
}
|
||||
// Only the group itself is left of the pivot's side.
|
||||
var groups int64
|
||||
if err := db.Model(&models.UserGroup{}).Where("id = ?", group.ID).Count(&groups).Error; err != nil || groups != 1 {
|
||||
t.Fatalf("the cleanup removed the group: %d %v", groups, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
49
classes/authorizer.go
Normal file
49
classes/authorizer.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/lighthouse"
|
||||
)
|
||||
|
||||
// AuthorizeUser is the lighthouse authorizer for the user namespace
|
||||
// (D-17, T-19-10). It allows only user:{id} for that user. ChannelID is
|
||||
// the two-segment reader (segment 1 is the id). A second presence: prefix
|
||||
// or extra segments are denied.
|
||||
func AuthorizeUser() lighthouse.AuthorizerFunc {
|
||||
return func(_ context.Context, userID uint, channel string) lighthouse.Result {
|
||||
name := strings.TrimPrefix(channel, "presence:")
|
||||
if strings.HasPrefix(name, "presence:") {
|
||||
return lighthouse.Denied("invalid user channel")
|
||||
}
|
||||
parts := strings.Split(name, ":")
|
||||
if len(parts) != 2 || parts[0] != "user" {
|
||||
return lighthouse.Denied("invalid user channel")
|
||||
}
|
||||
if userID == 0 || lighthouse.ChannelID(name) != int64(userID) {
|
||||
return lighthouse.Denied("not that user")
|
||||
}
|
||||
return lighthouse.Allowed(nil)
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterUserAuthorizer registers the user namespace if it is free. A
|
||||
// missing lighthouse service is skipped so Boot stays additive on hosts
|
||||
// that never mount realtime.
|
||||
func RegisterUserAuthorizer(app *backpack.App) error {
|
||||
svc, err := lighthouse.From(app)
|
||||
if err != nil {
|
||||
slog.Default().Warn("golem15.user: lighthouse unavailable; user authorizer not registered", "err", err)
|
||||
return nil
|
||||
}
|
||||
if svc == nil || svc.Registry() == nil {
|
||||
return nil
|
||||
}
|
||||
if _, ok := svc.Registry().Get("user"); ok {
|
||||
return nil
|
||||
}
|
||||
return svc.Registry().Register("user", AuthorizeUser())
|
||||
}
|
||||
36
classes/authorizer_test.go
Normal file
36
classes/authorizer_test.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/lighthouse"
|
||||
)
|
||||
|
||||
// TestUserAuthorizer: user:9 is allowed only for user 9 (T-19-10).
|
||||
func TestUserAuthorizer(t *testing.T) {
|
||||
auth := AuthorizeUser()
|
||||
ctx := context.Background()
|
||||
|
||||
if got := auth.Authorize(ctx, 9, "user:9"); !got.Allowed {
|
||||
t.Fatalf("user:9 for 9 denied: %s", got.Reason())
|
||||
}
|
||||
if got := auth.Authorize(ctx, 9, "presence:user:9"); !got.Allowed {
|
||||
t.Fatalf("presence:user:9 for 9 denied: %s", got.Reason())
|
||||
}
|
||||
if lighthouse.ChannelID("user:9") != 9 {
|
||||
t.Fatalf("ChannelID(user:9) = %d, want 9", lighthouse.ChannelID("user:9"))
|
||||
}
|
||||
|
||||
for _, channel := range []string{"user:8", "user:9:extra", "chat:9", "user:", "user", "presence:presence:user:9"} {
|
||||
if got := auth.Authorize(ctx, 9, channel); got.Allowed {
|
||||
t.Errorf("%q for 9 allowed, want deny", channel)
|
||||
}
|
||||
}
|
||||
if got := auth.Authorize(ctx, 8, "user:9"); got.Allowed {
|
||||
t.Fatal("user:9 for 8 allowed, want deny")
|
||||
}
|
||||
if got := auth.Authorize(ctx, 0, "user:0"); got.Allowed {
|
||||
t.Fatal("user:0 for 0 allowed, want deny")
|
||||
}
|
||||
}
|
||||
65
classes/avatar.go
Normal file
65
classes/avatar.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"gocloud.dev/blob"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// AvatarURL returns the display picture URL of user at size pixels, the
|
||||
// rule the user API payload follows: the thumbnail (size by size, mode
|
||||
// auto) of the user's avatar attachment when there is one and a file
|
||||
// bucket is published, the attachment's file path when the thumbnail
|
||||
// fails (logged), and otherwise the gravatar URL
|
||||
// //www.gravatar.com/avatar/{md5 of the email}?s={size}&d=mm. The URL may
|
||||
// be protocol-relative or relative; a caller that needs an absolute URL
|
||||
// resolves it. Only a failing database lookup is an error.
|
||||
func AvatarURL(ctx context.Context, app *backpack.App, user *models.User, size int) (string, error) {
|
||||
if user == nil {
|
||||
return "", errors.New("golem15.user: avatar needs a user")
|
||||
}
|
||||
fallback := gravatar(user.Email, size)
|
||||
if app == nil || user.ID == 0 {
|
||||
return fallback, nil
|
||||
}
|
||||
gdb, ok := app.Lookup[*gorm.DB]()
|
||||
if !ok || gdb == nil {
|
||||
return fallback, nil
|
||||
}
|
||||
var f attach.File
|
||||
err := gdb.WithContext(ctx).
|
||||
Where("attachment_type = ? AND attachment_id = ? AND field = ?", user.MorphName(), strconv.FormatUint(uint64(user.ID), 10), models.AvatarField).
|
||||
Take(&f).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fallback, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
bucket, ok := app.Lookup[*blob.Bucket]()
|
||||
if !ok || bucket == nil {
|
||||
return fallback, nil
|
||||
}
|
||||
url, err := f.Thumb(ctx, bucket, size, size, "auto")
|
||||
if err != nil {
|
||||
slog.Default().Error("golem15.user: avatar thumb", "err", err)
|
||||
return "/" + attach.BlobKey(f.DiskName), nil
|
||||
}
|
||||
return url, nil
|
||||
}
|
||||
|
||||
// gravatar is the gravatar URL of an email at size pixels.
|
||||
func gravatar(email string, size int) string {
|
||||
sum := md5.Sum([]byte(strings.ToLower(strings.TrimSpace(email))))
|
||||
return fmt.Sprintf("//www.gravatar.com/avatar/%x?s=%d&d=mm", sum, size)
|
||||
}
|
||||
@@ -1,6 +1,18 @@
|
||||
package classes
|
||||
|
||||
import "git.golem15.com/golem15/sm-user-plugin/models"
|
||||
import (
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// CreatedEventName is the festival name of CreatedEvent (D-13 / RESEARCH A6).
|
||||
const CreatedEventName = "user.Created"
|
||||
|
||||
// DeletingEventName is the festival name of DeletingEvent (D-13 / RESEARCH A6).
|
||||
const DeletingEventName = "user.Deleting"
|
||||
|
||||
// DeactivatingEventName is the festival name of DeactivatingEvent.
|
||||
const DeactivatingEventName = "user.Deactivating"
|
||||
|
||||
// GetApiArrayEvent is the fire-and-collect payload other plugins extend.
|
||||
type GetApiArrayEvent struct {
|
||||
@@ -27,3 +39,29 @@ type RegisterEvent struct {
|
||||
// or hashed. Listeners must treat it as read-only input.
|
||||
Payload map[string]any
|
||||
}
|
||||
|
||||
// CreatedEvent fires from every user create path (API register and admin
|
||||
// create) so listeners can run inside the same write, including handle
|
||||
// generation (D-13, D-15). Tx is the create transaction when there is one.
|
||||
type CreatedEvent struct {
|
||||
User *models.User
|
||||
Tx *gorm.DB
|
||||
}
|
||||
|
||||
// DeletingEvent fires from FormAfterDelete before ForceDeleteCleanup /
|
||||
// unscoped delete, inside the same transaction, so listeners (chatchannels
|
||||
// GDPR) can sever rows before the user row is gone (D-13, T-19-07).
|
||||
type DeletingEvent struct {
|
||||
User *models.User
|
||||
Tx *gorm.DB
|
||||
}
|
||||
|
||||
// DeactivatingEvent fires after a user is soft-deleted (deactivated, the
|
||||
// PHP $user->delete()) by the admin deactivate action, inside the same
|
||||
// transaction, so listeners can revoke what a deactivated account must not
|
||||
// keep (OAuth grants, for example) while leaving what a restore needs. A
|
||||
// listener error rolls the deactivation back.
|
||||
type DeactivatingEvent struct {
|
||||
User *models.User
|
||||
Tx *gorm.DB
|
||||
}
|
||||
|
||||
@@ -46,3 +46,41 @@ func TestRegisterEventFires(t *testing.T) {
|
||||
t.Fatalf("event user = %#v", seen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreatedEventFires(t *testing.T) {
|
||||
if CreatedEventName != "user.Created" {
|
||||
t.Fatalf("CreatedEventName = %q, want user.Created", CreatedEventName)
|
||||
}
|
||||
bus := festival.New()
|
||||
var seen *models.User
|
||||
bus.Listen[*CreatedEvent]("golem15.user", func(_ context.Context, e *CreatedEvent) error {
|
||||
seen = e.User
|
||||
return nil
|
||||
})
|
||||
user := &models.User{ID: 9, Email: "created@example.test"}
|
||||
if err := bus.Fire(context.Background(), &CreatedEvent{User: user}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if seen == nil || seen.Email != user.Email {
|
||||
t.Fatalf("created event user = %#v", seen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeletingEventFires(t *testing.T) {
|
||||
if DeletingEventName != "user.Deleting" {
|
||||
t.Fatalf("DeletingEventName = %q, want user.Deleting", DeletingEventName)
|
||||
}
|
||||
bus := festival.New()
|
||||
var seen *models.User
|
||||
bus.Listen[*DeletingEvent]("golem15.user", func(_ context.Context, e *DeletingEvent) error {
|
||||
seen = e.User
|
||||
return nil
|
||||
})
|
||||
user := &models.User{ID: 9, Email: "gone@example.test"}
|
||||
if err := bus.Fire(context.Background(), &DeletingEvent{User: user}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if seen == nil || seen.Email != user.Email {
|
||||
t.Fatalf("deleting event user = %#v", seen)
|
||||
}
|
||||
}
|
||||
|
||||
160
classes/handle_generator.go
Normal file
160
classes/handle_generator.go
Normal file
@@ -0,0 +1,160 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
handleMinLen = 2
|
||||
handleMaxLen = 255
|
||||
)
|
||||
|
||||
// HandleGenerator ports the PHP ChatChannels HandleGenerator. The emitted
|
||||
// charset [a-z0-9._-] is a strict subset of MentionParser [A-Za-z0-9._-],
|
||||
// length 2–255, so every generated handle is matchable as an @-token.
|
||||
type HandleGenerator struct{}
|
||||
|
||||
// Slug transliterates name to ASCII, lowercases, drops every rune outside
|
||||
// [a-z0-9._-], then trims leading/trailing `._-`. A result shorter than 2
|
||||
// is not a valid base (Generate falls back to user{id}).
|
||||
func (HandleGenerator) Slug(name string) string {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return ""
|
||||
}
|
||||
var b strings.Builder
|
||||
b.Grow(len(name))
|
||||
for _, r := range name {
|
||||
b.WriteString(foldHandleRune(r))
|
||||
}
|
||||
return strings.Trim(b.String(), "._-")
|
||||
}
|
||||
|
||||
// Generate returns a unique handle for name. The base is Slug(name); if
|
||||
// that is shorter than 2 it falls back to "user{fallbackID}" (or "user"
|
||||
// when no id is known). The smallest free integer suffix is then appended
|
||||
// until isTaken returns false: first "James" → "james", second → "james1".
|
||||
func (g HandleGenerator) Generate(name string, isTaken func(string) bool, fallbackID *uint) string {
|
||||
base := g.Slug(name)
|
||||
if len(base) < handleMinLen {
|
||||
if fallbackID != nil {
|
||||
base = "user" + strconv.FormatUint(uint64(*fallbackID), 10)
|
||||
} else {
|
||||
base = "user"
|
||||
}
|
||||
}
|
||||
base = clipHandle(base)
|
||||
candidate := base
|
||||
i := 0
|
||||
for isTaken != nil && isTaken(candidate) {
|
||||
i++
|
||||
candidate = clipHandle(base + strconv.Itoa(i))
|
||||
}
|
||||
return candidate
|
||||
}
|
||||
|
||||
// AssignHandle writes a unique handle onto user when it has none, using
|
||||
// the user's display name and id. It is idempotent when handle is already
|
||||
// set. The write uses db (the create transaction when there is one).
|
||||
func AssignHandle(ctx context.Context, db *gorm.DB, user *models.User) error {
|
||||
if user == nil {
|
||||
return errors.New("golem15.user: a handle needs a user")
|
||||
}
|
||||
if user.Handle != nil && strings.TrimSpace(*user.Handle) != "" {
|
||||
return nil
|
||||
}
|
||||
if db == nil {
|
||||
return errors.New("golem15.user: a handle needs a database")
|
||||
}
|
||||
name := ""
|
||||
if user.Name != nil {
|
||||
name = *user.Name
|
||||
}
|
||||
var fallback *uint
|
||||
if user.ID != 0 {
|
||||
id := user.ID
|
||||
fallback = &id
|
||||
}
|
||||
gen := HandleGenerator{}
|
||||
for attempt := 0; attempt < 8; attempt++ {
|
||||
handle := gen.Generate(name, func(candidate string) bool {
|
||||
var n int64
|
||||
q := db.WithContext(ctx).Model(&models.User{}).Where("handle = ?", candidate)
|
||||
if user.ID != 0 {
|
||||
q = q.Where("id <> ?", user.ID)
|
||||
}
|
||||
if err := q.Count(&n).Error; err != nil {
|
||||
return true
|
||||
}
|
||||
return n > 0
|
||||
}, fallback)
|
||||
user.Handle = &handle
|
||||
res := db.WithContext(ctx).Model(user).Where("id = ?", user.ID).Update("handle", handle)
|
||||
if res.Error == nil {
|
||||
return nil
|
||||
}
|
||||
if !isUniqueHandleConflict(res.Error) {
|
||||
return res.Error
|
||||
}
|
||||
}
|
||||
return errors.New("golem15.user: could not allocate a unique handle")
|
||||
}
|
||||
|
||||
func clipHandle(s string) string {
|
||||
if len(s) <= handleMaxLen {
|
||||
return s
|
||||
}
|
||||
return s[:handleMaxLen]
|
||||
}
|
||||
|
||||
func isUniqueHandleConflict(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, gorm.ErrDuplicatedKey) {
|
||||
return true
|
||||
}
|
||||
msg := strings.ToLower(err.Error())
|
||||
return strings.Contains(msg, "users_handle_unique") || strings.Contains(msg, "duplicate key")
|
||||
}
|
||||
|
||||
// foldHandleRune maps r into the handle charset [a-z0-9._-] or "".
|
||||
func foldHandleRune(r rune) string {
|
||||
r = unicode.ToLower(r)
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '.', r == '_', r == '-':
|
||||
return string(r)
|
||||
}
|
||||
if mapped, ok := latinHandleFold[r]; ok {
|
||||
return mapped
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// latinHandleFold covers Latin-1 / Latin Extended-A letters PHP Str::ascii
|
||||
// would emit for the names we generate handles from (Polish, French, German).
|
||||
var latinHandleFold = map[rune]string{
|
||||
'à': "a", 'á': "a", 'â': "a", 'ã': "a", 'ä': "a", 'å': "a", 'ą': "a", 'ā': "a",
|
||||
'æ': "ae",
|
||||
'ç': "c", 'ć': "c", 'č': "c",
|
||||
'ď': "d", 'đ': "d", 'ð': "d",
|
||||
'è': "e", 'é': "e", 'ê': "e", 'ë': "e", 'ę': "e", 'ē': "e", 'ě': "e",
|
||||
'ì': "i", 'í': "i", 'î': "i", 'ï': "i", 'ī': "i",
|
||||
'ł': "l",
|
||||
'ñ': "n", 'ń': "n", 'ň': "n",
|
||||
'ò': "o", 'ó': "o", 'ô': "o", 'õ': "o", 'ö': "o", 'ø': "o", 'ō': "o",
|
||||
'œ': "oe",
|
||||
'ř': "r",
|
||||
'ś': "s", 'š': "s", 'ş': "s", 'ß': "ss",
|
||||
'ť': "t", 'þ': "th",
|
||||
'ù': "u", 'ú': "u", 'û': "u", 'ü': "u", 'ū': "u",
|
||||
'ý': "y", 'ÿ': "y",
|
||||
'ź': "z", 'ż': "z", 'ž': "z",
|
||||
}
|
||||
78
classes/handle_generator_test.go
Normal file
78
classes/handle_generator_test.go
Normal file
@@ -0,0 +1,78 @@
|
||||
package classes
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestHandle: generator charset is a subset of MentionParser, uniqueness
|
||||
// uses the smallest free integer suffix, and short names fall back to user{id}.
|
||||
func TestHandle(t *testing.T) {
|
||||
t.Parallel()
|
||||
g := HandleGenerator{}
|
||||
|
||||
if got := g.Slug("Paweł"); got != "pawel" {
|
||||
t.Fatalf("slug Paweł = %q, want pawel", got)
|
||||
}
|
||||
if got := g.Slug("John Doe"); got != "johndoe" {
|
||||
t.Fatalf("slug John Doe = %q, want johndoe", got)
|
||||
}
|
||||
if got := g.Slug("Zoë"); got != "zoe" {
|
||||
t.Fatalf("slug Zoë = %q, want zoe", got)
|
||||
}
|
||||
|
||||
handle := g.Generate("James", func(string) bool { return false }, nil)
|
||||
if handle != "james" {
|
||||
t.Fatalf("generate James = %q, want james", handle)
|
||||
}
|
||||
if !validHandle(handle) {
|
||||
t.Fatalf("generated %q is outside [a-z0-9._-]{2,255}", handle)
|
||||
}
|
||||
|
||||
taken := map[string]struct{}{}
|
||||
isTaken := func(c string) bool {
|
||||
_, ok := taken[c]
|
||||
return ok
|
||||
}
|
||||
first := g.Generate("James", isTaken, nil)
|
||||
taken[first] = struct{}{}
|
||||
second := g.Generate("James", isTaken, nil)
|
||||
taken[second] = struct{}{}
|
||||
third := g.Generate("James", isTaken, nil)
|
||||
if first != "james" || second != "james1" || third != "james2" {
|
||||
t.Fatalf("suffixes = %q %q %q, want james james1 james2", first, second, third)
|
||||
}
|
||||
|
||||
id := uint(42)
|
||||
if got := g.Generate("", func(string) bool { return false }, &id); got != "user42" {
|
||||
t.Fatalf("empty name = %q, want user42", got)
|
||||
}
|
||||
if got := g.Generate("x", func(string) bool { return false }, &id); got != "user42" {
|
||||
t.Fatalf("short name = %q, want user42", got)
|
||||
}
|
||||
if got := g.Generate("???", func(string) bool { return false }, &id); got != "user42" {
|
||||
t.Fatalf("punctuation name = %q, want user42", got)
|
||||
}
|
||||
if got := g.Generate("", func(string) bool { return false }, nil); got != "user" {
|
||||
t.Fatalf("no id = %q, want user", got)
|
||||
}
|
||||
|
||||
names := []string{"James", "Paweł", "John Doe", "???", "a", "Zoë", " ", "....", "O'Brien"}
|
||||
for _, name := range names {
|
||||
got := g.Generate(name, func(string) bool { return false }, &id)
|
||||
if !validHandle(got) {
|
||||
t.Errorf("generated %q for %q is outside the MentionParser subset", got, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func validHandle(s string) bool {
|
||||
if len(s) < 2 || len(s) > 255 {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '.', r == '_', r == '-':
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
27
classes/last_seen.go
Normal file
27
classes/last_seen.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// TouchLastSeen stamps users.last_seen with the current time, at most once
|
||||
// per five minutes per user: it is one UPDATE that matches the row only when
|
||||
// last_seen is NULL or older than five minutes, so a busy client costs one
|
||||
// write per window. It does not touch updated_at, and it applies to a
|
||||
// deactivated user too. Login and token refresh call it and ignore its
|
||||
// error apart from logging it: authentication never depends on this write.
|
||||
func TouchLastSeen(ctx context.Context, db *gorm.DB, userID uint) error {
|
||||
if db == nil {
|
||||
return fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
if userID == 0 {
|
||||
return nil
|
||||
}
|
||||
return fresh(ctx, db).Exec(
|
||||
`UPDATE users SET last_seen = NOW() WHERE id = ? AND (last_seen IS NULL OR last_seen < NOW() - INTERVAL '5 minutes')`,
|
||||
userID,
|
||||
).Error
|
||||
}
|
||||
124
classes/last_seen_test.go
Normal file
124
classes/last_seen_test.go
Normal file
@@ -0,0 +1,124 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// contextCancelled returns a context that is already cancelled, so a query
|
||||
// through it fails.
|
||||
func contextCancelled(t *testing.T) (context.Context, context.CancelFunc) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
return ctx, cancel
|
||||
}
|
||||
|
||||
// TestTouchLastSeen pins the five-minute rule of users.last_seen on both
|
||||
// sides of the boundary, for an active and a deactivated user (D-17).
|
||||
func TestTouchLastSeen(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
db := throttleDB(t)
|
||||
user := models.User{Email: "touch@example.test", IsActivated: true}
|
||||
gone := models.User{Email: "touch-gone@example.test", IsActivated: true, DeletedAt: gorm.DeletedAt{Time: time.Now(), Valid: true}}
|
||||
for _, u := range []*models.User{&user, &gone} {
|
||||
if err := db.Omit("Groups").Create(u).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
read := func(id uint) *time.Time {
|
||||
t.Helper()
|
||||
var row struct{ LastSeen *time.Time }
|
||||
if err := db.Raw(`SELECT last_seen FROM users WHERE id = ?`, id).Scan(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return row.LastSeen
|
||||
}
|
||||
set := func(id uint, age time.Duration) time.Time {
|
||||
t.Helper()
|
||||
at := time.Now().Add(-age).Truncate(time.Microsecond)
|
||||
if err := db.Exec(`UPDATE users SET last_seen = ? WHERE id = ?`, at, id).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return at
|
||||
}
|
||||
updatedAt := func(id uint) time.Time {
|
||||
t.Helper()
|
||||
var at time.Time
|
||||
if err := db.Raw(`SELECT updated_at FROM users WHERE id = ?`, id).Scan(&at).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return at
|
||||
}
|
||||
|
||||
for _, id := range []uint{user.ID, gone.ID} {
|
||||
if read(id) != nil {
|
||||
t.Fatalf("user %d starts with last_seen", id)
|
||||
}
|
||||
stamped := updatedAt(id)
|
||||
started := time.Now().Add(-time.Second)
|
||||
if err := TouchLastSeen(ctx, db, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first := read(id)
|
||||
if first == nil || first.Before(started) {
|
||||
t.Fatalf("user %d: a NULL last_seen was not stamped: %v", id, first)
|
||||
}
|
||||
if !updatedAt(id).Equal(stamped) {
|
||||
t.Fatalf("user %d: the stamp touched updated_at", id)
|
||||
}
|
||||
// Just inside the window: untouched. Just outside: stamped again.
|
||||
for _, tc := range []struct {
|
||||
age time.Duration
|
||||
stamped bool
|
||||
}{
|
||||
{0, false}, {4*time.Minute + 55*time.Second, false},
|
||||
{5*time.Minute + 5*time.Second, true}, {24 * time.Hour, true},
|
||||
} {
|
||||
was := set(id, tc.age)
|
||||
if err := TouchLastSeen(ctx, db, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := read(id)
|
||||
if now == nil || now.Equal(was) == tc.stamped {
|
||||
t.Fatalf("user %d, last seen %s ago: stamped = %v, want %v", id, tc.age, !now.Equal(was), tc.stamped)
|
||||
}
|
||||
}
|
||||
}
|
||||
// One user's stamp never moves another's.
|
||||
other := set(gone.ID, time.Hour)
|
||||
if err := TouchLastSeen(ctx, db, user.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := read(gone.ID); got == nil || !got.Equal(other) {
|
||||
t.Fatal("a stamp moved another user's last_seen")
|
||||
}
|
||||
// An unknown id and the zero id are no error; a missing handle and a
|
||||
// failed write are.
|
||||
if err := TouchLastSeen(ctx, db, 987654); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := TouchLastSeen(ctx, db, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := TouchLastSeen(ctx, nil, user.ID); err == nil {
|
||||
t.Fatal("TouchLastSeen without a handle")
|
||||
}
|
||||
cancelled, cancel := contextCancelled(t)
|
||||
defer cancel()
|
||||
set(user.ID, time.Hour)
|
||||
if err := TouchLastSeen(cancelled, db, user.ID); err == nil {
|
||||
t.Fatal("TouchLastSeen swallowed a failed write")
|
||||
}
|
||||
// The handle's own conditions do not leak into the update.
|
||||
if err := TouchLastSeen(ctx, db.Where("1 = 0"), user.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := read(user.ID); got == nil || time.Since(*got) > time.Minute {
|
||||
t.Fatalf("a scoped handle kept the stamp from being written: %v", got)
|
||||
}
|
||||
}
|
||||
31
classes/oauth_providers.go
Normal file
31
classes/oauth_providers.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package classes
|
||||
|
||||
import "context"
|
||||
|
||||
// OAuthProvider is one social sign-in provider as GET
|
||||
// /_user/api/v1/oauth-providers lists it: Name is the route segment
|
||||
// (/oauth/{name}) and Label the button text.
|
||||
type OAuthProvider struct {
|
||||
Name string `json:"name"`
|
||||
Label string `json:"label"`
|
||||
}
|
||||
|
||||
// OAuthProviderSource is what a social-login plugin publishes so the user
|
||||
// plugin can list its providers and accept them in the unlink routes. The
|
||||
// user plugin looks it up on every request, so a plugin that boots later is
|
||||
// still found.
|
||||
//
|
||||
// Publish it with an explicit type argument,
|
||||
//
|
||||
// app.Publish[classes.OAuthProviderSource](src)
|
||||
//
|
||||
// because a bare app.Publish(src) keys the service on its concrete type and
|
||||
// the lookup misses it (the list then stays empty).
|
||||
type OAuthProviderSource interface {
|
||||
// EnabledOAuthProviders returns the providers that are configured right
|
||||
// now, in display order.
|
||||
EnabledOAuthProviders(ctx context.Context) []OAuthProvider
|
||||
// KnownOAuthProviders returns the name of every registered provider,
|
||||
// enabled or not: an identity of any of them may be unlinked.
|
||||
KnownOAuthProviders() []string
|
||||
}
|
||||
133
classes/permissions.go
Normal file
133
classes/permissions.go
Normal file
@@ -0,0 +1,133 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// MergedPermissions returns the frontend permissions of a user as PHP
|
||||
// User::getMergedPermissions builds them:
|
||||
//
|
||||
// 1. the permissions of every group the user belongs to are merged, and
|
||||
// where two groups name the same code the higher value wins ("most
|
||||
// positive wins": 1 over 0 over -1);
|
||||
// 2. the user's own permissions are laid over the result, and a user value
|
||||
// replaces the groups' value whatever it is (a user-level -1 overrides a
|
||||
// group's 1, and a user-level 1 overrides a group's -1).
|
||||
//
|
||||
// The result maps a code to 1 (allowed), -1 (denied) or 0. Use HasPermission
|
||||
// to ask it a question. A deactivated user's permissions are read as well.
|
||||
func MergedPermissions(ctx context.Context, db *gorm.DB, userID uint) (map[string]int, error) {
|
||||
if db == nil {
|
||||
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
var groups []struct{ Permissions models.PermissionSet }
|
||||
err := fresh(ctx, db).
|
||||
Table("user_groups").
|
||||
Select("user_groups.permissions").
|
||||
Joins("JOIN users_groups ON users_groups.user_group_id = user_groups.id").
|
||||
Where("users_groups.user_id = ?", userID).
|
||||
Order("user_groups.id").
|
||||
Scan(&groups).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
merged := map[string]int{}
|
||||
for _, group := range groups {
|
||||
for code, value := range group.Permissions {
|
||||
if held, ok := merged[code]; !ok || value > held {
|
||||
merged[code] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
var own []struct{ Permissions models.PermissionSet }
|
||||
err = fresh(ctx, db).
|
||||
Table("users").
|
||||
Select("users.permissions").
|
||||
Where("users.id = ?", userID).
|
||||
Scan(&own).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range own {
|
||||
for code, value := range row.Permissions {
|
||||
merged[code] = value
|
||||
}
|
||||
}
|
||||
return merged, nil
|
||||
}
|
||||
|
||||
// HasPermission reports whether merged holds code, the single-permission
|
||||
// case of Winter's User::hasPermission. A permission is held only when the
|
||||
// matching value is exactly 1. Wildcards work as in Winter:
|
||||
//
|
||||
// - code ending in "*" is held when a different stored code starts with the
|
||||
// part before the asterisk and has the value 1;
|
||||
// - code starting with "*" is held when a different stored code ends with
|
||||
// the part after the asterisk and has the value 1;
|
||||
// - otherwise code is held when it is stored with the value 1, or when a
|
||||
// stored code ending in "*" with the value 1 is a proper prefix of it.
|
||||
//
|
||||
// A stored code that starts with "*" is not treated as a wildcard; Winter
|
||||
// does not treat it as one either.
|
||||
func HasPermission(merged map[string]int, code string) bool {
|
||||
switch {
|
||||
case len(code) > 1 && strings.HasSuffix(code, "*"):
|
||||
prefix := strings.TrimSuffix(code, "*")
|
||||
for stored, value := range merged {
|
||||
if prefix != stored && strings.HasPrefix(stored, prefix) && value == 1 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
case len(code) > 1 && strings.HasPrefix(code, "*"):
|
||||
suffix := strings.TrimPrefix(code, "*")
|
||||
for stored, value := range merged {
|
||||
if suffix != stored && strings.HasSuffix(stored, suffix) && value == 1 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
for stored, value := range merged {
|
||||
if len(stored) > 1 && strings.HasSuffix(stored, "*") {
|
||||
prefix := strings.TrimSuffix(stored, "*")
|
||||
if prefix != code && strings.HasPrefix(code, prefix) && value == 1 {
|
||||
return true
|
||||
}
|
||||
continue
|
||||
}
|
||||
if stored == code && value == 1 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// UserHasPermission reports whether the user holds the frontend permission
|
||||
// code: MergedPermissions followed by HasPermission.
|
||||
func UserHasPermission(ctx context.Context, db *gorm.DB, userID uint, code string) (bool, error) {
|
||||
merged, err := MergedPermissions(ctx, db, userID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return HasPermission(merged, code), nil
|
||||
}
|
||||
|
||||
// FrontendPermissionOptions returns the rows of
|
||||
// golem15_user_frontend_permissions ordered by tab, then code, as PHP
|
||||
// FrontendPermission::listTabbedPermissions reads them.
|
||||
func FrontendPermissionOptions(ctx context.Context, db *gorm.DB) ([]models.FrontendPermission, error) {
|
||||
if db == nil {
|
||||
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
rows := []models.FrontendPermission{}
|
||||
if err := fresh(ctx, db).Order("tab ASC, code ASC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
359
classes/permissions_test.go
Normal file
359
classes/permissions_test.go
Normal file
@@ -0,0 +1,359 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
)
|
||||
|
||||
// TestMergedPermissions pins the port of PHP User::getMergedPermissions and
|
||||
// Winter's hasPermission: groups merge with "most positive wins", the user's
|
||||
// own values override the groups' whatever they are, a permission is held
|
||||
// only at exactly 1, and wildcards work as in Winter.
|
||||
func TestMergedPermissions(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
db := throttleDB(t)
|
||||
|
||||
type ask struct {
|
||||
code string
|
||||
want bool
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
groups []string // permissions column of each group, as stored
|
||||
own string // users.permissions, as stored; "NULL" stores NULL
|
||||
merged map[string]int
|
||||
asks []ask
|
||||
}{
|
||||
{
|
||||
name: "two groups, the higher value wins",
|
||||
groups: []string{`{"blog.post":-1,"blog.edit":0}`, `{"blog.post":1,"blog.edit":-1}`},
|
||||
own: "NULL",
|
||||
merged: map[string]int{"blog.post": 1, "blog.edit": 0},
|
||||
asks: []ask{{"blog.post", true}, {"blog.edit", false}, {"blog.other", false}},
|
||||
},
|
||||
{
|
||||
name: "the order of the groups does not matter",
|
||||
groups: []string{`{"blog.post":1}`, `{"blog.post":-1}`},
|
||||
own: "NULL",
|
||||
merged: map[string]int{"blog.post": 1},
|
||||
asks: []ask{{"blog.post", true}},
|
||||
},
|
||||
{
|
||||
name: "a user-level deny overrides a group's allow",
|
||||
groups: []string{`{"blog.post":1,"blog.edit":1}`},
|
||||
own: `{"blog.post":-1}`,
|
||||
merged: map[string]int{"blog.post": -1, "blog.edit": 1},
|
||||
asks: []ask{{"blog.post", false}, {"blog.edit", true}},
|
||||
},
|
||||
{
|
||||
// The port is not "deny wins".
|
||||
name: "a user-level allow overrides a group's deny",
|
||||
groups: []string{`{"blog.post":-1}`, `{"blog.post":-1}`},
|
||||
own: `{"blog.post":1}`,
|
||||
merged: map[string]int{"blog.post": 1},
|
||||
asks: []ask{{"blog.post", true}},
|
||||
},
|
||||
{
|
||||
name: "a code held only at 0 or -1 is not held",
|
||||
groups: []string{`{"blog.zero":0,"blog.denied":-1}`},
|
||||
own: `{"blog.own_denied":-1}`,
|
||||
merged: map[string]int{"blog.zero": 0, "blog.denied": -1, "blog.own_denied": -1},
|
||||
asks: []ask{{"blog.zero", false}, {"blog.denied", false}, {"blog.own_denied", false}},
|
||||
},
|
||||
{
|
||||
name: "a user with no groups has only their own permissions",
|
||||
groups: nil,
|
||||
own: `{"blog.post":1,"shop.buy":-1}`,
|
||||
merged: map[string]int{"blog.post": 1, "shop.buy": -1},
|
||||
asks: []ask{{"blog.post", true}, {"shop.buy", false}},
|
||||
},
|
||||
{
|
||||
name: "a user with nothing stored holds nothing",
|
||||
groups: nil,
|
||||
own: "NULL",
|
||||
merged: map[string]int{},
|
||||
asks: []ask{{"blog.post", false}, {"*", false}, {"blog.*", false}},
|
||||
},
|
||||
{
|
||||
name: "an asked code ending in an asterisk matches a stored code by prefix",
|
||||
groups: []string{`{"blog.post":1,"shop.buy":-1}`},
|
||||
own: "NULL",
|
||||
merged: map[string]int{"blog.post": 1, "shop.buy": -1},
|
||||
asks: []ask{
|
||||
{"blog.*", true},
|
||||
{"shop.*", false}, // the only match is denied
|
||||
{"blog.post*", false}, // the prefix must not equal the stored code
|
||||
{"news.*", false},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "an asked code starting with an asterisk matches a stored code by suffix",
|
||||
groups: []string{`{"blog.post":1,"shop.post":-1,"shop.buy":-1}`},
|
||||
own: "NULL",
|
||||
merged: map[string]int{"blog.post": 1, "shop.post": -1, "shop.buy": -1},
|
||||
asks: []ask{{"*.post", true}, {"*.buy", false}, {"*blog.post", false}},
|
||||
},
|
||||
{
|
||||
name: "a stored code ending in an asterisk grants the codes under it",
|
||||
groups: []string{`{"blog.*":1,"shop.*":-1}`},
|
||||
own: `{"news.*":0}`,
|
||||
merged: map[string]int{"blog.*": 1, "shop.*": -1, "news.*": 0},
|
||||
asks: []ask{
|
||||
{"blog.post", true},
|
||||
{"blog.", false}, // the stored prefix itself is not under it
|
||||
{"shop.buy", false},
|
||||
{"news.read", false},
|
||||
},
|
||||
},
|
||||
{
|
||||
// Winter treats a leading asterisk as a wildcard only on the asked
|
||||
// code, never on a stored one. Asking "*.post" still matches the
|
||||
// stored "*.post" as a longer code with that suffix.
|
||||
name: "a stored code starting with an asterisk is not a wildcard",
|
||||
groups: []string{`{"*.post":1}`},
|
||||
own: "NULL",
|
||||
merged: map[string]int{"*.post": 1},
|
||||
asks: []ask{{"blog.post", false}, {"*.post", true}},
|
||||
},
|
||||
{
|
||||
name: "stored shapes are read tolerantly",
|
||||
groups: []string{``, `[]`, `{"blog.post":"1","blog.bad":"yes","blog.edit":"-1"}`},
|
||||
own: ``,
|
||||
merged: map[string]int{"blog.post": 1, "blog.edit": -1},
|
||||
asks: []ask{{"blog.post", true}, {"blog.bad", false}, {"blog.edit", false}},
|
||||
},
|
||||
{
|
||||
name: "several groups: the highest value of each code wins",
|
||||
groups: []string{
|
||||
`{"blog.post":-1,"blog.edit":1,"shop.buy":0}`,
|
||||
`{"blog.post":0,"blog.edit":-1,"news.read":1}`,
|
||||
`{"blog.post":1,"shop.buy":-1}`,
|
||||
`{}`,
|
||||
},
|
||||
own: "NULL",
|
||||
merged: map[string]int{"blog.post": 1, "blog.edit": 1, "shop.buy": 0, "news.read": 1},
|
||||
asks: []ask{{"blog.post", true}, {"blog.edit", true}, {"shop.buy", false}, {"news.read", true}, {"news.*", true}},
|
||||
},
|
||||
{
|
||||
name: "numbers stored as text count at both levels",
|
||||
groups: []string{`{"blog.post":"1","blog.edit":"1","shop.buy":"-1"}`},
|
||||
own: `{"blog.edit":"-1","shop.buy":"1","news.read":"0"}`,
|
||||
merged: map[string]int{"blog.post": 1, "blog.edit": -1, "shop.buy": 1, "news.read": 0},
|
||||
asks: []ask{{"blog.post", true}, {"blog.edit", false}, {"shop.buy", true}, {"news.read", false}},
|
||||
},
|
||||
{
|
||||
name: "groups that store nothing leave the user's own permissions",
|
||||
groups: []string{`{}`, ``, `[]`},
|
||||
own: `{"blog.post":1}`,
|
||||
merged: map[string]int{"blog.post": 1},
|
||||
asks: []ask{{"blog.post", true}, {"blog.edit", false}},
|
||||
},
|
||||
{
|
||||
name: "a code present only at user level is held or denied by that value alone",
|
||||
groups: []string{`{"blog.post":1}`},
|
||||
own: `{"only.allow":1,"only.deny":-1,"only.inherit":0}`,
|
||||
merged: map[string]int{"blog.post": 1, "only.allow": 1, "only.deny": -1, "only.inherit": 0},
|
||||
asks: []ask{{"only.allow", true}, {"only.deny", false}, {"only.inherit", false}, {"only.*", true}, {"blog.post", true}},
|
||||
},
|
||||
{
|
||||
// 12.1-SECURITY-REVIEW.md, open item 5: the resolver reads
|
||||
// numbers only. A boolean is not a grant here.
|
||||
name: "a boolean value is not a grant",
|
||||
groups: []string{`{"blog.post":true,"blog.edit":false}`},
|
||||
own: `{"shop.buy":true}`,
|
||||
merged: map[string]int{},
|
||||
asks: []ask{{"blog.post", false}, {"shop.buy", false}},
|
||||
},
|
||||
}
|
||||
for i, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
user := models.User{Email: fmt.Sprintf("merged-%d@example.test", i)}
|
||||
if err := db.Omit("Groups").Create(&user).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.own != "NULL" {
|
||||
if err := db.Exec(`UPDATE users SET permissions = ? WHERE id = ?`, c.own, user.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for j, stored := range c.groups {
|
||||
var groupID uint
|
||||
if err := db.Raw(`INSERT INTO user_groups (name, permissions, created_at, updated_at) VALUES (?, ?, NOW(), NOW()) RETURNING id`,
|
||||
fmt.Sprintf("Merged %d.%d", i, j), stored).Scan(&groupID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`INSERT INTO users_groups (user_id, user_group_id) VALUES (?, ?)`, user.ID, groupID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
merged, err := MergedPermissions(ctx, db, user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(merged, c.merged) {
|
||||
t.Fatalf("merged = %v, want %v", merged, c.merged)
|
||||
}
|
||||
for _, a := range c.asks {
|
||||
if got := HasPermission(merged, a.code); got != a.want {
|
||||
t.Errorf("HasPermission(%q) = %v, want %v", a.code, got, a.want)
|
||||
}
|
||||
got, err := UserHasPermission(ctx, db, user.ID, a.code)
|
||||
if err != nil || got != a.want {
|
||||
t.Errorf("UserHasPermission(%q) = %v %v, want %v", a.code, got, err, a.want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A deactivated user's permissions are still read.
|
||||
gone := models.User{Email: "merged-gone@example.test"}
|
||||
if err := db.Omit("Groups").Create(&gone).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`UPDATE users SET permissions = '{"blog.post":1}', deleted_at = NOW() WHERE id = ?`, gone.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if held, err := UserHasPermission(ctx, db, gone.ID, "blog.post"); err != nil || !held {
|
||||
t.Fatalf("deactivated user: %v %v", held, err)
|
||||
}
|
||||
// A user who does not exist holds nothing.
|
||||
if merged, err := MergedPermissions(ctx, db, 987654321); err != nil || len(merged) != 0 {
|
||||
t.Fatalf("unknown user: %v %v", merged, err)
|
||||
}
|
||||
// A damaged row is an error, never "no permissions".
|
||||
damaged := models.User{Email: "merged-damaged@example.test"}
|
||||
if err := db.Omit("Groups").Create(&damaged).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`UPDATE users SET permissions = '{"blog.post":' WHERE id = ?`, damaged.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := MergedPermissions(ctx, db, damaged.ID); err == nil {
|
||||
t.Fatal("damaged permissions were read without an error")
|
||||
}
|
||||
if _, err := UserHasPermission(ctx, db, damaged.ID, "blog.post"); err == nil {
|
||||
t.Fatal("UserHasPermission swallowed the error")
|
||||
}
|
||||
if err := db.Exec(`DELETE FROM users WHERE id = ?`, damaged.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := MergedPermissions(ctx, nil, gone.ID); err == nil {
|
||||
t.Fatal("MergedPermissions without a handle")
|
||||
}
|
||||
if _, err := FrontendPermissionOptions(ctx, nil); err == nil {
|
||||
t.Fatal("FrontendPermissionOptions without a handle")
|
||||
}
|
||||
|
||||
// The option catalogue is read by tab, then code.
|
||||
if err := db.Exec(`INSERT INTO golem15_user_frontend_permissions (code, label, tab, comment) VALUES
|
||||
('merged.b', 'B', 'Zeta', NULL), ('merged.c', 'C', 'Alpha', 'A comment'), ('merged.a', 'A', 'Zeta', NULL)`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
options, err := FrontendPermissionOptions(ctx, db)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var codes []string
|
||||
for _, option := range options {
|
||||
if len(option.Code) > 7 && option.Code[:7] == "merged." {
|
||||
codes = append(codes, option.Code)
|
||||
if option.Code == "merged.c" && (option.Comment == nil || *option.Comment != "A comment" || option.Tab != "Alpha" || option.Label != "C") {
|
||||
t.Fatalf("option = %+v", option)
|
||||
}
|
||||
}
|
||||
}
|
||||
if want := []string{"merged.c", "merged.a", "merged.b"}; !reflect.DeepEqual(codes, want) {
|
||||
t.Fatalf("option order = %v, want %v", codes, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPermissionSetScan pins the tolerant read and the strict write of a
|
||||
// stored permission column.
|
||||
func TestPermissionSetScan(t *testing.T) {
|
||||
scans := []struct {
|
||||
name string
|
||||
src any
|
||||
want models.PermissionSet
|
||||
wantErr bool
|
||||
}{
|
||||
{"NULL", nil, models.PermissionSet{}, false},
|
||||
{"empty string", "", models.PermissionSet{}, false},
|
||||
{"blank string", " \n", models.PermissionSet{}, false},
|
||||
{"the text []", "[]", models.PermissionSet{}, false},
|
||||
{"the text null", "null", models.PermissionSet{}, false},
|
||||
{"empty object", "{}", models.PermissionSet{}, false},
|
||||
{"bytes", []byte(`{"a.b":1}`), models.PermissionSet{"a.b": 1}, false},
|
||||
{"integers", `{"a.b":1,"c.d":-1,"e.f":0}`, models.PermissionSet{"a.b": 1, "c.d": -1, "e.f": 0}, false},
|
||||
{"numeric strings", `{"a.b":"1","c.d":"-1"," e.f":" 1 "}`, models.PermissionSet{"a.b": 1, "c.d": -1, " e.f": 1}, false},
|
||||
{"a non-numeric entry is skipped", `{"a.b":1,"c.d":"yes","e.f":true,"g.h":null,"i.j":1.5,"k.l":[1],"m.n":{"x":1}}`, models.PermissionSet{"a.b": 1}, false},
|
||||
{"malformed JSON", `{"a.b":1`, nil, true},
|
||||
{"a non-empty list", `["a.b"]`, nil, true},
|
||||
{"a scalar", `1`, nil, true},
|
||||
{"a string scalar", `"a.b"`, nil, true},
|
||||
{"trailing data", `{"a.b":1} {"c.d":1}`, nil, true},
|
||||
{"an unsupported driver type", 42, nil, true},
|
||||
}
|
||||
for _, c := range scans {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
set := models.PermissionSet{"stale": 1}
|
||||
err := set.Scan(c.src)
|
||||
if c.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("Scan(%v) = %v, want an error", c.src, set)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || set == nil || !reflect.DeepEqual(set, c.want) {
|
||||
t.Fatalf("Scan(%v) = %v %v, want %v", c.src, set, err, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
values := []struct {
|
||||
name string
|
||||
set models.PermissionSet
|
||||
want any
|
||||
}{
|
||||
{"nil set", nil, nil},
|
||||
{"empty set", models.PermissionSet{}, nil},
|
||||
{"only zeros", models.PermissionSet{"a.b": 0}, nil},
|
||||
{"a zero is left out", models.PermissionSet{"b.c": -1, "a.b": 1, "z.z": 0}, `{"a.b":1,"b.c":-1}`},
|
||||
}
|
||||
for _, c := range values {
|
||||
t.Run("value of "+c.name, func(t *testing.T) {
|
||||
got, err := c.set.Value()
|
||||
if err != nil || !reflect.DeepEqual(got, c.want) {
|
||||
t.Fatalf("Value() = %#v %v, want %#v", got, err, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Through GORM: a stored set comes back as written, an empty one as NULL.
|
||||
db := throttleDB(t)
|
||||
user := models.User{Email: "permission-set@example.test", Permissions: models.PermissionSet{"a.b": 1, "c.d": -1, "e.f": 0}}
|
||||
if err := db.Omit("Groups").Create(&user).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var stored *string
|
||||
if err := db.Raw(`SELECT permissions FROM users WHERE id = ?`, user.ID).Scan(&stored).Error; err != nil || stored == nil || *stored != `{"a.b":1,"c.d":-1}` {
|
||||
t.Fatalf("stored permissions = %v err = %v", stored, err)
|
||||
}
|
||||
var loaded models.User
|
||||
if err := db.Take(&loaded, user.ID).Error; err != nil || !reflect.DeepEqual(loaded.Permissions, models.PermissionSet{"a.b": 1, "c.d": -1}) {
|
||||
t.Fatalf("loaded permissions = %v err = %v", loaded.Permissions, err)
|
||||
}
|
||||
loaded.Permissions = models.PermissionSet{}
|
||||
if err := db.Omit("Groups").Save(&loaded).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Raw(`SELECT permissions FROM users WHERE id = ?`, user.ID).Scan(&stored).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var isNull bool
|
||||
if err := db.Raw(`SELECT permissions IS NULL FROM users WHERE id = ?`, user.ID).Scan(&isNull).Error; err != nil || !isNull {
|
||||
t.Fatalf("an empty set was not stored as NULL: %v", err)
|
||||
}
|
||||
}
|
||||
119
classes/privileged.go
Normal file
119
classes/privileged.go
Normal file
@@ -0,0 +1,119 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// PermissionManagePrivilegedGroups is the backend permission an administrator
|
||||
// needs, on top of golem15.users.access_users, to change the email or the
|
||||
// password of a member of a privileged group, or to delete such a user for
|
||||
// good.
|
||||
const PermissionManagePrivilegedGroups = "golem15.users.manage_privileged_groups"
|
||||
|
||||
// privilegedGroupsKey is the config list of privileged group codes.
|
||||
const privilegedGroupsKey = "golem15.user.privileged_groups"
|
||||
|
||||
// defaultPrivilegedGroup is the only privileged code when the config names
|
||||
// none: the site-admin group.
|
||||
const defaultPrivilegedGroup = "admin"
|
||||
|
||||
// PrivilegedGroupCodes returns the group codes whose members are protected,
|
||||
// read from golem15.user.privileged_groups on every call so a config change
|
||||
// applies without a restart. A nil config or a missing key gives the single
|
||||
// code admin. Blank entries are dropped; a key that is present and empty
|
||||
// means that no group is privileged.
|
||||
func PrivilegedGroupCodes(cfg *compass.Config) []string {
|
||||
if cfg == nil {
|
||||
return []string{defaultPrivilegedGroup}
|
||||
}
|
||||
raw, ok := cfg.Lookup(privilegedGroupsKey)
|
||||
if !ok {
|
||||
return []string{defaultPrivilegedGroup}
|
||||
}
|
||||
var entries []string
|
||||
switch v := raw.(type) {
|
||||
case []string:
|
||||
entries = v
|
||||
case []any:
|
||||
for _, item := range v {
|
||||
if s, ok := item.(string); ok {
|
||||
entries = append(entries, s)
|
||||
}
|
||||
}
|
||||
case string:
|
||||
// An environment override arrives as one comma-separated string.
|
||||
entries = strings.Split(v, ",")
|
||||
}
|
||||
codes := make([]string, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if code := strings.TrimSpace(entry); code != "" {
|
||||
codes = append(codes, code)
|
||||
}
|
||||
}
|
||||
return codes
|
||||
}
|
||||
|
||||
// IsPrivilegedCode reports whether a group's code is in codes. Codes compare
|
||||
// case-sensitively, as HasGroupCode does, and a group without a code is
|
||||
// never privileged.
|
||||
func IsPrivilegedCode(codes []string, code *string) bool {
|
||||
if code == nil || *code == "" {
|
||||
return false
|
||||
}
|
||||
for _, privileged := range codes {
|
||||
if privileged == *code {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// PrivilegedGroupIDs returns the ids of the user_groups rows whose code is in
|
||||
// codes, ordered by id.
|
||||
func PrivilegedGroupIDs(ctx context.Context, db *gorm.DB, codes []string) ([]uint, error) {
|
||||
if db == nil {
|
||||
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
ids := []uint{}
|
||||
if len(codes) == 0 {
|
||||
return ids, nil
|
||||
}
|
||||
err := fresh(ctx, db).
|
||||
Table("user_groups").
|
||||
Where("code IN ?", codes).
|
||||
Order("id").
|
||||
Pluck("id", &ids).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IsPrivilegedMember reports whether the user belongs to at least one group
|
||||
// whose code is in codes. A user in no group, and a group without a code,
|
||||
// give false. A deactivated user's membership counts: it survives the soft
|
||||
// delete. The membership is read through an empty statement on db's
|
||||
// connection, so conditions the caller's handle carries never narrow it.
|
||||
func IsPrivilegedMember(ctx context.Context, db *gorm.DB, codes []string, userID uint) (bool, error) {
|
||||
if db == nil {
|
||||
return false, fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
if len(codes) == 0 || userID == 0 {
|
||||
return false, nil
|
||||
}
|
||||
held, err := UserGroupCodes(ctx, fresh(ctx, db), userID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for i := range held {
|
||||
if IsPrivilegedCode(codes, &held[i]) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
207
classes/privileged_test.go
Normal file
207
classes/privileged_test.go
Normal file
@@ -0,0 +1,207 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
)
|
||||
|
||||
// privilegedConfig opens a config whose golem15.user.privileged_groups is
|
||||
// value; a nil value leaves the key out.
|
||||
func privilegedConfig(t *testing.T, value any, environ ...string) *compass.Config {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: privileged\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)
|
||||
}
|
||||
if value != nil {
|
||||
if err := cfg.Set(privilegedGroupsKey, value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
// TestPrivilegedGroupCodes pins how the privileged list is read (D-05): the
|
||||
// default, an override, blank entries and the comma-separated form of an
|
||||
// environment variable.
|
||||
func TestPrivilegedGroupCodes(t *testing.T) {
|
||||
if got := PrivilegedGroupCodes(nil); !reflect.DeepEqual(got, []string{"admin"}) {
|
||||
t.Fatalf("nil config = %v", got)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
value any
|
||||
want []string
|
||||
}{
|
||||
{"a missing key", nil, []string{"admin"}},
|
||||
{"a list", []string{"admin", "moderator"}, []string{"admin", "moderator"}},
|
||||
{"a list of any", []any{"owner", 7, "staff"}, []string{"owner", "staff"}},
|
||||
{"blank entries", []string{" admin ", "", " ", "staff"}, []string{"admin", "staff"}},
|
||||
{"an empty list", []string{}, []string{}},
|
||||
{"a comma-separated string", "admin, staff ,,owner", []string{"admin", "staff", "owner"}},
|
||||
{"an empty string", "", []string{}},
|
||||
{"a value of another type", 5, []string{}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := PrivilegedGroupCodes(privilegedConfig(t, tc.value))
|
||||
if got == nil || !reflect.DeepEqual(got, tc.want) {
|
||||
t.Fatalf("codes = %#v, want %#v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
// The key is read on every call: a change applies without a new config.
|
||||
cfg := privilegedConfig(t, []string{"first"})
|
||||
if got := PrivilegedGroupCodes(cfg); !reflect.DeepEqual(got, []string{"first"}) {
|
||||
t.Fatalf("codes = %v", got)
|
||||
}
|
||||
if err := cfg.Set(privilegedGroupsKey, []string{"second"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := PrivilegedGroupCodes(cfg); !reflect.DeepEqual(got, []string{"second"}) {
|
||||
t.Fatalf("codes after the change = %v", got)
|
||||
}
|
||||
if PermissionManagePrivilegedGroups != "golem15.users.manage_privileged_groups" {
|
||||
t.Fatalf("permission code = %q", PermissionManagePrivilegedGroups)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsPrivilegedCode: codes compare case-sensitively and a group without a
|
||||
// code is never privileged.
|
||||
func TestIsPrivilegedCode(t *testing.T) {
|
||||
str := func(s string) *string { return &s }
|
||||
codes := []string{"admin", "Staff"}
|
||||
for _, tc := range []struct {
|
||||
code *string
|
||||
want bool
|
||||
}{
|
||||
{str("admin"), true}, {str("Staff"), true},
|
||||
{str("Admin"), false}, {str("ADMIN"), false}, {str("staff"), false},
|
||||
{str("admin "), false}, {str(" admin"), false}, {str("administrator"), false},
|
||||
{str(""), false}, {nil, false},
|
||||
} {
|
||||
if got := IsPrivilegedCode(codes, tc.code); got != tc.want {
|
||||
label := "<nil>"
|
||||
if tc.code != nil {
|
||||
label = *tc.code
|
||||
}
|
||||
t.Errorf("IsPrivilegedCode(%q) = %v, want %v", label, got, tc.want)
|
||||
}
|
||||
}
|
||||
if IsPrivilegedCode(nil, str("admin")) || IsPrivilegedCode([]string{}, str("admin")) {
|
||||
t.Error("an empty list has a privileged code")
|
||||
}
|
||||
// An empty entry in the list never matches a group without a code.
|
||||
if IsPrivilegedCode([]string{""}, str("")) || IsPrivilegedCode([]string{""}, nil) {
|
||||
t.Error("an empty code is privileged")
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsPrivilegedMember covers the membership question behind the takeover
|
||||
// guard (D-30) and PrivilegedGroupIDs behind the groups lock (D-07).
|
||||
func TestIsPrivilegedMember(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
db := throttleDB(t)
|
||||
str := func(s string) *string { return &s }
|
||||
admins := models.UserGroup{Name: "Admins", Code: str("admin")}
|
||||
second := models.UserGroup{Name: "Second admins", Code: str("admin2")}
|
||||
ordinary := models.UserGroup{Name: "Ordinary", Code: str("ordinary")}
|
||||
upper := models.UserGroup{Name: "Upper", Code: str("ADMIN")}
|
||||
uncoded := models.UserGroup{Name: "Uncoded"}
|
||||
for _, group := range []*models.UserGroup{&admins, &second, &ordinary, &upper, &uncoded} {
|
||||
if err := db.Create(group).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
user := func(label string, groups ...*models.UserGroup) uint {
|
||||
t.Helper()
|
||||
u := models.User{Email: "privileged-" + label + "@example.test", IsActivated: true}
|
||||
if err := db.Omit("Groups").Create(&u).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, group := range groups {
|
||||
if err := db.Create(&models.UsersGroup{UserID: u.ID, UserGroupID: group.ID}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return u.ID
|
||||
}
|
||||
nobody := user("nobody")
|
||||
plain := user("plain", &ordinary)
|
||||
codeless := user("codeless", &uncoded, &upper)
|
||||
member := user("member", &ordinary, &admins)
|
||||
gone := user("gone", &admins)
|
||||
if err := db.Exec(`UPDATE users SET deleted_at = NOW() WHERE id = ?`, gone).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
defaults := PrivilegedGroupCodes(nil)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
codes []string
|
||||
user uint
|
||||
want bool
|
||||
}{
|
||||
{"a user in no group", defaults, nobody, false},
|
||||
{"an ordinary group only", defaults, plain, false},
|
||||
{"a group without a code and a case variant", defaults, codeless, false},
|
||||
{"a member of a listed group", defaults, member, true},
|
||||
{"a deactivated member", defaults, gone, true},
|
||||
{"an overridden list without admin", []string{"ordinary"}, gone, false},
|
||||
{"an overridden list with the ordinary code", []string{"ordinary"}, plain, true},
|
||||
{"an overridden list, a member of both", []string{"ordinary"}, member, true},
|
||||
{"a case variant in the list", []string{"ADMIN"}, codeless, true},
|
||||
{"an empty list", []string{}, member, false},
|
||||
{"a nil list", nil, member, false},
|
||||
{"an unknown user", defaults, 987654, false},
|
||||
{"the zero user", defaults, 0, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, err := IsPrivilegedMember(ctx, db, tc.codes, tc.user)
|
||||
if err != nil || got != tc.want {
|
||||
t.Fatalf("IsPrivilegedMember = %v %v, want %v", got, err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
if _, err := IsPrivilegedMember(ctx, nil, defaults, member); err == nil {
|
||||
t.Fatal("IsPrivilegedMember without a handle")
|
||||
}
|
||||
// The handle's own conditions do not leak into the query.
|
||||
scoped := db.Where("1 = 0")
|
||||
if got, err := IsPrivilegedMember(ctx, scoped, defaults, member); err != nil || !got {
|
||||
t.Fatalf("with a scoped handle = %v %v", got, err)
|
||||
}
|
||||
// A failing query is an error, never "not a member".
|
||||
cancelled, cancel := contextCancelled(t)
|
||||
defer cancel()
|
||||
if got, err := IsPrivilegedMember(cancelled, db, defaults, member); err == nil || got {
|
||||
t.Fatalf("a failed query answered %v %v", got, err)
|
||||
}
|
||||
|
||||
ids, err := PrivilegedGroupIDs(ctx, db, []string{"admin", "admin2", "missing"})
|
||||
if err != nil || !reflect.DeepEqual(ids, []uint{admins.ID, second.ID}) {
|
||||
t.Fatalf("PrivilegedGroupIDs = %v %v", ids, err)
|
||||
}
|
||||
if ids, err = PrivilegedGroupIDs(ctx, scoped, defaults); err != nil || !reflect.DeepEqual(ids, []uint{admins.ID}) {
|
||||
t.Fatalf("PrivilegedGroupIDs with a scoped handle = %v %v", ids, err)
|
||||
}
|
||||
for _, codes := range [][]string{nil, {}, {"nothing"}} {
|
||||
if ids, err = PrivilegedGroupIDs(ctx, db, codes); err != nil || ids == nil || len(ids) != 0 {
|
||||
t.Fatalf("PrivilegedGroupIDs(%v) = %#v %v", codes, ids, err)
|
||||
}
|
||||
}
|
||||
if _, err = PrivilegedGroupIDs(ctx, nil, defaults); err == nil {
|
||||
t.Fatal("PrivilegedGroupIDs without a handle")
|
||||
}
|
||||
if _, err = PrivilegedGroupIDs(cancelled, db, defaults); err == nil {
|
||||
t.Fatal("PrivilegedGroupIDs swallowed a failed query")
|
||||
}
|
||||
}
|
||||
152
classes/session_user.go
Normal file
152
classes/session_user.go
Normal file
@@ -0,0 +1,152 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// sessionCookieNames are the cookies the plugin's "jwt" guard reads after
|
||||
// the Authorization header, in the same order (plugin.go Boot).
|
||||
var sessionCookieNames = []string{"token", "auth_token"}
|
||||
|
||||
// RequestUser returns the signed-in user of r for handlers that run without
|
||||
// the jwt.auth middleware and must also serve anonymous requests (an OAuth
|
||||
// provider's authorize page, for example). The token is read and checked
|
||||
// exactly as the plugin's "jwt" guard does: the Authorization bearer header
|
||||
// first, then the token and auth_token cookies; the plugin's JWT secret;
|
||||
// the published bouncer.BlacklistStore when there is one; and the user's
|
||||
// tokens_valid_after cutoff. A soft-deleted user is not returned.
|
||||
//
|
||||
// An anonymous request, or a token that is invalid, expired, blacklisted or
|
||||
// names no user, returns (nil, nil). Only an infrastructure failure (no
|
||||
// database handle, a failing query or blacklist lookup) returns an error.
|
||||
func RequestUser(ctx context.Context, app *backpack.App, r *http.Request) (*models.User, error) {
|
||||
if r == nil {
|
||||
return nil, nil
|
||||
}
|
||||
raw := sessionToken(r)
|
||||
if raw == "" {
|
||||
return nil, nil
|
||||
}
|
||||
secret, err := JWTSecret(app)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sub, iat, _, jti, err := bouncer.VerifyClaims(raw, secret)
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
id, err := strconv.ParseUint(sub, 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
gdb, ok := app.Lookup[*gorm.DB]()
|
||||
if !ok || gdb == nil {
|
||||
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
var user models.User
|
||||
err = gdb.WithContext(ctx).Where("id = ?", uint(id)).Take(&user).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if bl, ok := app.Lookup[bouncer.BlacklistStore](); ok && bl != nil {
|
||||
blocked, err := bl.IsBlacklisted(ctx, jti)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if blocked {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
if user.TokensValidAfter != nil && iat.Before(*user.TokensValidAfter) {
|
||||
return nil, nil
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// EndRequestSession signs the request's user out the way Logout does and
|
||||
// forgets the token cookie. When r carries a valid session JWT its jti is
|
||||
// added to the published bouncer.BlacklistStore until the token expires;
|
||||
// the response always gets the forget cookie of
|
||||
// bouncer.LoadCookieConfig(app.Config), so its Domain and Path match the
|
||||
// cookie the login wrote. It is best effort, as in the PHP provider: a
|
||||
// blacklist failure is logged and never returned, and the function writes
|
||||
// no status or body.
|
||||
func EndRequestSession(ctx context.Context, app *backpack.App, w http.ResponseWriter, r *http.Request) error {
|
||||
if r != nil {
|
||||
if raw := sessionToken(r); raw != "" {
|
||||
revokeSessionToken(ctx, app, raw)
|
||||
}
|
||||
}
|
||||
if w == nil {
|
||||
return nil
|
||||
}
|
||||
cfg := bouncer.CookieConfig{Name: bouncer.DefaultCookieName, Path: "/", SameSite: http.SameSiteLaxMode}
|
||||
if app != nil && app.Config != nil {
|
||||
loaded, err := bouncer.LoadCookieConfig(app.Config)
|
||||
if err != nil {
|
||||
slog.Default().Warn("golem15.user: end session: cookie config", "err", err)
|
||||
} else {
|
||||
cfg = loaded
|
||||
}
|
||||
}
|
||||
http.SetCookie(w, cfg.ForgetTokenCookie())
|
||||
return nil
|
||||
}
|
||||
|
||||
// revokeSessionToken blacklists raw's jti until its expiry (best effort).
|
||||
func revokeSessionToken(ctx context.Context, app *backpack.App, raw string) {
|
||||
if app == nil {
|
||||
return
|
||||
}
|
||||
secret, err := JWTSecret(app)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, _, exp, jti, err := bouncer.VerifyClaims(raw, secret)
|
||||
if err != nil || jti == "" {
|
||||
return
|
||||
}
|
||||
bl, ok := app.Lookup[bouncer.BlacklistStore]()
|
||||
if !ok || bl == nil {
|
||||
return
|
||||
}
|
||||
if err := bl.Add(ctx, jti, exp, time.Now()); err != nil {
|
||||
slog.Default().Warn("golem15.user: end session: blacklist token", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// sessionToken extracts the session JWT as the "jwt" guard does: the
|
||||
// Authorization bearer header, then each session cookie in order.
|
||||
func sessionToken(r *http.Request) string {
|
||||
h := strings.TrimSpace(r.Header.Get("Authorization"))
|
||||
if token, ok := strings.CutPrefix(h, "Bearer "); ok {
|
||||
if token = strings.TrimSpace(token); token != "" {
|
||||
return token
|
||||
}
|
||||
}
|
||||
for _, name := range sessionCookieNames {
|
||||
c, err := r.Cookie(name)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if v := strings.TrimSpace(c.Value); v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -22,3 +22,10 @@ password:
|
||||
min_length: 8
|
||||
api_tokens:
|
||||
prefix: usr_
|
||||
privileged_groups:
|
||||
- admin
|
||||
# Cloudflare Turnstile on POST /login and /register. Empty (the default) adds
|
||||
# nothing. "open" lets requests pass when Cloudflare is unreachable, "closed"
|
||||
# refuses them. The turnstile:* middleware comes from the framework (summercms
|
||||
# v0.3.0 and later); its secret is turnstile.secret (SUMMER_TURNSTILE__SECRET).
|
||||
turnstile: ""
|
||||
|
||||
@@ -16,16 +16,14 @@ import (
|
||||
|
||||
// APITokenCommands are the application-wide token create/list/revoke
|
||||
// commands. Domain plugins deliberately do not mint their own credentials.
|
||||
func APITokenCommands(app *backpack.App) []bonfire.Command {
|
||||
withDB := func(ctx context.Context, fn func(*gorm.DB) error) error {
|
||||
if app == nil {
|
||||
return fmt.Errorf("golem15.user: app is nil")
|
||||
}
|
||||
db, ok := app.Lookup[*gorm.DB]()
|
||||
if !ok || db == nil {
|
||||
// withDB is the plugin's database accessor so the commands work both during
|
||||
// serve and as one-shot CLI runs that open Postgres from config.
|
||||
func APITokenCommands(app *backpack.App, withDB func(context.Context, func(*gorm.DB) error) error) []bonfire.Command {
|
||||
open := func(ctx context.Context, fn func(*gorm.DB) error) error {
|
||||
if withDB == nil {
|
||||
return fmt.Errorf("golem15.user: database is not configured")
|
||||
}
|
||||
return fn(db.WithContext(ctx))
|
||||
return withDB(ctx, fn)
|
||||
}
|
||||
return []bonfire.Command{
|
||||
{
|
||||
@@ -54,7 +52,7 @@ func APITokenCommands(app *backpack.App) []bonfire.Command {
|
||||
}
|
||||
expiresAt = &parsed
|
||||
}
|
||||
return withDB(ctx, func(db *gorm.DB) error {
|
||||
return open(ctx, func(db *gorm.DB) error {
|
||||
user, err := classes.LookupByEmail(ctx, db, strings.TrimSpace(email))
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -83,7 +81,7 @@ func APITokenCommands(app *backpack.App) []bonfire.Command {
|
||||
{
|
||||
Name: "user:token:list", Description: "List API tokens",
|
||||
Run: func(ctx context.Context, _ bonfire.Input, out bonfire.Output) error {
|
||||
return withDB(ctx, func(db *gorm.DB) error {
|
||||
return open(ctx, func(db *gorm.DB) error {
|
||||
var tokens []models.APIToken
|
||||
if err := db.Order("id").Find(&tokens).Error; err != nil {
|
||||
return fmt.Errorf("user:token:list: %w", err)
|
||||
@@ -116,7 +114,7 @@ func APITokenCommands(app *backpack.App) []bonfire.Command {
|
||||
if err != nil || id == 0 {
|
||||
return fmt.Errorf("user:token:revoke: %q is not a token id", raw)
|
||||
}
|
||||
return withDB(ctx, func(db *gorm.DB) error {
|
||||
return open(ctx, func(db *gorm.DB) error {
|
||||
res := db.Model(&models.APIToken{}).Where("id = ? AND revoked_at IS NULL", id).UpdateColumn("revoked_at", time.Now())
|
||||
if res.Error != nil {
|
||||
return fmt.Errorf("user:token:revoke: %w", res.Error)
|
||||
|
||||
51
console/backfill_handles.go
Normal file
51
console/backfill_handles.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package console
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// BackfillHandles fills a unique handle on every user row that still has none.
|
||||
// It uses the database the serve command published or, when it runs as a
|
||||
// console command, opens one from the config for the duration of the run,
|
||||
// as the plugin's other commands do.
|
||||
func BackfillHandles(app *backpack.App) bonfire.Command {
|
||||
return bonfire.Command{
|
||||
Name: "user:backfill-handles",
|
||||
Description: "Assign unique handles to users that do not have one (D-15)",
|
||||
Run: func(ctx context.Context, _ bonfire.Input, out bonfire.Output) error {
|
||||
if app == nil {
|
||||
return fmt.Errorf("user:backfill-handles: app is nil")
|
||||
}
|
||||
gdb, ok := app.Lookup[*gorm.DB]()
|
||||
if !ok || gdb == nil {
|
||||
sqlDB, opened, err := lagoon.OpenFromApp(ctx, app)
|
||||
if err != nil {
|
||||
return fmt.Errorf("user:backfill-handles: %w", err)
|
||||
}
|
||||
defer sqlDB.Close()
|
||||
gdb = opened
|
||||
}
|
||||
var users []models.User
|
||||
if err := gdb.WithContext(ctx).Where("handle IS NULL OR handle = ''").Find(&users).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
n := 0
|
||||
for i := range users {
|
||||
if err := classes.AssignHandle(ctx, gdb, &users[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
n++
|
||||
}
|
||||
out.Success(fmt.Sprintf("Assigned handles to %d user(s)", n))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -7,13 +7,12 @@ import (
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// RequirePasswordChange forces the named account to set a new password on next login.
|
||||
func RequirePasswordChange(app *backpack.App) bonfire.Command {
|
||||
func RequirePasswordChange(withDB func(context.Context, func(*gorm.DB) error) error) bonfire.Command {
|
||||
return bonfire.Command{
|
||||
Name: "user:require-password-change",
|
||||
Description: "Force a user to change their password on next login (D-21)",
|
||||
@@ -28,29 +27,27 @@ func RequirePasswordChange(app *backpack.App) bonfire.Command {
|
||||
if !ok || email == "" {
|
||||
return fmt.Errorf("email is required")
|
||||
}
|
||||
if app == nil {
|
||||
return fmt.Errorf("user:require-password-change: app is nil")
|
||||
}
|
||||
gdb, ok := app.Lookup[*gorm.DB]()
|
||||
if !ok || gdb == nil {
|
||||
if withDB == nil {
|
||||
return fmt.Errorf("user:require-password-change: database is not configured")
|
||||
}
|
||||
user, err := classes.LookupByEmail(ctx, gdb, email)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if user == nil {
|
||||
return fmt.Errorf("user %s not found", email)
|
||||
}
|
||||
res := gdb.WithContext(ctx).Model(&models.User{}).Where("id = ?", user.ID).Update("must_change_password", true)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected != 1 {
|
||||
return fmt.Errorf("user %s was not updated", email)
|
||||
}
|
||||
out.Success("Password change required for " + user.Email)
|
||||
return nil
|
||||
return withDB(ctx, func(gdb *gorm.DB) error {
|
||||
user, err := classes.LookupByEmail(ctx, gdb, email)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if user == nil {
|
||||
return fmt.Errorf("user %s not found", email)
|
||||
}
|
||||
res := gdb.WithContext(ctx).Model(&models.User{}).Where("id = ?", user.ID).Update("must_change_password", true)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected != 1 {
|
||||
return fmt.Errorf("user %s was not updated", email)
|
||||
}
|
||||
out.Success("Password change required for " + user.Email)
|
||||
return nil
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
122
console_test.go
122
console_test.go
@@ -3,12 +3,15 @@ package user
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestRequirePasswordChange(t *testing.T) {
|
||||
@@ -16,17 +19,7 @@ func TestRequirePasswordChange(t *testing.T) {
|
||||
user := insertUser(t, gdb, "alice@example.com", "correct-horse")
|
||||
p := &Plugin{app: app}
|
||||
var _ pact.HasCommands = p
|
||||
cmds := p.Commands()
|
||||
var cmd bonfire.Command
|
||||
for _, candidate := range cmds {
|
||||
if candidate.Name == "user:require-password-change" {
|
||||
cmd = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
if cmd.Name == "" {
|
||||
t.Fatalf("commands = %#v", cmds)
|
||||
}
|
||||
cmd := commandNamed(t, p.Commands(), "user:require-password-change")
|
||||
var buf bytes.Buffer
|
||||
out := bonfire.NewOutput(nil, &buf, &buf)
|
||||
if err := cmd.Run(context.Background(), emailArg{email: "alice@example.com"}, out); err != nil {
|
||||
@@ -47,6 +40,89 @@ func TestRequirePasswordChange(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPITokenCreateCommand(t *testing.T) {
|
||||
app, gdb := sessionApp(t, "0s")
|
||||
user := insertUser(t, gdb, "pat@example.com", "correct-horse")
|
||||
cmd := commandNamed(t, (&Plugin{app: app}).Commands(), "user:token:create")
|
||||
var buf bytes.Buffer
|
||||
out := bonfire.NewOutput(nil, &buf, &buf)
|
||||
if err := cmd.Run(context.Background(), tokenCreateArg{email: user.Email, name: "rome scripts", scopes: "read,write"}, out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(buf.String(), "usr_") {
|
||||
t.Fatalf("secret missing from output %q", buf.String())
|
||||
}
|
||||
var n int64
|
||||
if err := gdb.Model(&models.APIToken{}).Where("user_id = ? AND revoked_at IS NULL", user.ID).Count(&n).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 1 {
|
||||
t.Fatalf("tokens = %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleWithDBOpensFromConfigWhenUnpublished(t *testing.T) {
|
||||
p := &Plugin{app: backpack.New(sessionConfig(t))}
|
||||
err := p.withDB(context.Background(), func(*gorm.DB) error {
|
||||
t.Fatal("fn should not run without a DSN")
|
||||
return nil
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected OpenFromApp to fail")
|
||||
}
|
||||
if strings.Contains(err.Error(), "database is not configured") {
|
||||
t.Fatalf("still the Lookup-only error: %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "database.dsn is empty") {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBackfillHandlesOpensFromConfigWhenUnpublished runs user:backfill-handles
|
||||
// as the console does: no published database, only database.dsn in the config.
|
||||
func TestBackfillHandlesOpensFromConfigWhenUnpublished(t *testing.T) {
|
||||
_, gdb := sessionApp(t, "0s")
|
||||
user := insertUser(t, gdb, "backfill-unpublished@example.test", "correct-horse")
|
||||
if err := gdb.Model(user).Update("handle", nil).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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")
|
||||
}
|
||||
cmd := commandNamed(t, (&Plugin{app: app}).Commands(), "user:backfill-handles")
|
||||
var buf bytes.Buffer
|
||||
out := bonfire.NewOutput(nil, &buf, &buf)
|
||||
if err := cmd.Run(context.Background(), emailArg{}, out); err != nil {
|
||||
t.Fatalf("run: %v (output %q)", err, buf.String())
|
||||
}
|
||||
var fresh models.User
|
||||
if err := gdb.First(&fresh, user.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fresh.Handle == nil || *fresh.Handle == "" {
|
||||
t.Fatal("the user still has no handle")
|
||||
}
|
||||
}
|
||||
|
||||
func commandNamed(t *testing.T, cmds []bonfire.Command, name string) bonfire.Command {
|
||||
t.Helper()
|
||||
for _, candidate := range cmds {
|
||||
if candidate.Name == name {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
t.Fatalf("commands = %#v", cmds)
|
||||
return bonfire.Command{}
|
||||
}
|
||||
|
||||
type emailArg struct{ email string }
|
||||
|
||||
func (e emailArg) Args() []string { return []string{e.email} }
|
||||
@@ -61,3 +137,27 @@ func (e emailArg) Argument(name string) (string, bool) {
|
||||
func (e emailArg) Flag(string) (string, bool) { return "", false }
|
||||
|
||||
func (e emailArg) Flags(string) []string { return nil }
|
||||
|
||||
type tokenCreateArg struct{ email, name, scopes string }
|
||||
|
||||
func (a tokenCreateArg) Args() []string { return []string{a.email} }
|
||||
|
||||
func (a tokenCreateArg) Argument(name string) (string, bool) {
|
||||
if name == "email" {
|
||||
return a.email, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func (a tokenCreateArg) Flag(name string) (string, bool) {
|
||||
switch name {
|
||||
case "name":
|
||||
return a.name, true
|
||||
case "scopes":
|
||||
return a.scopes, true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
func (a tokenCreateArg) Flags(string) []string { return nil }
|
||||
|
||||
60
controllers/admin_registry.go
Normal file
60
controllers/admin_registry.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
// AdminControllers is the plugin's admin controller list. app returns the
|
||||
// booted application; it is asked on every call, so a controller never keeps
|
||||
// a database handle, a config or a mailer of its own.
|
||||
func AdminControllers(app func() *backpack.App) []pact.AdminController {
|
||||
return []pact.AdminController{
|
||||
usersAdminController{app: app},
|
||||
usergroupsAdminController{app: appAccess(app)},
|
||||
organisationsAdminController{app: appAccess(app)},
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
var _ pact.AdminController = usersAdminController{}
|
||||
var _ pact.AdminPermissioned = usersAdminController{}
|
||||
var _ pact.AdminRecordSource = usersAdminController{}
|
||||
var _ pact.ListExtendQuery = usersAdminController{}
|
||||
var _ pact.FormExtendQuery = usersAdminController{}
|
||||
var _ pact.ListRowStates = usersAdminController{}
|
||||
var _ pact.FormRules = usersAdminController{}
|
||||
var _ pact.FilterOptions = usersAdminController{}
|
||||
var _ pact.FormBeforeUpdate = usersAdminController{}
|
||||
var _ pact.FormBeforeDelete = usersAdminController{}
|
||||
var _ pact.FormAfterDelete = usersAdminController{}
|
||||
var _ pact.HasAdminBulkActions = usersAdminController{}
|
||||
var _ pact.HasAdminRecordActions = usersAdminController{}
|
||||
var _ pact.AdminPartialData = usersAdminController{}
|
||||
var _ pact.FormVirtualFields = usersAdminController{}
|
||||
var _ pact.FormBeforeCreate = usersAdminController{}
|
||||
var _ pact.FormAfterCreate = usersAdminController{}
|
||||
var _ cabana.FieldRelationProvider = usersAdminController{}
|
||||
var _ cabana.RelationLockProvider = usersAdminController{}
|
||||
var _ cabana.PermissionEditorProvider = usersAdminController{}
|
||||
|
||||
var _ pact.AdminController = usergroupsAdminController{}
|
||||
var _ pact.AdminPermissioned = usergroupsAdminController{}
|
||||
var _ pact.AdminRecordSource = usergroupsAdminController{}
|
||||
var _ pact.ListExtendQuery = usergroupsAdminController{}
|
||||
var _ pact.FormBeforeCreate = usergroupsAdminController{}
|
||||
var _ pact.FormBeforeUpdate = usergroupsAdminController{}
|
||||
var _ pact.FormBeforeDelete = usergroupsAdminController{}
|
||||
var _ pact.FormAfterDelete = usergroupsAdminController{}
|
||||
var _ cabana.PermissionEditorProvider = usergroupsAdminController{}
|
||||
|
||||
var _ pact.AdminController = organisationsAdminController{}
|
||||
var _ pact.AdminPermissioned = organisationsAdminController{}
|
||||
var _ pact.AdminRecordSource = organisationsAdminController{}
|
||||
var _ pact.FormBeforeCreate = organisationsAdminController{}
|
||||
var _ pact.FormBeforeUpdate = organisationsAdminController{}
|
||||
var _ pact.FormBeforeDelete = organisationsAdminController{}
|
||||
var _ pact.RelationExtendManageQuery = organisationsAdminController{}
|
||||
var _ cabana.AdminRelationContractProvider = organisationsAdminController{}
|
||||
}
|
||||
@@ -108,6 +108,10 @@ func Login(app *backpack.App) http.HandlerFunc {
|
||||
_ = gdb.WithContext(ctx).Model(user).Update("password", next).Error
|
||||
}
|
||||
}
|
||||
// A failed last_seen write is logged and never fails the login.
|
||||
if err := classes.TouchLastSeen(ctx, gdb, user.ID); err != nil {
|
||||
slog.Default().Warn("golem15.user: stamp last_seen on login", "user_id", user.ID, "err", err)
|
||||
}
|
||||
token, err := mintFor(app, secret, user, requestURL(r))
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
@@ -174,7 +178,7 @@ func Fetch(app *backpack.App) http.HandlerFunc {
|
||||
// Refresh slides a still-refreshable bearer token.
|
||||
func Refresh(app *backpack.App) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
_, secret, ok := sessionDeps(w, app)
|
||||
gdb, secret, ok := sessionDeps(w, app)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -195,20 +199,48 @@ func Refresh(app *backpack.App) http.HandlerFunc {
|
||||
})
|
||||
return
|
||||
}
|
||||
// The refresh never loads the user row: the subject comes from the
|
||||
// new token. A failed last_seen write is logged and never fails it.
|
||||
if sub, _, _, _, err := bouncer.VerifyClaims(next, secret); err == nil {
|
||||
if id, err := strconv.ParseUint(sub, 10, 64); err == nil && id != 0 {
|
||||
if err := classes.TouchLastSeen(r.Context(), gdb, uint(id)); err != nil {
|
||||
slog.Default().Warn("golem15.user: stamp last_seen on refresh", "user_id", id, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"token": next})
|
||||
}
|
||||
}
|
||||
|
||||
// OAuthProviders reports that this app configures no social providers.
|
||||
// OAuthProviders lists the social sign-in providers a social-login plugin
|
||||
// has enabled, as {success: true, providers: [{name, label}]}. The plugin
|
||||
// publishes a classes.OAuthProviderSource, looked up on every request
|
||||
// because it boots after this plugin; without one the list is empty.
|
||||
func OAuthProviders(app *backpack.App) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
providers := []any{}
|
||||
if src, ok := oauthProviderSource(app); ok {
|
||||
for _, p := range src.EnabledOAuthProviders(r.Context()) {
|
||||
providers = append(providers, map[string]any{"name": p.Name, "label": p.Label})
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"providers": wire.Slice([]any{}),
|
||||
"providers": wire.Slice(providers),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// oauthProviderSource returns the social-login plugin's published provider
|
||||
// source, if any.
|
||||
func oauthProviderSource(app *backpack.App) (classes.OAuthProviderSource, bool) {
|
||||
if app == nil {
|
||||
return nil, false
|
||||
}
|
||||
src, ok := app.Lookup[classes.OAuthProviderSource]()
|
||||
return src, ok && src != nil
|
||||
}
|
||||
|
||||
const forgotPasswordBody = "If that email exists, a reset link has been sent."
|
||||
|
||||
// ForgotPassword always returns the same 200 body. A real account also gets a reset mail.
|
||||
@@ -636,6 +668,7 @@ func Register(app *backpack.App) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
_ = FireRegisterEvent(r.Context(), app, user, fields)
|
||||
_ = FireCreatedEvent(r.Context(), app, user)
|
||||
ctx := r.Context()
|
||||
if mode == "user" {
|
||||
vars := mailVars(displayName(user), "", "")
|
||||
@@ -668,6 +701,23 @@ func Register(app *backpack.App) http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// RegistrationSettings returns the registration settings /register
|
||||
// applies: allow is golem15.user.registration.allow_registration (default
|
||||
// true), throttle is golem15.user.registration.use_register_throttle
|
||||
// (default true), mode is golem15.user.activation.activate_mode (auto, user
|
||||
// or admin; default auto) and require is
|
||||
// golem15.user.activation.require_activation (default true).
|
||||
func RegistrationSettings(app *backpack.App) (allow, throttle bool, mode string, require bool) {
|
||||
return registrationSettings(app)
|
||||
}
|
||||
|
||||
// RegistrationsFromIP counts the users created from ip in the last 60
|
||||
// minutes (created_ip_address). /register refuses a registration when the
|
||||
// throttle is on and the count is 3 or more. A query error counts as 0.
|
||||
func RegistrationsFromIP(ctx context.Context, gdb *gorm.DB, ip string) int64 {
|
||||
return registrationsFromIP(ctx, gdb, ip)
|
||||
}
|
||||
|
||||
func registrationSettings(app *backpack.App) (allow, throttle bool, mode string, require bool) {
|
||||
allow, throttle, require = true, true, true
|
||||
mode = "auto"
|
||||
@@ -817,6 +867,13 @@ func mintFor(app *backpack.App, secret string, user *models.User, issuer string)
|
||||
return token, err
|
||||
}
|
||||
|
||||
// RefreshTTL is the refresh window of a session token:
|
||||
// golem15.user.jwt.refresh_ttl minutes, default 20160 (two weeks). A cookie
|
||||
// carrying the token should live this long.
|
||||
func RefreshTTL(app *backpack.App) time.Duration {
|
||||
return refreshTTL(app)
|
||||
}
|
||||
|
||||
func refreshTTL(app *backpack.App) time.Duration {
|
||||
mins := 20160
|
||||
if app != nil && app.Config != nil && app.Config.Int("golem15.user.jwt.refresh_ttl") > 0 {
|
||||
@@ -998,6 +1055,13 @@ func requestURL(r *http.Request) string {
|
||||
return scheme + "://" + r.Host + r.URL.Path
|
||||
}
|
||||
|
||||
// RemoteIP returns the host part of r.RemoteAddr, the address /login uses
|
||||
// for its throttle (r.RemoteAddr itself when it has no port, "" when it is
|
||||
// empty). /register records surf.ClientIP with the trusted proxies instead.
|
||||
func RemoteIP(r *http.Request) string {
|
||||
return remoteIP(r)
|
||||
}
|
||||
|
||||
func remoteIP(r *http.Request) string {
|
||||
if r.RemoteAddr == "" {
|
||||
return ""
|
||||
@@ -1269,17 +1333,9 @@ func applyAvatar(ctx context.Context, app *backpack.App, user *models.User, payl
|
||||
}
|
||||
payload["has_avatar"] = true
|
||||
payload["avatar"] = f.DiskName
|
||||
bucket, ok := app.Lookup[*blob.Bucket]()
|
||||
if !ok || bucket == nil {
|
||||
return
|
||||
if url, err := classes.AvatarURL(ctx, app, user, 128); err == nil && url != "" {
|
||||
payload["avatar_url"] = url
|
||||
}
|
||||
url, err := f.Thumb(ctx, bucket, 128, 128, "auto")
|
||||
if err != nil {
|
||||
slog.Default().Error("golem15.user: avatar thumb", "err", err)
|
||||
payload["avatar_url"] = "/" + attach.BlobKey(f.DiskName)
|
||||
return
|
||||
}
|
||||
payload["avatar_url"] = url
|
||||
}
|
||||
|
||||
func avatarExt(mime string) (string, bool) {
|
||||
|
||||
47
controllers/app_access.go
Normal file
47
controllers/app_access.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// appAccess resolves the booted application on every call, so an admin
|
||||
// controller never keeps a database handle or a config of its own.
|
||||
type appAccess func() *backpack.App
|
||||
|
||||
// application returns the booted app, or nil before boot.
|
||||
func (a appAccess) application() *backpack.App {
|
||||
if a == nil {
|
||||
return nil
|
||||
}
|
||||
return a()
|
||||
}
|
||||
|
||||
// db is the application pool, or nil when the app has none.
|
||||
func (a appAccess) db() *gorm.DB {
|
||||
app := a.application()
|
||||
if app == nil {
|
||||
return nil
|
||||
}
|
||||
gdb, ok := app.Lookup[*gorm.DB]()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return gdb
|
||||
}
|
||||
|
||||
// config is the application config, or nil before boot.
|
||||
func (a appAccess) config() *compass.Config {
|
||||
app := a.application()
|
||||
if app == nil {
|
||||
return nil
|
||||
}
|
||||
return app.Config
|
||||
}
|
||||
|
||||
// translator is the application translator, or nil when none is published.
|
||||
func (a appAccess) translator() *phrasebook.Translator {
|
||||
return appTranslator(a.application())
|
||||
}
|
||||
174
controllers/oauth_identities.go
Normal file
174
controllers/oauth_identities.go
Normal file
@@ -0,0 +1,174 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/wire"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// OAuthIdentitiesOptions configures host-mounted list/unlink handlers.
|
||||
// Providers is the unlink allow-list. When nil or empty, the allow-list is
|
||||
// read on every request: the KnownOAuthProviders of a published
|
||||
// classes.OAuthProviderSource, else google, facebook, github and microsoft.
|
||||
// WriteNotFound is injected by the host so 404 bodies match that app.
|
||||
type OAuthIdentitiesOptions struct {
|
||||
Providers []string
|
||||
WriteNotFound func(http.ResponseWriter, *http.Request)
|
||||
}
|
||||
|
||||
// defaultOAuthProviders is the unlink allow-list without options and without
|
||||
// a published provider source.
|
||||
var defaultOAuthProviders = []string{"google", "facebook", "github", "microsoft"}
|
||||
|
||||
// oauthGuardedDelete is the PHP unlink rule (User.php unlinkOAuthProvider):
|
||||
// the identity goes only when the user has a self-set password or another
|
||||
// identity remains.
|
||||
const oauthGuardedDelete = `DELETE FROM golem15_user_oauth_identities
|
||||
WHERE user_id = ? AND provider = ?
|
||||
AND (EXISTS (SELECT 1 FROM users u WHERE u.id = golem15_user_oauth_identities.user_id AND u.has_self_set_password)
|
||||
OR (SELECT COUNT(*) FROM golem15_user_oauth_identities oi WHERE oi.user_id = golem15_user_oauth_identities.user_id) > 1)`
|
||||
|
||||
// OAuthIdentitiesIndex lists the caller's linked OAuth providers.
|
||||
func OAuthIdentitiesIndex(app *backpack.App) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
db, user, ok := oauthIdentityDeps(w, r, app)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var rows []models.OAuthIdentity
|
||||
if err := db.WithContext(r.Context()).
|
||||
Where("user_id = ?", user.ID).
|
||||
Order("provider").
|
||||
Find(&rows).Error; err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
data := make([]map[string]any, 0, len(rows))
|
||||
for i := range rows {
|
||||
item := map[string]any{
|
||||
"provider": rows[i].Provider,
|
||||
"linked_at": nil,
|
||||
}
|
||||
if rows[i].LinkedAt != nil {
|
||||
item["linked_at"] = &wire.Time{Time: rows[i].LinkedAt.UTC()}
|
||||
}
|
||||
data = append(data, item)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": wire.Slice(data)})
|
||||
}
|
||||
}
|
||||
|
||||
// OAuthIdentitiesDestroy unlinks one provider for the caller, under the PHP
|
||||
// rule: it succeeds (204) when the user has a self-set password or another
|
||||
// identity remains, and answers 409 with the last_method_blocked phrase
|
||||
// otherwise. An unknown provider or a missing identity goes to WriteNotFound.
|
||||
func OAuthIdentitiesDestroy(app *backpack.App, opts OAuthIdentitiesOptions) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
db, user, ok := oauthIdentityDeps(w, r, app)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
provider := r.PathValue("provider")
|
||||
if !slices.Contains(unlinkProviders(app, opts), provider) {
|
||||
writeOAuthIdentityNotFound(w, r, opts)
|
||||
return
|
||||
}
|
||||
var row models.OAuthIdentity
|
||||
err := db.WithContext(r.Context()).
|
||||
Where("user_id = ? AND provider = ?", user.ID, provider).
|
||||
First(&row).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
writeOAuthIdentityNotFound(w, r, opts)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
// D-13: the guarded DELETE alone is not race-safe on Postgres. Under
|
||||
// READ COMMITTED two unlinks of different identities each see the
|
||||
// other's row in their COUNT and do not wait for each other, so both
|
||||
// succeed and a password-less user loses every sign-in method. The
|
||||
// lock on the users row serialises them: the second DELETE runs after
|
||||
// the first commits and sees one identity left.
|
||||
var deleted int64
|
||||
err = db.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Exec(`SELECT id FROM users WHERE id = ? FOR UPDATE`, user.ID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
res := tx.Exec(oauthGuardedDelete, user.ID, provider)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
deleted = res.RowsAffected
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
if deleted == 0 {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{
|
||||
"error": oauthLastMethodBlocked(r, app),
|
||||
})
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
// unlinkProviders is the unlink allow-list for one request.
|
||||
func unlinkProviders(app *backpack.App, opts OAuthIdentitiesOptions) []string {
|
||||
if len(opts.Providers) > 0 {
|
||||
return opts.Providers
|
||||
}
|
||||
if src, ok := oauthProviderSource(app); ok {
|
||||
return src.KnownOAuthProviders()
|
||||
}
|
||||
return defaultOAuthProviders
|
||||
}
|
||||
|
||||
func writeOAuthIdentityNotFound(w http.ResponseWriter, r *http.Request, opts OAuthIdentitiesOptions) {
|
||||
if opts.WriteNotFound != nil {
|
||||
opts.WriteNotFound(w, r)
|
||||
return
|
||||
}
|
||||
writeOpaque500(w)
|
||||
}
|
||||
|
||||
func oauthLastMethodBlocked(r *http.Request, app *backpack.App) string {
|
||||
const fallback = "This is the only remaining way to sign in. Link another method before disconnecting this one."
|
||||
tr := appTranslator(app)
|
||||
if tr == nil {
|
||||
return fallback
|
||||
}
|
||||
s := tr.Get(r.Context(), "golem15.user::lang.oauth.last_method_blocked", nil)
|
||||
if s == "" || s == "golem15.user::lang.oauth.last_method_blocked" {
|
||||
return fallback
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func oauthIdentityDeps(w http.ResponseWriter, r *http.Request, app *backpack.App) (*gorm.DB, *bouncer.Principal, bool) {
|
||||
if app == nil {
|
||||
writeOpaque500(w)
|
||||
return nil, nil, false
|
||||
}
|
||||
db, ok := app.Lookup[*gorm.DB]()
|
||||
if !ok || db == nil {
|
||||
writeOpaque500(w)
|
||||
return nil, nil, false
|
||||
}
|
||||
user, ok := bouncer.User(r.Context())
|
||||
if !ok || user == nil || user.ID == 0 {
|
||||
writeUnauthorized(w)
|
||||
return nil, nil, false
|
||||
}
|
||||
return db, user, true
|
||||
}
|
||||
18
controllers/organisations/config_form.yaml
Normal file
18
controllers/organisations/config_form.yaml
Normal file
@@ -0,0 +1,18 @@
|
||||
name: golem15.user::lang.organisation.label
|
||||
form: ~/plugins/golem15/user/models/organisation/fields.yaml
|
||||
modelClass: Golem15\User\Models\Organisation
|
||||
defaultRedirect: golem15/user/organisations
|
||||
|
||||
create:
|
||||
redirect: golem15/user/organisations/update/:id
|
||||
redirectClose: golem15/user/organisations
|
||||
|
||||
update:
|
||||
redirect: golem15/user/organisations
|
||||
redirectClose: golem15/user/organisations
|
||||
|
||||
messages:
|
||||
create: golem15.user::lang.organisation.new
|
||||
update: backend::lang.messages.form.update
|
||||
saved: backend::lang.messages.form.saved
|
||||
deleted: backend::lang.messages.form.deleted
|
||||
15
controllers/organisations/config_list.yaml
Normal file
15
controllers/organisations/config_list.yaml
Normal file
@@ -0,0 +1,15 @@
|
||||
list: ~/plugins/golem15/user/models/organisation/columns.yaml
|
||||
modelClass: Golem15\User\Models\Organisation
|
||||
title: golem15.user::lang.organisation.label_plural
|
||||
recordUrl: golem15/user/organisations/update/:id
|
||||
noRecordsMessage: backend::lang.list.no_records
|
||||
recordsPerPage: 20
|
||||
|
||||
toolbar:
|
||||
buttons: [create]
|
||||
search:
|
||||
prompt: backend::lang.list.search_prompt
|
||||
|
||||
messages:
|
||||
create: golem15.user::lang.organisation.new
|
||||
empty: golem15.user::lang.organisation.list_empty
|
||||
24
controllers/organisations/config_relation.yaml
Normal file
24
controllers/organisations/config_relation.yaml
Normal file
@@ -0,0 +1,24 @@
|
||||
members:
|
||||
label: golem15.user::lang.organisation.members
|
||||
messages:
|
||||
link: golem15.user::lang.organisation.add_member
|
||||
unlinkSelected: golem15.user::lang.organisation.remove_members
|
||||
unlinkConfirm: golem15.user::lang.organisation.remove_members_confirm
|
||||
empty: golem15.user::lang.organisation.members_empty
|
||||
view:
|
||||
list:
|
||||
columns:
|
||||
name:
|
||||
label: golem15.user::lang.user.name
|
||||
email:
|
||||
label: golem15.user::lang.user.email
|
||||
toolbarButtons: link|unlink
|
||||
showSearch: true
|
||||
manage:
|
||||
list:
|
||||
columns:
|
||||
name:
|
||||
label: golem15.user::lang.user.name
|
||||
email:
|
||||
label: golem15.user::lang.user.email
|
||||
showSearch: true
|
||||
117
controllers/organisations_admin_controller.go
Normal file
117
controllers/organisations_admin_controller.go
Normal file
@@ -0,0 +1,117 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"regexp"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// organisationSlugPattern is the PHP alpha_dash rule on the slug, kept to
|
||||
// ASCII. lagoon.Validate has no alpha_dash token, so the Form before-hooks
|
||||
// check it.
|
||||
var organisationSlugPattern = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
|
||||
|
||||
// membersRelation is the organisation's hasMany relation to its users.
|
||||
const membersRelation = "members"
|
||||
|
||||
// organisationsAdminController is the Winter Organisations backend
|
||||
// controller: the list, the form with the avatar, and the members relation
|
||||
// manager. The screen and every write need golem15.users.access_users, as in
|
||||
// PHP.
|
||||
//
|
||||
// The members manager sets and clears users.organisation_id and nothing
|
||||
// else. It never writes users_groups.
|
||||
type organisationsAdminController struct {
|
||||
app appAccess
|
||||
}
|
||||
|
||||
func (organisationsAdminController) ID() string { return "golem15.user.organisations" }
|
||||
|
||||
func (organisationsAdminController) ModelName() string { return `Golem15\User\Models\Organisation` }
|
||||
|
||||
func (organisationsAdminController) ConfigDir() string { return "controllers/organisations" }
|
||||
|
||||
func (organisationsAdminController) RequiredPermissions() []string {
|
||||
return []string{PermissionAccessUsers}
|
||||
}
|
||||
|
||||
func (organisationsAdminController) NewRecord() any { return &models.Organisation{} }
|
||||
|
||||
// FormBeforeCreate and FormBeforeUpdate check the slug's characters.
|
||||
func (c organisationsAdminController) FormBeforeCreate(ctx context.Context, model any) error {
|
||||
return c.requireSlugFormat(ctx, model)
|
||||
}
|
||||
|
||||
func (c organisationsAdminController) FormBeforeUpdate(ctx context.Context, model any) error {
|
||||
return c.requireSlugFormat(ctx, model)
|
||||
}
|
||||
|
||||
// requireSlugFormat answers 422 on slug when it holds anything but letters,
|
||||
// digits, underscore and hyphen. An empty slug is left to the required rule.
|
||||
func (c organisationsAdminController) requireSlugFormat(ctx context.Context, model any) error {
|
||||
organisation, ok := model.(*models.Organisation)
|
||||
if !ok || organisation == nil {
|
||||
return errors.New("organisations admin: form model is not an organisation")
|
||||
}
|
||||
if organisation.Slug == "" || organisationSlugPattern.MatchString(organisation.Slug) {
|
||||
return nil
|
||||
}
|
||||
message := "The slug may only contain letters, numbers, dashes and underscores."
|
||||
if tr := c.app.translator(); tr != nil {
|
||||
const key = "golem15.user::lang.organisation.slug_invalid"
|
||||
if text := tr.Get(ctx, key, nil); text != "" && text != key {
|
||||
message = text
|
||||
}
|
||||
}
|
||||
return &cabana.ValidationError{Details: map[string]any{"slug": []string{message}}}
|
||||
}
|
||||
|
||||
// AdminRelationContracts declares the members relation manager: the users
|
||||
// whose organisation_id is the organisation. Linking sets the column and
|
||||
// unlinking clears it; the column is nullable, so a user is never deleted.
|
||||
func (organisationsAdminController) AdminRelationContracts() []cabana.RelationContract {
|
||||
return []cabana.RelationContract{{
|
||||
Name: membersRelation,
|
||||
Kind: cabana.RelationHasMany,
|
||||
NewRelated: func() any { return &models.User{} },
|
||||
ForeignKey: "organisation_id",
|
||||
Columns: map[string]string{
|
||||
"name": "name",
|
||||
"email": "email",
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
// RelationExtendManageQuery fails closed: any relation name other than
|
||||
// members has no candidates.
|
||||
func (organisationsAdminController) RelationExtendManageQuery(_ context.Context, relation string, db *gorm.DB) *gorm.DB {
|
||||
if db == nil {
|
||||
return db
|
||||
}
|
||||
if relation != membersRelation {
|
||||
return db.Where("1 = 0")
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
// FormBeforeDelete releases the members of the organisation in the delete's
|
||||
// transaction: organisation_id and organisation_role are cleared, on
|
||||
// deactivated users too, so the delete does not fail on the users foreign key
|
||||
// and no user is deleted.
|
||||
func (organisationsAdminController) FormBeforeDelete(ctx context.Context, model any) error {
|
||||
organisation, ok := model.(*models.Organisation)
|
||||
if !ok || organisation == nil {
|
||||
return errors.New("organisations admin: form model is not an organisation")
|
||||
}
|
||||
tx, ok := cabana.TxFromContext(ctx)
|
||||
if !ok {
|
||||
return errors.New("organisations admin: a delete needs its transaction")
|
||||
}
|
||||
return tx.Session(&gorm.Session{NewDB: true}).WithContext(ctx).Unscoped().
|
||||
Model(&models.User{}).Where("organisation_id = ?", organisation.ID).
|
||||
Updates(map[string]any{"organisation_id": nil, "organisation_role": nil}).Error
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package controllers
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"net/http"
|
||||
"time"
|
||||
@@ -26,6 +27,11 @@ import (
|
||||
type RegisterOptions struct {
|
||||
Activate bool
|
||||
IP string
|
||||
// PasswordLess creates the account with has_self_set_password=false: its
|
||||
// password is random and was never known to the user (social sign-in,
|
||||
// PHP password_bootstrap_source oauth_registration). The zero value
|
||||
// keeps true.
|
||||
PasswordLess bool
|
||||
}
|
||||
|
||||
// RegisterUser validates fields against the user model's rules, hashes the
|
||||
@@ -68,7 +74,7 @@ func RegisterUser(ctx context.Context, app *backpack.App, db *gorm.DB, fields ma
|
||||
if err := lagoon.Fill(user, user.Fillable(), input, production); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
user.HasSelfSetPassword = true
|
||||
user.HasSelfSetPassword = !opts.PasswordLess
|
||||
if opts.Activate {
|
||||
user.IsActivated = true
|
||||
now := time.Now()
|
||||
@@ -77,9 +83,46 @@ func RegisterUser(ctx context.Context, app *backpack.App, db *gorm.DB, fields ma
|
||||
if err := db.WithContext(ctx).Create(user).Error; err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if err := classes.AssignHandle(ctx, db, user); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return user, nil, nil
|
||||
}
|
||||
|
||||
// FinishLogin runs the steps password Login takes after it has
|
||||
// authenticated a user, 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. It
|
||||
// checks no password, throttle, activation or ban and fires no event; the
|
||||
// caller does those checks (Go has no login event). A failed last_seen
|
||||
// write is logged and does not fail it, as in Login.
|
||||
func FinishLogin(ctx context.Context, app *backpack.App, db *gorm.DB, user *models.User, ip string) error {
|
||||
if db == nil {
|
||||
return errors.New("golem15.user: gorm handle is missing")
|
||||
}
|
||||
if user == nil || user.ID == 0 {
|
||||
return errors.New("golem15.user: finishing a login needs a stored user")
|
||||
}
|
||||
if user.DeletedAt.Valid {
|
||||
if err := db.WithContext(ctx).Unscoped().Model(user).Update("deleted_at", nil).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
user.DeletedAt = gorm.DeletedAt{}
|
||||
sendTemplateVars(ctx, app, mailName(ctx, 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 {
|
||||
return err
|
||||
}
|
||||
addr := ip
|
||||
user.LastIPAddress = &addr
|
||||
}
|
||||
if err := classes.TouchLastSeen(ctx, db, user.ID); err != nil {
|
||||
slog.Default().Warn("golem15.user: stamp last_seen on login", "user_id", user.ID, "err", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FireRegisterEvent fires classes.RegisterEvent for user with Payload set
|
||||
// to a copy of fields without password and password_confirmation, and
|
||||
// returns the listeners' error. /register ignores that error, as Winter
|
||||
@@ -97,6 +140,36 @@ func FireRegisterEvent(ctx context.Context, app *backpack.App, user *models.User
|
||||
return app.Events.Fire(ctx, &classes.RegisterEvent{User: user, Payload: payload})
|
||||
}
|
||||
|
||||
// FireCreatedEvent fires classes.CreatedEvent (user.Created) for user and
|
||||
// returns the listeners' error. /register ignores that error, as it does
|
||||
// for FireRegisterEvent.
|
||||
func FireCreatedEvent(ctx context.Context, app *backpack.App, user *models.User) error {
|
||||
if app == nil || app.Events == nil {
|
||||
return nil
|
||||
}
|
||||
return app.Events.Fire(ctx, &classes.CreatedEvent{User: user})
|
||||
}
|
||||
|
||||
// FireDeletingEvent fires classes.DeletingEvent (user.Deleting) for user
|
||||
// inside the delete transaction. FormAfterDelete returns the listeners'
|
||||
// error so a failed cascade rolls the delete back.
|
||||
func FireDeletingEvent(ctx context.Context, app *backpack.App, user *models.User, tx *gorm.DB) error {
|
||||
if app == nil || app.Events == nil {
|
||||
return nil
|
||||
}
|
||||
return app.Events.Fire(ctx, &classes.DeletingEvent{User: user, Tx: tx})
|
||||
}
|
||||
|
||||
// FireDeactivatingEvent fires classes.DeactivatingEvent (user.Deactivating)
|
||||
// for user inside the deactivation transaction and returns the listeners'
|
||||
// error, so a failed listener rolls the deactivation back.
|
||||
func FireDeactivatingEvent(ctx context.Context, app *backpack.App, user *models.User, tx *gorm.DB) error {
|
||||
if app == nil || app.Events == nil {
|
||||
return nil
|
||||
}
|
||||
return app.Events.Fire(ctx, &classes.DeactivatingEvent{User: user, Tx: tx})
|
||||
}
|
||||
|
||||
// IssueToken mints the session JWT for user exactly as /register and
|
||||
// /login do: the plugin's JWT secret, golem15.user.jwt.ttl and the request
|
||||
// URL as the issuer.
|
||||
|
||||
23
controllers/request_db.go
Normal file
23
controllers/request_db.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// requestDB is the database handle a hook or scope should read through. Inside
|
||||
// an admin write it is the transaction the write runs in, so the hook sees the
|
||||
// write's snapshot and does not take a second pool connection while the
|
||||
// transaction holds row locks. Outside a transaction (the list) it is the
|
||||
// application pool from the booted app. It is nil when neither exists.
|
||||
func requestDB(ctx context.Context, pool func() *gorm.DB) *gorm.DB {
|
||||
if tx, ok := cabana.TxFromContext(ctx); ok {
|
||||
return tx
|
||||
}
|
||||
if pool == nil {
|
||||
return nil
|
||||
}
|
||||
return pool()
|
||||
}
|
||||
19
controllers/usergroups/config_form.yaml
Normal file
19
controllers/usergroups/config_form.yaml
Normal file
@@ -0,0 +1,19 @@
|
||||
name: golem15.user::lang.group.label
|
||||
form: ~/plugins/golem15/user/models/usergroup/fields.yaml
|
||||
modelClass: Golem15\User\Models\UserGroup
|
||||
defaultRedirect: golem15/user/usergroups
|
||||
|
||||
create:
|
||||
redirect: golem15/user/usergroups/update/:id
|
||||
redirectClose: golem15/user/usergroups
|
||||
|
||||
update:
|
||||
redirect: golem15/user/usergroups
|
||||
redirectClose: golem15/user/usergroups
|
||||
|
||||
messages:
|
||||
create: golem15.user::lang.groups.new_group
|
||||
update: backend::lang.messages.form.update
|
||||
saved: backend::lang.messages.form.saved
|
||||
deleteConfirm: golem15.user::lang.groups.delete_confirm
|
||||
deleted: backend::lang.messages.form.deleted
|
||||
17
controllers/usergroups/config_list.yaml
Normal file
17
controllers/usergroups/config_list.yaml
Normal file
@@ -0,0 +1,17 @@
|
||||
list: ~/plugins/golem15/user/models/usergroup/columns.yaml
|
||||
modelClass: Golem15\User\Models\UserGroup
|
||||
title: golem15.user::lang.groups.list_title
|
||||
recordUrl: golem15/user/usergroups/update/:id
|
||||
noRecordsMessage: backend::lang.list.no_records
|
||||
recordsPerPage: 20
|
||||
showSetup: true
|
||||
showSorting: true
|
||||
|
||||
toolbar:
|
||||
buttons: [create]
|
||||
search:
|
||||
prompt: backend::lang.list.search_prompt
|
||||
|
||||
messages:
|
||||
create: golem15.user::lang.groups.new_group
|
||||
empty: golem15.user::lang.groups.list_empty
|
||||
246
controllers/usergroups_admin_controller.go
Normal file
246
controllers/usergroups_admin_controller.go
Normal file
@@ -0,0 +1,246 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// PermissionAccessGroups is the backend permission of the User Groups
|
||||
// screen, the PHP UserGroups::$requiredPermissions.
|
||||
const PermissionAccessGroups = "golem15.users.access_groups"
|
||||
|
||||
// groupsLang prefixes the phrase keys of the User Groups screen.
|
||||
const groupsLang = "golem15.user::lang.groups."
|
||||
|
||||
// groupCodePattern is the PHP UserGroup code rule
|
||||
// regex:/^[a-zA-Z0-9_\-]+$/. lagoon.Validate has no regex token, so the
|
||||
// Form before-hooks check it.
|
||||
var groupCodePattern = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
|
||||
|
||||
// usergroupsAdminController is the Winter UserGroups backend controller: the
|
||||
// list with the member count and the form with the frontend permissions of
|
||||
// the group. The screen and every write need golem15.users.access_groups.
|
||||
//
|
||||
// A group's code decides whether its members are privileged
|
||||
// (golem15.user.privileged_groups), so three writes additionally need
|
||||
// golem15.users.manage_privileged_groups: creating a group with a privileged
|
||||
// code, changing a code to or from a privileged one, and deleting a
|
||||
// privileged group. Everything else on a privileged group (its name,
|
||||
// description and frontend permissions) needs only the screen's permission.
|
||||
//
|
||||
// The screen never writes a membership: users_groups changes only through
|
||||
// the user form's groups field, and loses the rows of a deleted group.
|
||||
type usergroupsAdminController struct {
|
||||
app appAccess
|
||||
}
|
||||
|
||||
func (usergroupsAdminController) ID() string { return "golem15.user.usergroups" }
|
||||
|
||||
func (usergroupsAdminController) ModelName() string { return `Golem15\User\Models\UserGroup` }
|
||||
|
||||
func (usergroupsAdminController) ConfigDir() string { return "controllers/usergroups" }
|
||||
|
||||
func (usergroupsAdminController) RequiredPermissions() []string {
|
||||
return []string{PermissionAccessGroups}
|
||||
}
|
||||
|
||||
func (usergroupsAdminController) NewRecord() any { return &models.UserGroup{} }
|
||||
|
||||
// ListExtendQuery adds the member count of every group on the page, the PHP
|
||||
// users_count relation column, in the list's own query. The two select
|
||||
// arguments keep the list's count query a plain COUNT(*).
|
||||
func (usergroupsAdminController) ListExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB {
|
||||
if db == nil {
|
||||
return db
|
||||
}
|
||||
return db.Select("user_groups.*",
|
||||
"(SELECT COUNT(*) FROM users_groups WHERE users_groups.user_group_id = user_groups.id) AS users_count")
|
||||
}
|
||||
|
||||
// FormBeforeCreate checks the code's format and refuses a privileged code
|
||||
// without golem15.users.manage_privileged_groups.
|
||||
func (c usergroupsAdminController) FormBeforeCreate(ctx context.Context, model any) error {
|
||||
group, ok := model.(*models.UserGroup)
|
||||
if !ok || group == nil {
|
||||
return errors.New("user groups admin: form model is not a user group")
|
||||
}
|
||||
if err := c.requireCodeFormat(ctx, group); err != nil {
|
||||
return err
|
||||
}
|
||||
if !classes.IsPrivilegedCode(classes.PrivilegedGroupCodes(c.app.config()), group.Code) {
|
||||
return nil
|
||||
}
|
||||
return c.requirePrivilegedPermission(ctx)
|
||||
}
|
||||
|
||||
// FormBeforeUpdate checks the code's format and refuses a code change to or
|
||||
// from a privileged code without golem15.users.manage_privileged_groups. The
|
||||
// stored code is read through the write's transaction; a save that leaves
|
||||
// the code as it is passes, whatever the code.
|
||||
func (c usergroupsAdminController) FormBeforeUpdate(ctx context.Context, model any) error {
|
||||
group, ok := model.(*models.UserGroup)
|
||||
if !ok || group == nil {
|
||||
return errors.New("user groups admin: form model is not a user group")
|
||||
}
|
||||
if err := c.requireCodeFormat(ctx, group); err != nil {
|
||||
return err
|
||||
}
|
||||
db := requestDB(ctx, c.app.db)
|
||||
if db == nil {
|
||||
return errors.New("user groups admin: gorm handle is missing")
|
||||
}
|
||||
var stored []struct{ Code *string }
|
||||
err := db.Session(&gorm.Session{NewDB: true}).WithContext(ctx).
|
||||
Table("user_groups").Select("code").Where("id = ?", group.ID).Scan(&stored).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(stored) != 1 {
|
||||
return errors.New("user groups admin: the group being updated was not found")
|
||||
}
|
||||
if sameCode(stored[0].Code, group.Code) {
|
||||
return nil
|
||||
}
|
||||
codes := classes.PrivilegedGroupCodes(c.app.config())
|
||||
if !classes.IsPrivilegedCode(codes, stored[0].Code) && !classes.IsPrivilegedCode(codes, group.Code) {
|
||||
return nil
|
||||
}
|
||||
return c.requirePrivilegedPermission(ctx)
|
||||
}
|
||||
|
||||
// FormBeforeDelete refuses the delete of a privileged group without
|
||||
// golem15.users.manage_privileged_groups: it would take the privilege from
|
||||
// every member. The record is the stored row, loaded in the delete's
|
||||
// transaction.
|
||||
func (c usergroupsAdminController) FormBeforeDelete(ctx context.Context, model any) error {
|
||||
group, ok := model.(*models.UserGroup)
|
||||
if !ok || group == nil {
|
||||
return errors.New("user groups admin: form model is not a user group")
|
||||
}
|
||||
if !classes.IsPrivilegedCode(classes.PrivilegedGroupCodes(c.app.config()), group.Code) {
|
||||
return nil
|
||||
}
|
||||
return c.requirePrivilegedPermission(ctx)
|
||||
}
|
||||
|
||||
// FormAfterDelete removes the memberships of the deleted group in the same
|
||||
// transaction: users_groups has no foreign key that would do it. The member
|
||||
// users stay.
|
||||
func (usergroupsAdminController) FormAfterDelete(ctx context.Context, model any) error {
|
||||
group, ok := model.(*models.UserGroup)
|
||||
if !ok || group == nil {
|
||||
return errors.New("user groups admin: form model is not a user group")
|
||||
}
|
||||
tx, ok := cabana.TxFromContext(ctx)
|
||||
if !ok {
|
||||
return errors.New("user groups admin: a delete needs its transaction")
|
||||
}
|
||||
return tx.Session(&gorm.Session{NewDB: true}).WithContext(ctx).
|
||||
Where("user_group_id = ?", group.ID).Delete(&models.UsersGroup{}).Error
|
||||
}
|
||||
|
||||
// requirePrivilegedPermission answers nil when the administrator on ctx
|
||||
// holds golem15.users.manage_privileged_groups, else the 403 of the screen.
|
||||
// A context without a principal is refused.
|
||||
func (usergroupsAdminController) requirePrivilegedPermission(ctx context.Context) error {
|
||||
principal, _ := bouncer.User(ctx)
|
||||
if cabana.Allows(principal, []string{classes.PermissionManagePrivilegedGroups}) {
|
||||
return nil
|
||||
}
|
||||
const message = groupsLang + "privileged_forbidden"
|
||||
return &cabana.ForbiddenError{Message: message, Details: map[string]any{"code": []string{message}}}
|
||||
}
|
||||
|
||||
// requireCodeFormat answers 422 on code when it holds anything but letters,
|
||||
// digits, underscore and hyphen. An empty code is left to the required rule.
|
||||
func (c usergroupsAdminController) requireCodeFormat(ctx context.Context, group *models.UserGroup) error {
|
||||
if group.Code == nil || *group.Code == "" || groupCodePattern.MatchString(*group.Code) {
|
||||
return nil
|
||||
}
|
||||
message := "The code may only contain letters, numbers, dashes and underscores."
|
||||
if tr := c.app.translator(); tr != nil {
|
||||
const key = "golem15.user::lang.group.code_invalid"
|
||||
if text := tr.Get(ctx, key, nil); text != "" && text != key {
|
||||
message = text
|
||||
}
|
||||
}
|
||||
return &cabana.ValidationError{Details: map[string]any{"code": []string{message}}}
|
||||
}
|
||||
|
||||
// sameCode compares two nullable group codes, case-sensitively.
|
||||
func sameCode(a, b *string) bool {
|
||||
if a == nil || b == nil {
|
||||
return a == nil && b == nil
|
||||
}
|
||||
return *a == *b
|
||||
}
|
||||
|
||||
// AdminPermissionOptions offers the rows of
|
||||
// golem15_user_frontend_permissions, by tab and code. None is locked.
|
||||
func (c usergroupsAdminController) AdminPermissionOptions(ctx context.Context, field string) ([]cabana.PermissionOption, error) {
|
||||
if field != permissionsField {
|
||||
return nil, fmt.Errorf("user groups admin: unknown permission field %q", field)
|
||||
}
|
||||
db := requestDB(ctx, c.app.db)
|
||||
if db == nil {
|
||||
return nil, errors.New("user groups admin: gorm handle is missing")
|
||||
}
|
||||
rows, err := classes.FrontendPermissionOptions(ctx, db)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
options := make([]cabana.PermissionOption, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
option := cabana.PermissionOption{Code: row.Code, Label: row.Label, Tab: row.Tab}
|
||||
if row.Comment != nil {
|
||||
option.Comment = *row.Comment
|
||||
}
|
||||
options = append(options, option)
|
||||
}
|
||||
return options, nil
|
||||
}
|
||||
|
||||
// AdminPermissionValues returns the group's stored permissions, read with
|
||||
// the tolerance of models.ParsePermissionSet.
|
||||
func (usergroupsAdminController) AdminPermissionValues(_ context.Context, field string, record any) (map[string]int, error) {
|
||||
group, ok := record.(*models.UserGroup)
|
||||
if field != permissionsField || !ok || group == nil {
|
||||
return nil, fmt.Errorf("user groups admin: cannot read permission field %q", field)
|
||||
}
|
||||
if group.Permissions == nil {
|
||||
return map[string]int{}, nil
|
||||
}
|
||||
set, err := models.ParsePermissionSet([]byte(*group.Permissions))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
values := make(map[string]int, len(set))
|
||||
for code, value := range set {
|
||||
values[code] = value
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// AdminSetPermissionValues writes the validated set back as the JSON object
|
||||
// PHP stores (checkbox mode: 1 per allowed code), or NULL for an empty set.
|
||||
// The save writes the row.
|
||||
func (usergroupsAdminController) AdminSetPermissionValues(_ context.Context, field string, record any, values map[string]int) error {
|
||||
group, ok := record.(*models.UserGroup)
|
||||
if field != permissionsField || !ok || group == nil {
|
||||
return fmt.Errorf("user groups admin: cannot write permission field %q", field)
|
||||
}
|
||||
set := make(models.PermissionSet, len(values))
|
||||
for code, value := range values {
|
||||
set[code] = value
|
||||
}
|
||||
group.Permissions = set.Text()
|
||||
return nil
|
||||
}
|
||||
7
controllers/users/_hint.htm
Normal file
7
controllers/users/_hint.htm
Normal file
@@ -0,0 +1,7 @@
|
||||
{{- /* Status hint above the user preview: one callout, or nothing (usersHintView). */ -}}
|
||||
{{- if .Data.Title -}}
|
||||
<div class="summer-callout summer-callout--{{ .Data.Kind }}" role="status">
|
||||
<p class="summer-callout__title">{{ trans .Data.Title }}</p>
|
||||
<p class="summer-callout__text">{{ trans .Data.Text }}</p>
|
||||
</div>
|
||||
{{- end -}}
|
||||
14
controllers/users/config_filter.yaml
Normal file
14
controllers/users/config_filter.yaml
Normal file
@@ -0,0 +1,14 @@
|
||||
scopes:
|
||||
groups:
|
||||
label: golem15.user::lang.group.label
|
||||
modelClass: Golem15\User\Models\UserGroup
|
||||
nameFrom: name
|
||||
scope: filterByGroup
|
||||
created_date:
|
||||
label: golem15.user::lang.user.created_at
|
||||
type: daterange
|
||||
column: created_at
|
||||
activated:
|
||||
label: golem15.user::lang.user.status_activated
|
||||
type: switch
|
||||
column: is_activated
|
||||
25
controllers/users/config_form.yaml
Normal file
25
controllers/users/config_form.yaml
Normal file
@@ -0,0 +1,25 @@
|
||||
name: golem15.user::lang.user.label
|
||||
form: ~/plugins/golem15/user/models/user/fields.yaml
|
||||
modelClass: Golem15\User\Models\User
|
||||
defaultRedirect: golem15/user/users
|
||||
|
||||
create:
|
||||
redirect: golem15/user/users/preview/:id
|
||||
redirectClose: golem15/user/users
|
||||
|
||||
update:
|
||||
redirect: golem15/user/users/update/:id
|
||||
redirectClose: golem15/user/users/preview/:id
|
||||
|
||||
preview:
|
||||
headerPartial: hint
|
||||
|
||||
recordActions: [activate, unban, unsuspend]
|
||||
|
||||
messages:
|
||||
create: golem15.user::lang.users.new_user
|
||||
update: backend::lang.messages.form.update
|
||||
saved: backend::lang.messages.form.saved
|
||||
deleteConfirm: golem15.user::lang.users.delete_confirm
|
||||
deleted: backend::lang.messages.form.deleted
|
||||
edit: golem15.user::lang.users.update_details
|
||||
25
controllers/users/config_list.yaml
Normal file
25
controllers/users/config_list.yaml
Normal file
@@ -0,0 +1,25 @@
|
||||
list: ~/plugins/golem15/user/models/user/columns.yaml
|
||||
modelClass: Golem15\User\Models\User
|
||||
title: golem15.user::lang.users.list_title
|
||||
recordUrl: golem15/user/users/preview/:id
|
||||
noRecordsMessage: backend::lang.list.no_records
|
||||
recordsPerPage: 20
|
||||
showCheckboxes: true
|
||||
showSetup: true
|
||||
filter: config_filter.yaml
|
||||
|
||||
toolbar:
|
||||
buttons: [create, delete]
|
||||
search:
|
||||
prompt: backend::lang.list.search_prompt
|
||||
|
||||
bulkActions: [activate, deactivate, restore, ban, unban]
|
||||
|
||||
messages:
|
||||
create: golem15.user::lang.users.new_user
|
||||
empty: golem15.user::lang.users.list_empty
|
||||
deleteConfirm: golem15.user::lang.users.delete_selected_confirm
|
||||
deleted: backend::lang.messages.list.deleted
|
||||
rowStateDeleted: golem15.user::lang.users.state_deactivated
|
||||
rowStateNegative: golem15.user::lang.users.state_banned
|
||||
rowStateDisabled: golem15.user::lang.users.state_not_activated
|
||||
747
controllers/users_admin_controller.go
Normal file
747
controllers/users_admin_controller.go
Normal file
@@ -0,0 +1,747 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"gocloud.dev/blob"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// PermissionAccessUsers is the backend permission of the Users screen, the
|
||||
// PHP Users::$requiredPermissions.
|
||||
const PermissionAccessUsers = "golem15.users.access_users"
|
||||
|
||||
// usersLang prefixes the phrase keys of the Users screen.
|
||||
const usersLang = "golem15.user::lang.users."
|
||||
|
||||
// usersAdminController is the Winter Users backend controller: the list with
|
||||
// its filters and row states, and the form. The screen and every write need
|
||||
// golem15.users.access_users.
|
||||
//
|
||||
// app is resolved per call from the booted plugin. Nothing is cached: the
|
||||
// database handle, the config and the privileged group list are read when a
|
||||
// request needs them.
|
||||
type usersAdminController struct {
|
||||
app func() *backpack.App
|
||||
}
|
||||
|
||||
func (usersAdminController) ID() string { return "golem15.user.users" }
|
||||
|
||||
func (usersAdminController) ModelName() string { return `Golem15\User\Models\User` }
|
||||
|
||||
func (usersAdminController) ConfigDir() string { return "controllers/users" }
|
||||
|
||||
func (usersAdminController) RequiredPermissions() []string {
|
||||
return []string{PermissionAccessUsers}
|
||||
}
|
||||
|
||||
func (usersAdminController) NewRecord() any { return &models.User{} }
|
||||
|
||||
// application returns the booted app, or nil before boot.
|
||||
func (c usersAdminController) application() *backpack.App {
|
||||
if c.app == nil {
|
||||
return nil
|
||||
}
|
||||
return c.app()
|
||||
}
|
||||
|
||||
// db is the application pool, or nil when the app has none.
|
||||
func (c usersAdminController) db() *gorm.DB {
|
||||
app := c.application()
|
||||
if app == nil {
|
||||
return nil
|
||||
}
|
||||
gdb, ok := app.Lookup[*gorm.DB]()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return gdb
|
||||
}
|
||||
|
||||
// config is the application config, or nil before boot.
|
||||
func (c usersAdminController) config() *compass.Config {
|
||||
app := c.application()
|
||||
if app == nil {
|
||||
return nil
|
||||
}
|
||||
return app.Config
|
||||
}
|
||||
|
||||
// ListExtendQuery and FormExtendQuery include deactivated (soft-deleted)
|
||||
// users, the PHP listExtendQuery and formExtendQuery withTrashed().
|
||||
func (usersAdminController) ListExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB {
|
||||
if db == nil {
|
||||
return db
|
||||
}
|
||||
return db.Unscoped()
|
||||
}
|
||||
|
||||
func (usersAdminController) FormExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB {
|
||||
if db == nil {
|
||||
return db
|
||||
}
|
||||
return db.Unscoped()
|
||||
}
|
||||
|
||||
// ListRowStates is the PHP listInjectRowClass: deleted for a deactivated
|
||||
// user, negative for a banned one, disabled for one who is not activated.
|
||||
// The ban state of the whole page comes from one user_throttle query.
|
||||
func (c usersAdminController) ListRowStates(ctx context.Context, db *gorm.DB, records []any) ([][]pact.RowState, error) {
|
||||
ids := make([]uint, 0, len(records))
|
||||
for _, record := range records {
|
||||
user, ok := record.(*models.User)
|
||||
if !ok || user == nil {
|
||||
return nil, errors.New("users admin: list record is not a user")
|
||||
}
|
||||
ids = append(ids, user.ID)
|
||||
}
|
||||
banned, _, err := classes.ThrottleStates(classes.ContextWithThrottle(ctx, c.application()), db, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([][]pact.RowState, len(records))
|
||||
for i, record := range records {
|
||||
user := record.(*models.User)
|
||||
if user.DeletedAt.Valid {
|
||||
out[i] = append(out[i], pact.RowStateDeleted)
|
||||
}
|
||||
if banned[user.ID] {
|
||||
out[i] = append(out[i], pact.RowStateNegative)
|
||||
}
|
||||
if !user.IsActivated {
|
||||
out[i] = append(out[i], pact.RowStateDisabled)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// FormVirtualFields are the form fields that are not columns of the form:
|
||||
// the password with its confirmation, and the create-only invitation
|
||||
// checkbox. The framework never fills or returns them; the Form hooks read
|
||||
// them with cabana.VirtualFieldsFromContext.
|
||||
func (usersAdminController) FormVirtualFields() []string {
|
||||
return []string{"password", "password_confirmation", "send_invite"}
|
||||
}
|
||||
|
||||
// FormRules are the rules of an admin save. They replace User.Rules(), which
|
||||
// is the register contract and would ask every admin update for a confirmed
|
||||
// password: a create needs a confirmed password, an update takes one only
|
||||
// when the administrator types it (empty means unchanged). The minimum
|
||||
// length is golem15.user.password.min_length.
|
||||
func (c usersAdminController) FormRules(_ context.Context, op string) map[string]string {
|
||||
length := "between:" + strconv.Itoa(c.configInt("golem15.user.password.min_length", 8)) + ",255"
|
||||
password := "nullable|" + length + "|confirmed"
|
||||
if op == "create" {
|
||||
password = "required|" + length + "|confirmed"
|
||||
}
|
||||
return map[string]string{
|
||||
"email": "required|between:6,255|email|unique:users",
|
||||
"password": password,
|
||||
}
|
||||
}
|
||||
|
||||
// configInt reads a positive integer config value, else fallback.
|
||||
func (c usersAdminController) configInt(key string, fallback int) int {
|
||||
if cfg := c.config(); cfg != nil {
|
||||
if n := cfg.Int(key); n > 0 {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
// FilterOptions serves the choices of the groups filter (scope
|
||||
// filterByGroup): every user group by name. Any other scope has no choices.
|
||||
func (c usersAdminController) FilterOptions(scope string) []pact.Option {
|
||||
if scope != models.FilterByGroup {
|
||||
return nil
|
||||
}
|
||||
db := c.db()
|
||||
if db == nil {
|
||||
return nil
|
||||
}
|
||||
var groups []models.UserGroup
|
||||
if err := db.Session(&gorm.Session{NewDB: true}).Order("name ASC, id ASC").Find(&groups).Error; err != nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]pact.Option, 0, len(groups))
|
||||
for _, group := range groups {
|
||||
out = append(out, pact.Option{Value: strconv.FormatUint(uint64(group.ID), 10), Label: group.Name})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// guardPrivilegedMember protects the account of a privileged-group member
|
||||
// against takeover. It answers nil when the administrator on ctx holds
|
||||
// golem15.users.manage_privileged_groups, or when the user is not a member of
|
||||
// a group whose code is in golem15.user.privileged_groups; otherwise it
|
||||
// refuses with a 403 carrying message and details. Membership is read
|
||||
// through the write's transaction. A failed query is returned as it is.
|
||||
func (c usersAdminController) guardPrivilegedMember(ctx context.Context, userID uint, message string, details map[string]any) error {
|
||||
principal, _ := bouncer.User(ctx)
|
||||
if cabana.Allows(principal, []string{classes.PermissionManagePrivilegedGroups}) {
|
||||
return nil
|
||||
}
|
||||
db := requestDB(ctx, c.db)
|
||||
if db == nil {
|
||||
return errors.New("users admin: gorm handle is missing")
|
||||
}
|
||||
privileged, err := classes.IsPrivilegedMember(ctx, db, classes.PrivilegedGroupCodes(c.config()), userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !privileged {
|
||||
return nil
|
||||
}
|
||||
return &cabana.ForbiddenError{Message: message, Details: details}
|
||||
}
|
||||
|
||||
// FormBeforeUpdate starts with the takeover guard: a changed email or a
|
||||
// submitted password on a member of a privileged group needs
|
||||
// golem15.users.manage_privileged_groups. Everything else an update does
|
||||
// comes after it.
|
||||
func (c usersAdminController) FormBeforeUpdate(ctx context.Context, model any) error {
|
||||
user, ok := model.(*models.User)
|
||||
if !ok || user == nil {
|
||||
return errors.New("users admin: form model is not a user")
|
||||
}
|
||||
if err := c.guardCredentials(ctx, user); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := c.requireFreeEmail(ctx, user); err != nil {
|
||||
return err
|
||||
}
|
||||
changed, err := c.storePassword(ctx, user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if changed {
|
||||
// An admin password reset ends every session of the user, as the
|
||||
// user's own change-password does.
|
||||
now := time.Now()
|
||||
user.TokensValidAfter = &now
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FormBeforeCreate checks the email against deactivated users too and stores
|
||||
// the hash of the submitted password. A user created here starts not
|
||||
// activated: is_activated is never written from the form, and only the
|
||||
// activate actions (or the invitation link) set it.
|
||||
func (c usersAdminController) FormBeforeCreate(ctx context.Context, model any) error {
|
||||
user, ok := model.(*models.User)
|
||||
if !ok || user == nil {
|
||||
return errors.New("users admin: form model is not a user")
|
||||
}
|
||||
if err := c.requireFreeEmail(ctx, user); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := c.storePassword(ctx, user); err != nil {
|
||||
return err
|
||||
}
|
||||
user.IsActivated = false
|
||||
// The column defaults to true; only an account created through a social
|
||||
// login starts without a password of its own.
|
||||
user.HasSelfSetPassword = true
|
||||
return nil
|
||||
}
|
||||
|
||||
// requireFreeEmail refuses an email another user already has, deactivated
|
||||
// users included: the unique rule leaves deactivated rows out, and the
|
||||
// database constraint does not.
|
||||
func (c usersAdminController) requireFreeEmail(ctx context.Context, user *models.User) error {
|
||||
db := requestDB(ctx, c.db)
|
||||
if db == nil {
|
||||
return errors.New("users admin: gorm handle is missing")
|
||||
}
|
||||
var taken int64
|
||||
err := db.Session(&gorm.Session{NewDB: true}).WithContext(ctx).Unscoped().
|
||||
Model(&models.User{}).Where("email = ? AND id <> ?", user.Email, user.ID).Count(&taken).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if taken == 0 {
|
||||
return nil
|
||||
}
|
||||
message := "The email has already been taken."
|
||||
if tr := appTranslator(c.application()); tr != nil {
|
||||
const key = "lagoon::validate.unique"
|
||||
if text := tr.Get(ctx, key, map[string]string{"attribute": "email"}); text != "" && text != key {
|
||||
message = text
|
||||
}
|
||||
}
|
||||
return &cabana.ValidationError{Details: map[string]any{"email": []string{message}}}
|
||||
}
|
||||
|
||||
// storePassword hashes a submitted password onto the user with
|
||||
// golem15.user.password.bcrypt_cost and reports whether one was submitted.
|
||||
// An absent or empty password changes nothing.
|
||||
func (c usersAdminController) storePassword(ctx context.Context, user *models.User) (bool, error) {
|
||||
values, _ := cabana.VirtualFieldsFromContext(ctx)
|
||||
plain, _ := values["password"].(string)
|
||||
if plain == "" {
|
||||
return false, nil
|
||||
}
|
||||
hashed, err := bouncer.HashPassword(c.configInt("golem15.user.password.bcrypt_cost", 10), plain)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
user.Password = hashed
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// FormAfterCreate assigns a unique handle, fires user.Created
|
||||
// (CreatedEventName) inside the create transaction, and sends the
|
||||
// invitation when the send_invite checkbox was set: an activation code is
|
||||
// issued inside the same transaction, and exactly one
|
||||
// golem15.user::mail.invite message with the activation link leaves after
|
||||
// the commit. A create that rolls back sends nothing.
|
||||
func (c usersAdminController) FormAfterCreate(ctx context.Context, model any) error {
|
||||
user, ok := model.(*models.User)
|
||||
if !ok || user == nil {
|
||||
return errors.New("users admin: form model is not a user")
|
||||
}
|
||||
tx, ok := cabana.TxFromContext(ctx)
|
||||
if !ok {
|
||||
return errors.New("users admin: a create needs its transaction")
|
||||
}
|
||||
if err := classes.AssignHandle(ctx, tx.Session(&gorm.Session{NewDB: true}), user); err != nil {
|
||||
return err
|
||||
}
|
||||
if app := c.application(); app != nil && app.Events != nil {
|
||||
if err := app.Events.Fire(ctx, &classes.CreatedEvent{User: user, Tx: tx}); err != nil {
|
||||
return fmt.Errorf("%s: %w", classes.CreatedEventName, err)
|
||||
}
|
||||
}
|
||||
values, _ := cabana.VirtualFieldsFromContext(ctx)
|
||||
if invite, _ := values["send_invite"].(bool); !invite {
|
||||
return nil
|
||||
}
|
||||
code, err := classes.IssueActivationCode(ctx, tx.Session(&gorm.Session{NewDB: true}), user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
app := c.application()
|
||||
id, email := user.ID, user.Email
|
||||
vars := mailVars(displayName(user), activationLink(app, id, code), strconv.FormatUint(uint64(id), 10)+"!"+code)
|
||||
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")
|
||||
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, _ *gorm.DB) {
|
||||
sendTemplateVars(ctx, app, template, email, vars)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// groupsField is the form's group membership field.
|
||||
const groupsField = "groups"
|
||||
|
||||
// AdminFieldRelations binds the organisation picker and the groups field.
|
||||
// organisation_id is a protected column, so the contract opts in to writing
|
||||
// it through this one field; the submitted id is still checked against the
|
||||
// options. groups is the users_groups pivot: a save that carries the field
|
||||
// replaces the user's memberships, and AdminRelationLocks decides which of
|
||||
// them the administrator may change.
|
||||
func (usersAdminController) AdminFieldRelations() []cabana.FieldRelationContract {
|
||||
return []cabana.FieldRelationContract{
|
||||
{
|
||||
Field: "organisation",
|
||||
Kind: "belongsTo",
|
||||
NewRelated: func() any { return &models.Organisation{} },
|
||||
ForeignKey: "organisation_id",
|
||||
LabelColumn: "name",
|
||||
WritableForeignKey: true,
|
||||
},
|
||||
{
|
||||
Field: groupsField,
|
||||
Kind: "belongsToMany",
|
||||
NewRelated: func() any { return &models.UserGroup{} },
|
||||
NewPivot: func() any { return &models.UsersGroup{} },
|
||||
ParentForeignKey: "user_id",
|
||||
RelatedForeignKey: "user_group_id",
|
||||
LabelColumn: "name",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// AdminRelationLocks locks the privileged groups in the groups field for an
|
||||
// administrator who lacks golem15.users.manage_privileged_groups: the
|
||||
// framework shows them locked and answers 403, before any row is written, to
|
||||
// a create or update that would add or remove one. Membership of a
|
||||
// privileged group makes a site administrator, so golem15.users.access_users
|
||||
// alone must not be able to grant or revoke it. The privileged codes come
|
||||
// from golem15.user.privileged_groups on every call and the group ids are
|
||||
// read through the write's transaction when there is one. An administrator
|
||||
// without a principal on the context gets the locks. Every other field has
|
||||
// none.
|
||||
func (c usersAdminController) AdminRelationLocks(ctx context.Context, field string) (cabana.RelationLock, error) {
|
||||
if field != groupsField {
|
||||
return cabana.RelationLock{}, nil
|
||||
}
|
||||
principal, _ := bouncer.User(ctx)
|
||||
if cabana.Allows(principal, []string{classes.PermissionManagePrivilegedGroups}) {
|
||||
return cabana.RelationLock{}, nil
|
||||
}
|
||||
db := requestDB(ctx, c.db)
|
||||
if db == nil {
|
||||
return cabana.RelationLock{}, errors.New("users admin: gorm handle is missing")
|
||||
}
|
||||
ids, err := classes.PrivilegedGroupIDs(ctx, db, classes.PrivilegedGroupCodes(c.config()))
|
||||
if err != nil {
|
||||
return cabana.RelationLock{}, err
|
||||
}
|
||||
return cabana.RelationLock{IDs: ids, Message: usersLang + "privileged_group_forbidden"}, nil
|
||||
}
|
||||
|
||||
// permissionsField is the form's permission editor field.
|
||||
const permissionsField = "permissions"
|
||||
|
||||
// AdminPermissionOptions offers the rows of
|
||||
// golem15_user_frontend_permissions, by tab and code. None is locked.
|
||||
func (c usersAdminController) AdminPermissionOptions(ctx context.Context, field string) ([]cabana.PermissionOption, error) {
|
||||
if field != permissionsField {
|
||||
return nil, fmt.Errorf("users admin: unknown permission field %q", field)
|
||||
}
|
||||
db := requestDB(ctx, c.db)
|
||||
if db == nil {
|
||||
return nil, errors.New("users admin: gorm handle is missing")
|
||||
}
|
||||
rows, err := classes.FrontendPermissionOptions(ctx, db)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
options := make([]cabana.PermissionOption, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
option := cabana.PermissionOption{Code: row.Code, Label: row.Label, Tab: row.Tab}
|
||||
if row.Comment != nil {
|
||||
option.Comment = *row.Comment
|
||||
}
|
||||
options = append(options, option)
|
||||
}
|
||||
return options, nil
|
||||
}
|
||||
|
||||
// AdminPermissionValues returns the user's own stored permissions.
|
||||
func (usersAdminController) AdminPermissionValues(_ context.Context, field string, record any) (map[string]int, error) {
|
||||
user, ok := record.(*models.User)
|
||||
if field != permissionsField || !ok || user == nil {
|
||||
return nil, fmt.Errorf("users admin: cannot read permission field %q", field)
|
||||
}
|
||||
values := make(map[string]int, len(user.Permissions))
|
||||
for code, value := range user.Permissions {
|
||||
values[code] = value
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// AdminSetPermissionValues puts the validated set on the user; the save
|
||||
// writes the row. Zero values are left out on write (PermissionSet.Value).
|
||||
func (usersAdminController) AdminSetPermissionValues(_ context.Context, field string, record any, values map[string]int) error {
|
||||
user, ok := record.(*models.User)
|
||||
if field != permissionsField || !ok || user == nil {
|
||||
return fmt.Errorf("users admin: cannot write permission field %q", field)
|
||||
}
|
||||
set := make(models.PermissionSet, len(values))
|
||||
for code, value := range values {
|
||||
set[code] = value
|
||||
}
|
||||
user.Permissions = set
|
||||
return nil
|
||||
}
|
||||
|
||||
// guardCredentials compares the email the save would write with the stored
|
||||
// one and looks for a submitted password, then asks guardPrivilegedMember
|
||||
// for the fields that would change.
|
||||
func (c usersAdminController) guardCredentials(ctx context.Context, user *models.User) error {
|
||||
db := requestDB(ctx, c.db)
|
||||
if db == nil {
|
||||
return errors.New("users admin: gorm handle is missing")
|
||||
}
|
||||
var stored []string
|
||||
err := db.Session(&gorm.Session{NewDB: true}).WithContext(ctx).Unscoped().
|
||||
Model(&models.User{}).Where("id = ?", user.ID).Pluck("email", &stored).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(stored) != 1 {
|
||||
return errors.New("users admin: the user being updated was not found")
|
||||
}
|
||||
const message = usersLang + "privileged_member_forbidden"
|
||||
details := map[string]any{}
|
||||
if stored[0] != user.Email {
|
||||
details["email"] = []string{message}
|
||||
}
|
||||
if values, ok := cabana.VirtualFieldsFromContext(ctx); ok {
|
||||
if password, _ := values["password"].(string); password != "" {
|
||||
details["password"] = []string{message}
|
||||
}
|
||||
}
|
||||
if len(details) == 0 {
|
||||
return nil
|
||||
}
|
||||
return c.guardPrivilegedMember(ctx, user.ID, message, details)
|
||||
}
|
||||
|
||||
// FormBeforeDelete refuses the delete of a privileged-group member without
|
||||
// golem15.users.manage_privileged_groups. The framework calls it for the
|
||||
// form's delete and once per record inside the bulk delete's transaction, so
|
||||
// one refused record rolls the whole selection back.
|
||||
func (c usersAdminController) FormBeforeDelete(ctx context.Context, model any) error {
|
||||
user, ok := model.(*models.User)
|
||||
if !ok || user == nil {
|
||||
return errors.New("users admin: form model is not a user")
|
||||
}
|
||||
return c.guardPrivilegedMember(ctx, user.ID, usersLang+"privileged_member_delete_forbidden", nil)
|
||||
}
|
||||
|
||||
// FormAfterDelete makes the delete permanent, the PHP update_onDelete and
|
||||
// bulk delete forceDelete(): the list keeps deactivated users, so the
|
||||
// framework's soft delete alone would change nothing an administrator can
|
||||
// see. The user's throttle rows, group memberships and attachments go in the
|
||||
// same transaction; the files' blobs are removed after it commits.
|
||||
// FormBeforeDelete has already refused a privileged-group member.
|
||||
func (c usersAdminController) FormAfterDelete(ctx context.Context, model any) error {
|
||||
user, ok := model.(*models.User)
|
||||
if !ok || user == nil {
|
||||
return errors.New("users admin: form model is not a user")
|
||||
}
|
||||
tx, ok := cabana.TxFromContext(ctx)
|
||||
if !ok {
|
||||
return errors.New("users admin: a delete needs its transaction")
|
||||
}
|
||||
if err := FireDeletingEvent(ctx, c.application(), user, tx); err != nil {
|
||||
return fmt.Errorf("%s: %w", classes.DeletingEventName, err)
|
||||
}
|
||||
if err := classes.ForceDeleteCleanup(ctx, tx, c.bucket(), user); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Session(&gorm.Session{NewDB: true}).WithContext(ctx).Unscoped().
|
||||
Where("id = ?", user.ID).Delete(&models.User{}).Error
|
||||
}
|
||||
|
||||
// bucket is the application's blob bucket, or nil when none is published.
|
||||
func (c usersAdminController) bucket() *blob.Bucket {
|
||||
app := c.application()
|
||||
if app == nil {
|
||||
return nil
|
||||
}
|
||||
bucket, ok := app.Lookup[*blob.Bucket]()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return bucket
|
||||
}
|
||||
|
||||
// usersOf asserts that every record of a bulk action is a user.
|
||||
func usersOf(records []any) ([]*models.User, error) {
|
||||
users := make([]*models.User, 0, len(records))
|
||||
for _, record := range records {
|
||||
user, ok := record.(*models.User)
|
||||
if !ok || user == nil {
|
||||
return nil, errors.New("users admin: bulk record is not a user")
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// AdminBulkActions are the PHP index_onBulkAction cases next to the built-in
|
||||
// delete: activate, deactivate, restore, ban and unban. Each needs only
|
||||
// golem15.users.access_users, changes the users it applies to and reports how
|
||||
// many that were. The fixed success phrase is returned only when every
|
||||
// selected user was changed; otherwise the framework shows its count text,
|
||||
// which never overstates. None of them touches users_groups.
|
||||
func (c usersAdminController) AdminBulkActions() []pact.AdminBulkAction {
|
||||
bulk := func(name string, run func(ctx context.Context, tx *gorm.DB, users []*models.User) (int, error)) pact.AdminBulkAction {
|
||||
return pact.AdminBulkAction{
|
||||
Name: name,
|
||||
Label: usersLang + name + "_selected",
|
||||
Confirm: usersLang + name + "_selected_confirm",
|
||||
Permissions: []string{PermissionAccessUsers},
|
||||
Run: func(ctx context.Context, in pact.AdminBulkActionInput) (pact.AdminBulkActionResult, error) {
|
||||
users, err := usersOf(in.Records)
|
||||
if err != nil {
|
||||
return pact.AdminBulkActionResult{}, err
|
||||
}
|
||||
tx, ok := cabana.TxFromContext(ctx)
|
||||
if !ok {
|
||||
return pact.AdminBulkActionResult{}, errors.New("users admin: a bulk action needs its transaction")
|
||||
}
|
||||
affected, err := run(classes.ContextWithThrottle(ctx, c.application()), tx, users)
|
||||
if err != nil {
|
||||
return pact.AdminBulkActionResult{}, err
|
||||
}
|
||||
result := pact.AdminBulkActionResult{Affected: affected}
|
||||
if affected == len(users) {
|
||||
result.Message = usersLang + name + "_selected_success"
|
||||
}
|
||||
return result, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
return []pact.AdminBulkAction{
|
||||
bulk("activate", classes.ActivateUsers),
|
||||
bulk("deactivate", c.deactivateUsers),
|
||||
bulk("restore", classes.RestoreUsers),
|
||||
bulk("ban", classes.BanUsers),
|
||||
bulk("unban", classes.UnbanUsers),
|
||||
}
|
||||
}
|
||||
|
||||
// deactivateUsers runs classes.DeactivateUsers unchanged and then fires
|
||||
// user.Deactivating, in the action's transaction, for every selected user
|
||||
// that was not deactivated before. A listener error rolls the action back.
|
||||
func (c usersAdminController) deactivateUsers(ctx context.Context, tx *gorm.DB, users []*models.User) (int, error) {
|
||||
pending := make([]*models.User, 0, len(users))
|
||||
for _, user := range users {
|
||||
if user != nil && user.ID != 0 && !user.DeletedAt.Valid {
|
||||
pending = append(pending, user)
|
||||
}
|
||||
}
|
||||
changed, err := classes.DeactivateUsers(ctx, tx, users)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for _, user := range pending {
|
||||
if err := FireDeactivatingEvent(ctx, c.application(), user, tx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
// throttleState reads whether one user is banned and whether they are
|
||||
// suspended, through the write's transaction when there is one.
|
||||
func (c usersAdminController) throttleState(ctx context.Context, userID uint) (banned, suspended bool, err error) {
|
||||
db := requestDB(ctx, c.db)
|
||||
if db == nil {
|
||||
return false, false, errors.New("users admin: gorm handle is missing")
|
||||
}
|
||||
bannedSet, suspendedSet, err := classes.ThrottleStates(classes.ContextWithThrottle(ctx, c.application()), db, []uint{userID})
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
return bannedSet[userID], suspendedSet[userID], nil
|
||||
}
|
||||
|
||||
// AdminRecordActions are the PHP preview handlers onActivate, onUnban and
|
||||
// onUnsuspendUser. Each is offered only while it applies; the checks only
|
||||
// read. There is no impersonate action and no guest action.
|
||||
func (c usersAdminController) AdminRecordActions() []pact.AdminRecordAction {
|
||||
asUser := func(record any) (*models.User, error) {
|
||||
user, ok := record.(*models.User)
|
||||
if !ok || user == nil {
|
||||
return nil, errors.New("users admin: action record is not a user")
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
action := func(name, label, confirm, success string,
|
||||
applies func(ctx context.Context, user *models.User) (bool, error),
|
||||
run func(ctx context.Context, tx *gorm.DB, user *models.User) error,
|
||||
) pact.AdminRecordAction {
|
||||
return pact.AdminRecordAction{
|
||||
Name: name,
|
||||
Label: usersLang + label,
|
||||
Confirm: usersLang + confirm,
|
||||
Permissions: []string{PermissionAccessUsers},
|
||||
Applies: func(ctx context.Context, record any) (bool, error) {
|
||||
user, err := asUser(record)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return applies(ctx, user)
|
||||
},
|
||||
Run: func(ctx context.Context, in pact.AdminRecordActionInput) (pact.AdminRecordActionResult, error) {
|
||||
user, err := asUser(in.Record)
|
||||
if err != nil {
|
||||
return pact.AdminRecordActionResult{}, err
|
||||
}
|
||||
tx, ok := cabana.TxFromContext(ctx)
|
||||
if !ok {
|
||||
return pact.AdminRecordActionResult{}, errors.New("users admin: a record action needs its transaction")
|
||||
}
|
||||
if err := run(ctx, tx, user); err != nil {
|
||||
return pact.AdminRecordActionResult{}, err
|
||||
}
|
||||
return pact.AdminRecordActionResult{Message: usersLang + success}, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
return []pact.AdminRecordAction{
|
||||
action("activate", "activate_user", "activate_confirm", "activated_success",
|
||||
func(_ context.Context, user *models.User) (bool, error) { return !user.IsActivated, nil },
|
||||
func(ctx context.Context, tx *gorm.DB, user *models.User) error {
|
||||
_, err := classes.ActivateUsers(ctx, tx, []*models.User{user})
|
||||
return err
|
||||
}),
|
||||
action("unban", "unban_user", "unban_confirm", "unbanned_success",
|
||||
func(ctx context.Context, user *models.User) (bool, error) {
|
||||
banned, _, err := c.throttleState(ctx, user.ID)
|
||||
return banned, err
|
||||
},
|
||||
func(ctx context.Context, tx *gorm.DB, user *models.User) error {
|
||||
_, err := classes.UnbanUsers(ctx, tx, []*models.User{user})
|
||||
return err
|
||||
}),
|
||||
action("unsuspend", "unsuspend_user", "unsuspend_confirm", "unsuspend_success",
|
||||
func(ctx context.Context, user *models.User) (bool, error) {
|
||||
_, suspended, err := c.throttleState(ctx, user.ID)
|
||||
return suspended, err
|
||||
},
|
||||
func(ctx context.Context, tx *gorm.DB, user *models.User) error {
|
||||
return classes.UnsuspendUser(ctx, tx, user.ID)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// usersHintView is the view model of controllers/users/_hint.htm, the status
|
||||
// callout above the preview: the callout kind (danger or warning) and the
|
||||
// phrase keys of its title and text. It is empty when no state applies, and
|
||||
// the template then renders nothing.
|
||||
type usersHintView struct {
|
||||
Kind string
|
||||
Title string
|
||||
Text string
|
||||
}
|
||||
|
||||
// PartialData serves the preview header partial `hint`: one callout by
|
||||
// precedence banned, deactivated, not activated, suspended (the PHP
|
||||
// _hint_banned, _hint_trashed and _hint_activate partials plus a suspension
|
||||
// hint). Any other partial name is an error.
|
||||
func (c usersAdminController) PartialData(ctx context.Context, name string, record any) (any, error) {
|
||||
if name != "hint" {
|
||||
return nil, fmt.Errorf("users admin: unknown partial %q", name)
|
||||
}
|
||||
user, ok := record.(*models.User)
|
||||
if !ok || user == nil {
|
||||
return usersHintView{}, nil
|
||||
}
|
||||
banned, suspended, err := c.throttleState(ctx, user.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch {
|
||||
case banned:
|
||||
return usersHintView{Kind: "danger", Title: usersLang + "banned_hint_title", Text: usersLang + "banned_hint_desc"}, nil
|
||||
case user.DeletedAt.Valid:
|
||||
return usersHintView{Kind: "danger", Title: usersLang + "trashed_hint_title", Text: usersLang + "trashed_hint_desc"}, nil
|
||||
case !user.IsActivated:
|
||||
return usersHintView{Kind: "warning", Title: usersLang + "activate_warning_title", Text: usersLang + "activate_warning_desc"}, nil
|
||||
case suspended:
|
||||
return usersHintView{Kind: "warning", Title: usersLang + "suspended_hint_title", Text: usersLang + "suspended_hint_desc"}, nil
|
||||
}
|
||||
return usersHintView{}, nil
|
||||
}
|
||||
110
deactivating_event_test.go
Normal file
110
deactivating_event_test.go
Normal file
@@ -0,0 +1,110 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// TestDeactivatingEvent pins user.Deactivating (D-05): the admin deactivate
|
||||
// bulk action fires one event per newly deactivated user inside the
|
||||
// action's transaction, already deactivated users fire none, a listener
|
||||
// error rolls the whole action back, and the event name is the constant.
|
||||
func TestDeactivatingEvent(t *testing.T) {
|
||||
if classes.DeactivatingEventName != "user.Deactivating" {
|
||||
t.Fatalf("DeactivatingEventName = %q", classes.DeactivatingEventName)
|
||||
}
|
||||
env := newAdminEnv(t)
|
||||
token := env.admin(t, permAccessUsers)
|
||||
|
||||
var mu sync.Mutex
|
||||
var fired []uint
|
||||
var failFor uint
|
||||
var txSawDeactivation = map[uint]bool{}
|
||||
env.app.Events.Listen[*classes.DeactivatingEvent]("test.deactivating", func(ctx context.Context, e *classes.DeactivatingEvent) error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if e.User == nil || e.Tx == nil {
|
||||
return errors.New("event without user or transaction")
|
||||
}
|
||||
fired = append(fired, e.User.ID)
|
||||
// Inside the action's transaction the row is already deactivated.
|
||||
var deleted int64
|
||||
if err := e.Tx.Session(&gorm.Session{NewDB: true}).Unscoped().Model(&models.User{}).
|
||||
Where("id = ? AND deleted_at IS NOT NULL", e.User.ID).Count(&deleted).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
txSawDeactivation[e.User.ID] = deleted == 1
|
||||
if e.User.ID == failFor {
|
||||
return errors.New("listener refuses")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
reset := func() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
fired, txSawDeactivation = nil, map[uint]bool{}
|
||||
}
|
||||
|
||||
a, b := env.seedUser(t, "deact-a", nil), env.seedUser(t, "deact-b", nil)
|
||||
if rec := env.bulk(t, token, "deactivate", a, b); rec.Code != http.StatusOK {
|
||||
t.Fatalf("deactivate: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
mu.Lock()
|
||||
if len(fired) != 2 || !txSawDeactivation[a.ID] || !txSawDeactivation[b.ID] {
|
||||
t.Fatalf("events %v, seen in the transaction %v", fired, txSawDeactivation)
|
||||
}
|
||||
mu.Unlock()
|
||||
for _, u := range []*models.User{a, b} {
|
||||
if row := env.reload(t, u.ID); row == nil || !row.DeletedAt.Valid {
|
||||
t.Fatalf("user %d not deactivated", u.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// Already deactivated users fire nothing; a mixed selection fires only
|
||||
// for the newly deactivated one.
|
||||
reset()
|
||||
c := env.seedUser(t, "deact-c", nil)
|
||||
if rec := env.bulk(t, token, "deactivate", a, c); rec.Code != http.StatusOK {
|
||||
t.Fatalf("mixed deactivate: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
mu.Lock()
|
||||
if len(fired) != 1 || fired[0] != c.ID {
|
||||
t.Fatalf("mixed selection fired %v, want only %d", fired, c.ID)
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
// A listener error rolls the whole action back.
|
||||
reset()
|
||||
d, e := env.seedUser(t, "deact-d", nil), env.seedUser(t, "deact-e", nil)
|
||||
failFor = e.ID
|
||||
if rec := env.bulk(t, token, "deactivate", d, e); rec.Code < 400 {
|
||||
t.Fatalf("deactivate with a refusing listener: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
failFor = 0
|
||||
for _, u := range []*models.User{d, e} {
|
||||
if row := env.reload(t, u.ID); row == nil || row.DeletedAt.Valid {
|
||||
t.Fatalf("user %d deactivated although a listener refused", u.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// Other bulk actions fire nothing.
|
||||
reset()
|
||||
if rec := env.bulk(t, token, "restore", a); rec.Code != http.StatusOK {
|
||||
t.Fatalf("restore: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := env.bulk(t, token, "activate", d); rec.Code != http.StatusOK {
|
||||
t.Fatalf("activate: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
mu.Lock()
|
||||
if len(fired) != 0 {
|
||||
t.Fatalf("restore and activate fired %v", fired)
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
2
go.mod
2
go.mod
@@ -3,7 +3,7 @@ module git.golem15.com/golem15/sm-user-plugin
|
||||
go 1.27.0
|
||||
|
||||
require (
|
||||
git.golem15.com/golem15/summercms v0.0.0
|
||||
git.golem15.com/golem15/summercms v0.1.9
|
||||
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
|
||||
|
||||
@@ -1,3 +1,117 @@
|
||||
account:
|
||||
invalid_login: Invalid email or password
|
||||
no_avatar: Your account has no display picture to remove.
|
||||
plugin:
|
||||
tab: Users
|
||||
access_users: Manage Users
|
||||
access_groups: Manage User Groups
|
||||
access_settings: Manage User Settings
|
||||
impersonate_user: Impersonate Users
|
||||
manage_privileged_groups: Manage privileged group membership
|
||||
users:
|
||||
menu_label: Users
|
||||
new_user: New User
|
||||
list_title: Manage Users
|
||||
list_empty: No users match this view. Clear the filters, or add one with New User.
|
||||
state_deactivated: Deactivated
|
||||
state_banned: Banned
|
||||
state_not_activated: Not activated
|
||||
delete_confirm: Do you really want to delete this user? This user will be permanently removed and unrecoverable.
|
||||
delete_selected_confirm: Delete the selected users? These users will be permanently removed and unrecoverable.
|
||||
update_details: Update details
|
||||
activate_selected: Activate selected
|
||||
activate_selected_confirm: Activate the selected users?
|
||||
activate_selected_success: Successfully activated the selected users.
|
||||
deactivate_selected: Deactivate selected
|
||||
deactivate_selected_confirm: Deactivate the selected users?
|
||||
deactivate_selected_success: Successfully deactivated the selected users.
|
||||
restore_selected: Restore selected
|
||||
restore_selected_confirm: Restore the selected users?
|
||||
restore_selected_success: Successfully restored the selected users.
|
||||
ban_selected: Ban selected
|
||||
ban_selected_confirm: Ban the selected users?
|
||||
ban_selected_success: Successfully banned the selected users.
|
||||
unban_selected: Unban selected
|
||||
unban_selected_confirm: Unban the selected users?
|
||||
unban_selected_success: Successfully unbanned the selected users.
|
||||
banned_hint_title: User has been banned
|
||||
banned_hint_desc: This user has been banned by an administrator and will be unable to sign in.
|
||||
trashed_hint_title: User has deactivated their account
|
||||
trashed_hint_desc: This user has deactivated their account and no longer wants to appear on the site. They can restore their account at any time by signing back in.
|
||||
activate_warning_title: User not activated!
|
||||
activate_warning_desc: This user has not been activated and may be unable to sign in.
|
||||
suspended_hint_title: User is temporarily suspended
|
||||
suspended_hint_desc: Too many failed sign-in attempts. The suspension ends on its own, or you can lift it now with Unsuspend user.
|
||||
activate_user: Activate user
|
||||
activate_confirm: Do you really want to activate this user?
|
||||
activated_success: User has been activated
|
||||
unban_user: Unban this user
|
||||
unban_confirm: Do you really want to unban this user?
|
||||
unbanned_success: User has been unbanned
|
||||
unsuspend_user: Unsuspend user
|
||||
unsuspend_confirm: Unsuspend this user?
|
||||
unsuspend_success: User has been unsuspended.
|
||||
privileged_member_forbidden: This user belongs to a privileged group. You do not have permission to change their email or password. Nothing was saved.
|
||||
privileged_member_delete_forbidden: Users who belong to a privileged group cannot be deleted without the permission to manage privileged groups. Nothing was deleted.
|
||||
privileged_group_forbidden: You do not have permission to change membership of privileged groups. Nothing was saved.
|
||||
user:
|
||||
label: User
|
||||
id: ID
|
||||
name: Name
|
||||
surname: Surname
|
||||
email: Email
|
||||
account: Account
|
||||
created_at: Registered
|
||||
last_seen: Last seen
|
||||
created_ip_address: Created IP Address
|
||||
last_ip_address: Last IP Address
|
||||
status_activated: Activated
|
||||
send_invite: Send invitation by email
|
||||
send_invite_comment: Sends a welcome message containing login and password information.
|
||||
password: Password
|
||||
password_comment: On a new user, enter the sign-in password. On an existing user, leave empty to keep the current password.
|
||||
confirm_password: Password Confirmation
|
||||
confirm_password_comment: Enter the password again to confirm it.
|
||||
avatar: Avatar
|
||||
groups: Groups
|
||||
empty_groups: There are no user groups available.
|
||||
permissions_tab: Permissions
|
||||
group:
|
||||
label: Group
|
||||
id: ID
|
||||
name: Name
|
||||
code: Code
|
||||
code_comment: Enter a unique code used to identify this group.
|
||||
code_invalid: The code may only contain letters, numbers, dashes and underscores.
|
||||
description_field: Description
|
||||
created_at: Created
|
||||
users_count: Users
|
||||
groups:
|
||||
all_groups: User Groups
|
||||
menu_label: Groups
|
||||
list_title: Manage Groups
|
||||
new_group: New Group
|
||||
list_empty: No user groups yet. Create the first one with New Group.
|
||||
delete_confirm: Do you really want to delete this group?
|
||||
privileged_forbidden: You do not have permission to create, re-code or delete a privileged group. Nothing was saved.
|
||||
organisation:
|
||||
label: Organisation
|
||||
label_plural: Organisations
|
||||
menu_label: Organisations
|
||||
id: ID
|
||||
name: Name
|
||||
slug: Slug
|
||||
slug_comment: Auto-generated from the name if left blank.
|
||||
slug_invalid: The slug may only contain letters, numbers, dashes and underscores.
|
||||
description: Description
|
||||
avatar: Avatar
|
||||
members: Members
|
||||
new: New Organisation
|
||||
list_empty: No organisations yet. Create the first one with New Organisation.
|
||||
add_member: Add member
|
||||
remove_members: Remove selected
|
||||
remove_members_confirm: Remove the selected (:count) from this organisation? The users are not deleted.
|
||||
members_empty: This organisation has no members yet. Add users with Add member.
|
||||
empty_organisation: — No organisation —
|
||||
oauth:
|
||||
last_method_blocked: This is the only remaining way to sign in. Link another method before disconnecting this one.
|
||||
|
||||
@@ -1,3 +1,117 @@
|
||||
account:
|
||||
invalid_login: Nieprawidłowy email lub hasło
|
||||
no_avatar: Brak avatara
|
||||
plugin:
|
||||
tab: Użytkownicy
|
||||
access_users: Zarządzaj użytkownikami
|
||||
access_groups: Zarządzaj grupami użytkowników
|
||||
access_settings: Zarządzaj ustawieniami użytkownika
|
||||
impersonate_user: Wcielaj się w użytkowników
|
||||
manage_privileged_groups: Zarządzaj członkostwem w grupach uprzywilejowanych
|
||||
users:
|
||||
menu_label: Użytkownicy
|
||||
new_user: Nowy użytkownik
|
||||
list_title: Zarządzaj użytkownikami
|
||||
list_empty: Brak użytkowników w tym widoku. Wyczyść filtry lub dodaj użytkownika przyciskiem Nowy użytkownik.
|
||||
state_deactivated: Dezaktywowany
|
||||
state_banned: Zbanowany
|
||||
state_not_activated: Nieaktywowany
|
||||
delete_confirm: Czy na pewno chcesz usunąć tego użytkownika? Zostanie trwale usunięty bez możliwości odzyskania.
|
||||
delete_selected_confirm: Usunąć wybranych użytkowników? Zostaną trwale usunięci bez możliwości odzyskania.
|
||||
update_details: Zaktualizuj szczegóły
|
||||
activate_selected: Aktywuj wybranych
|
||||
activate_selected_confirm: Aktywować wybranych użytkowników?
|
||||
activate_selected_success: Pomyślnie aktywowano wybranych użytkowników.
|
||||
deactivate_selected: Dezaktywuj wybranych
|
||||
deactivate_selected_confirm: Dezaktywować wybranych użytkowników?
|
||||
deactivate_selected_success: Pomyślnie dezaktywowano wybranych użytkowników.
|
||||
restore_selected: Przywróć wybranych
|
||||
restore_selected_confirm: Przywrócić wybranych użytkowników?
|
||||
restore_selected_success: Pomyślnie przywrócono wybranych użytkowników.
|
||||
ban_selected: Zbanuj wybranych
|
||||
ban_selected_confirm: Zbanować wybranych użytkowników?
|
||||
ban_selected_success: Pomyślnie zbanowano wybranych użytkowników.
|
||||
unban_selected: Odbanuj wybranych
|
||||
unban_selected_confirm: Odbanować wybranych użytkowników?
|
||||
unban_selected_success: Pomyślnie odbanowano wybranych użytkowników.
|
||||
banned_hint_title: Użytkownik został zbanowany
|
||||
banned_hint_desc: Ten użytkownik został zbanowany przez administratora i nie będzie mógł się zalogować.
|
||||
trashed_hint_title: Użytkownik dezaktywował swoje konto
|
||||
trashed_hint_desc: Ten użytkownik dezaktywował swoje konto i nie chce już wyświetlać się na stronie. Może przywrócić konto w dowolnym momencie, logując się z powrotem.
|
||||
activate_warning_title: Użytkownik nieaktywowany!
|
||||
activate_warning_desc: Ten użytkownik nie został aktywowany i może nie być w stanie się zalogować.
|
||||
suspended_hint_title: Użytkownik jest tymczasowo zawieszony
|
||||
suspended_hint_desc: Zbyt wiele nieudanych prób logowania. Blokada wygaśnie sama; możesz też zdjąć ją teraz przyciskiem Odblokuj użytkownika.
|
||||
activate_user: Aktywuj użytkownika
|
||||
activate_confirm: Czy na pewno chcesz aktywować tego użytkownika?
|
||||
activated_success: Użytkownik został aktywowany
|
||||
unban_user: Odbanuj tego użytkownika
|
||||
unban_confirm: Czy na pewno chcesz odbanować tego użytkownika?
|
||||
unbanned_success: Użytkownik został odbanowany
|
||||
unsuspend_user: Odblokuj użytkownika
|
||||
unsuspend_confirm: Odblokować tego użytkownika?
|
||||
unsuspend_success: Udało się odblokować użytkownika.
|
||||
privileged_member_forbidden: Ten użytkownik należy do grupy uprzywilejowanej. Nie masz uprawnień do zmiany jego adresu e-mail ani hasła. Nic nie zostało zapisane.
|
||||
privileged_member_delete_forbidden: Użytkowników należących do grupy uprzywilejowanej nie można usunąć bez uprawnienia do zarządzania grupami uprzywilejowanymi. Nic nie zostało usunięte.
|
||||
privileged_group_forbidden: Nie masz uprawnień do zmiany członkostwa w grupach uprzywilejowanych. Nic nie zostało zapisane.
|
||||
user:
|
||||
label: Użytkownik
|
||||
id: ID
|
||||
name: Imię / nick
|
||||
surname: Nazwisko
|
||||
email: Email
|
||||
account: Konto
|
||||
created_at: Zarejestrowany
|
||||
last_seen: Ostatnio widziany
|
||||
created_ip_address: Stworzono z IP
|
||||
last_ip_address: Ostatnie IP
|
||||
status_activated: Aktywowany
|
||||
send_invite: Wyślij zaproszenie pocztą e-mail
|
||||
send_invite_comment: Wysyła wiadomość powitalną zawierającą dane logowania i hasło.
|
||||
password: Hasło
|
||||
password_comment: Dla nowego użytkownika wpisz hasło do logowania. Dla istniejącego pozostaw puste, aby nie zmieniać hasła.
|
||||
confirm_password: Potwierdzenie hasła
|
||||
confirm_password_comment: Wprowadź ponownie hasło, aby je potwierdzić.
|
||||
avatar: Avatar
|
||||
groups: Grupy
|
||||
empty_groups: Brak dostępnych grup użytkowników.
|
||||
permissions_tab: Uprawnienia
|
||||
group:
|
||||
label: Grupa
|
||||
id: ID
|
||||
name: Nazwa
|
||||
code: Kod
|
||||
code_comment: Wpisz unikalny kod służący do identyfikacji tej grupy.
|
||||
code_invalid: Kod może zawierać tylko litery, cyfry, myślniki i podkreślenia.
|
||||
description_field: Opis
|
||||
created_at: Utworzona
|
||||
users_count: Użytkownicy
|
||||
groups:
|
||||
all_groups: Grupy użytkowników
|
||||
menu_label: Grupy
|
||||
list_title: Zarządzaj grupami
|
||||
new_group: Nowa grupa
|
||||
list_empty: Brak grup użytkowników. Utwórz pierwszą przyciskiem Nowa grupa.
|
||||
delete_confirm: Czy na pewno chcesz usunąć tę grupę?
|
||||
privileged_forbidden: Nie masz uprawnień do tworzenia, zmiany kodu ani usuwania grup uprzywilejowanych. Nic nie zostało zapisane.
|
||||
organisation:
|
||||
label: Organizacja
|
||||
label_plural: Organizacje
|
||||
menu_label: Organizacje
|
||||
id: ID
|
||||
name: Nazwa
|
||||
slug: Identyfikator
|
||||
slug_comment: Generowany automatycznie z nazwy, jeśli pozostawiony pusty.
|
||||
slug_invalid: Identyfikator może zawierać tylko litery, cyfry, myślniki i podkreślenia.
|
||||
description: Opis
|
||||
avatar: Awatar
|
||||
members: Członkowie
|
||||
new: Nowa organizacja
|
||||
list_empty: Brak organizacji. Utwórz pierwszą przyciskiem Nowa organizacja.
|
||||
add_member: Dodaj członka
|
||||
remove_members: Usuń zaznaczonych
|
||||
remove_members_confirm: Usunąć zaznaczonych (:count) z tej organizacji? Użytkownicy nie zostaną usunięci.
|
||||
members_empty: Ta organizacja nie ma jeszcze członków. Dodaj użytkowników przyciskiem Dodaj członka.
|
||||
empty_organisation: — Brak organizacji —
|
||||
oauth:
|
||||
last_method_blocked: To jedyna droga logowania na to konto. Najpierw podłącz inną, zanim odetniesz tę.
|
||||
|
||||
231
last_seen_test.go
Normal file
231
last_seen_test.go
Normal file
@@ -0,0 +1,231 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/controllers"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// TestLastSeen covers users.last_seen (D-17, D-29): login and refresh stamp
|
||||
// it at most once per five minutes, a failing write never fails them, and it
|
||||
// never reaches a user API payload.
|
||||
func TestLastSeen(t *testing.T) {
|
||||
app, gdb := sessionApp(t, "0s")
|
||||
user := insertUser(t, gdb, "last-seen@example.test", "correct-horse")
|
||||
const credentials = `{"email":"last-seen@example.test","password":"correct-horse"}`
|
||||
|
||||
lastSeen := func() *time.Time {
|
||||
t.Helper()
|
||||
var row struct{ LastSeen *time.Time }
|
||||
if err := gdb.Raw(`SELECT last_seen FROM users WHERE id = ?`, user.ID).Scan(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return row.LastSeen
|
||||
}
|
||||
setLastSeen := func(age time.Duration) time.Time {
|
||||
t.Helper()
|
||||
at := time.Now().Add(-age).Truncate(time.Microsecond)
|
||||
if err := gdb.Exec(`UPDATE users SET last_seen = ? WHERE id = ?`, at, user.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return at
|
||||
}
|
||||
login := func() (string, map[string]any, string) {
|
||||
t.Helper()
|
||||
rec := postJSON(t, controllers.Login(app), "/_user/api/v1/login", credentials)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("login %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
Token string `json:"token"`
|
||||
User map[string]any `json:"user"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body.Token == "" || len(body.User) == 0 {
|
||||
t.Fatalf("login body %s", rec.Body.String())
|
||||
}
|
||||
return body.Token, body.User, rec.Body.String()
|
||||
}
|
||||
refresh := func(token string) (string, string) {
|
||||
t.Helper()
|
||||
rec := bearer(t, controllers.Refresh(app), http.MethodPost, "/_user/api/v1/refresh", token)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("refresh %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next, _ := body["token"].(string)
|
||||
if next == "" || len(body) != 1 {
|
||||
t.Fatalf("refresh body %s", rec.Body.String())
|
||||
}
|
||||
return next, rec.Body.String()
|
||||
}
|
||||
updatedAt := func() time.Time {
|
||||
t.Helper()
|
||||
var at time.Time
|
||||
if err := gdb.Raw(`SELECT updated_at FROM users WHERE id = ?`, user.ID).Scan(&at).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return at
|
||||
}
|
||||
|
||||
if lastSeen() != nil {
|
||||
t.Fatal("a new user already has last_seen")
|
||||
}
|
||||
stampedBefore := updatedAt()
|
||||
|
||||
// A login stamps it.
|
||||
started := time.Now().Add(-time.Second)
|
||||
token, payload, raw := login()
|
||||
first := lastSeen()
|
||||
if first == nil || first.Before(started) || first.After(time.Now().Add(time.Second)) {
|
||||
t.Fatalf("last_seen after the first login = %v", first)
|
||||
}
|
||||
if !updatedAt().Equal(stampedBefore) {
|
||||
t.Fatal("stamping last_seen touched updated_at")
|
||||
}
|
||||
// A second login and a refresh inside five minutes leave it alone.
|
||||
token2, _, _ := login()
|
||||
if got := lastSeen(); got == nil || !got.Equal(*first) {
|
||||
t.Fatalf("a second login inside five minutes moved last_seen: %v -> %v", first, got)
|
||||
}
|
||||
token, _ = refresh(token)
|
||||
if got := lastSeen(); got == nil || !got.Equal(*first) {
|
||||
t.Fatalf("a refresh inside five minutes moved last_seen: %v -> %v", first, got)
|
||||
}
|
||||
|
||||
// Six minutes later a refresh stamps it again, and so does a login.
|
||||
old := setLastSeen(6 * time.Minute)
|
||||
_, refreshRaw := refresh(token)
|
||||
afterRefresh := lastSeen()
|
||||
if afterRefresh == nil || !afterRefresh.After(old.Add(5*time.Minute)) {
|
||||
t.Fatalf("a refresh after six minutes did not stamp last_seen: %v (was %v)", afterRefresh, old)
|
||||
}
|
||||
old = setLastSeen(6 * time.Minute)
|
||||
login()
|
||||
if got := lastSeen(); got == nil || !got.After(old.Add(5*time.Minute)) {
|
||||
t.Fatalf("a login after six minutes did not stamp last_seen: %v", got)
|
||||
}
|
||||
// Four minutes is inside the window.
|
||||
recent := setLastSeen(4 * time.Minute)
|
||||
refresh(token2)
|
||||
if got := lastSeen(); got == nil || !got.Equal(recent) {
|
||||
t.Fatalf("a refresh after four minutes moved last_seen: %v -> %v", recent, got)
|
||||
}
|
||||
|
||||
// A failing write never fails authentication: with a trigger that
|
||||
// refuses every last_seen update, login and refresh still answer 200
|
||||
// with the same body shape.
|
||||
// last_seen is ten minutes old, so both handlers attempt the write.
|
||||
blocked := setLastSeen(10 * time.Minute)
|
||||
drop := func() {
|
||||
gdb.Exec(`DROP TRIGGER IF EXISTS test_refuse_last_seen ON users`)
|
||||
gdb.Exec(`DROP FUNCTION IF EXISTS test_refuse_last_seen()`)
|
||||
}
|
||||
t.Cleanup(drop)
|
||||
for _, stmt := range []string{
|
||||
`CREATE OR REPLACE FUNCTION test_refuse_last_seen() RETURNS trigger AS $$ BEGIN RAISE EXCEPTION 'last_seen cannot be written in this test'; END $$ LANGUAGE plpgsql`,
|
||||
`CREATE TRIGGER test_refuse_last_seen BEFORE UPDATE OF last_seen ON users FOR EACH ROW EXECUTE FUNCTION test_refuse_last_seen()`,
|
||||
} {
|
||||
if err := gdb.Exec(stmt).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := classes.TouchLastSeen(t.Context(), gdb, user.ID); err == nil {
|
||||
t.Fatal("the test trigger does not refuse the write, or TouchLastSeen swallowed the failure")
|
||||
}
|
||||
failedToken, failedPayload, _ := login()
|
||||
_, failedRefreshRaw := refresh(failedToken)
|
||||
if got := lastSeen(); got == nil || !got.Equal(blocked) {
|
||||
t.Fatalf("last_seen changed although the write is refused: %v -> %v", blocked, got)
|
||||
}
|
||||
if len(failedPayload) != len(payload) {
|
||||
t.Fatalf("the login payload changed shape when the write failed: %v vs %v", failedPayload, payload)
|
||||
}
|
||||
for key := range payload {
|
||||
if _, ok := failedPayload[key]; !ok {
|
||||
t.Fatalf("the login payload lost %s when the write failed", key)
|
||||
}
|
||||
}
|
||||
if !strings.HasPrefix(failedRefreshRaw, `{"token":"`) || !strings.HasPrefix(refreshRaw, `{"token":"`) {
|
||||
t.Fatalf("refresh bodies: %s / %s", refreshRaw, failedRefreshRaw)
|
||||
}
|
||||
drop()
|
||||
|
||||
// No user payload carries the admin columns; permissions stays null and
|
||||
// groups an empty list.
|
||||
current, _, _ := login()
|
||||
fetch := bearer(t, controllers.Fetch(app), http.MethodGet, "/_user/api/v1/fetch", current)
|
||||
if fetch.Code != http.StatusOK {
|
||||
t.Fatalf("fetch %d %s", fetch.Code, fetch.Body.String())
|
||||
}
|
||||
var fetched struct {
|
||||
User map[string]any `json:"user"`
|
||||
}
|
||||
if err := json.Unmarshal(fetch.Body.Bytes(), &fetched); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for name, body := range map[string]string{"login": raw, "fetch": fetch.Body.String(), "refresh": refreshRaw} {
|
||||
for _, key := range []string{"last_seen", "created_at", "updated_at", "LastSeen", "CreatedAt", "UpdatedAt", "Permissions"} {
|
||||
if strings.Contains(body, `"`+key+`"`) {
|
||||
t.Fatalf("the %s body carries %s: %s", name, key, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
for name, got := range map[string]map[string]any{"login": payload, "fetch": fetched.User} {
|
||||
if value, ok := got["permissions"]; !ok || value != nil {
|
||||
t.Fatalf("%s payload permissions = %v (%v)", name, value, ok)
|
||||
}
|
||||
if groups, ok := got["groups"].([]any); !ok || len(groups) != 0 {
|
||||
t.Fatalf("%s payload groups = %v", name, got["groups"])
|
||||
}
|
||||
}
|
||||
|
||||
// The model itself never serializes them either.
|
||||
now := time.Now()
|
||||
marshalled, err := json.Marshal(models.User{
|
||||
ID: 1, Email: "marshal@example.test", LastSeen: &now, CreatedAt: now, UpdatedAt: now,
|
||||
Permissions: models.PermissionSet{"blog.post": 1}, Groups: []models.UserGroup{{Name: "Admins"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lower := strings.ToLower(string(marshalled))
|
||||
for _, key := range []string{"last_seen", "lastseen", "permissions", "created_at", "createdat", "updated_at", "updatedat", "groups", "blog.post", "admins"} {
|
||||
if strings.Contains(lower, key) {
|
||||
t.Fatalf("a marshalled user carries %s: %s", key, marshalled)
|
||||
}
|
||||
}
|
||||
if strings.Contains(string(marshalled), `"Password"`) {
|
||||
t.Fatalf("a marshalled user carries the password: %s", marshalled)
|
||||
}
|
||||
|
||||
// The helper itself: a deactivated user is stamped, an unknown id and a
|
||||
// zero id are no error, a missing handle is.
|
||||
if err := gdb.Exec(`UPDATE users SET last_seen = NULL, deleted_at = NOW() WHERE id = ?`, user.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := classes.TouchLastSeen(t.Context(), gdb, user.ID); err != nil || lastSeen() == nil {
|
||||
t.Fatalf("a deactivated user was not stamped: %v", err)
|
||||
}
|
||||
if err := classes.TouchLastSeen(t.Context(), gdb, 987654321); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := classes.TouchLastSeen(t.Context(), gdb, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := classes.TouchLastSeen(t.Context(), (*gorm.DB)(nil), user.ID); err == nil {
|
||||
t.Fatal("TouchLastSeen without a handle")
|
||||
}
|
||||
}
|
||||
191
models/admin_models_test.go
Normal file
191
models/admin_models_test.go
Normal file
@@ -0,0 +1,191 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestAdminModelContracts pins what the admin screens read off the models:
|
||||
// fill lists, rules, morph names, attachment relations and filter scopes.
|
||||
func TestAdminModelContracts(t *testing.T) {
|
||||
if got := (UserGroup{}).Fillable(); !reflect.DeepEqual(got, []string{"name", "code", "description"}) {
|
||||
t.Fatalf("UserGroup.Fillable = %v", got)
|
||||
}
|
||||
if got := (UserGroup{}).Rules(); !reflect.DeepEqual(got, map[string]string{"name": "required|between:3,64", "code": "required|unique:user_groups"}) {
|
||||
t.Fatalf("UserGroup.Rules = %v", got)
|
||||
}
|
||||
if got := (Organisation{}).Fillable(); !reflect.DeepEqual(got, []string{"name", "slug", "description"}) {
|
||||
t.Fatalf("Organisation.Fillable = %v", got)
|
||||
}
|
||||
if got := (Organisation{}).Rules(); !reflect.DeepEqual(got, map[string]string{
|
||||
"name": "required|max:255", "slug": "required|unique:golem15_user_organisations", "description": "nullable|max:5000",
|
||||
}) {
|
||||
t.Fatalf("Organisation.Rules = %v", got)
|
||||
}
|
||||
// Neither fill list reaches a column that carries privilege or ownership.
|
||||
for _, forbidden := range []string{"permissions", "id", "users_count", "members", "created_at"} {
|
||||
for _, list := range [][]string{(UserGroup{}).Fillable(), (Organisation{}).Fillable()} {
|
||||
for _, name := range list {
|
||||
if name == forbidden {
|
||||
t.Fatalf("%s is fillable", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The user's fill list is the register and update contract and is not
|
||||
// widened by the admin screen.
|
||||
fillable := strings.Join((User{}).Fillable(), ",")
|
||||
for _, protected := range []string{"is_activated", "permissions", "last_seen", "activation_code", "reset_password_code", "tokens_valid_after", "deleted_at", "id"} {
|
||||
for _, name := range (User{}).Fillable() {
|
||||
if name == protected {
|
||||
t.Fatalf("users.%s is fillable (%s)", protected, fillable)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !reflect.DeepEqual((User{}).Hidden(), []string{"password", "reset_password_code", "activation_code"}) {
|
||||
t.Fatalf("User.Hidden = %v", (User{}).Hidden())
|
||||
}
|
||||
|
||||
if (User{}).MorphName() != `Golem15\User\Models\User` || (Organisation{}).MorphName() != `Golem15\User\Models\Organisation` {
|
||||
t.Fatalf("morph names = %q / %q", (User{}).MorphName(), (Organisation{}).MorphName())
|
||||
}
|
||||
for name, relations := range map[string]int{"user": len((User{}).AttachRelations()), "organisation": len((Organisation{}).AttachRelations())} {
|
||||
if relations != 1 {
|
||||
t.Fatalf("%s attach relations = %d", name, relations)
|
||||
}
|
||||
}
|
||||
if rel := (User{}).AttachRelations()[0]; AvatarField != "avatar" || rel.Name != AvatarField || !rel.Public {
|
||||
t.Fatalf("user avatar relation = %+v", rel)
|
||||
}
|
||||
if rel := (Organisation{}).AttachRelations()[0]; rel.Name != OrganisationAvatarField || !rel.Public {
|
||||
t.Fatalf("organisation avatar relation = %+v", rel)
|
||||
}
|
||||
|
||||
if got := (User{}).FilterScopes(); !reflect.DeepEqual(got, []string{FilterByGroup}) || FilterByGroup != "filterByGroup" {
|
||||
t.Fatalf("User.FilterScopes = %v", got)
|
||||
}
|
||||
// A nil handle passes through for every scope name.
|
||||
if (User{}).FilterScope(FilterByGroup, nil, 1) != nil || (User{}).FilterScope("other", nil, 1) != nil {
|
||||
t.Fatal("FilterScope invented a handle")
|
||||
}
|
||||
|
||||
for model, table := range map[string][2]string{
|
||||
"User": {(User{}).TableName(), "users"}, "UserGroup": {(UserGroup{}).TableName(), "user_groups"},
|
||||
"UsersGroup": {(UsersGroup{}).TableName(), "users_groups"}, "Organisation": {(Organisation{}).TableName(), "golem15_user_organisations"},
|
||||
"FrontendPermission": {(FrontendPermission{}).TableName(), "golem15_user_frontend_permissions"},
|
||||
} {
|
||||
if table[0] != table[1] {
|
||||
t.Fatalf("%s table = %q, want %q", model, table[0], table[1])
|
||||
}
|
||||
}
|
||||
if GroupGuest != "guest" || GroupRegistered != "registered" {
|
||||
t.Fatalf("seeded group codes = %q, %q", GroupGuest, GroupRegistered)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOrganisationBeforeValidate: an empty slug is filled from the name, a
|
||||
// given slug is kept.
|
||||
func TestOrganisationBeforeValidate(t *testing.T) {
|
||||
for _, tc := range []struct{ name, slug, want string }{
|
||||
{"Acme Records", "", "acme-records"},
|
||||
{"Acme Records", "custom", "custom"},
|
||||
{"", "", ""},
|
||||
{"---", "", ""},
|
||||
} {
|
||||
organisation := Organisation{Name: tc.name, Slug: tc.slug}
|
||||
if err := organisation.BeforeValidate(nil); err != nil || organisation.Slug != tc.want {
|
||||
t.Fatalf("BeforeValidate(%q, %q) = %q %v, want %q", tc.name, tc.slug, organisation.Slug, err, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminFieldsNeverMarshal: the columns and relations the admin screens
|
||||
// added never appear when a model is serialized (D-08, D-17; T-12.1-24,
|
||||
// T-12.1-34).
|
||||
func TestAdminFieldsNeverMarshal(t *testing.T) {
|
||||
now := time.Now()
|
||||
code := "admin"
|
||||
secret := "one-time-code"
|
||||
user := User{
|
||||
ID: 7, Email: "marshal@example.test", Password: "$2a$10$stored-hash", LastSeen: &now, CreatedAt: now, UpdatedAt: now,
|
||||
Permissions: PermissionSet{"blog.post": 1},
|
||||
ActivationCode: &secret, ResetPasswordCode: &secret,
|
||||
Groups: []UserGroup{{ID: 3, Name: "Site admins", Code: &code}},
|
||||
}
|
||||
raw, err := json.Marshal(user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var keys map[string]any
|
||||
if err := json.Unmarshal(raw, &keys); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, key := range []string{"LastSeen", "Permissions", "CreatedAt", "UpdatedAt", "Groups", "Password", "ActivationCode", "ResetPasswordCode"} {
|
||||
if _, ok := keys[key]; ok {
|
||||
t.Fatalf("a marshalled user has the key %s: %s", key, raw)
|
||||
}
|
||||
}
|
||||
lower := strings.ToLower(string(raw))
|
||||
for _, leak := range []string{"last_seen", "permissions", "groups", "blog.post", "site admins", "stored-hash", "one-time-code"} {
|
||||
if strings.Contains(lower, leak) {
|
||||
t.Fatalf("a marshalled user carries %q: %s", leak, raw)
|
||||
}
|
||||
}
|
||||
// The rest of the payload is unchanged by the admin fields.
|
||||
if keys["Email"] != "marshal@example.test" || keys["ID"] != float64(7) {
|
||||
t.Fatalf("marshalled user = %s", raw)
|
||||
}
|
||||
|
||||
organisation, err := json.Marshal(Organisation{ID: 1, Name: "Acme", Members: []User{user}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(organisation), "Members") || strings.Contains(string(organisation), "marshal@example.test") {
|
||||
t.Fatalf("a marshalled organisation carries its members: %s", organisation)
|
||||
}
|
||||
group, err := json.Marshal(UserGroup{ID: 3, Name: "Site admins", UsersCount: 5})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(group), "UsersCount") {
|
||||
t.Fatalf("a marshalled group carries the member count: %s", group)
|
||||
}
|
||||
}
|
||||
|
||||
// TestModelRegistry: the plugin registers its seven models, the pivot and the
|
||||
// permission catalog included.
|
||||
func TestModelRegistry(t *testing.T) {
|
||||
var names []string
|
||||
for _, model := range All() {
|
||||
names = append(names, reflect.TypeOf(model).Name())
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, want := range []string{"FrontendPermission", "Organisation", "User", "UserGroup", "UsersGroup"} {
|
||||
found := false
|
||||
for _, name := range names {
|
||||
found = found || name == want
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("model %s is not registered: %v", want, names)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestGroupFilterID: the group filter takes a positive whole number, as a
|
||||
// number or as its decimal text, and nothing else.
|
||||
func TestGroupFilterID(t *testing.T) {
|
||||
for _, value := range []any{"7", " 7 ", 7, uint(7), int64(7), float64(7), json.Number("7")} {
|
||||
if id, ok := groupFilterID(value); !ok || id != 7 {
|
||||
t.Errorf("groupFilterID(%#v) = %d %v, want 7", value, id, ok)
|
||||
}
|
||||
}
|
||||
for _, value := range []any{nil, "", " ", "abc", "7 OR 1=1", "7;", "-1", "0", 0, -3, 7.5, "7.0", "1e3", true, []int{7}, "99999999999999999999"} {
|
||||
if id, ok := groupFilterID(value); ok {
|
||||
t.Errorf("groupFilterID(%#v) = %d, want a refusal", value, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
25
models/frontend_permission.go
Normal file
25
models/frontend_permission.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// FrontendPermission is one row of golem15_user_frontend_permissions, the
|
||||
// PHP FrontendPermission model: a permission the user and group permission
|
||||
// editors offer. Rows come from migrations or seeds of the host application;
|
||||
// there is no registry that plugins declare permissions in. Label, Tab and
|
||||
// Comment are shown as stored; a value that is a translation key is
|
||||
// translated.
|
||||
type FrontendPermission struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
Code string `gorm:"column:code"`
|
||||
Label string `gorm:"column:label"`
|
||||
Tab string `gorm:"column:tab"`
|
||||
Comment *string `gorm:"column:comment"`
|
||||
CreatedAt *time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt *time.Time `gorm:"column:updated_at"`
|
||||
}
|
||||
|
||||
func (FrontendPermission) TableName() string { return "golem15_user_frontend_permissions" }
|
||||
|
||||
func init() {
|
||||
Register(FrontendPermission{})
|
||||
}
|
||||
32
models/oauth_identity.go
Normal file
32
models/oauth_identity.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
)
|
||||
|
||||
// OAuthIdentity is one linked social-login provider for a user.
|
||||
type OAuthIdentity struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
UserID uint `gorm:"column:user_id"`
|
||||
Provider string `gorm:"column:provider"`
|
||||
ProviderID string `gorm:"column:provider_id"`
|
||||
AccessToken lagoon.Encrypted `gorm:"column:access_token" json:"-"`
|
||||
RefreshToken lagoon.Encrypted `gorm:"column:refresh_token" json:"-"`
|
||||
TokenExpiresAt *time.Time `gorm:"column:token_expires_at"`
|
||||
ProfileData lagoon.Jsonable[map[string]any] `gorm:"column:profile_data" json:"-"`
|
||||
LinkedAt *time.Time `gorm:"column:linked_at"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
}
|
||||
|
||||
func (OAuthIdentity) TableName() string { return "golem15_user_oauth_identities" }
|
||||
|
||||
func (OAuthIdentity) Fillable() []string { return []string{} }
|
||||
|
||||
func (OAuthIdentity) Hidden() []string {
|
||||
return []string{"access_token", "refresh_token", "profile_data"}
|
||||
}
|
||||
|
||||
func init() { Register(OAuthIdentity{}) }
|
||||
@@ -1,9 +1,16 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"time"
|
||||
|
||||
// Organisation is the structure-only FK target for Fonoteka org credentials.
|
||||
// Roles and membership behavior belong to Phase 7 AUTH-02.
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Organisation is a row of golem15_user_organisations, the PHP Organisation
|
||||
// model: a named group of users (users.organisation_id) that other plugins
|
||||
// hang organisation-level data on. The table is shared with those plugins
|
||||
// and gets no column from the admin screen.
|
||||
type Organisation struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
Slug string `gorm:"column:slug"`
|
||||
@@ -11,10 +18,50 @@ type Organisation struct {
|
||||
Description *string `gorm:"column:description"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
// Members is the PHP hasMany members relation: the users whose
|
||||
// organisation_id is this organisation. It is not a column. It is loaded
|
||||
// only on request, written only by the admin members manager (which sets
|
||||
// and clears users.organisation_id), and never serialized.
|
||||
Members []User `gorm:"foreignKey:OrganisationID;references:ID" json:"-"`
|
||||
}
|
||||
|
||||
func (Organisation) TableName() string { return "golem15_user_organisations" }
|
||||
|
||||
// MorphName is the PHP class string stored in system_files.attachment_type.
|
||||
func (Organisation) MorphName() string { return `Golem15\User\Models\Organisation` }
|
||||
|
||||
// OrganisationAvatarField is the attachOne relation name of the
|
||||
// organisation's picture.
|
||||
const OrganisationAvatarField = "avatar"
|
||||
|
||||
// AttachRelations declares the public attachOne avatar (PHP $attachOne).
|
||||
func (Organisation) AttachRelations() []attach.Relation {
|
||||
return []attach.Relation{{Name: OrganisationAvatarField, Public: true}}
|
||||
}
|
||||
|
||||
// Fillable is the PHP $fillable list.
|
||||
func (Organisation) Fillable() []string {
|
||||
return []string{"name", "slug", "description"}
|
||||
}
|
||||
|
||||
// Rules is the PHP rule set without alpha_dash on slug, which the rule
|
||||
// engine does not know: the admin controller checks the slug's characters.
|
||||
func (Organisation) Rules() map[string]string {
|
||||
return map[string]string{
|
||||
"name": "required|max:255",
|
||||
"slug": "required|unique:golem15_user_organisations",
|
||||
"description": "nullable|max:5000",
|
||||
}
|
||||
}
|
||||
|
||||
// BeforeValidate fills an empty slug from the name, the PHP beforeValidate.
|
||||
func (o *Organisation) BeforeValidate(_ *gorm.DB) error {
|
||||
if o.Slug == "" && o.Name != "" {
|
||||
o.Slug = Slugify(o.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(Organisation{})
|
||||
}
|
||||
|
||||
14
models/organisation/columns.yaml
Normal file
14
models/organisation/columns.yaml
Normal file
@@ -0,0 +1,14 @@
|
||||
columns:
|
||||
id:
|
||||
label: golem15.user::lang.organisation.id
|
||||
invisible: true
|
||||
name:
|
||||
label: golem15.user::lang.organisation.name
|
||||
searchable: true
|
||||
slug:
|
||||
label: golem15.user::lang.organisation.slug
|
||||
searchable: true
|
||||
created_at:
|
||||
label: backend::lang.list.column_created
|
||||
type: datetime
|
||||
sortable: true
|
||||
30
models/organisation/fields.yaml
Normal file
30
models/organisation/fields.yaml
Normal file
@@ -0,0 +1,30 @@
|
||||
fields:
|
||||
name:
|
||||
label: golem15.user::lang.organisation.name
|
||||
type: text
|
||||
span: left
|
||||
required: true
|
||||
slug:
|
||||
label: golem15.user::lang.organisation.slug
|
||||
comment: golem15.user::lang.organisation.slug_comment
|
||||
type: text
|
||||
span: right
|
||||
preset:
|
||||
field: name
|
||||
type: slug
|
||||
description:
|
||||
label: golem15.user::lang.organisation.description
|
||||
type: textarea
|
||||
size: small
|
||||
avatar:
|
||||
label: golem15.user::lang.organisation.avatar
|
||||
type: fileupload
|
||||
mode: image
|
||||
imageWidth: 120
|
||||
imageHeight: 120
|
||||
members:
|
||||
type: relation-manager
|
||||
relation: members
|
||||
tab: golem15.user::lang.organisation.members
|
||||
span: full
|
||||
context: update
|
||||
124
models/permission_set.go
Normal file
124
models/permission_set.go
Normal file
@@ -0,0 +1,124 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// PermissionSet is a frontend permission map as Winter stores it in
|
||||
// users.permissions and user_groups.permissions: a JSON object of permission
|
||||
// code to integer, where 1 allows, -1 denies and 0 (or no entry) inherits.
|
||||
//
|
||||
// Reading is tolerant, because the rows a cutover imports were written by
|
||||
// several PHP code paths: NULL, an empty string, the texts [] and null all
|
||||
// mean "no permissions", and a value may be an integer or a numeric string.
|
||||
// Writing is strict: an object of integers without zero values, or NULL for
|
||||
// an empty set.
|
||||
type PermissionSet map[string]int
|
||||
|
||||
// GormDataType tells GORM the column type: a map is not a type it knows.
|
||||
func (PermissionSet) GormDataType() string { return "text" }
|
||||
|
||||
// Scan implements sql.Scanner. An entry whose value is not numeric is
|
||||
// skipped; content that is not a JSON object (and none of the empty forms
|
||||
// above) is an error, so a damaged row is never read as "no permissions",
|
||||
// which would silently drop its denials.
|
||||
func (p *PermissionSet) Scan(src any) error {
|
||||
var raw []byte
|
||||
switch v := src.(type) {
|
||||
case nil:
|
||||
*p = PermissionSet{}
|
||||
return nil
|
||||
case string:
|
||||
raw = []byte(v)
|
||||
case []byte:
|
||||
raw = v
|
||||
default:
|
||||
return fmt.Errorf("golem15.user: cannot scan %T into a permission set", src)
|
||||
}
|
||||
set, err := ParsePermissionSet(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*p = set
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParsePermissionSet decodes the stored text of a permission column with the
|
||||
// tolerance Scan documents.
|
||||
func ParsePermissionSet(raw []byte) (PermissionSet, error) {
|
||||
text := strings.TrimSpace(string(raw))
|
||||
if text == "" || text == "[]" || text == "null" {
|
||||
return PermissionSet{}, nil
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader([]byte(text)))
|
||||
dec.UseNumber()
|
||||
var entries map[string]any
|
||||
if err := dec.Decode(&entries); err != nil {
|
||||
return nil, fmt.Errorf("golem15.user: stored permissions are not a JSON object: %w", err)
|
||||
}
|
||||
if dec.More() {
|
||||
return nil, fmt.Errorf("golem15.user: stored permissions carry trailing data")
|
||||
}
|
||||
set := make(PermissionSet, len(entries))
|
||||
for code, value := range entries {
|
||||
if n, ok := permissionInt(value); ok {
|
||||
set[code] = n
|
||||
}
|
||||
}
|
||||
return set, nil
|
||||
}
|
||||
|
||||
// permissionInt reads one stored permission value: a JSON integer or a
|
||||
// string holding one. Anything else is not numeric.
|
||||
func permissionInt(value any) (int, bool) {
|
||||
var text string
|
||||
switch v := value.(type) {
|
||||
case json.Number:
|
||||
text = v.String()
|
||||
case string:
|
||||
text = strings.TrimSpace(v)
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
n, err := strconv.Atoi(text)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
return n, true
|
||||
}
|
||||
|
||||
// Text returns the set as the text of a permission column that is a plain
|
||||
// nullable string on its model (user_groups.permissions): the JSON object
|
||||
// Value writes, or nil for a set without a non-zero value.
|
||||
func (p PermissionSet) Text() *string {
|
||||
value, err := p.Value()
|
||||
text, ok := value.(string)
|
||||
if err != nil || !ok {
|
||||
return nil
|
||||
}
|
||||
return &text
|
||||
}
|
||||
|
||||
// Value implements driver.Valuer: NULL for a set without a non-zero value,
|
||||
// else a JSON object of integers with the zero values left out.
|
||||
func (p PermissionSet) Value() (driver.Value, error) {
|
||||
kept := make(map[string]int, len(p))
|
||||
for code, value := range p {
|
||||
if value != 0 {
|
||||
kept[code] = value
|
||||
}
|
||||
}
|
||||
if len(kept) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
raw, err := json.Marshal(kept)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return string(raw), nil
|
||||
}
|
||||
90
models/permission_set_test.go
Normal file
90
models/permission_set_test.go
Normal file
@@ -0,0 +1,90 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestPermissionSetRoundTrip: what Value writes, Scan and ParsePermissionSet
|
||||
// read back unchanged; Text is the same text for a plain string column.
|
||||
func TestPermissionSetRoundTrip(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
set PermissionSet
|
||||
text string // "" stands for NULL
|
||||
back PermissionSet
|
||||
}{
|
||||
{"allow and deny", PermissionSet{"blog.post": 1, "blog.edit": -1}, `{"blog.edit":-1,"blog.post":1}`, PermissionSet{"blog.post": 1, "blog.edit": -1}},
|
||||
{"a zero is not stored", PermissionSet{"blog.post": 1, "blog.zero": 0}, `{"blog.post":1}`, PermissionSet{"blog.post": 1}},
|
||||
{"a wildcard code", PermissionSet{"blog.*": 1}, `{"blog.*":1}`, PermissionSet{"blog.*": 1}},
|
||||
{"an empty set", PermissionSet{}, "", PermissionSet{}},
|
||||
{"a nil set", nil, "", PermissionSet{}},
|
||||
{"only zeros", PermissionSet{"blog.zero": 0}, "", PermissionSet{}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
value, err := tc.set.Value()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text := tc.set.Text()
|
||||
if tc.text == "" {
|
||||
if value != nil || text != nil {
|
||||
t.Fatalf("Value = %#v, Text = %v, want NULL", value, text)
|
||||
}
|
||||
} else if value != tc.text || text == nil || *text != tc.text {
|
||||
t.Fatalf("Value = %#v, Text = %v, want %s", value, text, tc.text)
|
||||
}
|
||||
var scanned PermissionSet
|
||||
if err := scanned.Scan(value); err != nil || !reflect.DeepEqual(scanned, tc.back) {
|
||||
t.Fatalf("Scan(Value) = %v %v, want %v", scanned, err, tc.back)
|
||||
}
|
||||
parsed, err := ParsePermissionSet([]byte(tc.text))
|
||||
if err != nil || !reflect.DeepEqual(parsed, tc.back) {
|
||||
t.Fatalf("ParsePermissionSet(%q) = %v %v, want %v", tc.text, parsed, err, tc.back)
|
||||
}
|
||||
})
|
||||
}
|
||||
if got := (PermissionSet{}).GormDataType(); got != "text" {
|
||||
t.Fatalf("GormDataType = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestParsePermissionSet: the tolerant read of what PHP may have stored, and
|
||||
// the error for content that is not a JSON object.
|
||||
func TestParsePermissionSet(t *testing.T) {
|
||||
for raw, want := range map[string]PermissionSet{
|
||||
"": {},
|
||||
" ": {},
|
||||
"[]": {},
|
||||
"null": {},
|
||||
" {} ": {},
|
||||
`{"a":1,"b":"1","c":" -1 "}`: {"a": 1, "b": 1, "c": -1},
|
||||
// Values that are not integers are skipped, never read as granted.
|
||||
`{"a":true,"b":"yes","c":1.5,"d":null,"e":[1],"f":{"x":1},"g":1}`: {"g": 1},
|
||||
`{"big":99999999999999999999}`: {},
|
||||
} {
|
||||
got, err := ParsePermissionSet([]byte(raw))
|
||||
if err != nil || got == nil || !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("ParsePermissionSet(%q) = %v %v, want %v", raw, got, err, want)
|
||||
}
|
||||
}
|
||||
for _, raw := range []string{`{"a":1`, `["a"]`, `1`, `"a"`, `true`, `{"a":1}{"b":1}`, `{"a":1} x`} {
|
||||
if got, err := ParsePermissionSet([]byte(raw)); err == nil {
|
||||
t.Errorf("ParsePermissionSet(%q) = %v, want an error", raw, got)
|
||||
}
|
||||
}
|
||||
// Scan keeps the previous value on an error and takes text or bytes.
|
||||
set := PermissionSet{"kept": 1}
|
||||
if err := set.Scan(`["a"]`); err == nil || !reflect.DeepEqual(set, PermissionSet{"kept": 1}) {
|
||||
t.Fatalf("a failed Scan changed the set: %v %v", set, err)
|
||||
}
|
||||
if err := set.Scan([]byte(`{"a":-1}`)); err != nil || !reflect.DeepEqual(set, PermissionSet{"a": -1}) {
|
||||
t.Fatalf("Scan(bytes) = %v %v", set, err)
|
||||
}
|
||||
if err := set.Scan(nil); err != nil || set == nil || len(set) != 0 {
|
||||
t.Fatalf("Scan(nil) = %#v %v", set, err)
|
||||
}
|
||||
if err := set.Scan(3.5); err == nil {
|
||||
t.Fatal("Scan accepted a float")
|
||||
}
|
||||
}
|
||||
26
models/slug.go
Normal file
26
models/slug.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package models
|
||||
|
||||
import "strings"
|
||||
|
||||
// Slugify turns text into a slug by the rule the admin form's slug preset
|
||||
// uses: lower-case ASCII letters and digits are kept, every run of other
|
||||
// characters becomes one hyphen, and there is no hyphen at either end.
|
||||
// Letters outside ASCII are not transliterated; they count as other
|
||||
// characters. A text without a letter or digit gives the empty string.
|
||||
func Slugify(text string) string {
|
||||
var b strings.Builder
|
||||
b.Grow(len(text))
|
||||
gap := false
|
||||
for _, r := range strings.ToLower(text) {
|
||||
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {
|
||||
if gap && b.Len() > 0 {
|
||||
b.WriteByte('-')
|
||||
}
|
||||
gap = false
|
||||
b.WriteRune(r)
|
||||
continue
|
||||
}
|
||||
gap = true
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
53
models/slug_test.go
Normal file
53
models/slug_test.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// slugCases is the table the admin SPA's slug preset is tested against as
|
||||
// well (admin/tests/form/formState.test.ts in the framework repository,
|
||||
// "slug preset matches the server rule"): the organisation model and the form
|
||||
// must derive the same slug from the same name.
|
||||
var slugCases = []struct{ text, want string }{
|
||||
{"Acme Records", "acme-records"},
|
||||
{" Acme -- Records ", "acme-records"},
|
||||
{"ACME_Records 2", "acme-records-2"},
|
||||
{"Zażółć gęślą", "za-g-l"},
|
||||
{"Rock & Roll!!!", "rock-roll"},
|
||||
{"...leading and trailing...", "leading-and-trailing"},
|
||||
{"tab\tand\nnewline", "tab-and-newline"},
|
||||
{"emoji 🎵 music", "emoji-music"},
|
||||
{"CamelCaseText", "camelcasetext"},
|
||||
{"9 lives", "9-lives"},
|
||||
{"a", "a"},
|
||||
{"---", ""},
|
||||
{" ", ""},
|
||||
{"", ""},
|
||||
{"ąęść", ""},
|
||||
{strings.Repeat("Long Name ", 40), strings.TrimSuffix(strings.Repeat("long-name-", 40), "-")},
|
||||
}
|
||||
|
||||
func TestSlugifyTable(t *testing.T) {
|
||||
for _, tc := range slugCases {
|
||||
if got := Slugify(tc.text); got != tc.want {
|
||||
t.Errorf("Slugify(%q) = %q, want %q", tc.text, got, tc.want)
|
||||
}
|
||||
}
|
||||
// A slug is a fixed point, and it only holds lower-case ASCII letters,
|
||||
// digits and single hyphens between them.
|
||||
for _, tc := range slugCases {
|
||||
slug := Slugify(tc.text)
|
||||
if again := Slugify(slug); again != slug {
|
||||
t.Errorf("Slugify(Slugify(%q)) = %q, want %q", tc.text, again, slug)
|
||||
}
|
||||
if strings.HasPrefix(slug, "-") || strings.HasSuffix(slug, "-") || strings.Contains(slug, "--") {
|
||||
t.Errorf("Slugify(%q) = %q has a stray hyphen", tc.text, slug)
|
||||
}
|
||||
for _, r := range slug {
|
||||
if !(r >= 'a' && r <= 'z') && !(r >= '0' && r <= '9') && r != '-' {
|
||||
t.Errorf("Slugify(%q) = %q holds %q", tc.text, slug, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
114
models/user.go
114
models/user.go
@@ -1,35 +1,56 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// User is the persisted account the JWT guard and user API load.
|
||||
type User struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
Email string `gorm:"column:email"`
|
||||
Password string `gorm:"column:password" json:"-"`
|
||||
MustChangePassword bool `gorm:"column:must_change_password"`
|
||||
Name *string `gorm:"column:name"`
|
||||
Surname *string `gorm:"column:surname"`
|
||||
IsActivated bool `gorm:"column:is_activated"`
|
||||
ActivatedAt *time.Time `gorm:"column:activated_at"`
|
||||
ActivationCode *string `gorm:"column:activation_code" json:"-"`
|
||||
ActivationCodeIssuedAt *time.Time `gorm:"column:activation_code_issued_at"`
|
||||
ResetPasswordCode *string `gorm:"column:reset_password_code" json:"-"`
|
||||
ResetPasswordCodeIssuedAt *time.Time `gorm:"column:reset_password_code_issued_at"`
|
||||
HasSelfSetPassword bool `gorm:"column:has_self_set_password"`
|
||||
MarketingConsent bool `gorm:"column:marketing_consent"`
|
||||
IsOnboarded bool `gorm:"column:is_onboarded"`
|
||||
OrganisationID *uint `gorm:"column:organisation_id"`
|
||||
OrganisationRole *string `gorm:"column:organisation_role"`
|
||||
PreferredLocale *string `gorm:"column:preferred_locale"`
|
||||
TokensValidAfter *time.Time `gorm:"column:tokens_valid_after"`
|
||||
CreatedIPAddress *string `gorm:"column:created_ip_address"`
|
||||
LastIPAddress *string `gorm:"column:last_ip_address"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at"`
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
Email string `gorm:"column:email"`
|
||||
Password string `gorm:"column:password" json:"-"`
|
||||
MustChangePassword bool `gorm:"column:must_change_password"`
|
||||
Name *string `gorm:"column:name"`
|
||||
Surname *string `gorm:"column:surname"`
|
||||
IsActivated bool `gorm:"column:is_activated"`
|
||||
ActivatedAt *time.Time `gorm:"column:activated_at"`
|
||||
ActivationCode *string `gorm:"column:activation_code" json:"-"`
|
||||
ActivationCodeIssuedAt *time.Time `gorm:"column:activation_code_issued_at"`
|
||||
ResetPasswordCode *string `gorm:"column:reset_password_code" json:"-"`
|
||||
ResetPasswordCodeIssuedAt *time.Time `gorm:"column:reset_password_code_issued_at"`
|
||||
HasSelfSetPassword bool `gorm:"column:has_self_set_password"`
|
||||
MarketingConsent bool `gorm:"column:marketing_consent"`
|
||||
IsOnboarded bool `gorm:"column:is_onboarded"`
|
||||
OrganisationID *uint `gorm:"column:organisation_id"`
|
||||
OrganisationRole *string `gorm:"column:organisation_role"`
|
||||
PreferredLocale *string `gorm:"column:preferred_locale"`
|
||||
TokensValidAfter *time.Time `gorm:"column:tokens_valid_after"`
|
||||
CreatedIPAddress *string `gorm:"column:created_ip_address"`
|
||||
LastIPAddress *string `gorm:"column:last_ip_address"`
|
||||
// Handle is the unique @mention identity (D-15). Generated on create,
|
||||
// never mass-assigned, and omitted from user API payloads unless a
|
||||
// golden requires it.
|
||||
Handle *string `gorm:"column:handle" json:"-"`
|
||||
// LastSeen is stamped by login and token refresh, at most once per five
|
||||
// minutes (classes.TouchLastSeen). It is shown in the admin list and is
|
||||
// never part of a user API payload.
|
||||
LastSeen *time.Time `gorm:"column:last_seen" json:"-"`
|
||||
// Permissions are the user's own frontend permissions (1 allows, -1
|
||||
// denies). classes.MergedPermissions combines them with the groups'. They
|
||||
// are written by the admin permission editor only and are never part of
|
||||
// a user API payload.
|
||||
Permissions PermissionSet `gorm:"column:permissions" json:"-"`
|
||||
// CreatedAt and UpdatedAt are read-only: the database defaults fill them
|
||||
// and GORM never writes or stamps them through this model.
|
||||
CreatedAt time.Time `gorm:"column:created_at;->" json:"-"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at;->" json:"-"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at"`
|
||||
// Groups is the PHP belongsToMany groups relation through users_groups.
|
||||
// It is loaded only on request, written only by a caller that
|
||||
// associates groups, and never serialized: the user API answers
|
||||
@@ -42,6 +63,17 @@ func (User) TableName() string { return "users" }
|
||||
// MorphName is the PHP class string stored in system_files.attachment_type.
|
||||
func (User) MorphName() string { return `Golem15\User\Models\User` }
|
||||
|
||||
// AvatarField is the attachOne relation name of the user's display picture,
|
||||
// the value of system_files.field the user API writes.
|
||||
const AvatarField = "avatar"
|
||||
|
||||
// AttachRelations declares the public attachOne avatar (PHP $attachOne), so
|
||||
// the admin form's file upload edits the same attachment the user API
|
||||
// serves.
|
||||
func (User) AttachRelations() []attach.Relation {
|
||||
return []attach.Relation{{Name: AvatarField, Public: true}}
|
||||
}
|
||||
|
||||
// Fillable is the register/update field list. Username, PIN, and GDPR columns
|
||||
// stay out of Phase 7 because no ported handler reads them.
|
||||
func (User) Fillable() []string {
|
||||
@@ -66,6 +98,44 @@ func (User) Rules() map[string]string {
|
||||
}
|
||||
}
|
||||
|
||||
// FilterByGroup is the admin list scope that keeps the members of one group,
|
||||
// the PHP User::scopeFilterByGroup.
|
||||
const FilterByGroup = "filterByGroup"
|
||||
|
||||
// FilterScopes lists the scope names a config_filter.yaml may call.
|
||||
func (User) FilterScopes() []string { return []string{FilterByGroup} }
|
||||
|
||||
// FilterScope narrows db to the members of the group whose id is value. Any
|
||||
// other scope name, and a value that is not a group id, match nothing.
|
||||
func (User) FilterScope(name string, db *gorm.DB, value any) *gorm.DB {
|
||||
if db == nil {
|
||||
return db
|
||||
}
|
||||
if name != FilterByGroup {
|
||||
return db.Where("1 = 0")
|
||||
}
|
||||
id, ok := groupFilterID(value)
|
||||
if !ok {
|
||||
return db.Where("1 = 0")
|
||||
}
|
||||
return db.Where("users.id IN (SELECT user_id FROM users_groups WHERE user_group_id = ?)", id)
|
||||
}
|
||||
|
||||
// groupFilterID reads the value of the group filter: a positive whole number,
|
||||
// as a number or as its decimal text. Anything else is not a group id, and
|
||||
// handing it to the database would fail the whole list.
|
||||
func groupFilterID(value any) (uint64, bool) {
|
||||
text := strings.TrimSpace(fmt.Sprint(value))
|
||||
if value == nil || text == "" {
|
||||
return 0, false
|
||||
}
|
||||
id, err := strconv.ParseUint(text, 10, 32)
|
||||
if err != nil || id == 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(User{})
|
||||
}
|
||||
|
||||
28
models/user/columns.yaml
Normal file
28
models/user/columns.yaml
Normal file
@@ -0,0 +1,28 @@
|
||||
columns:
|
||||
id:
|
||||
label: golem15.user::lang.user.id
|
||||
invisible: true
|
||||
name:
|
||||
label: golem15.user::lang.user.name
|
||||
searchable: true
|
||||
surname:
|
||||
label: golem15.user::lang.user.surname
|
||||
searchable: true
|
||||
invisible: true
|
||||
email:
|
||||
label: golem15.user::lang.user.email
|
||||
searchable: true
|
||||
created_at:
|
||||
label: golem15.user::lang.user.created_at
|
||||
type: datetime
|
||||
last_seen:
|
||||
label: golem15.user::lang.user.last_seen
|
||||
type: datetime
|
||||
created_ip_address:
|
||||
label: golem15.user::lang.user.created_ip_address
|
||||
searchable: true
|
||||
invisible: true
|
||||
last_ip_address:
|
||||
label: golem15.user::lang.user.last_ip_address
|
||||
searchable: true
|
||||
invisible: true
|
||||
75
models/user/fields.yaml
Normal file
75
models/user/fields.yaml
Normal file
@@ -0,0 +1,75 @@
|
||||
fields:
|
||||
name:
|
||||
label: golem15.user::lang.user.name
|
||||
type: text
|
||||
span: left
|
||||
tab: golem15.user::lang.user.account
|
||||
surname:
|
||||
label: golem15.user::lang.user.surname
|
||||
type: text
|
||||
span: right
|
||||
tab: golem15.user::lang.user.account
|
||||
email:
|
||||
label: golem15.user::lang.user.email
|
||||
type: text
|
||||
span: full
|
||||
tab: golem15.user::lang.user.account
|
||||
send_invite:
|
||||
label: golem15.user::lang.user.send_invite
|
||||
comment: golem15.user::lang.user.send_invite_comment
|
||||
type: checkbox
|
||||
default: true
|
||||
tab: golem15.user::lang.user.account
|
||||
context: create
|
||||
password:
|
||||
label: golem15.user::lang.user.password
|
||||
comment: golem15.user::lang.user.password_comment
|
||||
type: password
|
||||
span: left
|
||||
tab: golem15.user::lang.user.account
|
||||
context: [create, update]
|
||||
password_confirmation:
|
||||
label: golem15.user::lang.user.confirm_password
|
||||
comment: golem15.user::lang.user.confirm_password_comment
|
||||
type: password
|
||||
span: right
|
||||
tab: golem15.user::lang.user.account
|
||||
context: [create, update]
|
||||
groups:
|
||||
label: golem15.user::lang.user.groups
|
||||
type: relation
|
||||
span: full
|
||||
emptyOption: golem15.user::lang.user.empty_groups
|
||||
tab: golem15.user::lang.user.account
|
||||
organisation:
|
||||
label: golem15.user::lang.organisation.label
|
||||
type: relation
|
||||
nameFrom: name
|
||||
span: full
|
||||
emptyOption: golem15.user::lang.organisation.empty_organisation
|
||||
tab: golem15.user::lang.user.account
|
||||
avatar:
|
||||
label: golem15.user::lang.user.avatar
|
||||
type: fileupload
|
||||
mode: image
|
||||
imageWidth: 260
|
||||
imageHeight: 260
|
||||
tab: golem15.user::lang.user.account
|
||||
created_ip_address:
|
||||
label: golem15.user::lang.user.created_ip_address
|
||||
type: text
|
||||
span: left
|
||||
tab: golem15.user::lang.user.account
|
||||
context: preview
|
||||
last_ip_address:
|
||||
label: golem15.user::lang.user.last_ip_address
|
||||
type: text
|
||||
span: right
|
||||
tab: golem15.user::lang.user.account
|
||||
context: preview
|
||||
permissions:
|
||||
type: permissioneditor
|
||||
mode: radio
|
||||
span: full
|
||||
tab: golem15.user::lang.user.permissions_tab
|
||||
context: update
|
||||
@@ -4,7 +4,8 @@ import "time"
|
||||
|
||||
// UserGroup is a row of user_groups, the PHP UserGroup model. Membership
|
||||
// lives in the users_groups pivot (User.Groups). Permissions is the raw
|
||||
// jsonable text column.
|
||||
// jsonable text column; ParsePermissionSet reads it and PermissionSet.Text
|
||||
// writes it.
|
||||
type UserGroup struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
Name string `gorm:"column:name"`
|
||||
@@ -13,6 +14,11 @@ type UserGroup struct {
|
||||
Permissions *string `gorm:"column:permissions"`
|
||||
CreatedAt *time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt *time.Time `gorm:"column:updated_at"`
|
||||
// UsersCount is the number of members, the PHP users_count relation. It
|
||||
// is not a column of user_groups: only a query that selects an expression
|
||||
// named users_count fills it (the admin list does), it is never written,
|
||||
// and it is zero everywhere else.
|
||||
UsersCount int64 `gorm:"column:users_count;->" json:"-"`
|
||||
}
|
||||
|
||||
func (UserGroup) TableName() string { return "user_groups" }
|
||||
@@ -24,6 +30,21 @@ const (
|
||||
GroupRegistered = "registered"
|
||||
)
|
||||
|
||||
// Fillable is the field list an admin save may set. Permissions is written
|
||||
// through the permission editor, not by a fill.
|
||||
func (UserGroup) Fillable() []string {
|
||||
return []string{"name", "code", "description"}
|
||||
}
|
||||
|
||||
// Rules is the PHP UserGroup rule set without its regex on code, which the
|
||||
// rule engine does not know: the admin controller checks the code's format.
|
||||
func (UserGroup) Rules() map[string]string {
|
||||
return map[string]string{
|
||||
"name": "required|between:3,64",
|
||||
"code": "required|unique:user_groups",
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(UserGroup{})
|
||||
}
|
||||
|
||||
15
models/usergroup/columns.yaml
Normal file
15
models/usergroup/columns.yaml
Normal file
@@ -0,0 +1,15 @@
|
||||
columns:
|
||||
id:
|
||||
label: golem15.user::lang.group.id
|
||||
invisible: true
|
||||
name:
|
||||
label: golem15.user::lang.group.name
|
||||
searchable: true
|
||||
code:
|
||||
label: golem15.user::lang.group.code
|
||||
created_at:
|
||||
label: golem15.user::lang.group.created_at
|
||||
type: datetime
|
||||
users_count:
|
||||
label: golem15.user::lang.group.users_count
|
||||
sortable: false
|
||||
21
models/usergroup/fields.yaml
Normal file
21
models/usergroup/fields.yaml
Normal file
@@ -0,0 +1,21 @@
|
||||
fields:
|
||||
name:
|
||||
label: golem15.user::lang.group.name
|
||||
type: text
|
||||
span: left
|
||||
required: true
|
||||
code:
|
||||
label: golem15.user::lang.group.code
|
||||
comment: golem15.user::lang.group.code_comment
|
||||
type: text
|
||||
span: right
|
||||
preset: name
|
||||
description:
|
||||
label: golem15.user::lang.group.description_field
|
||||
type: textarea
|
||||
size: tiny
|
||||
permissions:
|
||||
type: permissioneditor
|
||||
mode: checkbox
|
||||
span: full
|
||||
tab: golem15.user::lang.user.permissions_tab
|
||||
17
models/users_group.go
Normal file
17
models/users_group.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package models
|
||||
|
||||
// UsersGroup is one row of users_groups, the pivot behind User.Groups: the
|
||||
// user is a member of the group. The table has exactly these two columns and
|
||||
// a composite primary key over them. The admin user form's groups field is
|
||||
// its only writer, apart from the cleanup of a permanently deleted user or
|
||||
// group.
|
||||
type UsersGroup struct {
|
||||
UserID uint `gorm:"column:user_id;primaryKey"`
|
||||
UserGroupID uint `gorm:"column:user_group_id;primaryKey"`
|
||||
}
|
||||
|
||||
func (UsersGroup) TableName() string { return "users_groups" }
|
||||
|
||||
func init() {
|
||||
Register(UsersGroup{})
|
||||
}
|
||||
420
oauth_identities_test.go
Normal file
420
oauth_identities_test.go
Normal file
@@ -0,0 +1,420 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/controllers"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||
"git.golem15.com/golem15/summercms/modules/towel"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
lastMethodBlockedEN = "This is the only remaining way to sign in. Link another method before disconnecting this one."
|
||||
lastMethodBlockedPL = "To jedyna droga logowania na to konto. Najpierw podłącz inną, zanim odetniesz tę."
|
||||
winter404Body = `<!DOCTYPE html>
|
||||
<html lang="pl">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Nie znaleziono strony</title>
|
||||
<link href="http://127.0.0.1:8423/modules/system/assets/css/styles.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1><i class="icon-chain-broken warning"></i> Nie znaleziono strony</h1>
|
||||
<p class="lead">Żądana strona nie została znaleziona.</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>`
|
||||
)
|
||||
|
||||
func TestOAuthIdentitiesIndexEmptyList(t *testing.T) {
|
||||
app, db := sessionApp(t, "0s")
|
||||
user := insertUser(t, db, "oauth-empty@example.test", "correct-horse")
|
||||
req := httptest.NewRequest(http.MethodGet, "/_fonoteka/api/v1/oauth-identities", nil)
|
||||
req = req.WithContext(bouncer.WithUser(req.Context(), &bouncer.Principal{ID: user.ID}))
|
||||
rec := httptest.NewRecorder()
|
||||
controllers.OAuthIdentitiesIndex(app).ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec.Body.String() != `{"data":[]}` {
|
||||
t.Fatalf("body = %s", rec.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(body) != 1 {
|
||||
t.Fatalf("top-level keys = %#v", body)
|
||||
}
|
||||
if cc := rec.Header().Get("Cache-Control"); !strings.Contains(cc, "no-cache") {
|
||||
t.Fatalf("Cache-Control = %q", cc)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOAuthIdentitiesDestroyNoContentKeepsSibling(t *testing.T) {
|
||||
app, db := sessionApp(t, "0s")
|
||||
user := insertUser(t, db, "oauth-unlink@example.test", "correct-horse")
|
||||
for _, row := range []models.OAuthIdentity{
|
||||
{UserID: user.ID, Provider: "facebook", ProviderID: "fb-alice"},
|
||||
{UserID: user.ID, Provider: "google", ProviderID: "goog-alice"},
|
||||
} {
|
||||
if err := db.Create(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodDelete, "/_fonoteka/api/v1/oauth-identities/facebook", nil)
|
||||
req.SetPathValue("provider", "facebook")
|
||||
req = req.WithContext(bouncer.WithUser(req.Context(), &bouncer.Principal{ID: user.ID}))
|
||||
rec := httptest.NewRecorder()
|
||||
controllers.OAuthIdentitiesDestroy(app, controllers.OAuthIdentitiesOptions{
|
||||
WriteNotFound: func(http.ResponseWriter, *http.Request) {
|
||||
t.Fatal("WriteNotFound called")
|
||||
},
|
||||
}).ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec.Body.Len() != 0 {
|
||||
t.Fatalf("body = %q", rec.Body.String())
|
||||
}
|
||||
var leftover []models.OAuthIdentity
|
||||
if err := db.Where("user_id = ?", user.ID).Order("provider").Find(&leftover).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(leftover) != 1 || leftover[0].Provider != "google" {
|
||||
t.Fatalf("remaining = %#v", leftover)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOAuthIdentitiesDestroyLastMethodBlockedENAndPL(t *testing.T) {
|
||||
app, db := sessionApp(t, "0s")
|
||||
activateOAuthIdentitiesLang(t, app)
|
||||
for _, tc := range []struct {
|
||||
locale, email, want string
|
||||
}{
|
||||
{"en", "oauth-last-en@example.test", lastMethodBlockedEN},
|
||||
{"pl", "oauth-last-pl@example.test", lastMethodBlockedPL},
|
||||
} {
|
||||
t.Run(tc.locale, func(t *testing.T) {
|
||||
user := insertUser(t, db, tc.email, "correct-horse")
|
||||
// The column defaults to TRUE; a user without a self-set
|
||||
// password is the one the last identity is kept for.
|
||||
if err := db.Model(user).Update("has_self_set_password", false).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seedOAuthIdentity(t, db, user.ID, "facebook", "fb-only-"+tc.locale)
|
||||
rec := destroyOAuthIdentity(t, app, user.ID, "facebook", tc.locale, winter404OrFatal(t))
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body["error"] != tc.want {
|
||||
t.Fatalf("golem15.user::lang.oauth.last_method_blocked %s = %#v", tc.locale, body["error"])
|
||||
}
|
||||
if remaining := countOAuthIdentities(t, db, user.ID); remaining != 1 {
|
||||
t.Fatalf("row still present = %d", remaining)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestOAuthIdentitiesDestroyLastIdentityWithPassword: under the PHP rule a
|
||||
// user with a self-set password may unlink the last identity (D-13).
|
||||
func TestOAuthIdentitiesDestroyLastIdentityWithPassword(t *testing.T) {
|
||||
app, db := sessionApp(t, "0s")
|
||||
activateOAuthIdentitiesLang(t, app)
|
||||
user := insertUser(t, db, "oauth-last-password@example.test", "correct-horse")
|
||||
if err := db.Model(user).Update("has_self_set_password", true).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seedOAuthIdentity(t, db, user.ID, "google", "g-only")
|
||||
rec := destroyOAuthIdentity(t, app, user.ID, "google", "en", winter404OrFatal(t))
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec.Body.Len() != 0 {
|
||||
t.Fatalf("body = %q", rec.Body.String())
|
||||
}
|
||||
if remaining := countOAuthIdentities(t, db, user.ID); remaining != 0 {
|
||||
t.Fatalf("identities left = %d, want 0", remaining)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOAuthIdentitiesDestroyConcurrentSmoke: two unlinks on a password-less
|
||||
// user with two identities never remove both (D-13, RESEARCH Pitfall 1).
|
||||
// Transaction A holds the users row lock and has deleted google; the
|
||||
// handler's unlink of facebook must wait for A, then see one identity left
|
||||
// and answer 409.
|
||||
func TestOAuthIdentitiesDestroyConcurrentSmoke(t *testing.T) {
|
||||
app, db := sessionApp(t, "0s")
|
||||
activateOAuthIdentitiesLang(t, app)
|
||||
user := insertUser(t, db, "oauth-concurrent@example.test", "correct-horse")
|
||||
if err := db.Model(user).Update("has_self_set_password", false).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seedOAuthIdentity(t, db, user.ID, "google", "g-concurrent")
|
||||
seedOAuthIdentity(t, db, user.ID, "facebook", "fb-concurrent")
|
||||
|
||||
txA := db.Begin()
|
||||
if txA.Error != nil {
|
||||
t.Fatal(txA.Error)
|
||||
}
|
||||
committed := false
|
||||
t.Cleanup(func() {
|
||||
if !committed {
|
||||
txA.Rollback()
|
||||
}
|
||||
})
|
||||
if err := txA.Exec(`SELECT id FROM users WHERE id = ? FOR UPDATE`, user.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res := txA.Exec(`DELETE FROM golem15_user_oauth_identities
|
||||
WHERE user_id = ? AND provider = ?
|
||||
AND (EXISTS (SELECT 1 FROM users u WHERE u.id = golem15_user_oauth_identities.user_id AND u.has_self_set_password)
|
||||
OR (SELECT COUNT(*) FROM golem15_user_oauth_identities oi WHERE oi.user_id = golem15_user_oauth_identities.user_id) > 1)`,
|
||||
user.ID, "google")
|
||||
if res.Error != nil || res.RowsAffected != 1 {
|
||||
t.Fatalf("transaction A delete: rows %d err %v", res.RowsAffected, res.Error)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/_fonoteka/api/v1/oauth-identities/facebook", nil)
|
||||
req.SetPathValue("provider", "facebook")
|
||||
req = req.WithContext(towel.WithLocale(bouncer.WithUser(req.Context(), &bouncer.Principal{ID: user.ID}), "en"))
|
||||
rec := httptest.NewRecorder()
|
||||
h := controllers.OAuthIdentitiesDestroy(app, controllers.OAuthIdentitiesOptions{
|
||||
WriteNotFound: func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNotFound) },
|
||||
})
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
h.ServeHTTP(rec, req)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatalf("the unlink answered %d while transaction A held the user row lock", rec.Code)
|
||||
case <-time.After(300 * time.Millisecond):
|
||||
}
|
||||
if err := txA.Commit().Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
committed = true
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("the unlink did not answer after transaction A committed")
|
||||
}
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body["error"] != lastMethodBlockedEN {
|
||||
t.Fatalf("409 body = %s", rec.Body.String())
|
||||
}
|
||||
var left []models.OAuthIdentity
|
||||
if err := db.Where("user_id = ?", user.ID).Find(&left).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(left) != 1 || left[0].Provider != "facebook" {
|
||||
t.Fatalf("remaining = %#v, want facebook only", left)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOAuthIdentitiesDestroyWinter404BodiesAreByteIdentical(t *testing.T) {
|
||||
app, db := sessionApp(t, "0s")
|
||||
owner := insertUser(t, db, "oauth-404-owner@example.test", "correct-horse")
|
||||
stranger := insertUser(t, db, "oauth-404-stranger@example.test", "correct-horse")
|
||||
seedOAuthIdentity(t, db, owner.ID, "google", "g-owner")
|
||||
seedOAuthIdentity(t, db, stranger.ID, "facebook", "fb-stranger")
|
||||
|
||||
foreign := destroyOAuthIdentity(t, app, stranger.ID, "google", "en", writeWinter404)
|
||||
missing := destroyOAuthIdentity(t, app, stranger.ID, "github", "en", writeWinter404)
|
||||
unknown := destroyOAuthIdentity(t, app, stranger.ID, "linkedin", "en", writeWinter404)
|
||||
for name, rec := range map[string]*httptest.ResponseRecorder{
|
||||
"foreign": foreign, "missing": missing, "unknown": unknown,
|
||||
} {
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("%s status %d body %s", name, rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec.Header().Get("Content-Type") != "text/html; charset=UTF-8" {
|
||||
t.Fatalf("%s Content-Type = %q", name, rec.Header().Get("Content-Type"))
|
||||
}
|
||||
if !bytes.Equal(rec.Body.Bytes(), []byte(winter404Body)) {
|
||||
t.Fatalf("%s body = %q", name, rec.Body.String())
|
||||
}
|
||||
}
|
||||
if !bytes.Equal(foreign.Body.Bytes(), missing.Body.Bytes()) || !bytes.Equal(missing.Body.Bytes(), unknown.Body.Bytes()) {
|
||||
t.Fatalf("404 bodies differ")
|
||||
}
|
||||
if remaining := countOAuthIdentities(t, db, owner.ID); remaining != 1 {
|
||||
t.Fatalf("owner google row = %d", remaining)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOAuthIdentitiesIndexDoesNotLeakEncryptedTokensOrProfileData(t *testing.T) {
|
||||
app, db := sessionApp(t, "0s")
|
||||
if err := lagoon.PublishEncryptionKeys(nil, bytes.Repeat([]byte("K"), 32), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
user := insertUser(t, db, "oauth-secret-leak@example.test", "correct-horse")
|
||||
const (
|
||||
plaintext = "secret-access-token-oauth-leak-probe"
|
||||
refresh = "secret-refresh-token-oauth-leak-probe"
|
||||
marker = "profile-distinctive-xyzzy-oauth"
|
||||
)
|
||||
now := time.Now().UTC()
|
||||
row := models.OAuthIdentity{
|
||||
UserID: user.ID,
|
||||
Provider: "google",
|
||||
ProviderID: "g-secret-leak",
|
||||
AccessToken: lagoon.NewEncrypted(plaintext),
|
||||
RefreshToken: lagoon.NewEncrypted(refresh),
|
||||
ProfileData: lagoon.Jsonable[map[string]any]{
|
||||
Data: map[string]any{"email": "leak@example.test", "marker": marker},
|
||||
Valid: true,
|
||||
},
|
||||
LinkedAt: &now,
|
||||
}
|
||||
if err := db.Create(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodGet, "/_fonoteka/api/v1/oauth-identities", nil)
|
||||
req = req.WithContext(bouncer.WithUser(req.Context(), &bouncer.Principal{ID: user.ID}))
|
||||
rec := httptest.NewRecorder()
|
||||
controllers.OAuthIdentitiesIndex(app).ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
body := rec.Body.String()
|
||||
for _, needle := range []string{plaintext, refresh, marker, "access_token", "refresh_token", "profile_data", "[redacted]"} {
|
||||
if strings.Contains(body, needle) {
|
||||
t.Fatalf("GET list leaked %q: %s", needle, body)
|
||||
}
|
||||
}
|
||||
var parsed struct {
|
||||
Data []map[string]any `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &parsed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(parsed.Data) != 1 {
|
||||
t.Fatalf("data = %#v", parsed.Data)
|
||||
}
|
||||
if len(parsed.Data[0]) != 2 {
|
||||
t.Fatalf("row keys = %#v, want provider and linked_at only", parsed.Data[0])
|
||||
}
|
||||
if parsed.Data[0]["provider"] != "google" {
|
||||
t.Fatalf("provider = %#v", parsed.Data[0]["provider"])
|
||||
}
|
||||
if _, ok := parsed.Data[0]["linked_at"]; !ok {
|
||||
t.Fatalf("linked_at missing: %#v", parsed.Data[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestOAuthIdentitiesUnauthorizedOnGoogle(t *testing.T) {
|
||||
app, _ := sessionApp(t, "0s")
|
||||
getReq := httptest.NewRequest(http.MethodGet, "/_fonoteka/api/v1/oauth-identities", nil)
|
||||
getRec := httptest.NewRecorder()
|
||||
controllers.OAuthIdentitiesIndex(app).ServeHTTP(getRec, getReq)
|
||||
assertOAuthIdentityUnauthorized(t, "GET", getRec)
|
||||
|
||||
delReq := httptest.NewRequest(http.MethodDelete, "/_fonoteka/api/v1/oauth-identities/google", nil)
|
||||
delReq.SetPathValue("provider", "google")
|
||||
delRec := httptest.NewRecorder()
|
||||
controllers.OAuthIdentitiesDestroy(app, controllers.OAuthIdentitiesOptions{
|
||||
WriteNotFound: func(http.ResponseWriter, *http.Request) {
|
||||
t.Fatal("unauthenticated /google must 401 before WriteNotFound")
|
||||
},
|
||||
}).ServeHTTP(delRec, delReq)
|
||||
assertOAuthIdentityUnauthorized(t, "DELETE /google", delRec)
|
||||
}
|
||||
|
||||
func activateOAuthIdentitiesLang(t *testing.T, app *backpack.App) {
|
||||
t.Helper()
|
||||
if err := phrasebook.Activate(app, []*Plugin{{}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func seedOAuthIdentity(t *testing.T, db *gorm.DB, userID uint, provider, providerID string) {
|
||||
t.Helper()
|
||||
now := time.Now().UTC()
|
||||
row := models.OAuthIdentity{
|
||||
UserID: userID,
|
||||
Provider: provider,
|
||||
ProviderID: providerID,
|
||||
LinkedAt: &now,
|
||||
}
|
||||
if err := db.Create(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func countOAuthIdentities(t *testing.T, db *gorm.DB, userID uint) int64 {
|
||||
t.Helper()
|
||||
var n int64
|
||||
if err := db.Model(&models.OAuthIdentity{}).Where("user_id = ?", userID).Count(&n).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func writeWinter404(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
|
||||
w.Header().Set("Cache-Control", "no-cache, private")
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(winter404Body))
|
||||
}
|
||||
|
||||
func winter404OrFatal(t *testing.T) func(http.ResponseWriter, *http.Request) {
|
||||
t.Helper()
|
||||
return func(http.ResponseWriter, *http.Request) {
|
||||
t.Fatal("WriteNotFound called")
|
||||
}
|
||||
}
|
||||
|
||||
func destroyOAuthIdentity(t *testing.T, app *backpack.App, userID uint, provider, locale string, notFound func(http.ResponseWriter, *http.Request)) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodDelete, "/_fonoteka/api/v1/oauth-identities/"+provider, nil)
|
||||
req.SetPathValue("provider", provider)
|
||||
ctx := bouncer.WithUser(req.Context(), &bouncer.Principal{ID: userID})
|
||||
if locale != "" {
|
||||
ctx = towel.WithLocale(ctx, locale)
|
||||
}
|
||||
req = req.WithContext(ctx)
|
||||
rec := httptest.NewRecorder()
|
||||
controllers.OAuthIdentitiesDestroy(app, controllers.OAuthIdentitiesOptions{
|
||||
WriteNotFound: notFound,
|
||||
}).ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func assertOAuthIdentityUnauthorized(t *testing.T, name string, rec *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("%s status %d body %s", name, rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec.Body.String() != `{"error":true,"message":"Unauthorized"}` {
|
||||
t.Fatalf("%s body = %s", name, rec.Body.String())
|
||||
}
|
||||
if cc := rec.Header().Get("Cache-Control"); cc != "no-cache, private" {
|
||||
t.Fatalf("%s Cache-Control = %q", name, cc)
|
||||
}
|
||||
}
|
||||
76
oauth_providers_smoke_test.go
Normal file
76
oauth_providers_smoke_test.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"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"
|
||||
)
|
||||
|
||||
// fakeProviderSource is a social-login plugin's provider source.
|
||||
type fakeProviderSource struct {
|
||||
enabled []classes.OAuthProvider
|
||||
known []string
|
||||
}
|
||||
|
||||
func (f fakeProviderSource) EnabledOAuthProviders(context.Context) []classes.OAuthProvider {
|
||||
return f.enabled
|
||||
}
|
||||
|
||||
func (f fakeProviderSource) KnownOAuthProviders() []string { return f.known }
|
||||
|
||||
// TestOAuthProvidersSourceSmoke checks that oauth-providers keeps the empty
|
||||
// body without a published source and lists the source's enabled providers,
|
||||
// looked up per request, once one is published.
|
||||
func TestOAuthProvidersSourceSmoke(t *testing.T) {
|
||||
app := backpack.New(sessionConfig(t))
|
||||
h := controllers.OAuthProviders(app)
|
||||
get := func() *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodGet, "/_user/api/v1/oauth-providers", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
h(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
empty := get()
|
||||
if empty.Code != http.StatusOK {
|
||||
t.Fatalf("status without a source = %d", empty.Code)
|
||||
}
|
||||
// The bytes the handler answered before sources existed (wire encodes
|
||||
// map keys sorted; the PHP recording has the same JSON value).
|
||||
if got := strings.TrimRight(empty.Body.String(), "\n"); got != `{"providers":[],"success":true}` {
|
||||
t.Fatalf("body without a source = %s", got)
|
||||
}
|
||||
|
||||
src := fakeProviderSource{
|
||||
enabled: []classes.OAuthProvider{{Name: "google", Label: "Google"}},
|
||||
known: []string{"google", "facebook"},
|
||||
}
|
||||
if err := app.Publish[classes.OAuthProviderSource](src); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := get()
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status with a source = %d", rec.Code)
|
||||
}
|
||||
if cc := rec.Header().Get("Cache-Control"); cc != "no-cache, private" {
|
||||
t.Fatalf("Cache-Control = %q", cc)
|
||||
}
|
||||
var body struct {
|
||||
Success bool `json:"success"`
|
||||
Providers []classes.OAuthProvider `json:"providers"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode %s: %v", rec.Body.String(), err)
|
||||
}
|
||||
if !body.Success || !reflect.DeepEqual(body.Providers, src.enabled) {
|
||||
t.Fatalf("body with a source = %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
966
phase121_security_test.go
Normal file
966
phase121_security_test.go
Normal file
@@ -0,0 +1,966 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
)
|
||||
|
||||
// pivotSnapshot is the whole users_groups table as text, for byte-identical
|
||||
// comparisons around a request.
|
||||
func (e *adminEnv) pivotSnapshot(t *testing.T) string {
|
||||
t.Helper()
|
||||
var rows []struct{ UserID, UserGroupID uint }
|
||||
if err := e.gdb.Raw(`SELECT user_id, user_group_id FROM users_groups ORDER BY user_id, user_group_id`).Scan(&rows).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var b strings.Builder
|
||||
for _, row := range rows {
|
||||
fmt.Fprintf(&b, "%d:%d;", row.UserID, row.UserGroupID)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// userPayload signs the user in and returns the token and the user payloads
|
||||
// of login and fetch.
|
||||
func (e *adminEnv) userPayloads(t *testing.T, email, password string) (string, map[string]map[string]any, map[string]string) {
|
||||
t.Helper()
|
||||
payloads, raws := map[string]map[string]any{}, map[string]string{}
|
||||
login := e.expect(t, http.StatusOK, http.MethodPost, "/_user/api/v1/login", "", map[string]string{"email": email, "password": password})
|
||||
var body struct {
|
||||
Token string `json:"token"`
|
||||
User map[string]any `json:"user"`
|
||||
}
|
||||
if err := json.Unmarshal(login.Body.Bytes(), &body); err != nil || body.Token == "" {
|
||||
t.Fatalf("login body %s (%v)", login.Body.String(), err)
|
||||
}
|
||||
payloads["login"], raws["login"] = body.User, login.Body.String()
|
||||
fetch := e.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/fetch", body.Token, nil)
|
||||
var fetched struct {
|
||||
User map[string]any `json:"user"`
|
||||
}
|
||||
if err := json.Unmarshal(fetch.Body.Bytes(), &fetched); err != nil {
|
||||
t.Fatalf("fetch body %s (%v)", fetch.Body.String(), err)
|
||||
}
|
||||
payloads["fetch"], raws["fetch"] = fetched.User, fetch.Body.String()
|
||||
return body.Token, payloads, raws
|
||||
}
|
||||
|
||||
// privilegedList boots an environment whose privileged group list is codes.
|
||||
func privilegedList(t *testing.T, codes ...string) *adminEnv {
|
||||
t.Helper()
|
||||
return newAdminEnv(t, func(cfg *compass.Config) {
|
||||
if err := cfg.Set("golem15.user.privileged_groups", codes); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestPhase121Threats has one subtest per mitigated plugin threat of Phase
|
||||
// 12.1, named by its id. Each asserts the protection through the admin API or
|
||||
// the user API of the booted plugin, so removing the protection fails the
|
||||
// subtest on an assertion (scripts/check-phase12.1.sh --removal in the
|
||||
// framework repository).
|
||||
//
|
||||
// T-12.1-26 and T-12.1-32 are accepted risks and T-12.1-33 is a publication
|
||||
// rule; they have no subtest.
|
||||
func TestPhase121Threats(t *testing.T) {
|
||||
// T-12.1-18: every Users, User Groups and Organisations route, bulk action
|
||||
// and record action needs its permission.
|
||||
t.Run("T-12.1-18", func(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
stranger := env.admin(t)
|
||||
usersOnly := env.admin(t, permAccessUsers)
|
||||
groupsOnly := env.admin(t, permAccessGroups)
|
||||
stamp := adminStamp()
|
||||
user := env.seedUser(t, "gated", func(u *models.User) { u.IsActivated = false })
|
||||
group := env.seedGroup(t, "Gated "+stamp, "gated-"+stamp)
|
||||
organisation := env.seedOrganisation(t, "Gated "+stamp)
|
||||
ids := map[string]any{"ids": []uint{user.ID}}
|
||||
type route struct {
|
||||
method, path string
|
||||
body any
|
||||
}
|
||||
users := []route{
|
||||
{http.MethodGet, adminAPI(adminUsersPath), nil},
|
||||
{http.MethodGet, adminAPI(adminUsersPath + "/schema/list"), nil},
|
||||
{http.MethodGet, adminAPI(adminUsersPath + "/schema/form"), nil},
|
||||
{http.MethodGet, adminAPI(adminUsersPath + "/filters/groups/options"), nil},
|
||||
{http.MethodGet, adminAPI(adminUsersPath + "/fields/groups/options"), nil},
|
||||
{http.MethodGet, adminAPI(adminUsersPath + "/fields/organisation/options"), nil},
|
||||
{http.MethodGet, adminAPI(adminUsersPath + "/partials/hint?id=" + strconv.FormatUint(uint64(user.ID), 10)), nil},
|
||||
{http.MethodGet, userPath(user.ID, ""), nil},
|
||||
{http.MethodPost, adminAPI(adminUsersPath), map[string]any{"name": "Made", "email": "made-" + stamp + "@example.test", "password": "made-password-1", "password_confirmation": "made-password-1"}},
|
||||
{http.MethodPut, userPath(user.ID, ""), map[string]any{"name": "Changed", "email": user.Email}},
|
||||
{http.MethodDelete, userPath(user.ID, ""), nil},
|
||||
{http.MethodPost, adminAPI(adminUsersPath + "/bulk-delete"), ids},
|
||||
}
|
||||
for _, action := range []string{"activate", "deactivate", "restore", "ban", "unban"} {
|
||||
users = append(users, route{http.MethodPost, adminAPI(adminUsersPath + "/bulk/" + action), ids})
|
||||
}
|
||||
for _, action := range []string{"activate", "unban", "unsuspend"} {
|
||||
users = append(users, route{http.MethodPost, userPath(user.ID, "/actions/"+action), map[string]any{}})
|
||||
}
|
||||
groups := []route{
|
||||
{http.MethodGet, adminAPI(adminGroupsPath), nil},
|
||||
{http.MethodGet, adminAPI(adminGroupsPath + "/schema/list"), nil},
|
||||
{http.MethodGet, adminAPI(adminGroupsPath + "/schema/form"), nil},
|
||||
{http.MethodGet, groupPath(group.ID), nil},
|
||||
{http.MethodPost, adminAPI(adminGroupsPath), map[string]any{"name": "Made " + stamp, "code": "made-" + stamp}},
|
||||
{http.MethodPut, groupPath(group.ID), map[string]any{"name": "Changed " + stamp, "code": "gated-" + stamp}},
|
||||
{http.MethodDelete, groupPath(group.ID), nil},
|
||||
{http.MethodPost, adminAPI(adminGroupsPath + "/bulk-delete"), map[string]any{"ids": []uint{group.ID}}},
|
||||
}
|
||||
organisations := []route{
|
||||
{http.MethodGet, adminAPI(adminOrganisationsPath), nil},
|
||||
{http.MethodGet, adminAPI(adminOrganisationsPath + "/schema/list"), nil},
|
||||
{http.MethodGet, adminAPI(adminOrganisationsPath + "/schema/form"), nil},
|
||||
{http.MethodGet, adminAPI(adminOrganisationsPath + "/schema/relation/members"), nil},
|
||||
{http.MethodGet, organisationPath(organisation.ID, ""), nil},
|
||||
{http.MethodPost, adminAPI(adminOrganisationsPath), map[string]any{"name": "Made " + stamp}},
|
||||
{http.MethodPut, organisationPath(organisation.ID, ""), map[string]any{"name": "Changed " + stamp, "slug": organisation.Slug}},
|
||||
{http.MethodDelete, organisationPath(organisation.ID, ""), nil},
|
||||
{http.MethodGet, organisationPath(organisation.ID, "/relations/members"), nil},
|
||||
{http.MethodGet, organisationPath(organisation.ID, "/relations/members/candidates"), nil},
|
||||
{http.MethodPost, organisationPath(organisation.ID, "/relations/members/link"), ids},
|
||||
{http.MethodPost, organisationPath(organisation.ID, "/relations/members/unlink"), ids},
|
||||
}
|
||||
refused := func(screen, token string, routes []route) {
|
||||
t.Helper()
|
||||
for _, r := range routes {
|
||||
rec := env.call(t, r.method, r.path, token, r.body)
|
||||
if rec.Code != http.StatusForbidden || adminDecode(t, rec).Error.Code != "forbidden" {
|
||||
t.Fatalf("%s: %s %s without the permission = %d %s", screen, r.method, r.path, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
refused("users", stranger, users)
|
||||
refused("users", groupsOnly, users)
|
||||
refused("user groups", stranger, groups)
|
||||
refused("user groups", usersOnly, groups)
|
||||
refused("organisations", stranger, organisations)
|
||||
refused("organisations", groupsOnly, organisations)
|
||||
|
||||
// Nothing was written by any refused request.
|
||||
got := env.reload(t, user.ID)
|
||||
if got == nil || got.IsActivated || got.DeletedAt.Valid || got.OrganisationID != nil || got.Name == nil || *got.Name != "gated" {
|
||||
t.Fatalf("a refused request changed the user: %+v", got)
|
||||
}
|
||||
if stored := env.group(t, group.ID); stored == nil || stored.Name != "Gated "+stamp {
|
||||
t.Fatalf("a refused request changed the group: %+v", stored)
|
||||
}
|
||||
if stored := env.organisation(t, organisation.ID); stored == nil || stored.Name != "Gated "+stamp {
|
||||
t.Fatalf("a refused request changed the organisation: %+v", stored)
|
||||
}
|
||||
var made int64
|
||||
if err := env.gdb.Raw(`SELECT (SELECT COUNT(*) FROM users WHERE email = ?) + (SELECT COUNT(*) FROM user_groups WHERE code = ?) + (SELECT COUNT(*) FROM golem15_user_organisations WHERE name = ?)`,
|
||||
"made-"+stamp+"@example.test", "made-"+stamp, "Made "+stamp).Scan(&made).Error; err != nil || made != 0 {
|
||||
t.Fatalf("a refused create wrote %d rows (%v)", made, err)
|
||||
}
|
||||
// The same routes open with the permission.
|
||||
env.expect(t, http.StatusOK, http.MethodGet, userPath(user.ID, ""), usersOnly, nil)
|
||||
env.expect(t, http.StatusOK, http.MethodGet, groupPath(group.ID), groupsOnly, nil)
|
||||
env.expect(t, http.StatusOK, http.MethodGet, organisationPath(organisation.ID, ""), usersOnly, nil)
|
||||
})
|
||||
|
||||
// T-12.1-19: no admin response carries a password, a hash or a one-time
|
||||
// code.
|
||||
t.Run("T-12.1-19", func(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
token := env.admin(t, permAccessUsers)
|
||||
stamp := adminStamp()
|
||||
activation, reset := "activation-"+stamp, "reset-"+stamp
|
||||
marker := "leak" + stamp
|
||||
user := env.seedUser(t, "leak", func(u *models.User) {
|
||||
u.Surname, u.IsActivated = &marker, false
|
||||
u.ActivationCode, u.ResetPasswordCode = &activation, &reset
|
||||
})
|
||||
const plain = "leak-password-1"
|
||||
id := strconv.FormatUint(uint64(user.ID), 10)
|
||||
bodies := map[string]string{
|
||||
"list": env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminUsersPath+"?search="+marker), token, nil).Body.String(),
|
||||
"show": env.expect(t, http.StatusOK, http.MethodGet, userPath(user.ID, ""), token, nil).Body.String(),
|
||||
"partial": env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminUsersPath+"/partials/hint?id="+id), token, nil).Body.String(),
|
||||
"update": env.expect(t, http.StatusOK, http.MethodPut, userPath(user.ID, ""), token,
|
||||
map[string]any{"name": "Leak", "email": user.Email, "password": plain, "password_confirmation": plain}).Body.String(),
|
||||
"mismatch": env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, userPath(user.ID, ""), token,
|
||||
map[string]any{"name": "Leak", "email": user.Email, "password": plain, "password_confirmation": "other-password-1"}).Body.String(),
|
||||
"create": env.expect(t, http.StatusCreated, http.MethodPost, adminAPI(adminUsersPath), token,
|
||||
map[string]any{"name": "Leak two", "email": "leak-two-" + stamp + "@example.test", "password": plain, "password_confirmation": plain}).Body.String(),
|
||||
"bulk": env.bulk(t, token, "ban", user).Body.String(),
|
||||
"action": env.expect(t, http.StatusOK, http.MethodPost, userPath(user.ID, "/actions/activate"), token, map[string]any{}).Body.String(),
|
||||
}
|
||||
stored := env.reload(t, user.ID)
|
||||
if !bouncer.CheckPassword(stored.Password, plain) {
|
||||
t.Fatal("the update did not store the submitted password")
|
||||
}
|
||||
for route, body := range bodies {
|
||||
if strings.Contains(body, plain) || strings.Contains(body, activation) || strings.Contains(body, reset) ||
|
||||
strings.Contains(body, stored.Password) || strings.Contains(body, user.Password) || strings.Contains(body, "$2a$") {
|
||||
t.Fatalf("the %s response carries a secret: %s", route, body)
|
||||
}
|
||||
// A 422 names the refused field; no other response has such a key.
|
||||
if route != "mismatch" {
|
||||
assertNoSecret(t, body)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// T-12.1-20: protected columns are never written from a body.
|
||||
t.Run("T-12.1-20", func(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
token := env.admin(t, permAccessUsers)
|
||||
stamp := adminStamp()
|
||||
organisation := env.seedOrganisation(t, "Assign "+stamp)
|
||||
user := env.seedUser(t, "assign", func(u *models.User) { u.IsActivated = false })
|
||||
forged, err := bouncer.HashPassword(4, "forged-password-1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
same := func(step string) {
|
||||
t.Helper()
|
||||
got := env.reload(t, user.ID)
|
||||
if got.IsActivated || got.ActivatedAt != nil || got.OrganisationID != nil || got.OrganisationRole != nil ||
|
||||
len(got.Permissions) != 0 || got.Password != user.Password || got.TokensValidAfter != nil || got.MustChangePassword {
|
||||
t.Fatalf("%s wrote a protected column: %+v", step, got)
|
||||
}
|
||||
}
|
||||
// Plain columns in a body are dropped; the rest of the body is saved.
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(user.ID, ""), token, map[string]any{
|
||||
"name": "Assigned", "email": user.Email, "is_activated": true, "activated_at": "2020-01-01T00:00:00Z",
|
||||
"organisation_id": organisation.ID, "organisation_role": "owner", "must_change_password": true,
|
||||
"Password": forged, "tokens_valid_after": "2020-01-01T00:00:00Z",
|
||||
})
|
||||
same("a body with plain protected columns")
|
||||
if got := env.reload(t, user.ID); got.Name == nil || *got.Name != "Assigned" {
|
||||
t.Fatalf("the allowed part of the body was not saved: %+v", got.Name)
|
||||
}
|
||||
// permissions is written by the editor's validated path only.
|
||||
for _, scalar := range []any{1, "all", true, []string{"blog.post"}} {
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, userPath(user.ID, ""), token,
|
||||
map[string]any{"name": "Assigned", "email": user.Email, "permissions": scalar})
|
||||
same(fmt.Sprintf("permissions sent as %v", scalar))
|
||||
}
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, userPath(user.ID, ""), token,
|
||||
map[string]any{"name": "Assigned", "email": user.Email, "permissions": map[string]int{"never.offered." + stamp: 1}})
|
||||
same("an unknown permission code")
|
||||
// A password without its confirmation is not a column write.
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, userPath(user.ID, ""), token,
|
||||
map[string]any{"name": "Assigned", "email": user.Email, "password": forged})
|
||||
same("a password without confirmation")
|
||||
// A create cannot switch the activation on either.
|
||||
created := env.expect(t, http.StatusCreated, http.MethodPost, adminAPI(adminUsersPath), token, map[string]any{
|
||||
"name": "Born", "email": "born-" + stamp + "@example.test", "password": "born-password-1", "password_confirmation": "born-password-1",
|
||||
"is_activated": true, "organisation_id": organisation.ID,
|
||||
})
|
||||
if got := env.reload(t, createdID(t, created)); got.IsActivated || got.OrganisationID != nil {
|
||||
t.Fatalf("a create wrote a protected column: %+v", got)
|
||||
}
|
||||
// The organisation is writable through its relation field only.
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(user.ID, ""), token,
|
||||
map[string]any{"name": "Assigned", "email": user.Email, "organisation": organisation.ID})
|
||||
if got := env.reload(t, user.ID); got.OrganisationID == nil || *got.OrganisationID != organisation.ID {
|
||||
t.Fatal("the organisation relation field did not write organisation_id")
|
||||
}
|
||||
})
|
||||
|
||||
// T-12.1-21: an admin password reset ends the user's sessions.
|
||||
t.Run("T-12.1-21", func(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
token := env.admin(t, permAccessUsers)
|
||||
user := env.seedUser(t, "reset", nil)
|
||||
status, old := env.userLogin(t, user.Email, "correct-horse")
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("login = %d", status)
|
||||
}
|
||||
env.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/fetch", old, nil)
|
||||
time.Sleep(1100 * time.Millisecond) // token timestamps have one-second resolution
|
||||
const next = "reset-password-2"
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(user.ID, ""), token,
|
||||
map[string]any{"name": "reset", "email": user.Email, "password": next, "password_confirmation": next})
|
||||
if got := env.reload(t, user.ID); got.TokensValidAfter == nil {
|
||||
t.Fatal("an admin password reset did not stamp tokens_valid_after")
|
||||
}
|
||||
if rec := env.call(t, http.MethodGet, "/_user/api/v1/fetch", old, nil); rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("a token issued before the reset still works: %d", rec.Code)
|
||||
}
|
||||
if status, _ := env.userLogin(t, user.Email, next); status != http.StatusOK {
|
||||
t.Fatalf("login with the new password = %d", status)
|
||||
}
|
||||
})
|
||||
|
||||
// T-12.1-22: exactly one invitation per created user and none on update.
|
||||
t.Run("T-12.1-22", func(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
token := env.admin(t, permAccessUsers)
|
||||
stamp := adminStamp()
|
||||
invited := "threat-invited-" + stamp + "@example.test"
|
||||
body := map[string]any{"name": "Invited", "email": invited, "password": "invite-password-1", "password_confirmation": "invite-password-1", "send_invite": true}
|
||||
id := createdID(t, env.expect(t, http.StatusCreated, http.MethodPost, adminAPI(adminUsersPath), token, body))
|
||||
if n := len(env.mails(invited)); n != 1 {
|
||||
t.Fatalf("invitations for one created user = %d, want 1", n)
|
||||
}
|
||||
// The same body again is a duplicate email: no second mail.
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodPost, adminAPI(adminUsersPath), token, body)
|
||||
// An update carrying the flag sends nothing.
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(id, ""), token, map[string]any{"name": "Invited", "email": invited, "send_invite": true})
|
||||
if n := len(env.mails(invited)); n != 1 {
|
||||
t.Fatalf("invitations after a failed create and an update = %d, want 1", n)
|
||||
}
|
||||
// No bulk or record action invites.
|
||||
for _, name := range []string{"invite", "send_invite"} {
|
||||
if rec := env.call(t, http.MethodPost, adminAPI(adminUsersPath+"/bulk/"+name), token, map[string]any{"ids": []uint{id}}); rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("bulk %s = %d, want 404", name, rec.Code)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// T-12.1-23: a permanent delete leaves no orphan and needs the permission.
|
||||
t.Run("T-12.1-23", func(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
token := env.admin(t, permAccessUsers)
|
||||
stranger := env.admin(t)
|
||||
group := env.seedGroup(t, "Purge "+adminStamp(), "purge-"+adminStamp())
|
||||
user := env.seedUser(t, "purge", nil)
|
||||
env.join(t, user, group)
|
||||
env.seedThrottle(t, user, "203.0.113.30", false, nil)
|
||||
key := env.seedAvatar(t, user)
|
||||
env.expect(t, http.StatusForbidden, http.MethodDelete, userPath(user.ID, ""), stranger, nil)
|
||||
if env.reload(t, user.ID) == nil || env.hangers(t, user) != (hangers{Throttle: 1, Groups: 1, Files: 1}) || !env.blobExists(t, key) {
|
||||
t.Fatalf("a refused delete changed the user: %+v", env.hangers(t, user))
|
||||
}
|
||||
env.expect(t, http.StatusOK, http.MethodDelete, userPath(user.ID, ""), token, nil)
|
||||
if env.reload(t, user.ID) != nil {
|
||||
t.Fatal("the user row survived the permanent delete")
|
||||
}
|
||||
if left := env.hangers(t, user); left != (hangers{}) {
|
||||
t.Fatalf("the permanent delete left user_throttle, users_groups or system_files rows: %+v", left)
|
||||
}
|
||||
if env.blobExists(t, key) {
|
||||
t.Fatal("the permanent delete left the avatar blob")
|
||||
}
|
||||
})
|
||||
|
||||
// T-12.1-24: the admin columns never reach a user API payload.
|
||||
t.Run("T-12.1-24", func(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
stamp := adminStamp()
|
||||
group := env.seedGroup(t, "Payload "+stamp, "payload-"+stamp)
|
||||
user := env.seedUser(t, "payload", func(u *models.User) { u.Permissions = models.PermissionSet{"payload." + stamp: 1} })
|
||||
env.join(t, user, group)
|
||||
if err := env.gdb.Exec(`UPDATE users SET last_seen = NOW() - INTERVAL '1 minute' WHERE id = ?`, user.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
userToken, payloads, raws := env.userPayloads(t, user.Email, "correct-horse")
|
||||
update := env.expect(t, http.StatusOK, http.MethodPost, "/_user/api/v1/update", userToken, map[string]any{"name": "Payload", "surname": "Shown", "email": user.Email})
|
||||
raws["update"] = update.Body.String()
|
||||
raws["refresh"] = env.expect(t, http.StatusOK, http.MethodPost, "/_user/api/v1/refresh", userToken, nil).Body.String()
|
||||
for name, raw := range raws {
|
||||
for _, key := range []string{"last_seen", "created_at", "updated_at", "LastSeen", "CreatedAt", "UpdatedAt", "Permissions", "payload." + stamp, "Payload " + stamp} {
|
||||
if strings.Contains(raw, key) {
|
||||
t.Fatalf("the %s body carries %s: %s", name, key, raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
for name, payload := range payloads {
|
||||
if value, ok := payload["permissions"]; !ok || value != nil {
|
||||
t.Fatalf("%s payload permissions = %v (present %v), want null", name, value, ok)
|
||||
}
|
||||
if groups, ok := payload["groups"].([]any); !ok || len(groups) != 0 {
|
||||
t.Fatalf("%s payload groups = %v, want an empty list", name, payload["groups"])
|
||||
}
|
||||
}
|
||||
// A user model marshalled as it is (another plugin's payload, a log
|
||||
// line) carries none of the admin columns either.
|
||||
loaded := env.reload(t, user.ID)
|
||||
if loaded == nil || loaded.LastSeen == nil || loaded.Permissions["payload."+stamp] != 1 || loaded.CreatedAt.IsZero() {
|
||||
t.Fatalf("the admin columns were not loaded: %+v", loaded)
|
||||
}
|
||||
marshalled, err := json.Marshal(loaded)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lower := strings.ToLower(string(marshalled))
|
||||
for _, key := range []string{"last_seen", "lastseen", "created_at", "createdat", "updated_at", "updatedat", "permissions", "payload." + stamp} {
|
||||
if strings.Contains(lower, key) {
|
||||
t.Fatalf("a marshalled user carries %s: %s", key, marshalled)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// T-12.1-25: a failing last_seen write never fails authentication.
|
||||
t.Run("T-12.1-25", func(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
user := env.seedUser(t, "seen", nil)
|
||||
drop := func() {
|
||||
env.gdb.Exec(`DROP TRIGGER IF EXISTS threat_refuse_last_seen ON users`)
|
||||
env.gdb.Exec(`DROP FUNCTION IF EXISTS threat_refuse_last_seen()`)
|
||||
}
|
||||
t.Cleanup(drop)
|
||||
for _, stmt := range []string{
|
||||
`CREATE OR REPLACE FUNCTION threat_refuse_last_seen() RETURNS trigger AS $$ BEGIN RAISE EXCEPTION 'last_seen cannot be written in this test'; END $$ LANGUAGE plpgsql`,
|
||||
`CREATE TRIGGER threat_refuse_last_seen BEFORE UPDATE OF last_seen ON users FOR EACH ROW EXECUTE FUNCTION threat_refuse_last_seen()`,
|
||||
} {
|
||||
if err := env.gdb.Exec(stmt).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := classes.TouchLastSeen(t.Context(), env.gdb, user.ID); err == nil {
|
||||
t.Fatal("the trigger does not refuse the write")
|
||||
}
|
||||
status, token := env.userLogin(t, user.Email, "correct-horse")
|
||||
if status != http.StatusOK || token == "" {
|
||||
t.Fatalf("login with a failing last_seen write = %d", status)
|
||||
}
|
||||
if rec := env.call(t, http.MethodPost, "/_user/api/v1/refresh", token, nil); rec.Code != http.StatusOK {
|
||||
t.Fatalf("refresh with a failing last_seen write = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := env.reload(t, user.ID); got.LastSeen != nil {
|
||||
t.Fatalf("last_seen was written although the write is refused: %v", got.LastSeen)
|
||||
}
|
||||
drop()
|
||||
// With the write allowed again, a login stamps it once.
|
||||
env.userLogin(t, user.Email, "correct-horse")
|
||||
first := env.reload(t, user.ID).LastSeen
|
||||
env.userLogin(t, user.Email, "correct-horse")
|
||||
if second := env.reload(t, user.ID).LastSeen; first == nil || second == nil || !second.Equal(*first) {
|
||||
t.Fatalf("last_seen is stamped more than once per five minutes: %v then %v", first, second)
|
||||
}
|
||||
})
|
||||
|
||||
// T-12.1-27: the permission resolver's override, exactly-1 and wildcard
|
||||
// rules.
|
||||
t.Run("T-12.1-27", func(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
stamp := adminStamp()
|
||||
store := func(group *models.UserGroup, permissions string) {
|
||||
t.Helper()
|
||||
if err := env.gdb.Exec(`UPDATE user_groups SET permissions = ? WHERE id = ?`, permissions, group.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
allow := env.seedGroup(t, "Allow "+stamp, "allow-"+stamp)
|
||||
deny := env.seedGroup(t, "Deny "+stamp, "deny-"+stamp)
|
||||
store(allow, `{"blog.post":1,"blog.edit":1,"shop.buy":-1,"wiki.*":1}`)
|
||||
store(deny, `{"blog.post":-1,"shop.buy":-1,"blog.zero":0}`)
|
||||
user := env.seedUser(t, "resolver", func(u *models.User) { u.Permissions = models.PermissionSet{"blog.edit": -1, "shop.buy": 1} })
|
||||
env.join(t, user, allow, deny)
|
||||
merged, err := classes.MergedPermissions(t.Context(), env.gdb, user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Among groups the higher value wins; the user's own value replaces it.
|
||||
want := map[string]int{"blog.post": 1, "blog.edit": -1, "shop.buy": 1, "wiki.*": 1, "blog.zero": 0}
|
||||
if !reflect.DeepEqual(merged, want) {
|
||||
t.Fatalf("merged = %v, want %v", merged, want)
|
||||
}
|
||||
for code, held := range map[string]bool{
|
||||
"blog.post": true, // a group's allow beats another group's deny
|
||||
"blog.edit": false, // a user-level deny overrides a group's allow
|
||||
"shop.buy": true, // a user-level allow overrides the groups' deny
|
||||
"blog.zero": false, // held only at exactly 1
|
||||
"blog.none": false,
|
||||
"wiki.page": true, // a stored trailing wildcard
|
||||
"wiki.": false,
|
||||
"blog.*": true, // an asked trailing wildcard
|
||||
"*.buy": true, // an asked leading wildcard
|
||||
"*.edit": false,
|
||||
"nothing.*": false,
|
||||
"*.nothing": false,
|
||||
"wikipedia": false,
|
||||
"shop.buy.x": false,
|
||||
} {
|
||||
if got := classes.HasPermission(merged, code); got != held {
|
||||
t.Fatalf("HasPermission(%q) = %v, want %v", code, got, held)
|
||||
}
|
||||
if got, err := classes.UserHasPermission(t.Context(), env.gdb, user.ID, code); err != nil || got != held {
|
||||
t.Fatalf("UserHasPermission(%q) = %v (%v), want %v", code, got, err, held)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// T-12.1-28 is T-12-18 revisited (the Phase 12 threat "a users_groups
|
||||
// write path makes a site admin"): the groups field of the user form is
|
||||
// the one writer of users_groups, and adding or removing a privileged
|
||||
// group through it needs golem15.users.manage_privileged_groups.
|
||||
t.Run("T-12.1-28", func(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
limited := env.admin(t, permAccessUsers)
|
||||
manager := env.admin(t, permAccessUsers, permManagePrivileged)
|
||||
stamp := adminStamp()
|
||||
adminGroup := env.seedGroup(t, "Admins "+stamp, "admin")
|
||||
ordinary := env.seedGroup(t, "Ordinary "+stamp, "ordinary-"+stamp)
|
||||
target := env.seedUser(t, "target", nil)
|
||||
env.join(t, target, ordinary)
|
||||
member := env.seedUser(t, "member", nil)
|
||||
env.join(t, member, adminGroup, ordinary)
|
||||
isAdmin := func(id uint) bool {
|
||||
t.Helper()
|
||||
held, err := classes.HasGroupCode(t.Context(), env.gdb, id, "admin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return held
|
||||
}
|
||||
put := func(token string, user *models.User, body map[string]any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
if _, ok := body["email"]; !ok {
|
||||
body["email"] = user.Email
|
||||
}
|
||||
return env.call(t, http.MethodPut, userPath(user.ID, ""), token, body)
|
||||
}
|
||||
refused := func(step string, rec *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
answer := adminDecode(t, rec)
|
||||
if rec.Code != http.StatusForbidden || answer.Error.Message != privilegedGroupForbidden || len(answer.Error.Details["groups"]) != 1 {
|
||||
t.Fatalf("%s = %d %s, want the privileged-group 403 on groups", step, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
create := func(token, email string, groups ...uint) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return env.call(t, http.MethodPost, adminAPI(adminUsersPath), token, map[string]any{
|
||||
"name": "Born", "email": email, "password": "born-password-1", "password_confirmation": "born-password-1", "groups": groups,
|
||||
})
|
||||
}
|
||||
|
||||
// Without the permission: add, remove and create are refused and the
|
||||
// pivot, the other fields of the body and the site-admin answer stay.
|
||||
before := env.pivotSnapshot(t)
|
||||
if isAdmin(target.ID) || !isAdmin(member.ID) {
|
||||
t.Fatal("seed: wrong site-admin state")
|
||||
}
|
||||
refused("add on update", put(limited, target, map[string]any{"name": "Promoted", "groups": []uint{ordinary.ID, adminGroup.ID}}))
|
||||
refused("add, crafted with other fields", put(limited, target, map[string]any{
|
||||
"name": "Promoted", "email": "promoted-" + stamp + "@example.test", "surname": "Crafted", "groups": []uint{adminGroup.ID},
|
||||
}))
|
||||
refused("remove on update", put(limited, member, map[string]any{"name": "Demoted", "groups": []uint{ordinary.ID}}))
|
||||
refused("remove by clearing", put(limited, member, map[string]any{"groups": []uint{}}))
|
||||
refusedEmail := "born-admin-" + stamp + "@example.test"
|
||||
refused("create with the group", create(limited, refusedEmail, adminGroup.ID, ordinary.ID))
|
||||
if got := env.pivotSnapshot(t); got != before {
|
||||
t.Fatalf("a refused request changed users_groups:\n%s\nwant\n%s", got, before)
|
||||
}
|
||||
for _, user := range []*models.User{target, member} {
|
||||
got := env.reload(t, user.ID)
|
||||
if got.Email != user.Email || !reflect.DeepEqual(got.Name, user.Name) || got.Surname != nil {
|
||||
t.Fatalf("a refused request saved another field of user %d: %+v", user.ID, got)
|
||||
}
|
||||
}
|
||||
var born int64
|
||||
if err := env.gdb.Raw(`SELECT COUNT(*) FROM users WHERE email = ?`, refusedEmail).Scan(&born).Error; err != nil || born != 0 {
|
||||
t.Fatalf("a refused create left %d users (%v)", born, err)
|
||||
}
|
||||
if isAdmin(target.ID) || !isAdmin(member.ID) {
|
||||
t.Fatal("a refused request moved the site-admin membership")
|
||||
}
|
||||
// Ordinary memberships still need only the users permission.
|
||||
if rec := put(limited, target, map[string]any{"name": "target", "groups": []uint{}}); rec.Code != http.StatusOK {
|
||||
t.Fatalf("an ordinary change = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// With the permission each of them succeeds.
|
||||
if rec := put(manager, target, map[string]any{"name": "target", "groups": []uint{adminGroup.ID}}); rec.Code != http.StatusOK || !isAdmin(target.ID) {
|
||||
t.Fatalf("manager add = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := put(manager, member, map[string]any{"name": "member", "groups": []uint{ordinary.ID}}); rec.Code != http.StatusOK || isAdmin(member.ID) {
|
||||
t.Fatalf("manager remove = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
rec := create(manager, "born-admin-ok-"+stamp+"@example.test", adminGroup.ID)
|
||||
if rec.Code != http.StatusCreated || !isAdmin(createdID(t, rec)) {
|
||||
t.Fatalf("manager create = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
// T-12.1-29: creating, re-coding to or from, and deleting a privileged
|
||||
// group code.
|
||||
t.Run("T-12.1-29", func(t *testing.T) {
|
||||
stamp := adminStamp()
|
||||
priv, second := "priv-"+stamp, "priv2-"+stamp
|
||||
env := privilegedList(t, "admin", priv, second)
|
||||
groupsOnly := env.admin(t, permAccessGroups)
|
||||
manager := env.admin(t, permAccessGroups, permManagePrivileged)
|
||||
privGroup := env.seedGroup(t, "Privileged "+stamp, priv)
|
||||
plainGroup := env.seedGroup(t, "Plain "+stamp, "plain-"+stamp)
|
||||
cases := []struct {
|
||||
name string
|
||||
run func(token string) *httptest.ResponseRecorder
|
||||
status int
|
||||
}{
|
||||
{"create with a privileged code", func(token string) *httptest.ResponseRecorder {
|
||||
return env.call(t, http.MethodPost, adminAPI(adminGroupsPath), token, map[string]any{"name": "Second " + stamp, "code": second})
|
||||
}, http.StatusCreated},
|
||||
{"re-code to a privileged code", func(token string) *httptest.ResponseRecorder {
|
||||
return env.call(t, http.MethodPut, groupPath(plainGroup.ID), token, map[string]any{"name": "Plain " + stamp, "code": "admin-like-" + stamp})
|
||||
}, http.StatusOK},
|
||||
{"re-code from a privileged code", func(token string) *httptest.ResponseRecorder {
|
||||
return env.call(t, http.MethodPut, groupPath(privGroup.ID), token, map[string]any{"name": "Privileged " + stamp, "code": "freed-" + stamp})
|
||||
}, http.StatusOK},
|
||||
{"delete a privileged group", func(token string) *httptest.ResponseRecorder {
|
||||
return env.call(t, http.MethodDelete, groupPath(privGroup.ID), token, nil)
|
||||
}, http.StatusOK},
|
||||
}
|
||||
// The second case re-codes an ordinary group to a privileged code.
|
||||
cases[1].run = func(token string) *httptest.ResponseRecorder {
|
||||
return env.call(t, http.MethodPut, groupPath(plainGroup.ID), token, map[string]any{"name": "Plain " + stamp, "code": second})
|
||||
}
|
||||
state := func() string {
|
||||
t.Helper()
|
||||
var rows []struct {
|
||||
ID uint
|
||||
Code *string
|
||||
}
|
||||
if err := env.gdb.Raw(`SELECT id, code FROM user_groups WHERE id IN (?, ?) OR code = ? ORDER BY id`, privGroup.ID, plainGroup.ID, second).Scan(&rows).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var b strings.Builder
|
||||
for _, row := range rows {
|
||||
code := "<nil>"
|
||||
if row.Code != nil {
|
||||
code = *row.Code
|
||||
}
|
||||
fmt.Fprintf(&b, "%d=%s;", row.ID, code)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
before := state()
|
||||
for _, tc := range cases {
|
||||
rec := tc.run(groupsOnly)
|
||||
answer := adminDecode(t, rec)
|
||||
if rec.Code != http.StatusForbidden || answer.Error.Message != privilegedGroupCodeForbidden || len(answer.Error.Details["code"]) != 1 {
|
||||
t.Fatalf("%s without the permission = %d %s", tc.name, rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := state(); got != before {
|
||||
t.Fatalf("%s without the permission changed the groups: %s, want %s", tc.name, got, before)
|
||||
}
|
||||
}
|
||||
// A name-only edit of a privileged group needs only the groups permission.
|
||||
if rec := env.call(t, http.MethodPut, groupPath(privGroup.ID), groupsOnly, map[string]any{"name": "Privileged renamed " + stamp, "code": priv}); rec.Code != http.StatusOK {
|
||||
t.Fatalf("a name-only edit of a privileged group = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
// With the permission: create, re-code from, then delete what is left.
|
||||
if rec := cases[0].run(manager); rec.Code != http.StatusCreated {
|
||||
t.Fatalf("manager %s = %d %s", cases[0].name, rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := cases[2].run(manager); rec.Code != http.StatusOK {
|
||||
t.Fatalf("manager %s = %d %s", cases[2].name, rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := env.call(t, http.MethodPut, groupPath(plainGroup.ID), manager, map[string]any{"name": "Plain " + stamp, "code": priv}); rec.Code != http.StatusOK {
|
||||
t.Fatalf("manager re-code to a privileged code = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := env.call(t, http.MethodDelete, groupPath(plainGroup.ID), manager, nil); rec.Code != http.StatusOK || env.group(t, plainGroup.ID) != nil {
|
||||
t.Fatalf("manager delete of a privileged group = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
// T-12.1-30: no second, unguarded writer of users_groups.
|
||||
t.Run("T-12.1-30", func(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
token := env.admin(t, permAccessUsers, permAccessGroups)
|
||||
stamp := adminStamp()
|
||||
adminGroup := env.seedGroup(t, "Admins "+stamp, "admin")
|
||||
ordinary := env.seedGroup(t, "Ordinary "+stamp, "ordinary-"+stamp)
|
||||
organisation := env.seedOrganisation(t, "Writers "+stamp)
|
||||
now := time.Now()
|
||||
member := env.seedUser(t, "writer-member", func(u *models.User) { u.IsActivated = false })
|
||||
plain := env.seedUser(t, "writer-plain", nil)
|
||||
env.join(t, member, adminGroup, ordinary)
|
||||
env.join(t, plain, ordinary)
|
||||
before := env.pivotSnapshot(t)
|
||||
same := func(step string) {
|
||||
t.Helper()
|
||||
if got := env.pivotSnapshot(t); got != before {
|
||||
t.Fatalf("%s changed users_groups:\n%s\nwant\n%s", step, got, before)
|
||||
}
|
||||
}
|
||||
for _, action := range []string{"activate", "deactivate", "restore", "ban", "unban"} {
|
||||
if rec := env.bulk(t, token, action, member, plain); rec.Code != http.StatusOK {
|
||||
t.Fatalf("bulk %s = %d %s", action, rec.Code, rec.Body.String())
|
||||
}
|
||||
same("bulk " + action)
|
||||
}
|
||||
// Bring each record action into its applicable state, then run it.
|
||||
if err := env.gdb.Exec(`UPDATE users SET is_activated = FALSE WHERE id = ?`, member.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
env.expect(t, http.StatusOK, http.MethodPost, userPath(member.ID, "/actions/activate"), token, map[string]any{})
|
||||
same("record activate")
|
||||
env.bulk(t, token, "ban", member)
|
||||
env.expect(t, http.StatusOK, http.MethodPost, userPath(member.ID, "/actions/unban"), token, map[string]any{})
|
||||
same("record unban")
|
||||
env.seedThrottle(t, plain, "203.0.113.40", false, &now)
|
||||
env.expect(t, http.StatusOK, http.MethodPost, userPath(plain.ID, "/actions/unsuspend"), token, map[string]any{})
|
||||
same("record unsuspend")
|
||||
// The organisation members manager writes organisation_id only.
|
||||
ids := map[string]any{"ids": []uint{member.ID, plain.ID}}
|
||||
env.expect(t, http.StatusOK, http.MethodPost, organisationPath(organisation.ID, "/relations/members/link"), token, ids)
|
||||
if got := env.reload(t, member.ID); got.OrganisationID == nil || *got.OrganisationID != organisation.ID {
|
||||
t.Fatal("the members link did not run")
|
||||
}
|
||||
same("organisation members link")
|
||||
env.expect(t, http.StatusOK, http.MethodPost, organisationPath(organisation.ID, "/relations/members/unlink"), token, ids)
|
||||
same("organisation members unlink")
|
||||
// A user update without the groups field and a group update.
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(plain.ID, ""), token, map[string]any{"name": "Renamed", "email": plain.Email})
|
||||
env.expect(t, http.StatusOK, http.MethodPut, groupPath(ordinary.ID), token, map[string]any{"name": "Ordinary renamed " + stamp, "code": "ordinary-" + stamp})
|
||||
same("updates without the groups field")
|
||||
|
||||
// No relation manager exists for groups on either controller, so the
|
||||
// relation routes (which do not ask the lock provider) cannot reach
|
||||
// the pivot.
|
||||
for _, path := range []string{
|
||||
userPath(member.ID, "/relations/groups"),
|
||||
userPath(member.ID, "/relations/Groups"),
|
||||
adminAPI(adminUsersPath + "/schema/relation/groups"),
|
||||
groupPath(ordinary.ID) + "/relations/users",
|
||||
adminAPI(adminGroupsPath + "/schema/relation/users"),
|
||||
organisationPath(organisation.ID, "/relations/groups"),
|
||||
} {
|
||||
if rec := env.call(t, http.MethodGet, path, token, nil); rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("GET %s = %d, want 404", path, rec.Code)
|
||||
}
|
||||
}
|
||||
for _, path := range []string{
|
||||
userPath(plain.ID, "/relations/groups/link"),
|
||||
groupPath(adminGroup.ID) + "/relations/users/link",
|
||||
organisationPath(organisation.ID, "/relations/groups/link"),
|
||||
} {
|
||||
body := map[string]any{"ids": []uint{adminGroup.ID, plain.ID}}
|
||||
if rec := env.call(t, http.MethodPost, path, token, body); rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("POST %s = %d, want 404", path, rec.Code)
|
||||
}
|
||||
}
|
||||
same("relation routes for groups")
|
||||
if held, err := classes.HasGroupCode(t.Context(), env.gdb, plain.ID, "admin"); err != nil || held {
|
||||
t.Fatalf("the plain user became a site admin: %v (%v)", held, err)
|
||||
}
|
||||
})
|
||||
|
||||
// T-12.1-31: the privileged list is read per request, compared
|
||||
// case-sensitively, and a group without a code is never privileged.
|
||||
t.Run("T-12.1-31", func(t *testing.T) {
|
||||
stamp := adminStamp()
|
||||
custom := "custom-" + stamp
|
||||
env := privilegedList(t, custom)
|
||||
limited := env.admin(t, permAccessUsers)
|
||||
adminGroup := env.seedGroup(t, "Admins "+stamp, "admin")
|
||||
customGroup := env.seedGroup(t, "Custom "+stamp, custom)
|
||||
upper := env.seedGroup(t, "Upper "+stamp, strings.ToUpper(custom))
|
||||
uncoded := env.seedGroup(t, "Uncoded "+stamp, "")
|
||||
options := env.groupOptions(t, limited, stamp)
|
||||
if len(options) != 4 || !options[customGroup.ID] || options[adminGroup.ID] || options[upper.ID] || options[uncoded.ID] {
|
||||
t.Fatalf("locked options under the overridden list = %v", options)
|
||||
}
|
||||
user := env.seedUser(t, "listed", nil)
|
||||
put := func(groups ...uint) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return env.call(t, http.MethodPut, userPath(user.ID, ""), limited, map[string]any{"name": "listed", "email": user.Email, "groups": groups})
|
||||
}
|
||||
// admin is no longer privileged; the case variant and the group
|
||||
// without a code never are.
|
||||
if rec := put(adminGroup.ID, upper.ID, uncoded.ID); rec.Code != http.StatusOK {
|
||||
t.Fatalf("ordinary groups under the overridden list = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := put(adminGroup.ID, customGroup.ID); rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("the overridden privileged group = %d %s, want 403", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := env.groupIDs(t, user.ID); !reflect.DeepEqual(got, sortedIDs(adminGroup, upper, uncoded)) {
|
||||
t.Fatalf("users_groups after the refusal = %v", got)
|
||||
}
|
||||
// The same request under the default list: read per request, so a new
|
||||
// environment with another list decides differently.
|
||||
byDefault := newAdminEnv(t)
|
||||
defaultLimited := byDefault.admin(t, permAccessUsers)
|
||||
rec := byDefault.call(t, http.MethodPut, userPath(user.ID, ""), defaultLimited, map[string]any{"name": "listed", "email": user.Email, "groups": []uint{adminGroup.ID, customGroup.ID, upper.ID, uncoded.ID}})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("adding the custom group under the default list = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
rec = byDefault.call(t, http.MethodPut, userPath(user.ID, ""), defaultLimited, map[string]any{"name": "listed", "email": user.Email, "groups": []uint{customGroup.ID}})
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("removing admin under the default list = %d %s, want 403", rec.Code, rec.Body.String())
|
||||
}
|
||||
// The class functions agree.
|
||||
codes := classes.PrivilegedGroupCodes(env.app.Config)
|
||||
if !reflect.DeepEqual(codes, []string{custom}) || classes.IsPrivilegedCode(codes, upper.Code) || classes.IsPrivilegedCode(codes, nil) || !classes.IsPrivilegedCode(codes, customGroup.Code) {
|
||||
t.Fatalf("privileged codes = %v", codes)
|
||||
}
|
||||
})
|
||||
|
||||
// T-12.1-34: group membership never reaches a user API payload.
|
||||
t.Run("T-12.1-34", func(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
stamp := adminStamp()
|
||||
group := env.seedGroup(t, "Hidden "+stamp, "admin")
|
||||
user := env.seedUser(t, "hidden", nil)
|
||||
env.join(t, user, group)
|
||||
_, payloads, raws := env.userPayloads(t, user.Email, "correct-horse")
|
||||
for name, payload := range payloads {
|
||||
if groups, ok := payload["groups"].([]any); !ok || len(groups) != 0 {
|
||||
t.Fatalf("%s payload groups = %v, want an empty list", name, payload["groups"])
|
||||
}
|
||||
if strings.Contains(raws[name], "Hidden "+stamp) || strings.Contains(raws[name], `"code":"admin"`) {
|
||||
t.Fatalf("the %s body names the group: %s", name, raws[name])
|
||||
}
|
||||
}
|
||||
loaded := models.User{}
|
||||
if err := env.gdb.Preload("Groups").First(&loaded, user.ID).Error; err != nil || len(loaded.Groups) != 1 {
|
||||
t.Fatalf("the relation did not load: %d groups (%v)", len(loaded.Groups), err)
|
||||
}
|
||||
marshalled, err := json.Marshal(loaded)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if lower := strings.ToLower(string(marshalled)); strings.Contains(lower, "groups") || strings.Contains(lower, "hidden "+stamp) {
|
||||
t.Fatalf("a marshalled user with loaded groups serializes them: %s", marshalled)
|
||||
}
|
||||
})
|
||||
|
||||
// T-12.1-38 (D-30): takeover of a privileged-group member's account by an
|
||||
// administrator who holds only golem15.users.access_users.
|
||||
t.Run("T-12.1-38", func(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
limited := env.admin(t, permAccessUsers)
|
||||
manager := env.admin(t, permAccessUsers, permManagePrivileged)
|
||||
stamp := adminStamp()
|
||||
adminGroup := env.seedGroup(t, "Admins "+stamp, "admin")
|
||||
member := env.seedUser(t, "takeover", nil)
|
||||
// The membership is given through the groups field, by an
|
||||
// administrator who may.
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(member.ID, ""), manager,
|
||||
map[string]any{"name": "takeover", "email": member.Email, "groups": []uint{adminGroup.ID}})
|
||||
original := env.reload(t, member.ID)
|
||||
const attempted = "takeover-password-1"
|
||||
takeover := "takeover-" + stamp + "@example.test"
|
||||
refused := func(step string, body map[string]any, fields ...string) {
|
||||
t.Helper()
|
||||
rec := env.call(t, http.MethodPut, userPath(member.ID, ""), limited, body)
|
||||
answer := adminDecode(t, rec)
|
||||
if rec.Code != http.StatusForbidden || answer.Error.Code != "forbidden" || answer.Error.Message != privilegedMemberForbidden {
|
||||
t.Fatalf("%s = %d %s, want the privileged-member 403", step, rec.Code, rec.Body.String())
|
||||
}
|
||||
if len(answer.Error.Details) != len(fields) {
|
||||
t.Fatalf("%s details = %v, want %v", step, answer.Error.Details, fields)
|
||||
}
|
||||
for _, field := range fields {
|
||||
if len(answer.Error.Details[field]) != 1 {
|
||||
t.Fatalf("%s has no detail on %s: %v", step, field, answer.Error.Details)
|
||||
}
|
||||
}
|
||||
got := env.reload(t, member.ID)
|
||||
if got.Email != original.Email || !reflect.DeepEqual(got.Name, original.Name) || got.Password != original.Password ||
|
||||
!reflect.DeepEqual(got.TokensValidAfter, original.TokensValidAfter) {
|
||||
t.Fatalf("%s changed the member: email=%q name=%v tokens_valid_after=%v", step, got.Email, got.Name, got.TokensValidAfter)
|
||||
}
|
||||
}
|
||||
refused("an email change", map[string]any{"name": "takeover", "email": takeover}, "email")
|
||||
refused("a password reset", map[string]any{"name": "takeover", "email": member.Email, "password": attempted, "password_confirmation": attempted}, "password")
|
||||
refused("email, password and name in one body", map[string]any{"name": "Taken over", "email": takeover, "password": attempted, "password_confirmation": attempted}, "email", "password")
|
||||
if status, _ := env.userLogin(t, member.Email, "correct-horse"); status != http.StatusOK {
|
||||
t.Fatalf("the old password after the refused requests = %d", status)
|
||||
}
|
||||
if status, _ := env.userLogin(t, member.Email, attempted); status != http.StatusUnauthorized {
|
||||
t.Fatalf("the attempted password signs in: %d", status)
|
||||
}
|
||||
if status, _ := env.userLogin(t, takeover, attempted); status == http.StatusOK {
|
||||
t.Fatal("the attempted email and password sign in")
|
||||
}
|
||||
// A name-only update is an ordinary update.
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(member.ID, ""), limited, map[string]any{"name": "Renamed", "email": member.Email})
|
||||
if got := env.reload(t, member.ID); got.Name == nil || *got.Name != "Renamed" {
|
||||
t.Fatal("a name-only update of a privileged member was not saved")
|
||||
}
|
||||
// With the permission both succeed.
|
||||
managed := "managed-" + stamp + "@example.test"
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(member.ID, ""), manager, map[string]any{"name": "Renamed", "email": managed})
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(member.ID, ""), manager,
|
||||
map[string]any{"name": "Renamed", "email": managed, "password": "managed-password-1", "password_confirmation": "managed-password-1"})
|
||||
if got := env.reload(t, member.ID); got.Email != managed || !bouncer.CheckPassword(got.Password, "managed-password-1") {
|
||||
t.Fatalf("the manager's changes were not saved: %+v", got)
|
||||
}
|
||||
// Once the membership is removed the limited administrator may change
|
||||
// the email.
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(member.ID, ""), manager, map[string]any{"name": "Renamed", "email": managed, "groups": []uint{}})
|
||||
released := "released-" + stamp + "@example.test"
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(member.ID, ""), limited, map[string]any{"name": "Renamed", "email": released})
|
||||
if got := env.reload(t, member.ID); got.Email != released {
|
||||
t.Fatalf("email after the membership was removed = %q", got.Email)
|
||||
}
|
||||
})
|
||||
|
||||
// T-12.1-39 (D-30): permanent delete of a privileged-group member.
|
||||
t.Run("T-12.1-39", func(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
limited := env.admin(t, permAccessUsers)
|
||||
manager := env.admin(t, permAccessUsers, permManagePrivileged)
|
||||
stamp := adminStamp()
|
||||
adminGroup := env.seedGroup(t, "Admins "+stamp, "admin")
|
||||
ordinary := env.seedGroup(t, "Ordinary "+stamp, "ordinary-"+stamp)
|
||||
loaded := func(label string, groups ...*models.UserGroup) (*models.User, string) {
|
||||
user := env.seedUser(t, label, nil)
|
||||
env.join(t, user, groups...)
|
||||
env.seedThrottle(t, user, "203.0.113.50", false, nil)
|
||||
return user, env.seedAvatar(t, user)
|
||||
}
|
||||
first, firstKey := loaded("del-first", ordinary)
|
||||
member, memberKey := loaded("del-member", adminGroup, ordinary)
|
||||
last, lastKey := loaded("del-last", ordinary)
|
||||
everyone := []*models.User{first, member, last}
|
||||
keys := []string{firstKey, memberKey, lastKey}
|
||||
before := map[uint]hangers{}
|
||||
for _, user := range everyone {
|
||||
before[user.ID] = env.hangers(t, user)
|
||||
}
|
||||
intact := func(step string) {
|
||||
t.Helper()
|
||||
for i, user := range everyone {
|
||||
if env.reload(t, user.ID) == nil {
|
||||
t.Fatalf("%s removed user %d", step, user.ID)
|
||||
}
|
||||
if got := env.hangers(t, user); got != before[user.ID] {
|
||||
t.Fatalf("%s removed rows of user %d: %+v, want %+v", step, user.ID, got, before[user.ID])
|
||||
}
|
||||
if !env.blobExists(t, keys[i]) {
|
||||
t.Fatalf("%s removed the avatar blob of user %d", step, user.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
refused := func(step string, rec *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
if rec.Code != http.StatusForbidden || adminDecode(t, rec).Error.Message != privilegedMemberDeleteForbidden {
|
||||
t.Fatalf("%s = %d %s, want the privileged-member delete 403", step, rec.Code, rec.Body.String())
|
||||
}
|
||||
intact(step)
|
||||
}
|
||||
refused("the form delete", env.call(t, http.MethodDelete, userPath(member.ID, ""), limited, nil))
|
||||
// The member sits between two ordinary users, so rows before it were
|
||||
// already deleted inside the transaction when it is refused.
|
||||
refused("the bulk delete", env.bulk(t, limited, "delete", first, member, last))
|
||||
// An ordinary user is deleted by the limited administrator.
|
||||
spare, spareKey := loaded("del-spare", ordinary)
|
||||
env.expect(t, http.StatusOK, http.MethodDelete, userPath(spare.ID, ""), limited, nil)
|
||||
if env.reload(t, spare.ID) != nil || env.blobExists(t, spareKey) {
|
||||
t.Fatal("an ordinary user was not deleted")
|
||||
}
|
||||
// With the permission both succeed.
|
||||
if rec := env.bulk(t, manager, "delete", first, member); rec.Code != http.StatusOK {
|
||||
t.Fatalf("manager bulk delete = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
other, _ := loaded("del-other", adminGroup)
|
||||
env.expect(t, http.StatusOK, http.MethodDelete, userPath(other.ID, ""), manager, nil)
|
||||
for _, user := range []*models.User{first, member, other} {
|
||||
if env.reload(t, user.ID) != nil || env.hangers(t, user) != (hangers{}) {
|
||||
t.Fatalf("the manager's delete left user %d: %+v", user.ID, env.hangers(t, user))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
31
plugin.go
31
plugin.go
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"embed"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
@@ -18,6 +19,7 @@ import (
|
||||
"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"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
@@ -103,10 +105,13 @@ func (p *Plugin) Boot(app *backpack.App) error {
|
||||
return err
|
||||
}
|
||||
trusted := surf.TrustedProxies(app.Config)
|
||||
return reg.Register(p.ID(), "api_token", &usermiddleware.APITokenGuard{
|
||||
if err := reg.Register(p.ID(), "api_token", &usermiddleware.APITokenGuard{
|
||||
App: app, Prefix: prefix,
|
||||
ClientIP: func(r *http.Request) string { return surf.ClientIP(r, trusted) },
|
||||
})
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return classes.RegisterUserAuthorizer(app)
|
||||
}
|
||||
|
||||
func (p *Plugin) startBlacklistSweep(bl bouncer.BlacklistStore) {
|
||||
@@ -189,6 +194,8 @@ func (p *Plugin) MailTemplates() []string {
|
||||
"golem15.user::mail.restore-en",
|
||||
"golem15.user::mail.reactivate",
|
||||
"golem15.user::mail.reactivate-en",
|
||||
"golem15.user::mail.invite",
|
||||
"golem15.user::mail.invite-en",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,7 +206,25 @@ func (p *Plugin) MailLayouts() map[string]string {
|
||||
}
|
||||
|
||||
func (p *Plugin) Commands() []bonfire.Command {
|
||||
return append([]bonfire.Command{console.RequirePasswordChange(p.app)}, console.APITokenCommands(p.app)...)
|
||||
return append([]bonfire.Command{console.RequirePasswordChange(p.withDB), console.BackfillHandles(p.app)}, console.APITokenCommands(p.app, p.withDB)...)
|
||||
}
|
||||
|
||||
// withDB runs fn with the application's database: the one the serve command
|
||||
// published, or, when a console command runs, one opened from the config for
|
||||
// the duration of fn.
|
||||
func (p *Plugin) withDB(ctx context.Context, fn func(*gorm.DB) error) error {
|
||||
if p == nil || p.app == nil {
|
||||
return fmt.Errorf("golem15.user: app is nil")
|
||||
}
|
||||
if gdb, ok := p.app.Lookup[*gorm.DB](); ok && gdb != nil {
|
||||
return fn(gdb)
|
||||
}
|
||||
sqlDB, gdb, err := lagoon.OpenFromApp(ctx, p.app)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer sqlDB.Close()
|
||||
return fn(gdb)
|
||||
}
|
||||
|
||||
func (p *Plugin) Migrations() []*gormigrate.Migration { return updates.All() }
|
||||
|
||||
30
routes.go
30
routes.go
@@ -1,18 +1,25 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/controllers"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
)
|
||||
|
||||
func (p *Plugin) Routes(r pact.Router) error {
|
||||
guard, err := p.turnstileGuard()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.Group("/_user/api/v1", surf.Use("throttle:user-api"), func(g pact.Router) {
|
||||
g.Post("/login", controllers.Login(p.app))
|
||||
g.Post("/login", controllers.Login(p.app), guard...)
|
||||
g.Post("/logout", controllers.Logout(p.app))
|
||||
g.Get("/fetch", controllers.Fetch(p.app))
|
||||
g.Post("/refresh", controllers.Refresh(p.app))
|
||||
g.Post("/register", controllers.Register(p.app))
|
||||
g.Post("/register", controllers.Register(p.app), guard...)
|
||||
g.Get("/oauth-providers", controllers.OAuthProviders(p.app))
|
||||
g.Post("/forgot-password", controllers.ForgotPassword(p.app))
|
||||
g.Post("/reset-password", controllers.ResetPassword(p.app))
|
||||
@@ -30,3 +37,22 @@ func (p *Plugin) Routes(r pact.Router) error {
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// turnstileGuard returns the middleware that golem15.user.turnstile adds to
|
||||
// POST /login and /register. The key is opt-in: empty (the default) adds
|
||||
// nothing, "open" and "closed" select the framework's turnstile:{mode}
|
||||
// middleware (summercms v0.3.0 and later), and any other value is refused so
|
||||
// a typo cannot silently leave the forms unprotected.
|
||||
func (p *Plugin) turnstileGuard() ([]string, error) {
|
||||
if p.app == nil || p.app.Config == nil {
|
||||
return nil, nil
|
||||
}
|
||||
switch mode := strings.TrimSpace(p.app.Config.String("golem15.user.turnstile")); mode {
|
||||
case "":
|
||||
return nil, nil
|
||||
case "open", "closed":
|
||||
return []string{"turnstile:" + mode}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("golem15.user: golem15.user.turnstile must be empty, open or closed, got %q", mode)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,16 +34,21 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
sessionSecret = "summercms-test-only-hs256-secret"
|
||||
invalidLoginBody = `{"error":true,"message":"Invalid email or password"}`
|
||||
prvHash = "a867434cbc213adfbe78a02bed7082a6bd99c883"
|
||||
sessionSecret = "summercms-test-only-hs256-secret"
|
||||
// adminHarnessSecret signs backend tokens in tests that mount the admin API.
|
||||
adminHarnessSecret = "summercms-test-only-admin-hs256-secret"
|
||||
invalidLoginBody = `{"error":true,"message":"Invalid email or password"}`
|
||||
prvHash = "a867434cbc213adfbe78a02bed7082a6bd99c883"
|
||||
)
|
||||
|
||||
var (
|
||||
sessionOnce sync.Once
|
||||
sessionGDB *gorm.DB
|
||||
sessionSQL *sql.DB
|
||||
sessionErr error
|
||||
// sessionDSN is the container's connection string; the admin harness
|
||||
// opens its own database in the same container with it.
|
||||
sessionDSN string
|
||||
sessionErr error
|
||||
)
|
||||
|
||||
func TestLogin(t *testing.T) {
|
||||
@@ -507,6 +512,9 @@ func sessionConfig(t *testing.T) *compass.Config {
|
||||
Environ: []string{
|
||||
"SUMMER_ENV=development",
|
||||
"SUMMER_GOLEM15__USER__JWT__SECRET=" + sessionSecret,
|
||||
// The plugin registers admin controllers, so assembling its
|
||||
// routes mounts the admin API, which needs its own secret.
|
||||
"SUMMER_ADMIN__JWT__SECRET=" + adminHarnessSecret,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
@@ -538,6 +546,7 @@ func sessionDB(t *testing.T) (*gorm.DB, *sql.DB) {
|
||||
sessionErr = err
|
||||
return
|
||||
}
|
||||
sessionDSN = dsn
|
||||
sqlDB, err := sql.Open("pgx", dsn)
|
||||
if err != nil {
|
||||
sessionErr = err
|
||||
|
||||
297
session_user_test.go
Normal file
297
session_user_test.go
Normal file
@@ -0,0 +1,297 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/controllers"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// failingBlacklist fails every call, as an unreachable blacklist table does.
|
||||
type failingBlacklist struct{}
|
||||
|
||||
var errBlacklistDown = errors.New("blacklist down")
|
||||
|
||||
func (failingBlacklist) Add(context.Context, string, time.Time, time.Time) error {
|
||||
return errBlacklistDown
|
||||
}
|
||||
func (failingBlacklist) IsBlacklisted(context.Context, string) (bool, error) {
|
||||
return false, errBlacklistDown
|
||||
}
|
||||
func (failingBlacklist) Sweep(context.Context, time.Time) error { return errBlacklistDown }
|
||||
|
||||
// sessionUserApp is an application without a database: the plugin's JWT secret
|
||||
// and, when cookie is set, the 19.3 cookie settings.
|
||||
func sessionUserApp(t *testing.T, environ ...string) *backpack.App {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: session-user\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)
|
||||
}
|
||||
|
||||
// sessionRequest is a GET carrying the session token the way kind says:
|
||||
// "bearer", "token" (cookie) or "auth_token" (cookie).
|
||||
func sessionRequest(kind, token string) *http.Request {
|
||||
r := httptest.NewRequest(http.MethodGet, "/oauth/authorize", nil)
|
||||
switch kind {
|
||||
case "bearer":
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
case "token", "auth_token":
|
||||
r.AddCookie(&http.Cookie{Name: kind, Value: token})
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// TestRequestUser pins classes.RequestUser (D-05): the session JWT from the
|
||||
// bearer header, then the token and auth_token cookies, checked like the
|
||||
// plugin's jwt guard; every rejected token is anonymous and only an
|
||||
// infrastructure failure is an error.
|
||||
func TestRequestUser(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
ctx := t.Context()
|
||||
issue := func(u *models.User) string {
|
||||
t.Helper()
|
||||
token, err := controllers.IssueToken(env.app, u, httptest.NewRequest(http.MethodPost, "https://app.example.test/login", nil))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
expectUser := func(name string, r *http.Request, want *models.User) {
|
||||
t.Helper()
|
||||
got, err := classes.RequestUser(ctx, env.app, r)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: error %v", name, err)
|
||||
}
|
||||
switch {
|
||||
case want == nil && got != nil:
|
||||
t.Fatalf("%s: signed in user %d, want anonymous", name, got.ID)
|
||||
case want != nil && (got == nil || got.ID != want.ID || got.Email != want.Email):
|
||||
t.Fatalf("%s: user %+v, want %d", name, got, want.ID)
|
||||
}
|
||||
}
|
||||
|
||||
ada, bea := env.seedUser(t, "ada", nil), env.seedUser(t, "bea", nil)
|
||||
adaToken, beaToken := issue(ada), issue(bea)
|
||||
|
||||
expectUser("bearer", sessionRequest("bearer", adaToken), ada)
|
||||
expectUser("token cookie", sessionRequest("token", adaToken), ada)
|
||||
expectUser("auth_token cookie", sessionRequest("auth_token", adaToken), ada)
|
||||
both := sessionRequest("bearer", adaToken)
|
||||
both.AddCookie(&http.Cookie{Name: "token", Value: beaToken})
|
||||
expectUser("bearer before cookie", both, ada)
|
||||
cookies := sessionRequest("token", beaToken)
|
||||
cookies.AddCookie(&http.Cookie{Name: "auth_token", Value: adaToken})
|
||||
expectUser("token before auth_token", cookies, bea)
|
||||
blankBearer := sessionRequest("token", beaToken)
|
||||
blankBearer.Header.Set("Authorization", "Bearer ")
|
||||
expectUser("blank bearer falls back to the cookie", blankBearer, bea)
|
||||
|
||||
expectUser("anonymous", httptest.NewRequest(http.MethodGet, "/", nil), nil)
|
||||
if u, err := classes.RequestUser(ctx, env.app, nil); u != nil || err != nil {
|
||||
t.Fatalf("nil request: %v %v", u, err)
|
||||
}
|
||||
|
||||
sub := strconv.FormatUint(uint64(ada.ID), 10)
|
||||
expired, _, _ := bouncer.Mint(sessionSecret, sub, "https://app.example.test", -time.Minute)
|
||||
expectUser("expired", sessionRequest("bearer", expired), nil)
|
||||
forged, _, _ := bouncer.Mint("another-secret-of-the-right-length-xyz1", sub, "https://app.example.test", time.Hour)
|
||||
expectUser("another secret", sessionRequest("bearer", forged), nil)
|
||||
expectUser("garbage", sessionRequest("bearer", "not-a-jwt"), nil)
|
||||
for _, s := range []string{"abc", "0", "-1"} {
|
||||
odd, _, _ := bouncer.Mint(sessionSecret, s, "https://app.example.test", time.Hour)
|
||||
expectUser("sub "+s, sessionRequest("bearer", odd), nil)
|
||||
}
|
||||
gone, _, _ := bouncer.Mint(sessionSecret, strconv.FormatUint(uint64(bea.ID+1_000_000), 10), "https://app.example.test", time.Hour)
|
||||
expectUser("unknown user", sessionRequest("bearer", gone), nil)
|
||||
|
||||
// Blacklisted: the jti EndRequestSession revoked signs nobody in.
|
||||
carl := env.seedUser(t, "carl", nil)
|
||||
carlToken := issue(carl)
|
||||
expectUser("carl before sign-out", sessionRequest("bearer", carlToken), carl)
|
||||
if err := classes.EndRequestSession(ctx, env.app, httptest.NewRecorder(), sessionRequest("bearer", carlToken)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expectUser("blacklisted", sessionRequest("bearer", carlToken), nil)
|
||||
|
||||
// tokens_valid_after after the token's iat (a password change).
|
||||
dora := env.seedUser(t, "dora", nil)
|
||||
doraToken := issue(dora)
|
||||
cutoff := time.Now().Add(time.Minute)
|
||||
if err := env.gdb.Model(&models.User{}).Where("id = ?", dora.ID).Update("tokens_valid_after", cutoff).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expectUser("tokens_valid_after", sessionRequest("bearer", doraToken), nil)
|
||||
|
||||
// A soft-deleted (deactivated) user.
|
||||
eve := env.seedUser(t, "eve", nil)
|
||||
eveToken := issue(eve)
|
||||
if err := env.gdb.Model(&models.User{}).Where("id = ?", eve.ID).Update("deleted_at", time.Now()).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expectUser("soft-deleted", sessionRequest("bearer", eveToken), nil)
|
||||
|
||||
// Only infrastructure failures are errors.
|
||||
noDB := sessionUserApp(t, "SUMMER_GOLEM15__USER__JWT__SECRET="+sessionSecret)
|
||||
if u, err := classes.RequestUser(ctx, noDB, sessionRequest("bearer", adaToken)); u != nil || err == nil {
|
||||
t.Fatalf("no database handle: %v %v", u, err)
|
||||
}
|
||||
noSecret := sessionUserApp(t)
|
||||
if u, err := classes.RequestUser(ctx, noSecret, sessionRequest("bearer", adaToken)); u != nil || err == nil {
|
||||
t.Fatalf("no JWT secret: %v %v", u, err)
|
||||
}
|
||||
if u, err := classes.RequestUser(ctx, noSecret, httptest.NewRequest(http.MethodGet, "/", nil)); u != nil || err != nil {
|
||||
t.Fatalf("anonymous without a secret: %v %v", u, err)
|
||||
}
|
||||
broken := sessionUserApp(t, "SUMMER_GOLEM15__USER__JWT__SECRET="+sessionSecret)
|
||||
if err := broken.Publish(env.gdb); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := broken.Publish[bouncer.BlacklistStore](failingBlacklist{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u, err := classes.RequestUser(ctx, broken, sessionRequest("bearer", adaToken)); u != nil || !errors.Is(err, errBlacklistDown) {
|
||||
t.Fatalf("failing blacklist: %v %v", u, err)
|
||||
}
|
||||
canceled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
if u, err := classes.RequestUser(canceled, env.app, sessionRequest("bearer", adaToken)); u != nil || err == nil {
|
||||
t.Fatalf("failing query: %v %v", u, err)
|
||||
}
|
||||
// Without a published blacklist the token is accepted on its own checks.
|
||||
plain := sessionUserApp(t, "SUMMER_GOLEM15__USER__JWT__SECRET="+sessionSecret)
|
||||
if err := plain.Publish[*gorm.DB](env.gdb); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u, err := classes.RequestUser(ctx, plain, sessionRequest("bearer", adaToken)); err != nil || u == nil || u.ID != ada.ID {
|
||||
t.Fatalf("without a blacklist: %v %v", u, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEndRequestSession pins classes.EndRequestSession (D-04, D-05) without
|
||||
// a database: the session's jti is blacklisted until the token expires, the
|
||||
// forget cookie carries the configured Domain and Path, a request without a
|
||||
// token still forgets the cookie, and a blacklist failure never fails the
|
||||
// call.
|
||||
func TestEndRequestSession(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
app := sessionUserApp(t,
|
||||
"SUMMER_GOLEM15__USER__JWT__SECRET="+sessionSecret,
|
||||
"SUMMER_AUTH__COOKIE__DOMAIN=app.example.test",
|
||||
"SUMMER_AUTH__COOKIE__PATH=/app",
|
||||
)
|
||||
bl := bouncer.NewMemoryBlacklist()
|
||||
if err := app.Publish[bouncer.BlacklistStore](bl); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
forgot := func(t *testing.T, rec *httptest.ResponseRecorder, domain, path string) {
|
||||
t.Helper()
|
||||
res := rec.Result()
|
||||
var found *http.Cookie
|
||||
for _, c := range res.Cookies() {
|
||||
if c.Name == bouncer.DefaultCookieName {
|
||||
found = c
|
||||
}
|
||||
}
|
||||
if found == nil || found.Value != "" || found.MaxAge >= 0 || found.Domain != domain || found.Path != path {
|
||||
t.Fatalf("forget cookie = %+v (Set-Cookie %q)", found, res.Header.Values("Set-Cookie"))
|
||||
}
|
||||
if rec.Body.Len() != 0 {
|
||||
t.Fatalf("EndRequestSession wrote a body: %q", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
for _, kind := range []string{"bearer", "token", "auth_token"} {
|
||||
token, jti, err := bouncer.Mint(sessionSecret, "7", "https://app.example.test", time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
if err := classes.EndRequestSession(ctx, app, rec, sessionRequest(kind, token)); err != nil {
|
||||
t.Fatalf("%s: %v", kind, err)
|
||||
}
|
||||
forgot(t, rec, "app.example.test", "/app")
|
||||
if blocked, _ := bl.IsBlacklisted(ctx, jti); !blocked {
|
||||
t.Fatalf("%s: the jti is not blacklisted", kind)
|
||||
}
|
||||
// Until the token's expiry, and no longer.
|
||||
_ = bl.Sweep(ctx, time.Now())
|
||||
if blocked, _ := bl.IsBlacklisted(ctx, jti); !blocked {
|
||||
t.Fatalf("%s: the entry left before the token expired", kind)
|
||||
}
|
||||
_ = bl.Sweep(ctx, time.Now().Add(time.Hour+time.Minute))
|
||||
if blocked, _ := bl.IsBlacklisted(ctx, jti); blocked {
|
||||
t.Fatalf("%s: the entry outlived the token", kind)
|
||||
}
|
||||
}
|
||||
|
||||
// No token, a token of another secret, garbage: the cookie is forgotten
|
||||
// and nothing is blacklisted.
|
||||
foreign, foreignJTI, _ := bouncer.Mint("another-secret-of-the-right-length-xyz1", "7", "https://app.example.test", time.Hour)
|
||||
for name, r := range map[string]*http.Request{
|
||||
"no token": httptest.NewRequest(http.MethodPost, "/", nil),
|
||||
"another secret": sessionRequest("bearer", foreign),
|
||||
"garbage": sessionRequest("token", "not-a-jwt"),
|
||||
} {
|
||||
rec := httptest.NewRecorder()
|
||||
if err := classes.EndRequestSession(ctx, app, rec, r); err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
forgot(t, rec, "app.example.test", "/app")
|
||||
}
|
||||
if blocked, _ := bl.IsBlacklisted(ctx, foreignJTI); blocked {
|
||||
t.Fatal("a token of another secret was blacklisted")
|
||||
}
|
||||
|
||||
// A blacklist failure is logged, never returned; the cookie still goes.
|
||||
down := sessionUserApp(t, "SUMMER_GOLEM15__USER__JWT__SECRET="+sessionSecret)
|
||||
if err := down.Publish[bouncer.BlacklistStore](failingBlacklist{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, _, _ := bouncer.Mint(sessionSecret, "7", "https://app.example.test", time.Hour)
|
||||
rec := httptest.NewRecorder()
|
||||
if err := classes.EndRequestSession(ctx, down, rec, sessionRequest("bearer", token)); err != nil {
|
||||
t.Fatalf("failing blacklist: %v", err)
|
||||
}
|
||||
forgot(t, rec, "", "/")
|
||||
|
||||
// Without an app or a writer it does what it can.
|
||||
rec = httptest.NewRecorder()
|
||||
if err := classes.EndRequestSession(ctx, nil, rec, sessionRequest("bearer", token)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
forgot(t, rec, "", "/")
|
||||
if err := classes.EndRequestSession(ctx, app, nil, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// An invalid cookie configuration falls back to the defaults.
|
||||
badCookie := sessionUserApp(t, "SUMMER_GOLEM15__USER__JWT__SECRET="+sessionSecret, "SUMMER_AUTH__COOKIE__PATH=relative")
|
||||
rec = httptest.NewRecorder()
|
||||
if err := classes.EndRequestSession(ctx, badCookie, rec, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
forgot(t, rec, "", "/")
|
||||
if !strings.Contains(strings.Join(rec.Result().Header.Values("Set-Cookie"), ";"), "token=") {
|
||||
t.Fatal("no Set-Cookie for the token cookie")
|
||||
}
|
||||
}
|
||||
86
social_hooks_smoke_test.go
Normal file
86
social_hooks_smoke_test.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/controllers"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/postcard"
|
||||
)
|
||||
|
||||
// TestSocialHooksSmoke drives the helpers a social-login plugin calls: a
|
||||
// password-less registration and FinishLogin on a soft-deleted account.
|
||||
func TestSocialHooksSmoke(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Postgres-backed; skipped under -short")
|
||||
}
|
||||
app, gdb := sessionApp(t, "0s")
|
||||
ctx := t.Context()
|
||||
|
||||
fields := map[string]any{
|
||||
"email": "social-hooks@example.test",
|
||||
"password": "random-password-never-shown",
|
||||
"password_confirmation": "random-password-never-shown",
|
||||
}
|
||||
user, errs, err := controllers.RegisterUser(ctx, app, gdb, fields, controllers.RegisterOptions{
|
||||
Activate: true, IP: "203.0.113.7", PasswordLess: true,
|
||||
})
|
||||
if err != nil || len(errs) > 0 {
|
||||
t.Fatalf("RegisterUser: %v %v", err, errs)
|
||||
}
|
||||
var stored models.User
|
||||
if err := gdb.First(&stored, user.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored.HasSelfSetPassword {
|
||||
t.Fatal("a password-less registration stored has_self_set_password=true")
|
||||
}
|
||||
if !stored.IsActivated {
|
||||
t.Fatal("the registration was not activated")
|
||||
}
|
||||
if stored.Handle == nil || *stored.Handle == "" {
|
||||
t.Fatal("the registration got no handle")
|
||||
}
|
||||
|
||||
// FinishLogin restores a soft-deleted account, records the IP, stamps
|
||||
// last_seen and sends exactly one reactivate mail.
|
||||
loc := "en"
|
||||
soft := &models.User{Email: "social-soft@example.test", Password: "x", PreferredLocale: &loc}
|
||||
if err := gdb.Create(soft).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := gdb.Model(soft).Update("deleted_at", time.Now()).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var trashed models.User
|
||||
if err := gdb.Unscoped().First(&trashed, soft.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !trashed.DeletedAt.Valid {
|
||||
t.Fatal("setup: the user is not soft-deleted")
|
||||
}
|
||||
mail := &captureMail{}
|
||||
if err := app.Publish[postcard.Mailer](mail); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := controllers.FinishLogin(ctx, app, gdb, &trashed, "198.51.100.4"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var after models.User
|
||||
if err := gdb.Unscoped().First(&after, soft.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after.DeletedAt.Valid {
|
||||
t.Fatal("FinishLogin did not restore the account")
|
||||
}
|
||||
if after.LastIPAddress == nil || *after.LastIPAddress != "198.51.100.4" {
|
||||
t.Fatalf("last_ip_address = %v", after.LastIPAddress)
|
||||
}
|
||||
if after.LastSeen == nil {
|
||||
t.Fatal("FinishLogin did not stamp last_seen")
|
||||
}
|
||||
if len(mail.got) != 1 || mail.got[0] != "golem15.user::mail.reactivate-en" {
|
||||
t.Fatalf("mails = %#v", mail.got)
|
||||
}
|
||||
}
|
||||
158
turnstile_routes_test.go
Normal file
158
turnstile_routes_test.go
Normal file
@@ -0,0 +1,158 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
// recordedRoute is one registration seen by recordingRouter.
|
||||
type recordedRoute struct {
|
||||
method string
|
||||
path string
|
||||
middleware []string
|
||||
}
|
||||
|
||||
// recordingRouter is a pact.Router that records each registration with its
|
||||
// full path and the group plus route middleware. The plugin requires a
|
||||
// framework whose surf does not know the turnstile:* names, so the smoke test
|
||||
// checks the declared middleware instead of assembling a real router.
|
||||
type recordingRouter struct {
|
||||
prefix string
|
||||
middleware []string
|
||||
routes *[]recordedRoute
|
||||
}
|
||||
|
||||
func newRecordingRouter() *recordingRouter {
|
||||
return &recordingRouter{routes: &[]recordedRoute{}}
|
||||
}
|
||||
|
||||
func (r *recordingRouter) Group(prefix string, middleware []string, fn func(pact.Router)) {
|
||||
fn(&recordingRouter{
|
||||
prefix: r.prefix + prefix,
|
||||
middleware: append(append([]string{}, r.middleware...), middleware...),
|
||||
routes: r.routes,
|
||||
})
|
||||
}
|
||||
|
||||
func (r *recordingRouter) GroupRaw(prefix string, middleware []string, fn func(pact.Router)) {
|
||||
r.Group(prefix, middleware, fn)
|
||||
}
|
||||
|
||||
func (r *recordingRouter) add(method, path string, middleware []string) {
|
||||
*r.routes = append(*r.routes, recordedRoute{
|
||||
method: method,
|
||||
path: r.prefix + path,
|
||||
middleware: append(append([]string{}, r.middleware...), middleware...),
|
||||
})
|
||||
}
|
||||
|
||||
func (r *recordingRouter) Get(path string, _ http.HandlerFunc, mw ...string) {
|
||||
r.add(http.MethodGet, path, mw)
|
||||
}
|
||||
func (r *recordingRouter) Post(path string, _ http.HandlerFunc, mw ...string) {
|
||||
r.add(http.MethodPost, path, mw)
|
||||
}
|
||||
func (r *recordingRouter) Put(path string, _ http.HandlerFunc, mw ...string) {
|
||||
r.add(http.MethodPut, path, mw)
|
||||
}
|
||||
func (r *recordingRouter) Patch(path string, _ http.HandlerFunc, mw ...string) {
|
||||
r.add(http.MethodPatch, path, mw)
|
||||
}
|
||||
func (r *recordingRouter) Delete(path string, _ http.HandlerFunc, mw ...string) {
|
||||
r.add(http.MethodDelete, path, mw)
|
||||
}
|
||||
func (r *recordingRouter) Where(string, string) {}
|
||||
func (r *recordingRouter) WhereIn(string, ...string) {}
|
||||
|
||||
func recordUserRoutes(t *testing.T, mode string) ([]recordedRoute, error) {
|
||||
t.Helper()
|
||||
app := bareApp(t)
|
||||
if err := app.Config.Set("golem15.user.turnstile", mode); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := newRecordingRouter()
|
||||
err := (&Plugin{app: app}).Routes(rec)
|
||||
return *rec.routes, err
|
||||
}
|
||||
|
||||
func turnstileOf(route recordedRoute) []string {
|
||||
var out []string
|
||||
for _, name := range route.middleware {
|
||||
if strings.HasPrefix(name, "turnstile") {
|
||||
out = append(out, name)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TestTurnstileRoutes pins golem15.user.turnstile (D-07): empty adds no
|
||||
// middleware; open and closed (surrounding spaces trimmed) append
|
||||
// turnstile:{mode} to POST /_user/api/v1/login and /register only, leaving
|
||||
// every other route's middleware as it is with the key empty; any other
|
||||
// value fails Routes naming the key.
|
||||
func TestTurnstileRoutes(t *testing.T) {
|
||||
off, err := recordUserRoutes(t, "")
|
||||
if err != nil {
|
||||
t.Fatalf("empty turnstile: Routes error %v", err)
|
||||
}
|
||||
if len(off) == 0 {
|
||||
t.Fatal("no routes recorded")
|
||||
}
|
||||
guarded := map[string]bool{
|
||||
http.MethodPost + " /_user/api/v1/login": true,
|
||||
http.MethodPost + " /_user/api/v1/register": true,
|
||||
}
|
||||
seen := 0
|
||||
for _, route := range off {
|
||||
if got := turnstileOf(route); len(got) > 0 {
|
||||
t.Errorf("empty turnstile: %s %s carries %v", route.method, route.path, got)
|
||||
}
|
||||
if guarded[route.method+" "+route.path] {
|
||||
seen++
|
||||
}
|
||||
}
|
||||
if seen != len(guarded) {
|
||||
t.Fatalf("found %d of the guarded routes, want %d", seen, len(guarded))
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name, mode, want string
|
||||
}{
|
||||
{name: "open", mode: "open", want: "turnstile:open"},
|
||||
{name: "closed", mode: "closed", want: "turnstile:closed"},
|
||||
{name: "closed with spaces", mode: " closed ", want: "turnstile:closed"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got, err := recordUserRoutes(t, c.mode)
|
||||
if err != nil {
|
||||
t.Fatalf("Routes error %v", err)
|
||||
}
|
||||
if len(got) != len(off) {
|
||||
t.Fatalf("%d routes, want %d", len(got), len(off))
|
||||
}
|
||||
for i, route := range got {
|
||||
base := off[i]
|
||||
if route.method != base.method || route.path != base.path {
|
||||
t.Fatalf("route %d is %s %s, want %s %s", i, route.method, route.path, base.method, base.path)
|
||||
}
|
||||
want := base.middleware
|
||||
if guarded[route.method+" "+route.path] {
|
||||
want = append(append([]string{}, base.middleware...), c.want)
|
||||
}
|
||||
if strings.Join(route.middleware, ",") != strings.Join(want, ",") {
|
||||
t.Errorf("%s %s middleware %v, want %v", route.method, route.path, route.middleware, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
for _, bad := range []string{"bogus", "Closed", "on", "true"} {
|
||||
if _, err := recordUserRoutes(t, bad); err == nil || !strings.Contains(err.Error(), "golem15.user.turnstile") {
|
||||
t.Errorf("turnstile %q: error %v, want one naming golem15.user.turnstile", bad, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
25
updates/202610040001_add_users_permissions.go
Normal file
25
updates/202610040001_add_users_permissions.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package updates
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// The users.permissions column of PHP updates/v1.0.1/create_users_table.php:
|
||||
// the user's own frontend permissions as a JSON object of code to 1 or -1,
|
||||
// NULL or an empty string when the user has none.
|
||||
var usersPermissionsMigrations = []*gormigrate.Migration{
|
||||
{
|
||||
ID: "202610040001_add_users_permissions",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
return tx.Exec(`ALTER TABLE users ADD COLUMN permissions TEXT NULL`).Error
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
return tx.Exec(`ALTER TABLE users DROP COLUMN IF EXISTS permissions`).Error
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(usersPermissionsMigrations...)
|
||||
}
|
||||
24
updates/202610040002_add_users_last_seen.go
Normal file
24
updates/202610040002_add_users_last_seen.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package updates
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// The users.last_seen column of PHP updates/v1.2.6/users_add_last_seen.php.
|
||||
// The auth path stamps it on login and on token refresh.
|
||||
var usersLastSeenMigrations = []*gormigrate.Migration{
|
||||
{
|
||||
ID: "202610040002_add_users_last_seen",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
return tx.Exec(`ALTER TABLE users ADD COLUMN last_seen TIMESTAMPTZ NULL`).Error
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
return tx.Exec(`ALTER TABLE users DROP COLUMN IF EXISTS last_seen`).Error
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(usersLastSeenMigrations...)
|
||||
}
|
||||
36
updates/202610040003_create_frontend_permissions.go
Normal file
36
updates/202610040003_create_frontend_permissions.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package updates
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// PHP updates/v2.8.0/create_frontend_permissions_table.php: the catalogue of
|
||||
// frontend permissions the user and group permission editors offer. Rows
|
||||
// come from migrations or seeds of the host application.
|
||||
var frontendPermissionsMigrations = []*gormigrate.Migration{
|
||||
{
|
||||
ID: "202610040003_create_frontend_permissions",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
return execStmts(tx, []string{
|
||||
`CREATE TABLE golem15_user_frontend_permissions (
|
||||
id SERIAL PRIMARY KEY,
|
||||
code VARCHAR(255) NOT NULL,
|
||||
label VARCHAR(255) NOT NULL,
|
||||
tab VARCHAR(255) NOT NULL,
|
||||
comment VARCHAR(255) NULL,
|
||||
created_at TIMESTAMPTZ NULL,
|
||||
updated_at TIMESTAMPTZ NULL
|
||||
)`,
|
||||
`CREATE UNIQUE INDEX golem15_user_frontend_permissions_code_unique ON golem15_user_frontend_permissions (code)`,
|
||||
})
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
return tx.Exec(`DROP TABLE IF EXISTS golem15_user_frontend_permissions`).Error
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(frontendPermissionsMigrations...)
|
||||
}
|
||||
36
updates/202610050001_create_oauth_identities.go
Normal file
36
updates/202610050001_create_oauth_identities.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package updates
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var oauthIdentityMigrations = []*gormigrate.Migration{
|
||||
{
|
||||
ID: "202610050001_create_oauth_identities",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
return execStmts(tx, []string{
|
||||
`CREATE TABLE golem15_user_oauth_identities (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
provider VARCHAR(50) NOT NULL,
|
||||
provider_id VARCHAR(255) NOT NULL,
|
||||
access_token TEXT NULL,
|
||||
refresh_token TEXT NULL,
|
||||
token_expires_at TIMESTAMPTZ NULL,
|
||||
profile_data jsonb NULL,
|
||||
linked_at TIMESTAMPTZ NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)`,
|
||||
`CREATE UNIQUE INDEX oauth_identities_user_provider_unique ON golem15_user_oauth_identities (user_id, provider)`,
|
||||
`CREATE UNIQUE INDEX oauth_identities_provider_identity_unique ON golem15_user_oauth_identities (provider, provider_id)`,
|
||||
})
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
return tx.Exec("DROP TABLE IF EXISTS golem15_user_oauth_identities").Error
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
func init() { Register(oauthIdentityMigrations...) }
|
||||
30
updates/202610160002_add_handle_to_users.go
Normal file
30
updates/202610160002_add_handle_to_users.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package updates
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// addHandleToUsers adds users.handle, the unique @mention identity (D-15),
|
||||
// only when it is missing: an application whose users table already has the
|
||||
// column (added on PHP by chatchannels) keeps it and its data. The rollback
|
||||
// is a no-op for the same reason: the column may predate this plugin.
|
||||
var addHandleToUsers = []*gormigrate.Migration{
|
||||
{
|
||||
ID: "202610160002_add_handle_to_users",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
if err := tx.Exec(`ALTER TABLE users ADD COLUMN IF NOT EXISTS handle VARCHAR(255) NULL`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS users_handle_unique ON users (handle)`).Error
|
||||
},
|
||||
Rollback: func(*gorm.DB) error {
|
||||
// No-op: the shared users column may predate the plugin.
|
||||
return nil
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(addHandleToUsers...)
|
||||
}
|
||||
168
updates/admin_columns_test.go
Normal file
168
updates/admin_columns_test.go
Normal file
@@ -0,0 +1,168 @@
|
||||
package updates
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
)
|
||||
|
||||
// TestAdminColumnsMigrations applies the three admin migrations on a real
|
||||
// Postgres, checks what each one adds, rolls each one back on its own and
|
||||
// applies them again.
|
||||
func TestAdminColumnsMigrations(t *testing.T) {
|
||||
sqlDB := dedicatedDB(t, "user_admin_columns")
|
||||
gdb, err := lagoon.Use(t.Context(), sqlDB)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := gormigrate.New(gdb, &gormigrate.Options{
|
||||
TableName: "summer_migrations_golem15_user",
|
||||
UseTransaction: true,
|
||||
}, All())
|
||||
if err := m.Migrate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
columnType := func(table, column string) (string, string) {
|
||||
t.Helper()
|
||||
var row struct {
|
||||
DataType string
|
||||
IsNullable string
|
||||
}
|
||||
if err := gdb.Raw(`SELECT data_type, is_nullable FROM information_schema.columns WHERE table_name = ? AND column_name = ?`, table, column).Scan(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return row.DataType, row.IsNullable
|
||||
}
|
||||
if typ, null := columnType("users", "permissions"); typ != "text" || null != "YES" {
|
||||
t.Fatalf("users.permissions = %q nullable %q", typ, null)
|
||||
}
|
||||
if typ, null := columnType("users", "last_seen"); typ != "timestamp with time zone" || null != "YES" {
|
||||
t.Fatalf("users.last_seen = %q nullable %q", typ, null)
|
||||
}
|
||||
const table = "golem15_user_frontend_permissions"
|
||||
want := map[string][2]string{
|
||||
"id": {"integer", "NO"},
|
||||
"code": {"character varying", "NO"},
|
||||
"label": {"character varying", "NO"},
|
||||
"tab": {"character varying", "NO"},
|
||||
"comment": {"character varying", "YES"},
|
||||
"created_at": {"timestamp with time zone", "YES"},
|
||||
"updated_at": {"timestamp with time zone", "YES"},
|
||||
}
|
||||
for column, shape := range want {
|
||||
if typ, null := columnType(table, column); typ != shape[0] || null != shape[1] {
|
||||
t.Fatalf("%s.%s = %q nullable %q", table, column, typ, null)
|
||||
}
|
||||
}
|
||||
insert := `INSERT INTO golem15_user_frontend_permissions (code, label, tab) VALUES (?, ?, ?)`
|
||||
if err := gdb.Exec(insert, "blog.post", "Post", "Blog").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := gdb.Exec(insert, "blog.post", "Post again", "Blog").Error; err == nil {
|
||||
t.Fatal("a duplicate permission code was accepted")
|
||||
}
|
||||
// An existing user keeps working with both columns empty.
|
||||
if err := gdb.Exec(`INSERT INTO users (email) VALUES ('columns@example.test')`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var empty int64
|
||||
if err := gdb.Raw(`SELECT COUNT(*) FROM users WHERE permissions IS NULL AND last_seen IS NULL`).Scan(&empty).Error; err != nil || empty != 1 {
|
||||
t.Fatalf("users with empty admin columns = %d err = %v", empty, err)
|
||||
}
|
||||
|
||||
if err := m.RollbackMigration(frontendPermissionsMigrations[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gdb.Migrator().HasTable(table) {
|
||||
t.Fatalf("%s survived rollback", table)
|
||||
}
|
||||
if err := m.RollbackMigration(usersLastSeenMigrations[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gdb.Migrator().HasColumn("users", "last_seen") || !gdb.Migrator().HasColumn("users", "permissions") {
|
||||
t.Fatal("last_seen rollback touched the wrong column")
|
||||
}
|
||||
if err := m.RollbackMigration(usersPermissionsMigrations[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gdb.Migrator().HasColumn("users", "permissions") {
|
||||
t.Fatal("users.permissions survived rollback")
|
||||
}
|
||||
for _, kept := range []string{"users", "user_groups", "user_throttle", "user_api_tokens"} {
|
||||
if !gdb.Migrator().HasTable(kept) {
|
||||
t.Fatalf("rollback dropped %s", kept)
|
||||
}
|
||||
}
|
||||
var users int64
|
||||
if err := gdb.Raw(`SELECT COUNT(*) FROM users`).Scan(&users).Error; err != nil || users != 1 {
|
||||
t.Fatalf("users after rollback = %d err = %v", users, err)
|
||||
}
|
||||
|
||||
if err := m.Migrate(); err != nil {
|
||||
t.Fatalf("re-up: %v", err)
|
||||
}
|
||||
if !gdb.Migrator().HasTable(table) || !gdb.Migrator().HasColumn("users", "permissions") || !gdb.Migrator().HasColumn("users", "last_seen") {
|
||||
t.Fatal("re-up did not restore the admin columns")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminColumnsHistory: the three admin migrations are part of the
|
||||
// plugin's history under their own ids, each id once, and applying the whole
|
||||
// history twice changes nothing.
|
||||
func TestAdminColumnsHistory(t *testing.T) {
|
||||
sqlDB := dedicatedDB(t, "user_admin_history")
|
||||
gdb, err := lagoon.Use(t.Context(), sqlDB)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seen := map[string]int{}
|
||||
for _, migration := range All() {
|
||||
seen[migration.ID]++
|
||||
if migration.Migrate == nil || migration.Rollback == nil {
|
||||
t.Fatalf("migration %s lacks an up or a down", migration.ID)
|
||||
}
|
||||
}
|
||||
admin := []string{usersPermissionsMigrations[0].ID, usersLastSeenMigrations[0].ID, frontendPermissionsMigrations[0].ID}
|
||||
for _, id := range admin {
|
||||
if seen[id] != 1 {
|
||||
t.Fatalf("migration %s is in the history %d times", id, seen[id])
|
||||
}
|
||||
}
|
||||
for id, n := range seen {
|
||||
if n != 1 {
|
||||
t.Fatalf("migration id %s is used %d times", id, n)
|
||||
}
|
||||
}
|
||||
m := gormigrate.New(gdb, &gormigrate.Options{
|
||||
TableName: "summer_migrations_golem15_user",
|
||||
UseTransaction: true,
|
||||
}, All())
|
||||
for range 2 {
|
||||
if err := m.Migrate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var applied int64
|
||||
if err := gdb.Raw(`SELECT COUNT(*) FROM summer_migrations_golem15_user WHERE id IN ?`, admin).Scan(&applied).Error; err != nil || applied != 3 {
|
||||
t.Fatalf("applied admin migrations = %d err = %v", applied, err)
|
||||
}
|
||||
// The permission code stays unique after a down and an up of its table.
|
||||
if err := m.RollbackMigration(frontendPermissionsMigrations[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.Migrate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
insert := `INSERT INTO golem15_user_frontend_permissions (code, label, tab) VALUES (?, ?, ?)`
|
||||
if err := gdb.Exec(insert, "history.code", "One", "Tab").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := gdb.Exec(insert, "history.code", "Two", "Other").Error; err == nil {
|
||||
t.Fatal("a duplicate permission code was accepted after the re-up")
|
||||
}
|
||||
if err := gdb.Exec(insert, "History.Code", "Three", "Tab").Error; err != nil {
|
||||
t.Fatalf("codes differing by case are distinct: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ func TestAPITokenMigration(t *testing.T) {
|
||||
if oauthClientType != "text" {
|
||||
t.Fatalf("oauth_client_id type = %q, want text for legacy OAuth client IDs", oauthClientType)
|
||||
}
|
||||
if err := m.RollbackLast(); err != nil {
|
||||
if err := m.RollbackMigration(apiTokenMigrations[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if db.Migrator().HasTable(&models.APIToken{}) {
|
||||
|
||||
88
updates/oauth_identities_test.go
Normal file
88
updates/oauth_identities_test.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package updates
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
)
|
||||
|
||||
func TestOAuthIdentitiesMigration(t *testing.T) {
|
||||
sqlDB := dedicatedDB(t, "user_oauth_identities")
|
||||
db, err := lagoon.Use(t.Context(), sqlDB)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := gormigrate.New(db, &gormigrate.Options{TableName: "summer_migrations_golem15_user", UseTransaction: true}, All())
|
||||
if err := m.Migrate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
table := (&models.OAuthIdentity{}).TableName()
|
||||
if table != "golem15_user_oauth_identities" {
|
||||
t.Fatalf("TableName = %q", table)
|
||||
}
|
||||
if !db.Migrator().HasTable(table) {
|
||||
t.Fatal("golem15_user_oauth_identities missing")
|
||||
}
|
||||
for _, column := range []string{
|
||||
"id", "user_id", "provider", "provider_id", "access_token", "refresh_token",
|
||||
"token_expires_at", "profile_data", "linked_at", "created_at", "updated_at",
|
||||
} {
|
||||
if !db.Migrator().HasColumn(&models.OAuthIdentity{}, column) {
|
||||
t.Fatalf("golem15_user_oauth_identities.%s missing", column)
|
||||
}
|
||||
}
|
||||
var udt string
|
||||
if err := db.Raw(`SELECT udt_name FROM information_schema.columns WHERE table_name = 'golem15_user_oauth_identities' AND column_name = 'profile_data'`).Scan(&udt).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if udt != "jsonb" {
|
||||
t.Fatalf("profile_data udt = %q, want jsonb", udt)
|
||||
}
|
||||
var indexes []string
|
||||
if err := db.Raw(`SELECT indexname FROM pg_indexes WHERE tablename = 'golem15_user_oauth_identities'`).Scan(&indexes).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantIdx := map[string]bool{
|
||||
"oauth_identities_user_provider_unique": false,
|
||||
"oauth_identities_provider_identity_unique": false,
|
||||
}
|
||||
for _, name := range indexes {
|
||||
if _, ok := wantIdx[name]; ok {
|
||||
wantIdx[name] = true
|
||||
}
|
||||
}
|
||||
for name, found := range wantIdx {
|
||||
if !found {
|
||||
t.Fatalf("missing unique index %s in %v", name, indexes)
|
||||
}
|
||||
}
|
||||
var fk struct {
|
||||
ForeignTable string
|
||||
DeleteRule string
|
||||
}
|
||||
if err := db.Raw(`
|
||||
SELECT ccu.table_name AS foreign_table, rc.delete_rule
|
||||
FROM information_schema.table_constraints tc
|
||||
JOIN information_schema.key_column_usage kcu
|
||||
ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
|
||||
JOIN information_schema.constraint_column_usage ccu
|
||||
ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
|
||||
JOIN information_schema.referential_constraints rc
|
||||
ON rc.constraint_name = tc.constraint_name AND rc.constraint_schema = tc.table_schema
|
||||
WHERE tc.table_name = 'golem15_user_oauth_identities'
|
||||
AND tc.constraint_type = 'FOREIGN KEY'
|
||||
AND kcu.column_name = 'user_id'`).Scan(&fk).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fk.ForeignTable != "users" || fk.DeleteRule != "CASCADE" {
|
||||
t.Fatalf("user_id FK = %+v, want users ON DELETE CASCADE", fk)
|
||||
}
|
||||
if err := m.RollbackMigration(oauthIdentityMigrations[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if db.Migrator().HasTable(table) {
|
||||
t.Fatal("golem15_user_oauth_identities survived rollback")
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,12 @@ func TestCreateOrganisationsMigration(t *testing.T) {
|
||||
"202609220006_create_user_throttle",
|
||||
"202609220007_create_jwt_blacklist",
|
||||
"202610020001_create_user_groups",
|
||||
"202610040001_add_users_permissions",
|
||||
"202610040001_create_user_api_tokens",
|
||||
"202610040002_add_users_last_seen",
|
||||
"202610040003_create_frontend_permissions",
|
||||
"202610050001_create_oauth_identities",
|
||||
"202610160002_add_handle_to_users",
|
||||
}
|
||||
if len(ids) != len(want) {
|
||||
t.Fatalf("history = %v", ids)
|
||||
@@ -56,8 +61,9 @@ func TestCreateOrganisationsMigration(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// API tokens, user groups, jwt blacklist, throttle, extend-users, then organisations.
|
||||
for range 6 {
|
||||
// Handle, OAuth identities, the three admin migrations, API tokens, user groups, jwt blacklist,
|
||||
// throttle, extend-users, then organisations.
|
||||
for range 11 {
|
||||
if err := m.RollbackLast(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -54,7 +54,8 @@ func TestUserGroupsMigration(t *testing.T) {
|
||||
t.Fatalf("users_groups primary key = %q", pk)
|
||||
}
|
||||
|
||||
for range 2 { // API tokens, then user groups.
|
||||
// Handle, OAuth identities, frontend permissions, last seen, API tokens, user permissions, then user groups.
|
||||
for range 7 {
|
||||
if err := m.RollbackLast(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -47,8 +47,9 @@ func TestExtendUsersMigration(t *testing.T) {
|
||||
if !row.HasSelfSetPassword || row.IsActivated || row.MarketingConsent || row.IsOnboarded {
|
||||
t.Fatalf("defaults = %+v", row)
|
||||
}
|
||||
// API tokens, user groups, jwt blacklist, throttle, then extend-users.
|
||||
for range 5 {
|
||||
// Handle, OAuth identities, the three admin migrations, API tokens, user groups, jwt blacklist,
|
||||
// throttle, then extend-users.
|
||||
for range 10 {
|
||||
if err := m.RollbackLast(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -87,8 +88,8 @@ func TestCreateUserThrottleMigration(t *testing.T) {
|
||||
t.Fatalf("missing column %s", col)
|
||||
}
|
||||
}
|
||||
// API tokens, user groups, jwt blacklist, then throttle.
|
||||
for range 4 {
|
||||
// Handle, OAuth identities, the three admin migrations, API tokens, user groups, jwt blacklist, then throttle.
|
||||
for range 9 {
|
||||
if err := m.RollbackLast(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -119,8 +120,8 @@ func TestCreateJwtBlacklistMigration(t *testing.T) {
|
||||
t.Fatalf("missing column %s", col)
|
||||
}
|
||||
}
|
||||
// API tokens, user groups, then jwt blacklist.
|
||||
for range 3 {
|
||||
// Handle, OAuth identities, the three admin migrations, API tokens, user groups, then jwt blacklist.
|
||||
for range 8 {
|
||||
if err := m.RollbackLast(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
13
views/mail/invite-en.htm
Normal file
13
views/mail/invite-en.htm
Normal file
@@ -0,0 +1,13 @@
|
||||
subject = "An account has been created for you"
|
||||
description = "Invite a new user to the website"
|
||||
layout = "user"
|
||||
==
|
||||
Hello **{{ .Name }}**.
|
||||
|
||||
An account has been created for you. Use the link below to activate it:
|
||||
|
||||
[Activate your account]({{ .Link }})
|
||||
|
||||
This link expires in {{ .Hours }} hours. If it has expired, ask your administrator for a new invitation.
|
||||
|
||||
Your login: `{{ .Login }}`
|
||||
13
views/mail/invite.htm
Normal file
13
views/mail/invite.htm
Normal file
@@ -0,0 +1,13 @@
|
||||
subject = "Utworzono dla Ciebie konto"
|
||||
description = "Zaproszenie nowego użytkownika"
|
||||
layout = "user"
|
||||
==
|
||||
Cześć **{{ .Name }}**.
|
||||
|
||||
Utworzono dla Ciebie konto. Aktywuj je, korzystając z poniższego linku:
|
||||
|
||||
[Aktywuj konto]({{ .Link }})
|
||||
|
||||
Link wygasa po {{ .Hours }} godz. Jeśli wygasł, poproś administratora o nowe zaproszenie.
|
||||
|
||||
Twój login: `{{ .Login }}`
|
||||
Reference in New Issue
Block a user