Compare commits

..
147 Commits
Author SHA1 Message Date
Gani Georgiev 3bfa0b6dd4 updated ui/dist 2022-08-25 11:13:52 +03:00
Gani Georgiev 9e3c59f966 reverted changes to the mailer To: address format 2022-08-25 10:59:55 +03:00
Gani Georgiev 0b8c7f6883 fixed typo and removed unusued import 2022-08-21 14:47:33 +03:00
Gani Georgiev 587cfc335c [#75] added option to test s3 connection and send test emails 2022-08-21 14:30:36 +03:00
Gani Georgiev 3f4f4cf031 [#282] reversed the X-Forwarded-For ips iteration 2022-08-20 08:01:54 +03:00
Gani Georgiev d4f160d959 updated the user and admin login email validator to check only the string format 2022-08-20 07:58:42 +03:00
Gani Georgiev 07cd758112 [#282] fixed "real" user ip extraction 2022-08-20 07:57:17 +03:00
Gani Georgiev beb8e7924d [#282] fixed X-Forward-For ip extraction 2022-08-20 05:56:56 +03:00
Gani Georgiev 72fdf0d116 updated test data.db 2022-08-18 21:05:17 +03:00
Gani Georgiev 7e14ea7cfb [#210] change the uploaded filename strategy to include the original filename 2022-08-18 20:44:29 +03:00
Gani Georgiev 25c4db7a30 updated ui/dist with older sdk version 2022-08-18 20:32:07 +03:00
Gani Georgiev e86b1f54a0 updated ui/dist 2022-08-18 20:28:20 +03:00
Gani Georgiev 7be389704d added hideControls setting 2022-08-18 18:45:27 +03:00
Gani Georgiev cfaff31d97 [#282] added the "real" user ip to the logs 2022-08-18 15:27:45 +03:00
Gani Georgiev 9bf66be870 fixed typos 2022-08-17 22:32:10 +03:00
Gani Georgiev efda3d5a0b [#87] added additional thumb resizers 2022-08-17 22:29:47 +03:00
Gani Georgiev a516435f2e fixed settings clone test 2022-08-16 13:37:59 +03:00
Gani Georgiev ccd010c490 simplified mail settings ui 2022-08-16 13:32:32 +03:00
Gani Georgiev 456ced75ce [#197] added now datetime filter constant 2022-08-15 22:38:17 +03:00
Gani Georgiev b7d32c23aa updated ui/dist 2022-08-15 21:42:01 +03:00
Gani Georgiev 04ddae46c9 updated SMTP recommendation 2022-08-15 21:31:25 +03:00
Gani Georgiev 7d10d20de1 [#275] added support to customize the default user email templates from the Admin UI 2022-08-14 19:30:45 +03:00
Gani Georgiev 1de56d3d9e [#302] fixed admin reset password email link 2022-08-12 17:08:36 +03:00
Gani Georgiev 80f710731c updated vite dependency 2022-08-12 12:30:11 +03:00
Gani Georgiev bd76130cd8 [#] added missing import in the api preview for deleting records 2022-08-12 12:20:56 +03:00
Gani Georgiev d60dd13581 [#294] added additional inline serving mime types 2022-08-11 20:09:26 +03:00
Gani Georgiev 19d4fc04c1 fixed UI import preview when replacing ids with missing old fields 2022-08-11 15:59:14 +03:00
Gani Georgiev a7b29c1961 updated dependencies and rebuilt ui/dist 2022-08-11 11:33:01 +03:00
Gani Georgiev 147344546b added custom insertion id regex check 2022-08-11 10:29:01 +03:00
Gani Georgiev ff935a39a1 removed spacing 2022-08-11 08:13:07 +03:00
Gani Georgiev 2cce0b17b0 synced with master 2022-08-10 20:53:13 +03:00
Gani Georgiev 5f25572e95 updated ui/dist 2022-08-10 20:46:45 +03:00
Gani Georgiev dd5c9ccce8 changed btns transition to local 2022-08-10 20:45:32 +03:00
Olle MånssonandOlle Månsson da29141248 [#288] added info about the default 100x100 thumb size in the field tooltip
Co-authored-by: Olle Månsson <olle.mansson@zenseact.com>
2022-08-10 20:40:52 +03:00
Gani Georgiev 7f6049ebd6 updated test db and ui/dist 2022-08-10 20:37:41 +03:00
Gani Georgiev 119e1fb3f2 use fixed ids in the default profiles system collections migration 2022-08-10 19:08:29 +03:00
Gani Georgiev c5091898ae added test to test schema field persistence after import 2022-08-10 17:43:55 +03:00
Gani Georgiev 35bd395e55 removed unused lib 2022-08-10 17:43:08 +03:00
Gani Georgiev d56b8fcb90 updated import popup handling and api preview examples 2022-08-10 16:16:59 +03:00
Gani Georgiev 65b830198b test deleteMissing with schema changes 2022-08-10 13:22:27 +03:00
Gani Georgiev ac0c23ff64 fixed list js example 2022-08-09 17:57:32 +03:00
Gani Georgiev a355c8e8a9 removed duplicated method 2022-08-09 17:20:22 +03:00
Gani Georgiev c346dd69a4 updated ui/dist 2022-08-09 17:17:13 +03:00
Gani Georgiev f8f785d6e3 call transaction Dao events only after commit, added totalPages to the search response and updated the tests 2022-08-09 16:20:39 +03:00
Gani Georgiev 8288da8372 added version number in the footer 2022-08-09 16:16:09 +03:00
Gani Georgiev 8b2b26c196 fixed after hooks 2022-08-08 20:14:46 +03:00
Gani Georgiev 8009d37d24 updated tests 2022-08-08 19:16:33 +03:00
Gani Georgiev 6e9d000426 before updateding test data 2022-08-07 20:58:21 +03:00
Gani Georgiev a426484916 added WithConfig factory to all forms 2022-08-07 15:38:21 +03:00
Gani Georgiev b0ca9b2f1b updated export/import form 2022-08-07 11:14:49 +03:00
Gani Georgiev 956263d1fc updated admin and user upsert forms 2022-08-06 22:16:58 +03:00
Gani Georgiev 51d635bc12 fixed popup hide 2022-08-06 18:59:28 +03:00
Gani Georgiev 5fb45a1864 updated CollectionsImport and CollectionUpsert forms 2022-08-06 18:15:18 +03:00
Gani Georgiev 4e58e7ad6a added ImportPopup 2022-08-06 08:03:34 +03:00
Gani Georgiev 93ab5fbea2 added page export and import 2022-08-05 23:25:16 +03:00
Gani Georgiev f459dd8812 import scaffoldings 2022-08-05 06:00:38 +03:00
Gani Georgiev 95f9d685dc updated base model comments 2022-08-03 16:26:36 +03:00
Gani Georgiev bb00f198bc changed btns transition to local 2022-08-03 10:16:13 +03:00
Gani Georgiev 0e1b9a3897 updated go version constraint for the github action 2022-08-02 21:36:36 +03:00
Gani Georgiev e32cf12908 updated ui/dist 2022-08-02 21:32:36 +03:00
Gani Georgiev c152f99793 fixed datepicker clipped input borders 2022-08-02 21:31:42 +03:00
Gani Georgiev f8b7a40837 switch to stable go 1.19.0 2022-08-02 20:57:03 +03:00
Gani Georgiev a049a37624 updated sdk to ^0.3.0 2022-08-02 17:00:14 +03:00
Gani Georgiev 8268c26d8b fixed README typo 2022-08-01 22:30:14 +03:00
Gani Georgiev 6292e6cc2e unify the prod and dev env and use only relative base path ./ in the Admin UI 2022-08-01 20:55:31 +03:00
Gani Georgiev fbeaabf6aa removed no longer needed ui.DistIndexHTML var 2022-08-01 20:53:06 +03:00
Gani Georgiev 30d1b9f358 refactored the admin ui routes registration for better sub-path deployment support 2022-08-01 20:37:51 +03:00
Gani Georgiev 16fa099685 added default admin CSP 2022-08-01 18:10:18 +03:00
Gani Georgiev bb4bebc724 removed box-shadow for image-preview modals 2022-08-01 18:00:06 +03:00
Gani Georgiev 9d0ea7635b [#204] fixed query string parsing 2022-08-01 14:20:21 +03:00
Yin Shanyang d35134e913 [#250] added armv7 on linux as a build target 2022-08-01 10:29:06 +03:00
Gani Georgiev ce8af46fff unified file field styles 2022-07-31 23:28:47 +03:00
Gani Georgiev 87ecb1114c cleaning up no longer needed ui helper methods 2022-07-31 23:21:55 +03:00
Gani Georgiev c070be2c47 [#238] removed implicit select items grouping 2022-07-31 18:52:51 +03:00
Gani Georgiev 4f0041a128 added dart-sdk to the readme 2022-07-31 13:05:05 +03:00
Gani Georgiev 0ac24af7c9 updated ui/dist 2022-07-31 11:51:06 +03:00
Gani Georgiev 96b2c5fedf added Dart to the api preview examples 2022-07-30 21:04:44 +03:00
Gani Georgiev 4019ca5f00 [#223] change the default prod backend url to relative path to support sub-path deployment 2022-07-30 20:59:09 +03:00
Gani Georgiev 20fe3c8c91 added debug log for the invalid uploaded file(s) 2022-07-30 14:11:08 +03:00
Gani Georgiev d87a5e544c updated admin ui dependencies 2022-07-30 08:02:41 +03:00
Gani Georgiev bb527be493 fixed panic on expanding existing byt non-relation type field 2022-07-30 07:58:42 +03:00
Gani Georgiev 9e3b230c8e added debug log for established realtime connection 2022-07-28 08:26:05 +03:00
Gani Georgiev 686198a22e normalize number filter literals
Always cast number literals to provide consistent eq/neq behavior when combined with COALESCE, because '1' = 1 is TRUE but COALESCE('1', '') = COALESCE(1, '') will result to FALSE.
2022-07-28 05:23:58 +03:00
Gani Georgiev 086b992c7d [#228] added target=_blank to the email links 2022-07-26 15:17:10 +03:00
Takeshi Sato 88d8cec3d9 [#207] use read-only scopes for the GitHub OAuth2 provider 2022-07-24 18:04:53 +03:00
Gani Georgiev 7926501649 updated comments and added CSP header check in the tests 2022-07-21 17:22:31 +03:00
Gani Georgiev 4c2cd5a534 simplify the svg extension check 2022-07-21 12:58:06 +03:00
Gani Georgiev 5d8fc939e2 [#164] serve common media files inline and fix svg content-type 2022-07-21 12:56:17 +03:00
Gani Georgiev 1a5180d7d3 added support to filter request.user.profile relation fields 2022-07-20 22:33:24 +03:00
Gani Georgiev 8a08a4764d [#166] fixed api preview examples 2022-07-19 19:41:03 +03:00
Gani Georgiev 66b317f01c run tests before goreleaser 2022-07-19 17:24:58 +03:00
Gani Georgiev ab5a770346 updated tests 2022-07-19 17:23:34 +03:00
Gani Georgiev 65697add43 temporary skip tests in the release action until the async email hooks get fixed 2022-07-19 14:46:02 +03:00
Gani Georgiev 841415f0ff move field delete in a dropdown to prevent accidental clicks 2022-07-19 14:36:35 +03:00
Gani Georgiev f295ce9403 run added password reset and verification sent hooks tests 2022-07-19 14:20:28 +03:00
Gani Georgiev 383b2a1279 [#160] support expand query parameter for create and update requests 2022-07-19 13:31:52 +03:00
Gani Georgiev 73fb12c2bc [#156] added forcePathStyle to the s3 config 2022-07-19 10:45:38 +03:00
Kenneth Lee 571c4dcc8d [#163] fixed migrate down cmd 2022-07-18 23:00:54 +03:00
Gani Georgiev f56adf26f4 added the app name in the document title and fixed the double initial load on records list 2022-07-18 19:44:10 +03:00
Gani Georgiev f8f3ca25ee updated duplicated field name error 2022-07-18 18:10:30 +03:00
Gani Georgiev e01f76d37b allow switching schema field names when renaming fields 2022-07-18 16:26:37 +03:00
Gani Georgiev 47fc9b1066 normalized null handling in search filters 2022-07-18 14:07:25 +03:00
Gani Georgiev eaf08a5c15 [#151] updated the tests to ensure that the cascaded record files are also deleted 2022-07-18 13:19:07 +03:00
Gani Georgiev 8ef3d4e966 [#151] remove files on cascade deletion 2022-07-18 12:04:27 +03:00
Gani Georgiev 04e0cec32c updated ui/dist 2022-07-18 01:06:55 +03:00
Gani Georgiev 9a231ba7b3 applied some of the changes from #149 2022-07-18 01:03:09 +03:00
Gani Georgiev 7f959011b8 moved field option btns inside the panel 2022-07-18 00:55:53 +03:00
Gani Georgiev 994761b728 normalized the caster to return always non-null value and fixed minor ui issues 2022-07-18 00:16:09 +03:00
Gani Georgiev f19b9e3552 commented golangci-lint action as it is not go1.18+ ready 2022-07-17 22:25:28 +03:00
Gani Georgiev 36783b8f04 added golangci-lint action 2022-07-17 22:20:40 +03:00
Gani Georgiev a076cc906f [#147] added CONTRIBUTING.md 2022-07-17 20:33:12 +03:00
Gani Georgiev b1a30f4050 fixed figure tag typo 2022-07-16 11:57:31 +03:00
Gani Georgiev 4506fb17e9 adding video presets to the file options 2022-07-16 11:54:54 +03:00
Gani Georgiev 72f72bc84f added invalid form-group styles 2022-07-16 10:40:04 +03:00
Gani Georgiev 7fd5102fb5 updated EmailOptions domain input tooltips 2022-07-16 10:39:19 +03:00
Gani Georgiev d6bdc51009 changed the storage slide panel transition to local 2022-07-16 10:38:47 +03:00
Gani Georgiev 789373d15d [#100] resets the initial loadList results 2022-07-15 19:37:30 +03:00
Gani Georgiev 2dc000da65 improve error reporting on OAuth2 user profile fetch 2022-07-15 18:52:37 +03:00
Simon Krauter 1095637bcd [#116] fix BaseModel.RefreshUpdated comment 2022-07-14 23:17:53 +03:00
Gani Georgiev c4fcba5210 [#109] prealocated handlers and replaced OnRecordBeforeDeleteRequest with OnModelBeforeDelete 2022-07-14 22:35:57 +03:00
Gani Georgiev d8c8289269 added odd default circle icon size for better visual vertical alignment in firefox 2022-07-14 21:21:47 +03:00
Gani Georgiev dbbfa243bc added new lines for readability and consistency 2022-07-14 20:01:53 +03:00
Valley a16b0c9004 [#114] simplified some code by returning early and added cap for slices 2022-07-14 19:26:08 +03:00
Gani Georgiev 03a7bafa66 use the original vite2 default port and bump the min js-sdk to v0.2.1 2022-07-14 17:09:08 +03:00
Gani Georgiev d129959098 added store.RemoveAll() helper method 2022-07-14 16:39:42 +03:00
Gani Georgiev 6749559a22 log the response error not the handler one 2022-07-14 11:52:35 +03:00
Gani Georgiev 28bc2678e9 minor ui improvements and upgraded dependencies 2022-07-14 09:58:53 +03:00
Gani Georgiev d4202e696b [#99] fix AutoExpandTextArea scrolling 2022-07-13 22:44:59 +03:00
Gani Georgiev 9de3cc99a0 updated api preview body params col sizes 2022-07-13 08:48:38 +03:00
Franco Profeti 111bc59472 [#93] improved the README for no golang devs 2022-07-13 08:12:25 +03:00
Gani Georgiev b2647ebca9 synced refresh button js timeout with the css animation 2022-07-12 20:03:13 +03:00
Gani Georgiev ef226cf9c1 added refresh button to the other listing pages 2022-07-12 19:56:22 +03:00
Valley 63d5a8d633 [#89] simplified some code by returning early and reducing local variable scopes 2022-07-12 19:52:09 +03:00
Gani Georgiev d71c3cd19c updated ui/dist 2022-07-12 18:11:50 +03:00
Cornelius Müller 240bd6790a [#83] added refresh button to page records view 2022-07-12 18:08:57 +03:00
Gani Georgiev 05a4071eba [#80] fixed before hooks data and added optional interceptor to upsert submit 2022-07-12 13:42:06 +03:00
Valley ce857985be [#82] removed version cmd and make use of cobra.Version 2022-07-12 07:57:36 +03:00
Gani Georgiev 320d1482a4 [#77] add warning on storage type change 2022-07-11 22:23:22 +03:00
Gani Georgiev 46399dddac [#78] enable fully qualified URIs for S3 endpoints and improved error reporting when uploading or deleting files 2022-07-11 21:00:17 +03:00
Gani Georgiev 52c288d9db added linter skip comments and removed the Presentator specific inflector.Usernamify 2022-07-11 16:16:01 +03:00
Gani Georgiev ed741662b2 removed the v prefix from the version command 2022-07-11 10:30:34 +03:00
Gani Georgiev 0c14f32822 added additional info about the @expand query parameter 2022-07-11 10:30:20 +03:00
毛亚琛 ec0d3b0d3d [#69] automatically add version information 2022-07-11 10:26:55 +03:00
wenqingl 10d7faea31 [#62] fixed typo in README
defintions -> definitions
2022-07-11 07:36:38 +03:00
Gani Georgiev f62664098e updated ui/dist 2022-07-10 21:14:38 +03:00
毛亚琛 1dfc314bc1 [#60] fix list api docs example 2022-07-10 21:07:04 +03:00
Gani Georgiev 7b2d88fa30 [#45] don't set Last-Modified header if time.location data cannot be loaded 2022-07-10 20:53:24 +03:00
269 changed files with 11391 additions and 4052 deletions

No files matched your search

+9 -1
View File
@@ -21,7 +21,7 @@ jobs:
- name: Set up Go - name: Set up Go
uses: actions/setup-go@v3 uses: actions/setup-go@v3
with: with:
go-version: '1.19.0-beta.1' go-version: '>=1.19.0'
# This step usually is not needed because the /ui/dist is pregenerated locally # This step usually is not needed because the /ui/dist is pregenerated locally
# but its here to ensure that each release embeds the latest admin ui artifacts. # but its here to ensure that each release embeds the latest admin ui artifacts.
@@ -29,6 +29,14 @@ jobs:
- name: Build Admin dashboard UI - name: Build Admin dashboard UI
run: npm --prefix=./ui ci && npm --prefix=./ui run build run: npm --prefix=./ui ci && npm --prefix=./ui run build
# The prebuilt golangci-lint doesn't support go 1.18+ yet
# https://github.com/golangci/golangci-lint/issues/2649
# - name: Run linter
# uses: golangci/golangci-lint-action@v3
- name: Run tests
run: go test ./...
- name: Run GoReleaser - name: Run GoReleaser
uses: goreleaser/goreleaser-action@v3 uses: goreleaser/goreleaser-action@v3
with: with:
+12 -3
View File
@@ -9,6 +9,8 @@ before:
builds: builds:
- main: ./examples/base - main: ./examples/base
binary: pocketbase binary: pocketbase
ldflags:
- -s -w -X github.com/pocketbase/pocketbase.Version={{ .Version }}
env: env:
- CGO_ENABLED=0 - CGO_ENABLED=0
goos: goos:
@@ -18,13 +20,20 @@ builds:
goarch: goarch:
- amd64 - amd64
- arm64 - arm64
- arm
goarm:
- 7
ignore:
- goos: windows
goarch: arm
- goos: darwin
goarch: arm
release: release:
draft: true draft: true
archives: archives:
- - format: zip
format: zip
files: files:
- LICENSE* - LICENSE*
- CHANGELOG* - CHANGELOG*
@@ -33,7 +42,7 @@ checksum:
name_template: 'checksums.txt' name_template: 'checksums.txt'
snapshot: snapshot:
name_template: "{{ incpatch .Version }}-next" name_template: '{{ incpatch .Version }}-next'
changelog: changelog:
sort: asc sort: asc
+80
View File
@@ -0,0 +1,80 @@
Contributing to PocketBase
======================================================================
Thanks for taking the time to improve PocketBase!
This document describes how to prepare a PR for a change in the main repository.
- [Prerequisites](#prerequisites)
- [Making changes in the Go code](#making-changes-in-the-go-code)
- [Making changes in the Admin UI](#making-changes-in-the-admin-ui)
## Prerequisites
- Go 1.18+ (for making changes in the Go code)
- Node 16+ (for making changes in the Admin UI)
If you haven't already, you can fork the main repository and clone your fork so that you can work locally:
```
git clone https://github.com/your_username/pocketbase.git
```
> It is recommended to create a new branch from master for each of your bugfixes and features.
> This is required if you are planning to submit multiple PRs in order to keep the changes separate for review until they eventually get merged.
## Making changes in the Go code
PocketBase is a Go package, which means that in order to run the project you'll have to create a Go `main` program that imports the package.
The repository already includes such program, located in `/examples/base`, that is also used for the prebuilt executables.
So, let's assume that you already done some changes in the PocketBase Go code and you want now to run them:
1. Navigate to `examples/base`
2. Run `go run main.go serve`
This will start a web server on `http://localhost:8090` with the embedded prebuilt Admin UI from `ui/dist`. And that's it!
**Before making a PR to the main repository, it is a good idea to:**
- Add unit/integration tests for your changes (we are using the standard `testing` go package).
To run the tests, you could execute (while in the root project directory):
```sh
go test ./...
# or using the Makefile
make test
```
- Run the linter - **golangci** ([see how to install](https://golangci-lint.run/usage/install/#local-installation)):
```sh
golangci-lint run -c ./golangci.yml ./...
# or using the Makefile
make lint
```
## Making changes in the Admin UI
PocketBase Admin UI is a single-page application (SPA) built with Svelte and Vite.
To start the Admin UI:
1. Navigate to the `ui` project directory
2. Run `npm install` to install the node dependencies
3. Start vite's dev server
```sh
npm run dev
```
You could open the browser and access the running Admin UI at `http://localhost:3000`.
Since the Admin UI is just a client-side application, you need to have the PocketBase backend server also running in the background (either manually running the `examples/base/main.go` or download a prebuilt executable).
> By default, the Admin UI is expecting the backend server to be started at `http://localhost:8090`, but you could change that by creating a new `ui/.env.development.local` file with `PB_BACKEND_URL = YOUR_ADDRESS` variable inside it.
Every change you make in the Admin UI should be automatically reflected in the browser at `http://localhost:3000` without reloading the page.
Once you are done with your changes, you have to build the Admin UI with `npm run build`, so that it can be embedded in the go package. And that's it - you can make your PR to the main PocketBase repository.
+8 -5
View File
@@ -19,7 +19,7 @@
**For documentation and examples, please visit https://pocketbase.io/docs.** **For documentation and examples, please visit https://pocketbase.io/docs.**
> ⚠️ Although the web API defintions are considered stable, > ⚠️ Although the web API definitions are considered stable,
> please keep in mind that PocketBase is still under active development > please keep in mind that PocketBase is still under active development
> and therefore full backward compatibility is not guaranteed before reaching v1.0.0. > and therefore full backward compatibility is not guaranteed before reaching v1.0.0.
@@ -29,7 +29,7 @@
The easiest way to interact with the API is to use one of the official SDK clients: The easiest way to interact with the API is to use one of the official SDK clients:
- **JavaScript - [pocketbase/js-sdk](https://github.com/pocketbase/js-sdk)** (_browser and node_) - **JavaScript - [pocketbase/js-sdk](https://github.com/pocketbase/js-sdk)** (_browser and node_)
- **Dart** - _soon_ - **Dart - [pocketbase/dart-sdk](https://github.com/pocketbase/dart-sdk)** (_web, mobile, desktop_)
## Overview ## Overview
@@ -91,10 +91,12 @@ Running/building the application is the same as for any other Go program, aka. j
**PocketBase embeds SQLite, but doesn't require CGO.** **PocketBase embeds SQLite, but doesn't require CGO.**
If CGO is enabled, it will use [mattn/go-sqlite3](https://pkg.go.dev/github.com/mattn/go-sqlite3) driver, otherwise - [modernc.org/sqlite](https://pkg.go.dev/modernc.org/sqlite). If CGO is enabled, it will use [mattn/go-sqlite3](https://pkg.go.dev/github.com/mattn/go-sqlite3) driver, otherwise - [modernc.org/sqlite](https://pkg.go.dev/modernc.org/sqlite). You can enable and disable CGO by setting the `CGO_ENABLED` environment variable to `1` or `0` respectively.
Enable CGO only if you really need to squeeze the read/write query performance at the expense of complicating cross compilation. Enable CGO only if you really need to squeeze the read/write query performance at the expense of complicating cross compilation.
To build the minimal standalone executable, like the prebuilt ones in the releases page, you can simply run `go build` inside the `examples/base` directory.
### Testing ### Testing
PocketBase comes with mixed bag of unit and integration tests. PocketBase comes with mixed bag of unit and integration tests.
@@ -118,8 +120,9 @@ PocketBase is free and open source project licensed under the [MIT License](LICE
You could help continuing its development by: You could help continuing its development by:
- [Suggest new features, report issues and fix bugs](https://github.com/pocketbase/pocketbase/issues) - [Contribute to the source code](CONTRIBUTING.md)
- [Suggest new features and report issues](https://github.com/pocketbase/pocketbase/issues)
- [Donate a small amount](https://pocketbase.io/support-us) - [Donate a small amount](https://pocketbase.io/support-us)
> Please also note that PocketBase was initially created to serve as a new backend for my other open source project - [Presentator](https://presentator.io) (see [#183](https://github.com/presentator/presentator/issues/183)), > Please note that PocketBase was initially created to serve as a new backend for my other open source project - [Presentator](https://presentator.io) (see [#183](https://github.com/presentator/presentator/issues/183)),
so all feature requests will be first aligned with what we need for Presentator v3. so all feature requests will be first aligned with what we need for Presentator v3.
+29 -21
View File
@@ -66,7 +66,7 @@ func (api *adminApi) refresh(c echo.Context) error {
func (api *adminApi) emailAuth(c echo.Context) error { func (api *adminApi) emailAuth(c echo.Context) error {
form := forms.NewAdminLogin(api.app) form := forms.NewAdminLogin(api.app)
if readErr := c.Bind(form); readErr != nil { if readErr := c.Bind(form); readErr != nil {
return rest.NewBadRequestError("An error occurred while reading the submitted data.", readErr) return rest.NewBadRequestError("An error occurred while loading the submitted data.", readErr)
} }
admin, submitErr := form.Submit() admin, submitErr := form.Submit()
@@ -80,7 +80,7 @@ func (api *adminApi) emailAuth(c echo.Context) error {
func (api *adminApi) requestPasswordReset(c echo.Context) error { func (api *adminApi) requestPasswordReset(c echo.Context) error {
form := forms.NewAdminPasswordResetRequest(api.app) form := forms.NewAdminPasswordResetRequest(api.app)
if err := c.Bind(form); err != nil { if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("An error occurred while reading the submitted data.", err) return rest.NewBadRequestError("An error occurred while loading the submitted data.", err)
} }
if err := form.Validate(); err != nil { if err := form.Validate(); err != nil {
@@ -101,7 +101,7 @@ func (api *adminApi) requestPasswordReset(c echo.Context) error {
func (api *adminApi) confirmPasswordReset(c echo.Context) error { func (api *adminApi) confirmPasswordReset(c echo.Context) error {
form := forms.NewAdminPasswordResetConfirm(api.app) form := forms.NewAdminPasswordResetConfirm(api.app)
if readErr := c.Bind(form); readErr != nil { if readErr := c.Bind(form); readErr != nil {
return rest.NewBadRequestError("An error occurred while reading the submitted data.", readErr) return rest.NewBadRequestError("An error occurred while loading the submitted data.", readErr)
} }
admin, submitErr := form.Submit() admin, submitErr := form.Submit()
@@ -166,7 +166,7 @@ func (api *adminApi) create(c echo.Context) error {
// load request // load request
if err := c.Bind(form); err != nil { if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("Failed to read the submitted data due to invalid formatting.", err) return rest.NewBadRequestError("Failed to load the submitted data due to invalid formatting.", err)
} }
event := &core.AdminCreateEvent{ event := &core.AdminCreateEvent{
@@ -174,20 +174,24 @@ func (api *adminApi) create(c echo.Context) error {
Admin: admin, Admin: admin,
} }
handlerErr := api.app.OnAdminBeforeCreateRequest().Trigger(event, func(e *core.AdminCreateEvent) error { // create the admin
// create the admin submitErr := form.Submit(func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
if err := form.Submit(); err != nil { return func() error {
return rest.NewBadRequestError("Failed to create admin.", err) return api.app.OnAdminBeforeCreateRequest().Trigger(event, func(e *core.AdminCreateEvent) error {
} if err := next(); err != nil {
return rest.NewBadRequestError("Failed to create admin.", err)
}
return e.HttpContext.JSON(http.StatusOK, e.Admin) return e.HttpContext.JSON(http.StatusOK, e.Admin)
})
}
}) })
if handlerErr == nil { if submitErr == nil {
api.app.OnAdminAfterCreateRequest().Trigger(event) api.app.OnAdminAfterCreateRequest().Trigger(event)
} }
return handlerErr return submitErr
} }
func (api *adminApi) update(c echo.Context) error { func (api *adminApi) update(c echo.Context) error {
@@ -205,7 +209,7 @@ func (api *adminApi) update(c echo.Context) error {
// load request // load request
if err := c.Bind(form); err != nil { if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("Failed to read the submitted data due to invalid formatting.", err) return rest.NewBadRequestError("Failed to load the submitted data due to invalid formatting.", err)
} }
event := &core.AdminUpdateEvent{ event := &core.AdminUpdateEvent{
@@ -213,20 +217,24 @@ func (api *adminApi) update(c echo.Context) error {
Admin: admin, Admin: admin,
} }
handlerErr := api.app.OnAdminBeforeUpdateRequest().Trigger(event, func(e *core.AdminUpdateEvent) error { // update the admin
// update the admin submitErr := form.Submit(func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
if err := form.Submit(); err != nil { return func() error {
return rest.NewBadRequestError("Failed to update admin.", err) return api.app.OnAdminBeforeUpdateRequest().Trigger(event, func(e *core.AdminUpdateEvent) error {
} if err := next(); err != nil {
return rest.NewBadRequestError("Failed to update admin.", err)
}
return e.HttpContext.JSON(http.StatusOK, e.Admin) return e.HttpContext.JSON(http.StatusOK, e.Admin)
})
}
}) })
if handlerErr == nil { if submitErr == nil {
api.app.OnAdminAfterUpdateRequest().Trigger(event) api.app.OnAdminAfterUpdateRequest().Trigger(event)
} }
return handlerErr return submitErr
} }
func (api *adminApi) delete(c echo.Context) error { func (api *adminApi) delete(c echo.Context) error {
+24 -17
View File
@@ -4,11 +4,14 @@ import (
"net/http" "net/http"
"strings" "strings"
"testing" "testing"
"time"
"github.com/labstack/echo/v5" "github.com/labstack/echo/v5"
"github.com/pocketbase/dbx" "github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/tests" "github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/types"
) )
func TestAdminAuth(t *testing.T) { func TestAdminAuth(t *testing.T) {
@@ -92,6 +95,7 @@ func TestAdminRequestPasswordReset(t *testing.T) {
Method: http.MethodPost, Method: http.MethodPost,
Url: "/api/admins/request-password-reset", Url: "/api/admins/request-password-reset",
Body: strings.NewReader(`{"email":"missing@example.com"}`), Body: strings.NewReader(`{"email":"missing@example.com"}`),
Delay: 100 * time.Millisecond,
ExpectedStatus: 204, ExpectedStatus: 204,
}, },
{ {
@@ -99,22 +103,34 @@ func TestAdminRequestPasswordReset(t *testing.T) {
Method: http.MethodPost, Method: http.MethodPost,
Url: "/api/admins/request-password-reset", Url: "/api/admins/request-password-reset",
Body: strings.NewReader(`{"email":"test@example.com"}`), Body: strings.NewReader(`{"email":"test@example.com"}`),
Delay: 100 * time.Millisecond,
ExpectedStatus: 204, ExpectedStatus: 204,
// usually this events are fired but since the submit is ExpectedEvents: map[string]int{
// executed in a separate go routine they are fired async "OnModelBeforeUpdate": 1,
// ExpectedEvents: map[string]int{ "OnModelAfterUpdate": 1,
// "OnModelBeforeUpdate": 1, "OnMailerBeforeAdminResetPasswordSend": 1,
// "OnModelAfterUpdate": 1, "OnMailerAfterAdminResetPasswordSend": 1,
// "OnMailerBeforeUserResetPasswordSend:1": 1, },
// "OnMailerAfterUserResetPasswordSend:1": 1,
// },
}, },
{ {
Name: "existing admin (after already sent)", Name: "existing admin (after already sent)",
Method: http.MethodPost, Method: http.MethodPost,
Url: "/api/admins/request-password-reset", Url: "/api/admins/request-password-reset",
Body: strings.NewReader(`{"email":"test@example.com"}`), Body: strings.NewReader(`{"email":"test@example.com"}`),
Delay: 100 * time.Millisecond,
ExpectedStatus: 204, ExpectedStatus: 204,
BeforeFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) {
// simulate recent password request
admin, err := app.Dao().FindAdminByEmail("test@example.com")
if err != nil {
t.Fatal(err)
}
admin.LastResetSentAt = types.NowDateTime()
dao := daos.New(app.Dao().DB()) // new dao to ignore hooks
if err := dao.Save(admin); err != nil {
t.Fatal(err)
}
},
}, },
} }
@@ -507,9 +523,6 @@ func TestAdminCreate(t *testing.T) {
}, },
ExpectedStatus: 400, ExpectedStatus: 400,
ExpectedContent: []string{`"data":{"email":{"code":"validation_required","message":"Cannot be blank."},"password":{"code":"validation_required","message":"Cannot be blank."}}`}, ExpectedContent: []string{`"data":{"email":{"code":"validation_required","message":"Cannot be blank."},"password":{"code":"validation_required","message":"Cannot be blank."}}`},
ExpectedEvents: map[string]int{
"OnAdminBeforeCreateRequest": 1,
},
}, },
{ {
Name: "authorized as admin + invalid data format", Name: "authorized as admin + invalid data format",
@@ -532,9 +545,6 @@ func TestAdminCreate(t *testing.T) {
}, },
ExpectedStatus: 400, ExpectedStatus: 400,
ExpectedContent: []string{`"data":{"avatar":{"code":"validation_max_less_equal_than_required","message":"Must be no greater than 9."},"email":{"code":"validation_admin_email_exists","message":"Admin email already exists."},"password":{"code":"validation_length_out_of_range","message":"The length must be between 10 and 100."},"passwordConfirm":{"code":"validation_values_mismatch","message":"Values don't match."}}`}, ExpectedContent: []string{`"data":{"avatar":{"code":"validation_max_less_equal_than_required","message":"Must be no greater than 9."},"email":{"code":"validation_admin_email_exists","message":"Admin email already exists."},"password":{"code":"validation_length_out_of_range","message":"The length must be between 10 and 100."},"passwordConfirm":{"code":"validation_values_mismatch","message":"Values don't match."}}`},
ExpectedEvents: map[string]int{
"OnAdminBeforeCreateRequest": 1,
},
}, },
{ {
Name: "authorized as admin + valid data", Name: "authorized as admin + valid data",
@@ -647,9 +657,6 @@ func TestAdminUpdate(t *testing.T) {
}, },
ExpectedStatus: 400, ExpectedStatus: 400,
ExpectedContent: []string{`"data":{"avatar":{"code":"validation_max_less_equal_than_required","message":"Must be no greater than 9."},"email":{"code":"validation_admin_email_exists","message":"Admin email already exists."},"password":{"code":"validation_length_out_of_range","message":"The length must be between 10 and 100."},"passwordConfirm":{"code":"validation_values_mismatch","message":"Values don't match."}}`}, ExpectedContent: []string{`"data":{"avatar":{"code":"validation_max_less_equal_than_required","message":"Must be no greater than 9."},"email":{"code":"validation_admin_email_exists","message":"Admin email already exists."},"password":{"code":"validation_length_out_of_range","message":"The length must be between 10 and 100."},"passwordConfirm":{"code":"validation_values_mismatch","message":"Values don't match."}}`},
ExpectedEvents: map[string]int{
"OnAdminBeforeUpdateRequest": 1,
},
}, },
{ {
Method: http.MethodPatch, Method: http.MethodPatch,
+26 -14
View File
@@ -18,6 +18,8 @@ import (
"github.com/spf13/cast" "github.com/spf13/cast"
) )
const trailedAdminPath = "/_/"
// InitApi creates a configured echo instance with registered // InitApi creates a configured echo instance with registered
// system and app specific routes and middlewares. // system and app specific routes and middlewares.
func InitApi(app core.App) (*echo.Echo, error) { func InitApi(app core.App) (*echo.Echo, error) {
@@ -25,7 +27,12 @@ func InitApi(app core.App) (*echo.Echo, error) {
e.Debug = app.IsDebug() e.Debug = app.IsDebug()
// default middlewares // default middlewares
e.Pre(middleware.RemoveTrailingSlash()) e.Pre(middleware.RemoveTrailingSlashWithConfig(middleware.RemoveTrailingSlashConfig{
Skipper: func(c echo.Context) bool {
// ignore Admin UI route(s)
return strings.HasPrefix(c.Request().URL.Path, trailedAdminPath)
},
}))
e.Use(middleware.Recover()) e.Use(middleware.Recover())
e.Use(middleware.Secure()) e.Use(middleware.Secure())
e.Use(LoadAuthContext(app)) e.Use(LoadAuthContext(app))
@@ -68,7 +75,7 @@ func InitApi(app core.App) (*echo.Echo, error) {
// truly rare case; eg. client already disconnected // truly rare case; eg. client already disconnected
if cErr != nil && app.IsDebug() { if cErr != nil && app.IsDebug() {
log.Println(err) log.Println(cErr)
} }
} }
@@ -128,21 +135,20 @@ func StaticDirectoryHandler(fileSystem fs.FS, disablePathUnescaping bool) echo.H
// bindStaticAdminUI registers the endpoints that serves the static admin UI. // bindStaticAdminUI registers the endpoints that serves the static admin UI.
func bindStaticAdminUI(app core.App, e *echo.Echo) error { func bindStaticAdminUI(app core.App, e *echo.Echo) error {
// serves /ui/dist/index.html file // redirect to trailing slash to ensure that relative urls will still work properly
// (explicit route is used to avoid conflicts with `RemoveTrailingSlash` middleware) e.GET(
e.FileFS( strings.TrimRight(trailedAdminPath, "/"),
"/_", func(c echo.Context) error {
"index.html", return c.Redirect(http.StatusTemporaryRedirect, trailedAdminPath)
ui.DistIndexHTML, },
middleware.Gzip(),
installerRedirect(app),
) )
// serves static files from the /ui/dist directory // serves static files from the /ui/dist directory
// (similar to echo.StaticFS but with gzip middleware enabled) // (similar to echo.StaticFS but with gzip middleware enabled)
e.GET( e.GET(
"/_/*", trailedAdminPath+"*",
StaticDirectoryHandler(ui.DistDirFS, false), echo.StaticDirectoryHandler(ui.DistDirFS, false),
installerRedirect(app),
middleware.Gzip(), middleware.Gzip(),
) )
@@ -175,6 +181,12 @@ func installerRedirect(app core.App) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc { return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {
// skip redirect checks for non-root level index.html requests
path := c.Request().URL.Path
if path != trailedAdminPath && path != trailedAdminPath+"index.html" {
return next(c)
}
// load into cache (if not already) // load into cache (if not already)
if !app.Cache().Has(totalAdminsCacheKey) { if !app.Cache().Has(totalAdminsCacheKey) {
if err := updateTotalAdminsCache(app); err != nil { if err := updateTotalAdminsCache(app); err != nil {
@@ -188,12 +200,12 @@ func installerRedirect(app core.App) echo.MiddlewareFunc {
if totalAdmins == 0 && !hasInstallerParam { if totalAdmins == 0 && !hasInstallerParam {
// redirect to the installer page // redirect to the installer page
return c.Redirect(http.StatusTemporaryRedirect, "/_/?installer#") return c.Redirect(http.StatusTemporaryRedirect, trailedAdminPath+"?installer#")
} }
if totalAdmins != 0 && hasInstallerParam { if totalAdmins != 0 && hasInstallerParam {
// redirect to the home page // redirect to the home page
return c.Redirect(http.StatusTemporaryRedirect, "/_/#/") return c.Redirect(http.StatusTemporaryRedirect, trailedAdminPath+"#/")
} }
return next(c) return next(c)
+59 -39
View File
@@ -1,8 +1,6 @@
package apis package apis
import ( import (
"errors"
"log"
"net/http" "net/http"
"github.com/labstack/echo/v5" "github.com/labstack/echo/v5"
@@ -23,6 +21,7 @@ func BindCollectionApi(app core.App, rg *echo.Group) {
subGroup.GET("/:collection", api.view) subGroup.GET("/:collection", api.view)
subGroup.PATCH("/:collection", api.update) subGroup.PATCH("/:collection", api.update)
subGroup.DELETE("/:collection", api.delete) subGroup.DELETE("/:collection", api.delete)
subGroup.PUT("/import", api.bulkImport)
} }
type collectionApi struct { type collectionApi struct {
@@ -76,9 +75,9 @@ func (api *collectionApi) create(c echo.Context) error {
form := forms.NewCollectionUpsert(api.app, collection) form := forms.NewCollectionUpsert(api.app, collection)
// read // load request
if err := c.Bind(form); err != nil { if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("Failed to read the submitted data due to invalid formatting.", err) return rest.NewBadRequestError("Failed to load the submitted data due to invalid formatting.", err)
} }
event := &core.CollectionCreateEvent{ event := &core.CollectionCreateEvent{
@@ -86,20 +85,24 @@ func (api *collectionApi) create(c echo.Context) error {
Collection: collection, Collection: collection,
} }
handlerErr := api.app.OnCollectionBeforeCreateRequest().Trigger(event, func(e *core.CollectionCreateEvent) error { // create the collection
// submit submitErr := form.Submit(func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
if err := form.Submit(); err != nil { return func() error {
return rest.NewBadRequestError("Failed to create the collection.", err) return api.app.OnCollectionBeforeCreateRequest().Trigger(event, func(e *core.CollectionCreateEvent) error {
} if err := next(); err != nil {
return rest.NewBadRequestError("Failed to create the collection.", err)
}
return e.HttpContext.JSON(http.StatusOK, e.Collection) return e.HttpContext.JSON(http.StatusOK, e.Collection)
})
}
}) })
if handlerErr == nil { if submitErr == nil {
api.app.OnCollectionAfterCreateRequest().Trigger(event) api.app.OnCollectionAfterCreateRequest().Trigger(event)
} }
return handlerErr return submitErr
} }
func (api *collectionApi) update(c echo.Context) error { func (api *collectionApi) update(c echo.Context) error {
@@ -110,9 +113,9 @@ func (api *collectionApi) update(c echo.Context) error {
form := forms.NewCollectionUpsert(api.app, collection) form := forms.NewCollectionUpsert(api.app, collection)
// read // load request
if err := c.Bind(form); err != nil { if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("Failed to read the submitted data due to invalid formatting.", err) return rest.NewBadRequestError("Failed to load the submitted data due to invalid formatting.", err)
} }
event := &core.CollectionUpdateEvent{ event := &core.CollectionUpdateEvent{
@@ -120,20 +123,24 @@ func (api *collectionApi) update(c echo.Context) error {
Collection: collection, Collection: collection,
} }
handlerErr := api.app.OnCollectionBeforeUpdateRequest().Trigger(event, func(e *core.CollectionUpdateEvent) error { // update the collection
// submit submitErr := form.Submit(func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
if err := form.Submit(); err != nil { return func() error {
return rest.NewBadRequestError("Failed to update the collection.", err) return api.app.OnCollectionBeforeUpdateRequest().Trigger(event, func(e *core.CollectionUpdateEvent) error {
} if err := next(); err != nil {
return rest.NewBadRequestError("Failed to update the collection.", err)
}
return e.HttpContext.JSON(http.StatusOK, e.Collection) return e.HttpContext.JSON(http.StatusOK, e.Collection)
})
}
}) })
if handlerErr == nil { if submitErr == nil {
api.app.OnCollectionAfterUpdateRequest().Trigger(event) api.app.OnCollectionAfterUpdateRequest().Trigger(event)
} }
return handlerErr return submitErr
} }
func (api *collectionApi) delete(c echo.Context) error { func (api *collectionApi) delete(c echo.Context) error {
@@ -152,13 +159,6 @@ func (api *collectionApi) delete(c echo.Context) error {
return rest.NewBadRequestError("Failed to delete collection. Make sure that the collection is not referenced by other collections.", err) return rest.NewBadRequestError("Failed to delete collection. Make sure that the collection is not referenced by other collections.", err)
} }
// try to delete the collection files
if err := api.deleteCollectionFiles(e.Collection); err != nil && api.app.IsDebug() {
// non critical error - only log for debug
// (usually could happen because of S3 api limits)
log.Println(err)
}
return e.HttpContext.NoContent(http.StatusNoContent) return e.HttpContext.NoContent(http.StatusNoContent)
}) })
@@ -169,17 +169,37 @@ func (api *collectionApi) delete(c echo.Context) error {
return handlerErr return handlerErr
} }
func (api *collectionApi) deleteCollectionFiles(collection *models.Collection) error { func (api *collectionApi) bulkImport(c echo.Context) error {
fs, err := api.app.NewFilesystem() form := forms.NewCollectionsImport(api.app)
if err != nil {
return err
}
defer fs.Close()
failed := fs.DeletePrefix(collection.BaseFilesPath()) // load request data
if len(failed) > 0 { if err := c.Bind(form); err != nil {
return errors.New("Failed to delete all record files.") return rest.NewBadRequestError("Failed to load the submitted data due to invalid formatting.", err)
} }
return nil event := &core.CollectionsImportEvent{
HttpContext: c,
Collections: form.Collections,
}
// import collections
submitErr := form.Submit(func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
return api.app.OnCollectionsBeforeImportRequest().Trigger(event, func(e *core.CollectionsImportEvent) error {
form.Collections = e.Collections // ensures that the form always has the latest changes
if err := next(); err != nil {
return rest.NewBadRequestError("Failed to import the submitted collections.", err)
}
return e.HttpContext.NoContent(http.StatusNoContent)
})
}
})
if submitErr == nil {
api.app.OnCollectionsAfterImportRequest().Trigger(event)
}
return submitErr
} }
+265 -9
View File
@@ -5,6 +5,8 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/labstack/echo/v5"
"github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/tests" "github.com/pocketbase/pocketbase/tests"
) )
@@ -297,9 +299,6 @@ func TestCollectionCreate(t *testing.T) {
`"name":{"code":"validation_required"`, `"name":{"code":"validation_required"`,
`"schema":{"code":"validation_required"`, `"schema":{"code":"validation_required"`,
}, },
ExpectedEvents: map[string]int{
"OnCollectionBeforeCreateRequest": 1,
},
}, },
{ {
Name: "authorized as admin + invalid data (eg. existing name)", Name: "authorized as admin + invalid data (eg. existing name)",
@@ -315,9 +314,6 @@ func TestCollectionCreate(t *testing.T) {
`"name":{"code":"validation_collection_name_exists"`, `"name":{"code":"validation_collection_name_exists"`,
`"schema":{"0":{"name":{"code":"validation_required"`, `"schema":{"0":{"name":{"code":"validation_required"`,
}, },
ExpectedEvents: map[string]int{
"OnCollectionBeforeCreateRequest": 1,
},
}, },
{ {
Name: "authorized as admin + valid data", Name: "authorized as admin + valid data",
@@ -399,9 +395,6 @@ func TestCollectionUpdate(t *testing.T) {
`"data":{`, `"data":{`,
`"name":{"code":"validation_collection_name_exists"`, `"name":{"code":"validation_collection_name_exists"`,
}, },
ExpectedEvents: map[string]int{
"OnCollectionBeforeUpdateRequest": 1,
},
}, },
{ {
Name: "authorized as admin + valid data", Name: "authorized as admin + valid data",
@@ -449,3 +442,266 @@ func TestCollectionUpdate(t *testing.T) {
scenario.Test(t) scenario.Test(t)
} }
} }
func TestCollectionImport(t *testing.T) {
scenarios := []tests.ApiScenario{
{
Name: "unauthorized",
Method: http.MethodPut,
Url: "/api/collections/import",
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
},
{
Name: "authorized as user",
Method: http.MethodPut,
Url: "/api/collections/import",
RequestHeaders: map[string]string{
"Authorization": "User eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjRkMDE5N2NjLTJiNGEtM2Y4My1hMjZiLWQ3N2JjODQyM2QzYyIsInR5cGUiOiJ1c2VyIiwiZXhwIjoxODkzNDc0MDAwfQ.Wq5ac1q1f5WntIzEngXk22ydMj-eFgvfSRg7dhmPKic",
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
},
{
Name: "authorized as admin + empty collections",
Method: http.MethodPut,
Url: "/api/collections/import",
Body: strings.NewReader(`{"collections":[]}`),
RequestHeaders: map[string]string{
"Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"collections":{"code":"validation_required"`,
},
AfterFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) {
collections := []*models.Collection{}
if err := app.Dao().CollectionQuery().All(&collections); err != nil {
t.Fatal(err)
}
if len(collections) != 5 {
t.Fatalf("Expected %d collections, got %d", 5, len(collections))
}
},
},
{
Name: "authorized as admin + trying to delete system collections",
Method: http.MethodPut,
Url: "/api/collections/import",
Body: strings.NewReader(`{"deleteMissing": true, "collections":[{"name": "test123"}]}`),
RequestHeaders: map[string]string{
"Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"collections":{"code":"collections_import_failure"`,
},
ExpectedEvents: map[string]int{
"OnCollectionsBeforeImportRequest": 1,
},
AfterFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) {
collections := []*models.Collection{}
if err := app.Dao().CollectionQuery().All(&collections); err != nil {
t.Fatal(err)
}
if len(collections) != 5 {
t.Fatalf("Expected %d collections, got %d", 5, len(collections))
}
},
},
{
Name: "authorized as admin + collections validator failure",
Method: http.MethodPut,
Url: "/api/collections/import",
Body: strings.NewReader(`{
"collections":[
{
"name": "import1",
"schema": [
{
"id": "koih1lqx",
"name": "test",
"type": "text"
}
]
},
{"name": "import2"}
]
}`),
RequestHeaders: map[string]string{
"Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"collections":{"code":"collections_import_failure"`,
},
ExpectedEvents: map[string]int{
"OnCollectionsBeforeImportRequest": 1,
"OnModelBeforeCreate": 2,
},
AfterFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) {
collections := []*models.Collection{}
if err := app.Dao().CollectionQuery().All(&collections); err != nil {
t.Fatal(err)
}
if len(collections) != 5 {
t.Fatalf("Expected %d collections, got %d", 5, len(collections))
}
},
},
{
Name: "authorized as admin + successful collections save",
Method: http.MethodPut,
Url: "/api/collections/import",
Body: strings.NewReader(`{
"collections":[
{
"name": "import1",
"schema": [
{
"id": "koih1lqx",
"name": "test",
"type": "text"
}
]
},
{
"name": "import2",
"schema": [
{
"id": "koih1lqx",
"name": "test",
"type": "text"
}
]
}
]
}`),
RequestHeaders: map[string]string{
"Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo",
},
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"OnCollectionsBeforeImportRequest": 1,
"OnCollectionsAfterImportRequest": 1,
"OnModelBeforeCreate": 2,
"OnModelAfterCreate": 2,
},
AfterFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) {
collections := []*models.Collection{}
if err := app.Dao().CollectionQuery().All(&collections); err != nil {
t.Fatal(err)
}
if len(collections) != 7 {
t.Fatalf("Expected %d collections, got %d", 7, len(collections))
}
},
},
{
Name: "authorized as admin + successful collections save and old non-system collections deletion",
Method: http.MethodPut,
Url: "/api/collections/import",
Body: strings.NewReader(`{
"deleteMissing": true,
"collections":[
{
"id":"abe78266-fd4d-4aea-962d-8c0138ac522b",
"name":"profiles",
"system":true,
"listRule":"userId = @request.user.id",
"viewRule":"created > 'test_change'",
"createRule":"userId = @request.user.id",
"updateRule":"userId = @request.user.id",
"deleteRule":"userId = @request.user.id",
"schema":[
{
"id":"koih1lqx",
"name":"userId",
"type":"user",
"system":true,
"required":true,
"unique":true,
"options":{
"maxSelect":1,
"cascadeDelete":true
}
},
{
"id":"69ycbg3q",
"name":"rel",
"type":"relation",
"system":false,
"required":false,
"unique":false,
"options":{
"maxSelect":2,
"collectionId":"abe78266-fd4d-4aea-962d-8c0138ac522b",
"cascadeDelete":false
}
}
]
},
{
"id":"3f2888f8-075d-49fe-9d09-ea7e951000dc",
"name":"demo",
"schema":[
{
"id":"_2hlxbmp",
"name":"title",
"type":"text",
"system":false,
"required":true,
"unique":false,
"options":{
"min":3,
"max":null,
"pattern":""
}
}
]
},
{
"name": "new_import",
"schema": [
{
"id": "koih1lqx",
"name": "test",
"type": "text"
}
]
}
]
}`),
RequestHeaders: map[string]string{
"Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo",
},
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"OnCollectionsAfterImportRequest": 1,
"OnCollectionsBeforeImportRequest": 1,
"OnModelBeforeDelete": 3,
"OnModelAfterDelete": 3,
"OnModelBeforeUpdate": 2,
"OnModelAfterUpdate": 2,
"OnModelBeforeCreate": 1,
"OnModelAfterCreate": 1,
},
AfterFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) {
collections := []*models.Collection{}
if err := app.Dao().CollectionQuery().All(&collections); err != nil {
t.Fatal(err)
}
if len(collections) != 3 {
t.Fatalf("Expected %d collections, got %d", 3, len(collections))
}
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
+1 -1
View File
@@ -78,7 +78,7 @@ func (api *fileApi) download(c echo.Context) error {
// - if exists - compare last modified dates to determine whether the thumb should be recreated // - if exists - compare last modified dates to determine whether the thumb should be recreated
tAttrs, tAttrsErr := fs.Attributes(servedPath) tAttrs, tAttrsErr := fs.Attributes(servedPath)
if tAttrsErr != nil || oAttrs.ModTime.After(tAttrs.ModTime) { if tAttrsErr != nil || oAttrs.ModTime.After(tAttrs.ModTime) {
if err := fs.CreateThumb(originalPath, servedPath, thumbSize, false); err != nil { if err := fs.CreateThumb(originalPath, servedPath, thumbSize); err != nil {
servedPath = originalPath // fallback to the original servedPath = originalPath // fallback to the original
} }
} }
+85 -5
View File
@@ -16,7 +16,12 @@ func TestFileDownload(t *testing.T) {
dataDirRelPath := "../tests/data/" dataDirRelPath := "../tests/data/"
testFilePath := filepath.Join(path.Dir(currentFile), dataDirRelPath, "storage/3f2888f8-075d-49fe-9d09-ea7e951000dc/848a1dea-5ddd-42d6-a00d-030547bffcfe/8fe61d65-6a2e-4f11-87b3-d8a3170bfd4f.txt") testFilePath := filepath.Join(path.Dir(currentFile), dataDirRelPath, "storage/3f2888f8-075d-49fe-9d09-ea7e951000dc/848a1dea-5ddd-42d6-a00d-030547bffcfe/8fe61d65-6a2e-4f11-87b3-d8a3170bfd4f.txt")
testImgPath := filepath.Join(path.Dir(currentFile), dataDirRelPath, "storage/3f2888f8-075d-49fe-9d09-ea7e951000dc/577bd676-aacb-4072-b7da-99d00ee210a4/4881bdef-06b4-4dea-8d97-6125ad242677.png") testImgPath := filepath.Join(path.Dir(currentFile), dataDirRelPath, "storage/3f2888f8-075d-49fe-9d09-ea7e951000dc/577bd676-aacb-4072-b7da-99d00ee210a4/4881bdef-06b4-4dea-8d97-6125ad242677.png")
testThumbPath := filepath.Join(path.Dir(currentFile), dataDirRelPath, "storage/3f2888f8-075d-49fe-9d09-ea7e951000dc/577bd676-aacb-4072-b7da-99d00ee210a4/thumbs_4881bdef-06b4-4dea-8d97-6125ad242677.png/100x100_4881bdef-06b4-4dea-8d97-6125ad242677.png") testThumbCropCenterPath := filepath.Join(path.Dir(currentFile), dataDirRelPath, "storage/3f2888f8-075d-49fe-9d09-ea7e951000dc/577bd676-aacb-4072-b7da-99d00ee210a4/thumbs_4881bdef-06b4-4dea-8d97-6125ad242677.png/70x50_4881bdef-06b4-4dea-8d97-6125ad242677.png")
testThumbCropTopPath := filepath.Join(path.Dir(currentFile), dataDirRelPath, "storage/3f2888f8-075d-49fe-9d09-ea7e951000dc/577bd676-aacb-4072-b7da-99d00ee210a4/thumbs_4881bdef-06b4-4dea-8d97-6125ad242677.png/70x50t_4881bdef-06b4-4dea-8d97-6125ad242677.png")
testThumbCropBottomPath := filepath.Join(path.Dir(currentFile), dataDirRelPath, "storage/3f2888f8-075d-49fe-9d09-ea7e951000dc/577bd676-aacb-4072-b7da-99d00ee210a4/thumbs_4881bdef-06b4-4dea-8d97-6125ad242677.png/70x50b_4881bdef-06b4-4dea-8d97-6125ad242677.png")
testThumbFitPath := filepath.Join(path.Dir(currentFile), dataDirRelPath, "storage/3f2888f8-075d-49fe-9d09-ea7e951000dc/577bd676-aacb-4072-b7da-99d00ee210a4/thumbs_4881bdef-06b4-4dea-8d97-6125ad242677.png/70x50f_4881bdef-06b4-4dea-8d97-6125ad242677.png")
testThumbZeroWidthPath := filepath.Join(path.Dir(currentFile), dataDirRelPath, "storage/3f2888f8-075d-49fe-9d09-ea7e951000dc/577bd676-aacb-4072-b7da-99d00ee210a4/thumbs_4881bdef-06b4-4dea-8d97-6125ad242677.png/0x50_4881bdef-06b4-4dea-8d97-6125ad242677.png")
testThumbZeroHeightPath := filepath.Join(path.Dir(currentFile), dataDirRelPath, "storage/3f2888f8-075d-49fe-9d09-ea7e951000dc/577bd676-aacb-4072-b7da-99d00ee210a4/thumbs_4881bdef-06b4-4dea-8d97-6125ad242677.png/70x0_4881bdef-06b4-4dea-8d97-6125ad242677.png")
testFile, fileErr := os.ReadFile(testFilePath) testFile, fileErr := os.ReadFile(testFilePath)
if fileErr != nil { if fileErr != nil {
@@ -28,7 +33,32 @@ func TestFileDownload(t *testing.T) {
t.Fatal(imgErr) t.Fatal(imgErr)
} }
testThumb, thumbErr := os.ReadFile(testThumbPath) testThumbCropCenter, thumbErr := os.ReadFile(testThumbCropCenterPath)
if thumbErr != nil {
t.Fatal(thumbErr)
}
testThumbCropTop, thumbErr := os.ReadFile(testThumbCropTopPath)
if thumbErr != nil {
t.Fatal(thumbErr)
}
testThumbCropBottom, thumbErr := os.ReadFile(testThumbCropBottomPath)
if thumbErr != nil {
t.Fatal(thumbErr)
}
testThumbFit, thumbErr := os.ReadFile(testThumbFitPath)
if thumbErr != nil {
t.Fatal(thumbErr)
}
testThumbZeroWidth, thumbErr := os.ReadFile(testThumbZeroWidthPath)
if thumbErr != nil {
t.Fatal(thumbErr)
}
testThumbZeroHeight, thumbErr := os.ReadFile(testThumbZeroHeightPath)
if thumbErr != nil { if thumbErr != nil {
t.Fatal(thumbErr) t.Fatal(thumbErr)
} }
@@ -76,11 +106,61 @@ func TestFileDownload(t *testing.T) {
}, },
}, },
{ {
Name: "existing image - existing thumb", Name: "existing image - existing thumb (crop center)",
Method: http.MethodGet, Method: http.MethodGet,
Url: "/api/files/demo/577bd676-aacb-4072-b7da-99d00ee210a4/4881bdef-06b4-4dea-8d97-6125ad242677.png?thumb=100x100", Url: "/api/files/demo/577bd676-aacb-4072-b7da-99d00ee210a4/4881bdef-06b4-4dea-8d97-6125ad242677.png?thumb=70x50",
ExpectedStatus: 200, ExpectedStatus: 200,
ExpectedContent: []string{string(testThumb)}, ExpectedContent: []string{string(testThumbCropCenter)},
ExpectedEvents: map[string]int{
"OnFileDownloadRequest": 1,
},
},
{
Name: "existing image - existing thumb (crop top)",
Method: http.MethodGet,
Url: "/api/files/demo/577bd676-aacb-4072-b7da-99d00ee210a4/4881bdef-06b4-4dea-8d97-6125ad242677.png?thumb=70x50t",
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbCropTop)},
ExpectedEvents: map[string]int{
"OnFileDownloadRequest": 1,
},
},
{
Name: "existing image - existing thumb (crop bottom)",
Method: http.MethodGet,
Url: "/api/files/demo/577bd676-aacb-4072-b7da-99d00ee210a4/4881bdef-06b4-4dea-8d97-6125ad242677.png?thumb=70x50b",
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbCropBottom)},
ExpectedEvents: map[string]int{
"OnFileDownloadRequest": 1,
},
},
{
Name: "existing image - existing thumb (fit)",
Method: http.MethodGet,
Url: "/api/files/demo/577bd676-aacb-4072-b7da-99d00ee210a4/4881bdef-06b4-4dea-8d97-6125ad242677.png?thumb=70x50f",
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbFit)},
ExpectedEvents: map[string]int{
"OnFileDownloadRequest": 1,
},
},
{
Name: "existing image - existing thumb (zero width)",
Method: http.MethodGet,
Url: "/api/files/demo/577bd676-aacb-4072-b7da-99d00ee210a4/4881bdef-06b4-4dea-8d97-6125ad242677.png?thumb=0x50",
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbZeroWidth)},
ExpectedEvents: map[string]int{
"OnFileDownloadRequest": 1,
},
},
{
Name: "existing image - existing thumb (zero height)",
Method: http.MethodGet,
Url: "/api/files/demo/577bd676-aacb-4072-b7da-99d00ee210a4/4881bdef-06b4-4dea-8d97-6125ad242677.png?thumb=70x0",
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbZeroHeight)},
ExpectedEvents: map[string]int{ ExpectedEvents: map[string]int{
"OnFileDownloadRequest": 1, "OnFileDownloadRequest": 1,
}, },
+1 -1
View File
@@ -28,7 +28,7 @@ type logsApi struct {
var requestFilterFields = []string{ var requestFilterFields = []string{
"rowid", "id", "created", "updated", "rowid", "id", "created", "updated",
"url", "method", "status", "auth", "url", "method", "status", "auth",
"ip", "referer", "userAgent", "remoteIp", "userIp", "referer", "userAgent",
} }
func (api *logsApi) requestsList(c echo.Context) error { func (api *logsApi) requestsList(c echo.Context) error {
+32 -2
View File
@@ -3,6 +3,7 @@ package apis
import ( import (
"fmt" "fmt"
"log" "log"
"net"
"net/http" "net/http"
"strings" "strings"
"time" "time"
@@ -77,7 +78,7 @@ func RequireAdminAuth() echo.MiddlewareFunc {
} }
} }
// RequireAdminAuthIfAny middleware requires a request to have // RequireAdminAuthOnlyIfAny middleware requires a request to have
// a valid admin Authorization header set (aka. `Authorization: Admin ...`) // a valid admin Authorization header set (aka. `Authorization: Admin ...`)
// ONLY if the application has at least 1 existing Admin model. // ONLY if the application has at least 1 existing Admin model.
func RequireAdminAuthOnlyIfAny(app core.App) echo.MiddlewareFunc { func RequireAdminAuthOnlyIfAny(app core.App) echo.MiddlewareFunc {
@@ -247,12 +248,15 @@ func ActivityLogger(app core.App) echo.MiddlewareFunc {
requestAuth = models.RequestAuthAdmin requestAuth = models.RequestAuthAdmin
} }
ip, _, _ := net.SplitHostPort(httpRequest.RemoteAddr)
model := &models.Request{ model := &models.Request{
Url: httpRequest.URL.RequestURI(), Url: httpRequest.URL.RequestURI(),
Method: strings.ToLower(httpRequest.Method), Method: strings.ToLower(httpRequest.Method),
Status: status, Status: status,
Auth: requestAuth, Auth: requestAuth,
Ip: httpRequest.RemoteAddr, UserIp: realUserIp(httpRequest, ip),
RemoteIp: ip,
Referer: httpRequest.Referer(), Referer: httpRequest.Referer(),
UserAgent: httpRequest.UserAgent(), UserAgent: httpRequest.UserAgent(),
Meta: meta, Meta: meta,
@@ -297,3 +301,29 @@ func ActivityLogger(app core.App) echo.MiddlewareFunc {
} }
} }
} }
// Returns the "real" user IP from common proxy headers (or fallbackIp if none is found).
//
// The returned IP value shouldn't be trusted if not behind a trusted reverse proxy!
func realUserIp(r *http.Request, fallbackIp string) string {
if ip := r.Header.Get("CF-Connecting-IP"); ip != "" {
return ip
}
if ip := r.Header.Get("X-Real-IP"); ip != "" {
return ip
}
if ipsList := r.Header.Get("X-Forwarded-For"); ipsList != "" {
ips := strings.Split(ipsList, ",")
// extract the rightmost ip
for i := len(ips) - 1; i >= 0; i-- {
ip := strings.TrimSpace(ips[i])
if ip != "" {
return ip
}
}
}
return fallbackIp
}
+36 -21
View File
@@ -58,6 +58,10 @@ func (api *realtimeApi) connect(c echo.Context) error {
return err return err
} }
if api.app.IsDebug() {
log.Printf("Realtime connection establisehd: %s\n", client.Id())
}
// signalize established connection (aka. fire "connect" message) // signalize established connection (aka. fire "connect" message)
fmt.Fprint(c.Response(), "id:"+client.Id()+"\n") fmt.Fprint(c.Response(), "id:"+client.Id()+"\n")
fmt.Fprint(c.Response(), "event:PB_CONNECT\n") fmt.Fprint(c.Response(), "event:PB_CONNECT\n")
@@ -159,8 +163,8 @@ func (api *realtimeApi) bindEvents() {
adminTable := (&models.Admin{}).TableName() adminTable := (&models.Admin{}).TableName()
// update user/admin auth state // update user/admin auth state
api.app.OnModelAfterUpdate().Add(func(data *core.ModelEvent) error { api.app.OnModelAfterUpdate().Add(func(e *core.ModelEvent) error {
modelTable := data.Model.TableName() modelTable := e.Model.TableName()
var contextKey string var contextKey string
switch modelTable { switch modelTable {
@@ -174,8 +178,8 @@ func (api *realtimeApi) bindEvents() {
for _, client := range api.app.SubscriptionsBroker().Clients() { for _, client := range api.app.SubscriptionsBroker().Clients() {
model, _ := client.Get(contextKey).(models.Model) model, _ := client.Get(contextKey).(models.Model)
if model != nil && model.GetId() == data.Model.GetId() { if model != nil && model.GetId() == e.Model.GetId() {
client.Set(contextKey, data.Model) client.Set(contextKey, e.Model)
} }
} }
@@ -183,8 +187,8 @@ func (api *realtimeApi) bindEvents() {
}) })
// remove user/admin client(s) // remove user/admin client(s)
api.app.OnModelAfterDelete().Add(func(data *core.ModelEvent) error { api.app.OnModelAfterDelete().Add(func(e *core.ModelEvent) error {
modelTable := data.Model.TableName() modelTable := e.Model.TableName()
var contextKey string var contextKey string
switch modelTable { switch modelTable {
@@ -198,7 +202,7 @@ func (api *realtimeApi) bindEvents() {
for _, client := range api.app.SubscriptionsBroker().Clients() { for _, client := range api.app.SubscriptionsBroker().Clients() {
model, _ := client.Get(contextKey).(models.Model) model, _ := client.Get(contextKey).(models.Model)
if model != nil && model.GetId() == data.Model.GetId() { if model != nil && model.GetId() == e.Model.GetId() {
api.app.SubscriptionsBroker().Unregister(client.Id()) api.app.SubscriptionsBroker().Unregister(client.Id())
} }
} }
@@ -206,18 +210,24 @@ func (api *realtimeApi) bindEvents() {
return nil return nil
}) })
api.app.OnRecordAfterCreateRequest().Add(func(data *core.RecordCreateEvent) error { api.app.OnModelAfterCreate().Add(func(e *core.ModelEvent) error {
api.broadcastRecord("create", data.Record) if record, ok := e.Model.(*models.Record); ok {
api.broadcastRecord("create", record)
}
return nil return nil
}) })
api.app.OnRecordAfterUpdateRequest().Add(func(data *core.RecordUpdateEvent) error { api.app.OnModelAfterUpdate().Add(func(e *core.ModelEvent) error {
api.broadcastRecord("update", data.Record) if record, ok := e.Model.(*models.Record); ok {
api.broadcastRecord("update", record)
}
return nil return nil
}) })
api.app.OnRecordAfterDeleteRequest().Add(func(data *core.RecordDeleteEvent) error { api.app.OnModelBeforeDelete().Add(func(e *core.ModelEvent) error {
api.broadcastRecord("delete", data.Record) if record, ok := e.Model.(*models.Record); ok {
api.broadcastRecord("delete", record)
}
return nil return nil
}) })
} }
@@ -286,19 +296,24 @@ func (api *realtimeApi) broadcastRecord(action string, record *models.Record) er
return nil // no subscribers return nil // no subscribers
} }
// remove the expand from the broadcasted record because we don't
// know if the clients have access to view the expanded records
cleanRecord := *record
cleanRecord.SetExpand(nil)
subscriptionRuleMap := map[string]*string{ subscriptionRuleMap := map[string]*string{
(collection.Name + "/" + record.Id): collection.ViewRule, (collection.Name + "/" + cleanRecord.Id): collection.ViewRule,
(collection.Id + "/" + record.Id): collection.ViewRule, (collection.Id + "/" + cleanRecord.Id): collection.ViewRule,
collection.Name: collection.ListRule, collection.Name: collection.ListRule,
collection.Id: collection.ListRule, collection.Id: collection.ListRule,
} }
recordData := &recordData{ data := &recordData{
Action: action, Action: action,
Record: record, Record: &cleanRecord,
} }
serializedData, err := json.Marshal(recordData) serializedData, err := json.Marshal(data)
if err != nil { if err != nil {
if api.app.IsDebug() { if api.app.IsDebug() {
log.Println(err) log.Println(err)
@@ -312,7 +327,7 @@ func (api *realtimeApi) broadcastRecord(action string, record *models.Record) er
continue continue
} }
if !api.canAccessRecord(client, record, rule) { if !api.canAccessRecord(client, data.Record, rule) {
continue continue
} }
+82 -60
View File
@@ -52,10 +52,9 @@ func (api *recordApi) list(c echo.Context) error {
return rest.NewForbiddenError("Only admins can perform this action.", nil) return rest.NewForbiddenError("Only admins can perform this action.", nil)
} }
// forbid user/guest defined non-relational joins (aka. @collection.*) // forbid users and guests to query special filter/sort fields
queryStr := c.QueryString() if err := api.checkForForbiddenQueryFields(c); err != nil {
if admin == nil && queryStr != "" && (strings.Contains(queryStr, "@collection") || strings.Contains(queryStr, "%40collection")) { return err
return rest.NewForbiddenError("Only admins can filter by @collection.", nil)
} }
requestData := api.exportRequestData(c) requestData := api.exportRequestData(c)
@@ -63,14 +62,15 @@ func (api *recordApi) list(c echo.Context) error {
fieldsResolver := resolvers.NewRecordFieldResolver(api.app.Dao(), collection, requestData) fieldsResolver := resolvers.NewRecordFieldResolver(api.app.Dao(), collection, requestData)
searchProvider := search.NewProvider(fieldsResolver). searchProvider := search.NewProvider(fieldsResolver).
Query(api.app.Dao().RecordQuery(collection)) Query(api.app.Dao().RecordQuery(collection)).
CountColumn(fmt.Sprintf("%s.id", api.app.Dao().DB().QuoteSimpleColumnName(collection.Name)))
if admin == nil && collection.ListRule != nil { if admin == nil && collection.ListRule != nil {
searchProvider.AddFilter(search.FilterData(*collection.ListRule)) searchProvider.AddFilter(search.FilterData(*collection.ListRule))
} }
var rawRecords = []dbx.NullStringMap{} var rawRecords = []dbx.NullStringMap{}
result, err := searchProvider.ParseAndExec(queryStr, &rawRecords) result, err := searchProvider.ParseAndExec(c.QueryString(), &rawRecords)
if err != nil { if err != nil {
return rest.NewBadRequestError("Invalid filter parameters.", err) return rest.NewBadRequestError("Invalid filter parameters.", err)
} }
@@ -80,13 +80,13 @@ func (api *recordApi) list(c echo.Context) error {
// expand records relations // expand records relations
expands := strings.Split(c.QueryParam(expandQueryParam), ",") expands := strings.Split(c.QueryParam(expandQueryParam), ",")
if len(expands) > 0 { if len(expands) > 0 {
expandErr := api.app.Dao().ExpandRecords( failed := api.app.Dao().ExpandRecords(
records, records,
expands, expands,
api.expandFunc(c, requestData), api.expandFunc(c, requestData),
) )
if expandErr != nil && api.app.IsDebug() { if len(failed) > 0 && api.app.IsDebug() {
log.Println("Failed to expand relations: ", expandErr) log.Println("Failed to expand relations: ", failed)
} }
} }
@@ -141,16 +141,14 @@ func (api *recordApi) view(c echo.Context) error {
return rest.NewNotFoundError("", fetchErr) return rest.NewNotFoundError("", fetchErr)
} }
expands := strings.Split(c.QueryParam(expandQueryParam), ",") // expand record relations
if len(expands) > 0 { failed := api.app.Dao().ExpandRecord(
expandErr := api.app.Dao().ExpandRecord( record,
record, strings.Split(c.QueryParam(expandQueryParam), ","),
expands, api.expandFunc(c, requestData),
api.expandFunc(c, requestData), )
) if len(failed) > 0 && api.app.IsDebug() {
if expandErr != nil && api.app.IsDebug() { log.Println("Failed to expand relations: ", failed)
log.Println("Failed to expand relations: ", expandErr)
}
} }
event := &core.RecordViewEvent{ event := &core.RecordViewEvent{
@@ -193,7 +191,7 @@ func (api *recordApi) create(c echo.Context) error {
testRecord := models.NewRecord(collection) testRecord := models.NewRecord(collection)
testForm := forms.NewRecordUpsert(api.app, testRecord) testForm := forms.NewRecordUpsert(api.app, testRecord)
if err := testForm.LoadData(c.Request()); err != nil { if err := testForm.LoadData(c.Request()); err != nil {
return rest.NewBadRequestError("Failed to read the submitted data due to invalid formatting.", err) return rest.NewBadRequestError("Failed to load the submitted data due to invalid formatting.", err)
} }
testErr := testForm.DrySubmit(func(txDao *daos.Dao) error { testErr := testForm.DrySubmit(func(txDao *daos.Dao) error {
@@ -210,7 +208,7 @@ func (api *recordApi) create(c echo.Context) error {
// load request // load request
if err := form.LoadData(c.Request()); err != nil { if err := form.LoadData(c.Request()); err != nil {
return rest.NewBadRequestError("Failed to read the submitted data due to invalid formatting.", err) return rest.NewBadRequestError("Failed to load the submitted data due to invalid formatting.", err)
} }
event := &core.RecordCreateEvent{ event := &core.RecordCreateEvent{
@@ -218,20 +216,34 @@ func (api *recordApi) create(c echo.Context) error {
Record: record, Record: record,
} }
handlerErr := api.app.OnRecordBeforeCreateRequest().Trigger(event, func(e *core.RecordCreateEvent) error { // create the record
// create the record submitErr := form.Submit(func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
if err := form.Submit(); err != nil { return func() error {
return rest.NewBadRequestError("Failed to create record.", err) return api.app.OnRecordBeforeCreateRequest().Trigger(event, func(e *core.RecordCreateEvent) error {
} if err := next(); err != nil {
return rest.NewBadRequestError("Failed to create record.", err)
}
return e.HttpContext.JSON(http.StatusOK, e.Record) // expand record relations
failed := api.app.Dao().ExpandRecord(
e.Record,
strings.Split(e.HttpContext.QueryParam(expandQueryParam), ","),
api.expandFunc(e.HttpContext, requestData),
)
if len(failed) > 0 && api.app.IsDebug() {
log.Println("Failed to expand relations: ", failed)
}
return e.HttpContext.JSON(http.StatusOK, e.Record)
})
}
}) })
if handlerErr == nil { if submitErr == nil {
api.app.OnRecordAfterCreateRequest().Trigger(event) api.app.OnRecordAfterCreateRequest().Trigger(event)
} }
return handlerErr return submitErr
} }
func (api *recordApi) update(c echo.Context) error { func (api *recordApi) update(c echo.Context) error {
@@ -276,7 +288,7 @@ func (api *recordApi) update(c echo.Context) error {
// load request // load request
if err := form.LoadData(c.Request()); err != nil { if err := form.LoadData(c.Request()); err != nil {
return rest.NewBadRequestError("Failed to read the submitted data due to invalid formatting.", err) return rest.NewBadRequestError("Failed to load the submitted data due to invalid formatting.", err)
} }
event := &core.RecordUpdateEvent{ event := &core.RecordUpdateEvent{
@@ -284,20 +296,34 @@ func (api *recordApi) update(c echo.Context) error {
Record: record, Record: record,
} }
handlerErr := api.app.OnRecordBeforeUpdateRequest().Trigger(event, func(e *core.RecordUpdateEvent) error { // update the record
// update the record submitErr := form.Submit(func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
if err := form.Submit(); err != nil { return func() error {
return rest.NewBadRequestError("Failed to update record.", err) return api.app.OnRecordBeforeUpdateRequest().Trigger(event, func(e *core.RecordUpdateEvent) error {
} if err := next(); err != nil {
return rest.NewBadRequestError("Failed to update record.", err)
}
return e.HttpContext.JSON(http.StatusOK, e.Record) // expand record relations
failed := api.app.Dao().ExpandRecord(
e.Record,
strings.Split(e.HttpContext.QueryParam(expandQueryParam), ","),
api.expandFunc(e.HttpContext, requestData),
)
if len(failed) > 0 && api.app.IsDebug() {
log.Println("Failed to expand relations: ", failed)
}
return e.HttpContext.JSON(http.StatusOK, e.Record)
})
}
}) })
if handlerErr == nil { if submitErr == nil {
api.app.OnRecordAfterUpdateRequest().Trigger(event) api.app.OnRecordAfterUpdateRequest().Trigger(event)
} }
return handlerErr return submitErr
} }
func (api *recordApi) delete(c echo.Context) error { func (api *recordApi) delete(c echo.Context) error {
@@ -348,13 +374,6 @@ func (api *recordApi) delete(c echo.Context) error {
return rest.NewBadRequestError("Failed to delete record. Make sure that the record is not part of a required relation reference.", err) return rest.NewBadRequestError("Failed to delete record. Make sure that the record is not part of a required relation reference.", err)
} }
// try to delete the record files
if err := api.deleteRecordFiles(e.Record); err != nil && api.app.IsDebug() {
// non critical error - only log for debug
// (usually could happen due to S3 api limits)
log.Println(err)
}
return e.HttpContext.NoContent(http.StatusNoContent) return e.HttpContext.NoContent(http.StatusNoContent)
}) })
@@ -365,21 +384,6 @@ func (api *recordApi) delete(c echo.Context) error {
return handlerErr return handlerErr
} }
func (api *recordApi) deleteRecordFiles(record *models.Record) error {
fs, err := api.app.NewFilesystem()
if err != nil {
return err
}
defer fs.Close()
failed := fs.DeletePrefix(record.BaseFilesPath())
if len(failed) > 0 {
return fmt.Errorf("Failed to delete %d record files.", len(failed))
}
return nil
}
func (api *recordApi) exportRequestData(c echo.Context) map[string]any { func (api *recordApi) exportRequestData(c echo.Context) map[string]any {
result := map[string]any{} result := map[string]any{}
queryParams := map[string]any{} queryParams := map[string]any{}
@@ -403,6 +407,24 @@ func (api *recordApi) exportRequestData(c echo.Context) map[string]any {
return result return result
} }
func (api *recordApi) checkForForbiddenQueryFields(c echo.Context) error {
admin, _ := c.Get(ContextAdminKey).(*models.Admin)
if admin != nil {
return nil // admins are allowed to query everything
}
decodedQuery := c.QueryParam(search.FilterQueryParam) + c.QueryParam(search.SortQueryParam)
forbiddenFields := []string{"@collection.", "@request."}
for _, field := range forbiddenFields {
if strings.Contains(decodedQuery, field) {
return rest.NewForbiddenError("Only admins can filter by @collection and @request query params", nil)
}
}
return nil
}
func (api *recordApi) expandFunc(c echo.Context, requestData map[string]any) daos.ExpandFetchFunc { func (api *recordApi) expandFunc(c echo.Context, requestData map[string]any) daos.ExpandFetchFunc {
admin, _ := c.Get(ContextAdminKey).(*models.Admin) admin, _ := c.Get(ContextAdminKey).(*models.Admin)
+170 -32
View File
@@ -127,7 +127,7 @@ func TestRecordsList(t *testing.T) {
ExpectedContent: []string{`"data":{}`}, ExpectedContent: []string{`"data":{}`},
}, },
{ {
Name: "expand", Name: "expand relations",
Method: http.MethodGet, Method: http.MethodGet,
Url: "/api/collections/demo2/records?expand=manyrels,onerel&perPage=2&sort=created", Url: "/api/collections/demo2/records?expand=manyrels,onerel&perPage=2&sort=created",
RequestHeaders: map[string]string{ RequestHeaders: map[string]string{
@@ -139,17 +139,17 @@ func TestRecordsList(t *testing.T) {
`"perPage":2`, `"perPage":2`,
`"totalItems":2`, `"totalItems":2`,
`"items":[{`, `"items":[{`,
`"@expand":{`,
`"id":"577bd676-aacb-4072-b7da-99d00ee210a4"`, `"id":"577bd676-aacb-4072-b7da-99d00ee210a4"`,
`"id":"848a1dea-5ddd-42d6-a00d-030547bffcfe"`, `"id":"848a1dea-5ddd-42d6-a00d-030547bffcfe"`,
`"manyrels":[{`, `"manyrels":[{`,
`"manyrels":[]`, `"manyrels":[]`,
`"rel_cascade":"`, `"cascaderel":"`,
`"rel_cascade":null`,
`"onerel":{"@collectionId":"3f2888f8-075d-49fe-9d09-ea7e951000dc","@collectionName":"demo",`, `"onerel":{"@collectionId":"3f2888f8-075d-49fe-9d09-ea7e951000dc","@collectionName":"demo",`,
`"json":[1,2,3]`, `"json":[1,2,3]`,
`"select":["a","b"]`, `"select":["a","b"]`,
`"select":[]`, `"select":[]`,
`"user":null`, `"user":""`,
`"bool":true`, `"bool":true`,
`"number":456`, `"number":456`,
`"user":"97cc3d3d-6ba2-383f-b42a-7bc84d27410c"`, `"user":"97cc3d3d-6ba2-383f-b42a-7bc84d27410c"`,
@@ -357,6 +357,7 @@ func TestRecordView(t *testing.T) {
`"@collectionId":"2c1010aa-b8fe-41d9-a980-99534ca8a167"`, `"@collectionId":"2c1010aa-b8fe-41d9-a980-99534ca8a167"`,
`"@collectionName":"demo2"`, `"@collectionName":"demo2"`,
`"id":"63c2ab80-84ab-4057-a592-4604a731f78f"`, `"id":"63c2ab80-84ab-4057-a592-4604a731f78f"`,
`"@expand":{`,
`"manyrels":[{`, `"manyrels":[{`,
`"onerel":{`, `"onerel":{`,
`"@collectionId":"3f2888f8-075d-49fe-9d09-ea7e951000dc"`, `"@collectionId":"3f2888f8-075d-49fe-9d09-ea7e951000dc"`,
@@ -455,11 +456,13 @@ func TestRecordDelete(t *testing.T) {
"OnRecordAfterDeleteRequest": 1, "OnRecordAfterDeleteRequest": 1,
"OnModelAfterUpdate": 1, // nullify related record "OnModelAfterUpdate": 1, // nullify related record
"OnModelBeforeUpdate": 1, // nullify related record "OnModelBeforeUpdate": 1, // nullify related record
"OnModelBeforeDelete": 2, // +1 cascade delete related record "OnModelBeforeDelete": 3, // +2 cascade delete related records
"OnModelAfterDelete": 2, // +1 cascade delete related record "OnModelAfterDelete": 3, // +2 cascade delete related records
}, },
AfterFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) { AfterFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) {
ensureDeletedFiles(app, "3f2888f8-075d-49fe-9d09-ea7e951000dc", "577bd676-aacb-4072-b7da-99d00ee210a4") ensureDeletedFiles(app, "3f2888f8-075d-49fe-9d09-ea7e951000dc", "577bd676-aacb-4072-b7da-99d00ee210a4")
ensureDeletedFiles(app, "2c1010aa-b8fe-41d9-a980-99534ca8a167", "94568ca2-0bee-49d7-b749-06cb97956fd9")
ensureDeletedFiles(app, "2c1010aa-b8fe-41d9-a980-99534ca8a167", "63c2ab80-84ab-4057-a592-4604a731f78f")
}, },
}, },
{ {
@@ -475,11 +478,13 @@ func TestRecordDelete(t *testing.T) {
"OnRecordAfterDeleteRequest": 1, "OnRecordAfterDeleteRequest": 1,
"OnModelAfterUpdate": 1, // nullify related record "OnModelAfterUpdate": 1, // nullify related record
"OnModelBeforeUpdate": 1, // nullify related record "OnModelBeforeUpdate": 1, // nullify related record
"OnModelBeforeDelete": 2, // +1 cascade delete related record "OnModelBeforeDelete": 3, // +2 cascade delete related records
"OnModelAfterDelete": 2, // +1 cascade delete related record "OnModelAfterDelete": 3, // +2 cascade delete related records
}, },
AfterFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) { AfterFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) {
ensureDeletedFiles(app, "3f2888f8-075d-49fe-9d09-ea7e951000dc", "577bd676-aacb-4072-b7da-99d00ee210a4") ensureDeletedFiles(app, "3f2888f8-075d-49fe-9d09-ea7e951000dc", "577bd676-aacb-4072-b7da-99d00ee210a4")
ensureDeletedFiles(app, "2c1010aa-b8fe-41d9-a980-99534ca8a167", "94568ca2-0bee-49d7-b749-06cb97956fd9")
ensureDeletedFiles(app, "2c1010aa-b8fe-41d9-a980-99534ca8a167", "63c2ab80-84ab-4057-a592-4604a731f78f")
}, },
}, },
{ {
@@ -554,8 +559,8 @@ func TestRecordDelete(t *testing.T) {
"OnRecordAfterDeleteRequest": 1, "OnRecordAfterDeleteRequest": 1,
"OnModelBeforeUpdate": 1, "OnModelBeforeUpdate": 1,
"OnModelAfterUpdate": 1, "OnModelAfterUpdate": 1,
"OnModelBeforeDelete": 2, "OnModelBeforeDelete": 3,
"OnModelAfterDelete": 2, "OnModelAfterDelete": 3,
}, },
AfterFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) { AfterFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) {
recId := "63c2ab80-84ab-4057-a592-4604a731f78f" recId := "63c2ab80-84ab-4057-a592-4604a731f78f"
@@ -565,6 +570,7 @@ func TestRecordDelete(t *testing.T) {
t.Errorf("Expected record %s to be cascade deleted", recId) t.Errorf("Expected record %s to be cascade deleted", recId)
} }
ensureDeletedFiles(app, "3f2888f8-075d-49fe-9d09-ea7e951000dc", "577bd676-aacb-4072-b7da-99d00ee210a4") ensureDeletedFiles(app, "3f2888f8-075d-49fe-9d09-ea7e951000dc", "577bd676-aacb-4072-b7da-99d00ee210a4")
ensureDeletedFiles(app, "2c1010aa-b8fe-41d9-a980-99534ca8a167", "94568ca2-0bee-49d7-b749-06cb97956fd9")
ensureDeletedFiles(app, "2c1010aa-b8fe-41d9-a980-99534ca8a167", "63c2ab80-84ab-4057-a592-4604a731f78f") ensureDeletedFiles(app, "2c1010aa-b8fe-41d9-a980-99534ca8a167", "63c2ab80-84ab-4057-a592-4604a731f78f")
}, },
}, },
@@ -646,11 +652,12 @@ func TestRecordCreate(t *testing.T) {
Method: http.MethodPost, Method: http.MethodPost,
Url: "/api/collections/demo2/records", Url: "/api/collections/demo2/records",
Body: strings.NewReader(`{ Body: strings.NewReader(`{
"rel_cascade": "577bd676-aacb-4072-b7da-99d00ee210a4", "cascaderel": "577bd676-aacb-4072-b7da-99d00ee210a4",
"onerel": "577bd676-aacb-4072-b7da-99d00ee210a4", "onerel": "577bd676-aacb-4072-b7da-99d00ee210a4",
"manyrels": ["577bd676-aacb-4072-b7da-99d00ee210a4"], "manyrels": ["577bd676-aacb-4072-b7da-99d00ee210a4"],
"text": "test123", "text": "test123",
"bool": "false" "bool": "false",
"number": 1
}`), }`),
RequestHeaders: map[string]string{ RequestHeaders: map[string]string{
// test@example.com // test@example.com
@@ -660,15 +667,17 @@ func TestRecordCreate(t *testing.T) {
ExpectedContent: []string{`"data":{}`}, ExpectedContent: []string{`"data":{}`},
}, },
{ {
Name: "user submit in restricted collection (rule pass check)", Name: "user submit in restricted collection (rule pass check) + expand relations",
Method: http.MethodPost, Method: http.MethodPost,
Url: "/api/collections/demo2/records", Url: "/api/collections/demo2/records?expand=missing,onerel,manyrels,selfrel",
Body: strings.NewReader(`{ Body: strings.NewReader(`{
"rel_cascade":"577bd676-aacb-4072-b7da-99d00ee210a4", "cascaderel":"577bd676-aacb-4072-b7da-99d00ee210a4",
"onerel":"577bd676-aacb-4072-b7da-99d00ee210a4", "onerel":"577bd676-aacb-4072-b7da-99d00ee210a4",
"manyrels":["577bd676-aacb-4072-b7da-99d00ee210a4"], "manyrels":["577bd676-aacb-4072-b7da-99d00ee210a4"],
"selfrel":"63c2ab80-84ab-4057-a592-4604a731f78f",
"text":"test123", "text":"test123",
"bool":true "bool":true,
"number":1
}`), }`),
RequestHeaders: map[string]string{ RequestHeaders: map[string]string{
// test3@example.com // test3@example.com
@@ -677,11 +686,21 @@ func TestRecordCreate(t *testing.T) {
ExpectedStatus: 200, ExpectedStatus: 200,
ExpectedContent: []string{ ExpectedContent: []string{
`"id":`, `"id":`,
`"rel_cascade":"577bd676-aacb-4072-b7da-99d00ee210a4"`, `"cascaderel":"577bd676-aacb-4072-b7da-99d00ee210a4"`,
`"onerel":"577bd676-aacb-4072-b7da-99d00ee210a4"`, `"onerel":"577bd676-aacb-4072-b7da-99d00ee210a4"`,
`"manyrels":["577bd676-aacb-4072-b7da-99d00ee210a4"]`, `"manyrels":["577bd676-aacb-4072-b7da-99d00ee210a4"]`,
`"selfrel":"63c2ab80-84ab-4057-a592-4604a731f78f"`,
`"text":"test123"`, `"text":"test123"`,
`"bool":true`, `"bool":true`,
`"number":1`,
`"@expand":{`,
`"selfrel":{`,
`"id":"63c2ab80-84ab-4057-a592-4604a731f78f"`,
},
NotExpectedContent: []string{
// user don't have access to view the below expands
`"manyrels":[{`,
`"onerel":{`,
}, },
ExpectedEvents: map[string]int{ ExpectedEvents: map[string]int{
"OnRecordBeforeCreateRequest": 1, "OnRecordBeforeCreateRequest": 1,
@@ -691,15 +710,17 @@ func TestRecordCreate(t *testing.T) {
}, },
}, },
{ {
Name: "admin submit in restricted collection (rule skip check)", Name: "admin submit in restricted collection (rule skip check) + expand relations",
Method: http.MethodPost, Method: http.MethodPost,
Url: "/api/collections/demo2/records", Url: "/api/collections/demo2/records?expand=missing,onerel,manyrels,selfrel",
Body: strings.NewReader(`{ Body: strings.NewReader(`{
"rel_cascade":"577bd676-aacb-4072-b7da-99d00ee210a4", "cascaderel": "577bd676-aacb-4072-b7da-99d00ee210a4",
"onerel":"577bd676-aacb-4072-b7da-99d00ee210a4", "onerel": "577bd676-aacb-4072-b7da-99d00ee210a4",
"manyrels":["577bd676-aacb-4072-b7da-99d00ee210a4"], "manyrels":["577bd676-aacb-4072-b7da-99d00ee210a4"],
"text":"test123", "selfrel":"94568ca2-0bee-49d7-b749-06cb97956fd9",
"bool":false "text": "test123",
"bool": false,
"number": 1
}`), }`),
RequestHeaders: map[string]string{ RequestHeaders: map[string]string{
"Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo", "Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo",
@@ -707,11 +728,20 @@ func TestRecordCreate(t *testing.T) {
ExpectedStatus: 200, ExpectedStatus: 200,
ExpectedContent: []string{ ExpectedContent: []string{
`"id":`, `"id":`,
`"rel_cascade":"577bd676-aacb-4072-b7da-99d00ee210a4"`, `"cascaderel":"577bd676-aacb-4072-b7da-99d00ee210a4"`,
`"onerel":"577bd676-aacb-4072-b7da-99d00ee210a4"`, `"onerel":"577bd676-aacb-4072-b7da-99d00ee210a4"`,
`"manyrels":["577bd676-aacb-4072-b7da-99d00ee210a4"]`, `"manyrels":["577bd676-aacb-4072-b7da-99d00ee210a4"]`,
`"text":"test123"`, `"text":"test123"`,
`"bool":false`, `"bool":false`,
`"number":1`,
`"@expand":{`,
`"manyrels":[{`,
`"onerel":{`,
`"selfrel":{`,
`"@collectionId":"3f2888f8-075d-49fe-9d09-ea7e951000dc"`,
`"@collectionName":"demo"`,
`"id":"577bd676-aacb-4072-b7da-99d00ee210a4"`,
`"id":"94568ca2-0bee-49d7-b749-06cb97956fd9"`,
}, },
ExpectedEvents: map[string]int{ ExpectedEvents: map[string]int{
"OnRecordBeforeCreateRequest": 1, "OnRecordBeforeCreateRequest": 1,
@@ -720,6 +750,62 @@ func TestRecordCreate(t *testing.T) {
"OnModelAfterCreate": 1, "OnModelAfterCreate": 1,
}, },
}, },
{
Name: "invalid custom insertion id (less than 15 chars)",
Method: http.MethodPost,
Url: "/api/collections/demo3/records",
Body: strings.NewReader(`{
"id": "12345678901234",
"title": "test"
}`),
RequestHeaders: map[string]string{
"Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"id":{"code":"validation_length_invalid"`,
},
},
{
Name: "invalid custom insertion id (more than 15 chars)",
Method: http.MethodPost,
Url: "/api/collections/demo3/records",
Body: strings.NewReader(`{
"id": "1234567890123456",
"title": "test"
}`),
RequestHeaders: map[string]string{
"Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"id":{"code":"validation_length_invalid"`,
},
},
{
Name: "valid custom insertion id (exactly 15 chars)",
Method: http.MethodPost,
Url: "/api/collections/demo3/records",
Body: strings.NewReader(`{
"id": "123456789012345",
"title": "test"
}`),
RequestHeaders: map[string]string{
"Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"id":"123456789012345"`,
`"title":"test"`,
},
ExpectedEvents: map[string]int{
"OnRecordBeforeCreateRequest": 1,
"OnRecordAfterCreateRequest": 1,
"OnModelBeforeCreate": 1,
"OnModelAfterCreate": 1,
},
},
{ {
Name: "submit via multipart form data", Name: "submit via multipart form data",
Method: http.MethodPost, Method: http.MethodPost,
@@ -835,12 +921,13 @@ func TestRecordUpdate(t *testing.T) {
ExpectedContent: []string{`"data":{}`}, ExpectedContent: []string{`"data":{}`},
}, },
{ {
Name: "user submit in restricted collection (rule pass check)", Name: "user submit in restricted collection (rule pass check) + expand relations",
Method: http.MethodPatch, Method: http.MethodPatch,
Url: "/api/collections/demo2/records/63c2ab80-84ab-4057-a592-4604a731f78f", Url: "/api/collections/demo2/records/63c2ab80-84ab-4057-a592-4604a731f78f?expand=missing,onerel,manyrels,selfrel",
Body: strings.NewReader(`{ Body: strings.NewReader(`{
"text":"test_new", "text":"test_new",
"bool":false "selfrel":"63c2ab80-84ab-4057-a592-4604a731f78f",
"bool":true
}`), }`),
RequestHeaders: map[string]string{ RequestHeaders: map[string]string{
// test3@example.com // test3@example.com
@@ -849,11 +936,19 @@ func TestRecordUpdate(t *testing.T) {
ExpectedStatus: 200, ExpectedStatus: 200,
ExpectedContent: []string{ ExpectedContent: []string{
`"id":"63c2ab80-84ab-4057-a592-4604a731f78f"`, `"id":"63c2ab80-84ab-4057-a592-4604a731f78f"`,
`"rel_cascade":"577bd676-aacb-4072-b7da-99d00ee210a4"`, `"cascaderel":"577bd676-aacb-4072-b7da-99d00ee210a4"`,
`"onerel":"848a1dea-5ddd-42d6-a00d-030547bffcfe"`, `"onerel":"848a1dea-5ddd-42d6-a00d-030547bffcfe"`,
`"manyrels":["848a1dea-5ddd-42d6-a00d-030547bffcfe","577bd676-aacb-4072-b7da-99d00ee210a4"]`, `"manyrels":["848a1dea-5ddd-42d6-a00d-030547bffcfe","577bd676-aacb-4072-b7da-99d00ee210a4"]`,
`"bool":false`, `"bool":true`,
`"text":"test_new"`, `"text":"test_new"`,
`"selfrel":"63c2ab80-84ab-4057-a592-4604a731f78f"`,
`"@expand":{`,
`"selfrel":{`,
},
NotExpectedContent: []string{
// user don't have access to view the below expands
`"manyrels":[{`,
`"onerel":{`,
}, },
ExpectedEvents: map[string]int{ ExpectedEvents: map[string]int{
"OnRecordBeforeUpdateRequest": 1, "OnRecordBeforeUpdateRequest": 1,
@@ -863,11 +958,44 @@ func TestRecordUpdate(t *testing.T) {
}, },
}, },
{ {
Name: "admin submit in restricted collection (rule skip check)", Name: "user submit in restricted collection (rule pass check) + expand relations (no view rule access when bool is false)",
Method: http.MethodPatch, Method: http.MethodPatch,
Url: "/api/collections/demo2/records/63c2ab80-84ab-4057-a592-4604a731f78f", Url: "/api/collections/demo2/records/63c2ab80-84ab-4057-a592-4604a731f78f?expand=missing,onerel,manyrels,selfrel",
Body: strings.NewReader(`{ Body: strings.NewReader(`{
"text":"test_new" "selfrel":"63c2ab80-84ab-4057-a592-4604a731f78f",
"bool":false
}`),
RequestHeaders: map[string]string{
// test3@example.com
"Authorization": "User eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoidXNlciIsImVtYWlsIjoidGVzdDNAZXhhbXBsZS5jb20iLCJpZCI6Ijk3Y2MzZDNkLTZiYTItMzgzZi1iNDJhLTdiYzg0ZDI3NDEwYyIsImV4cCI6MTg5MzUxNTU3Nn0.Q965uvlTxxOsZbACXSgJQNXykYK0TKZ87nyPzemvN4E",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"id":"63c2ab80-84ab-4057-a592-4604a731f78f"`,
`"bool":false`,
`"selfrel":"63c2ab80-84ab-4057-a592-4604a731f78f"`,
},
NotExpectedContent: []string{
`"@expand":{`,
`"manyrels":[{`, // admin only
`"onerel":{`, // admin only
`"selfrel":{`, // bool=true view rule
},
ExpectedEvents: map[string]int{
"OnRecordBeforeUpdateRequest": 1,
"OnRecordAfterUpdateRequest": 1,
"OnModelBeforeUpdate": 1,
"OnModelAfterUpdate": 1,
},
},
{
Name: "admin submit in restricted collection (rule skip check) + expand relations",
Method: http.MethodPatch,
Url: "/api/collections/demo2/records/63c2ab80-84ab-4057-a592-4604a731f78f?expand=onerel,manyrels,selfrel,missing",
Body: strings.NewReader(`{
"text":"test_new",
"number":1,
"selfrel":"94568ca2-0bee-49d7-b749-06cb97956fd9"
}`), }`),
RequestHeaders: map[string]string{ RequestHeaders: map[string]string{
"Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo", "Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo",
@@ -876,6 +1004,16 @@ func TestRecordUpdate(t *testing.T) {
ExpectedContent: []string{ ExpectedContent: []string{
`"id":"63c2ab80-84ab-4057-a592-4604a731f78f"`, `"id":"63c2ab80-84ab-4057-a592-4604a731f78f"`,
`"text":"test_new"`, `"text":"test_new"`,
`"number":1`,
`"@expand":{`,
`"manyrels":[{`,
`"onerel":{`,
`"selfrel":{`,
`"@collectionId":"3f2888f8-075d-49fe-9d09-ea7e951000dc"`,
`"@collectionName":"demo"`,
`"id":"848a1dea-5ddd-42d6-a00d-030547bffcfe"`,
`"id":"577bd676-aacb-4072-b7da-99d00ee210a4"`,
`"id":"94568ca2-0bee-49d7-b749-06cb97956fd9"`,
}, },
ExpectedEvents: map[string]int{ ExpectedEvents: map[string]int{
"OnRecordBeforeUpdateRequest": 1, "OnRecordBeforeUpdateRequest": 1,
+69 -12
View File
@@ -3,10 +3,12 @@ package apis
import ( import (
"net/http" "net/http"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/labstack/echo/v5" "github.com/labstack/echo/v5"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/forms" "github.com/pocketbase/pocketbase/forms"
"github.com/pocketbase/pocketbase/tools/rest" "github.com/pocketbase/pocketbase/tools/rest"
"github.com/pocketbase/pocketbase/tools/security"
) )
// BindSettingsApi registers the settings api endpoints. // BindSettingsApi registers the settings api endpoints.
@@ -16,6 +18,8 @@ func BindSettingsApi(app core.App, rg *echo.Group) {
subGroup := rg.Group("/settings", ActivityLogger(app), RequireAdminAuth()) subGroup := rg.Group("/settings", ActivityLogger(app), RequireAdminAuth())
subGroup.GET("", api.list) subGroup.GET("", api.list)
subGroup.PATCH("", api.set) subGroup.PATCH("", api.set)
subGroup.POST("/test/s3", api.testS3)
subGroup.POST("/test/email", api.testEmail)
} }
type settingsApi struct { type settingsApi struct {
@@ -40,8 +44,10 @@ func (api *settingsApi) list(c echo.Context) error {
func (api *settingsApi) set(c echo.Context) error { func (api *settingsApi) set(c echo.Context) error {
form := forms.NewSettingsUpsert(api.app) form := forms.NewSettingsUpsert(api.app)
// load request
if err := c.Bind(form); err != nil { if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("An error occurred while reading the submitted data.", err) return rest.NewBadRequestError("An error occurred while loading the submitted data.", err)
} }
event := &core.SettingsUpdateEvent{ event := &core.SettingsUpdateEvent{
@@ -50,22 +56,73 @@ func (api *settingsApi) set(c echo.Context) error {
NewSettings: form.Settings, NewSettings: form.Settings,
} }
handlerErr := api.app.OnSettingsBeforeUpdateRequest().Trigger(event, func(e *core.SettingsUpdateEvent) error { // update the settings
if err := form.Submit(); err != nil { submitErr := form.Submit(func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return rest.NewBadRequestError("An error occurred while submitting the form.", err) return func() error {
} return api.app.OnSettingsBeforeUpdateRequest().Trigger(event, func(e *core.SettingsUpdateEvent) error {
if err := next(); err != nil {
return rest.NewBadRequestError("An error occurred while submitting the form.", err)
}
redactedSettings, err := api.app.Settings().RedactClone() redactedSettings, err := api.app.Settings().RedactClone()
if err != nil { if err != nil {
return rest.NewBadRequestError("", err) return rest.NewBadRequestError("", err)
} }
return e.HttpContext.JSON(http.StatusOK, redactedSettings) return e.HttpContext.JSON(http.StatusOK, redactedSettings)
})
}
}) })
if handlerErr == nil { if submitErr == nil {
api.app.OnSettingsAfterUpdateRequest().Trigger(event) api.app.OnSettingsAfterUpdateRequest().Trigger(event)
} }
return handlerErr return submitErr
}
func (api *settingsApi) testS3(c echo.Context) error {
if !api.app.Settings().S3.Enabled {
return rest.NewBadRequestError("S3 storage is not enabled.", nil)
}
fs, err := api.app.NewFilesystem()
if err != nil {
return rest.NewBadRequestError("Failed to initialize the S3 storage. Raw error: \n"+err.Error(), nil)
}
defer fs.Close()
testFileKey := "pb_test_" + security.RandomString(5) + "/test.txt"
if err := fs.Upload([]byte("test"), testFileKey); err != nil {
return rest.NewBadRequestError("Failed to upload a test file. Raw error: \n"+err.Error(), nil)
}
if err := fs.Delete(testFileKey); err != nil {
return rest.NewBadRequestError("Failed to delete a test file. Raw error: \n"+err.Error(), nil)
}
return c.NoContent(http.StatusNoContent)
}
func (api *settingsApi) testEmail(c echo.Context) error {
form := forms.NewTestEmailSend(api.app)
// load request
if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("An error occurred while loading the submitted data.", err)
}
// send
if err := form.Submit(); err != nil {
if fErr, ok := err.(validation.Errors); ok {
// form error
return rest.NewBadRequestError("Failed to send the test email.", fErr)
}
// mailer error
return rest.NewBadRequestError("Failed to send the test email. Raw error: \n"+err.Error(), nil)
}
return c.NoContent(http.StatusNoContent)
} }
+190 -3
View File
@@ -5,6 +5,7 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/labstack/echo/v5"
"github.com/pocketbase/pocketbase/tests" "github.com/pocketbase/pocketbase/tests"
) )
@@ -139,9 +140,6 @@ func TestSettingsSet(t *testing.T) {
`"emailAuth":{"minPasswordLength":{"code":"validation_min_greater_equal_than_required","message":"Must be no less than 5."}}`, `"emailAuth":{"minPasswordLength":{"code":"validation_min_greater_equal_than_required","message":"Must be no less than 5."}}`,
`"meta":{"appName":{"code":"validation_required","message":"Cannot be blank."}}`, `"meta":{"appName":{"code":"validation_required","message":"Cannot be blank."}}`,
}, },
ExpectedEvents: map[string]int{
"OnSettingsBeforeUpdateRequest": 1,
},
}, },
{ {
Name: "authorized as admin submitting valid data", Name: "authorized as admin submitting valid data",
@@ -186,3 +184,192 @@ func TestSettingsSet(t *testing.T) {
scenario.Test(t) scenario.Test(t)
} }
} }
func TestSettingsTestS3(t *testing.T) {
scenarios := []tests.ApiScenario{
{
Name: "unauthorized",
Method: http.MethodPost,
Url: "/api/settings/test/s3",
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
},
{
Name: "authorized as user",
Method: http.MethodPost,
Url: "/api/settings/test/s3",
RequestHeaders: map[string]string{
"Authorization": "User eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjRkMDE5N2NjLTJiNGEtM2Y4My1hMjZiLWQ3N2JjODQyM2QzYyIsInR5cGUiOiJ1c2VyIiwiZXhwIjoxODkzNDc0MDAwfQ.Wq5ac1q1f5WntIzEngXk22ydMj-eFgvfSRg7dhmPKic",
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
},
{
Name: "authorized as admin (no s3)",
Method: http.MethodPost,
Url: "/api/settings/test/s3",
RequestHeaders: map[string]string{
"Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo",
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
},
// @todo consider creating a test S3 filesystem
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestSettingsTestEmail(t *testing.T) {
scenarios := []tests.ApiScenario{
{
Name: "unauthorized",
Method: http.MethodPost,
Url: "/api/settings/test/email",
Body: strings.NewReader(`{
"template": "verification",
"email": "test@example.com"
}`),
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
},
{
Name: "authorized as user",
Method: http.MethodPost,
Url: "/api/settings/test/email",
Body: strings.NewReader(`{
"template": "verification",
"email": "test@example.com"
}`),
RequestHeaders: map[string]string{
"Authorization": "User eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjRkMDE5N2NjLTJiNGEtM2Y4My1hMjZiLWQ3N2JjODQyM2QzYyIsInR5cGUiOiJ1c2VyIiwiZXhwIjoxODkzNDc0MDAwfQ.Wq5ac1q1f5WntIzEngXk22ydMj-eFgvfSRg7dhmPKic",
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
},
{
Name: "authorized as admin (invalid body)",
Method: http.MethodPost,
Url: "/api/settings/test/email",
Body: strings.NewReader(`{`),
RequestHeaders: map[string]string{
"Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo",
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
},
{
Name: "authorized as admin (empty json)",
Method: http.MethodPost,
Url: "/api/settings/test/email",
Body: strings.NewReader(`{}`),
RequestHeaders: map[string]string{
"Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"email":{"code":"validation_required"`,
`"template":{"code":"validation_required"`,
},
},
{
Name: "authorized as admin (verifiation template)",
Method: http.MethodPost,
Url: "/api/settings/test/email",
Body: strings.NewReader(`{
"template": "verification",
"email": "test@example.com"
}`),
RequestHeaders: map[string]string{
"Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo",
},
AfterFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) {
if app.TestMailer.TotalSend != 1 {
t.Fatalf("[verification] Expected 1 sent email, got %d", app.TestMailer.TotalSend)
}
if app.TestMailer.LastToAddress.Address != "test@example.com" {
t.Fatalf("[verification] Expected the email to be sent to %s, got %s", "test@example.com", app.TestMailer.LastToAddress.Address)
}
if !strings.Contains(app.TestMailer.LastHtmlBody, "Verify") {
t.Fatalf("[verification] Expected to sent a verification email, got \n%v\n%v", app.TestMailer.LastHtmlSubject, app.TestMailer.LastHtmlBody)
}
},
ExpectedStatus: 204,
ExpectedContent: []string{},
ExpectedEvents: map[string]int{
"OnMailerBeforeUserVerificationSend": 1,
"OnMailerAfterUserVerificationSend": 1,
},
},
{
Name: "authorized as admin (password reset template)",
Method: http.MethodPost,
Url: "/api/settings/test/email",
Body: strings.NewReader(`{
"template": "password-reset",
"email": "test@example.com"
}`),
RequestHeaders: map[string]string{
"Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo",
},
AfterFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) {
if app.TestMailer.TotalSend != 1 {
t.Fatalf("[password-reset] Expected 1 sent email, got %d", app.TestMailer.TotalSend)
}
if app.TestMailer.LastToAddress.Address != "test@example.com" {
t.Fatalf("[password-reset] Expected the email to be sent to %s, got %s", "test@example.com", app.TestMailer.LastToAddress.Address)
}
if !strings.Contains(app.TestMailer.LastHtmlBody, "Reset password") {
t.Fatalf("[password-reset] Expected to sent a password-reset email, got \n%v\n%v", app.TestMailer.LastHtmlSubject, app.TestMailer.LastHtmlBody)
}
},
ExpectedStatus: 204,
ExpectedContent: []string{},
ExpectedEvents: map[string]int{
"OnMailerBeforeUserResetPasswordSend": 1,
"OnMailerAfterUserResetPasswordSend": 1,
},
},
{
Name: "authorized as admin (email change)",
Method: http.MethodPost,
Url: "/api/settings/test/email",
Body: strings.NewReader(`{
"template": "email-change",
"email": "test@example.com"
}`),
RequestHeaders: map[string]string{
"Authorization": "Admin eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJiNGE5N2NjLTNmODMtNGQwMS1hMjZiLTNkNzdiYzg0MmQzYyIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTg3MzQ2Mjc5Mn0.AtRtXR6FHBrCUGkj5OffhmxLbSZaQ4L_Qgw4gfoHyfo",
},
AfterFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) {
if app.TestMailer.TotalSend != 1 {
t.Fatalf("[email-change] Expected 1 sent email, got %d", app.TestMailer.TotalSend)
}
if app.TestMailer.LastToAddress.Address != "test@example.com" {
t.Fatalf("[email-change] Expected the email to be sent to %s, got %s", "test@example.com", app.TestMailer.LastToAddress.Address)
}
if !strings.Contains(app.TestMailer.LastHtmlBody, "Confirm new email") {
t.Fatalf("[email-change] Expected to sent a confirm new email email, got \n%v\n%v", app.TestMailer.LastHtmlSubject, app.TestMailer.LastHtmlBody)
}
},
ExpectedStatus: 204,
ExpectedContent: []string{},
ExpectedEvents: map[string]int{
"OnMailerBeforeUserChangeEmailSend": 1,
"OnMailerAfterUserChangeEmailSend": 1,
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
+34 -26
View File
@@ -152,7 +152,7 @@ func (api *userApi) authMethods(c echo.Context) error {
func (api *userApi) oauth2Auth(c echo.Context) error { func (api *userApi) oauth2Auth(c echo.Context) error {
form := forms.NewUserOauth2Login(api.app) form := forms.NewUserOauth2Login(api.app)
if readErr := c.Bind(form); readErr != nil { if readErr := c.Bind(form); readErr != nil {
return rest.NewBadRequestError("An error occurred while reading the submitted data.", readErr) return rest.NewBadRequestError("An error occurred while loading the submitted data.", readErr)
} }
user, authData, submitErr := form.Submit() user, authData, submitErr := form.Submit()
@@ -170,7 +170,7 @@ func (api *userApi) emailAuth(c echo.Context) error {
form := forms.NewUserEmailLogin(api.app) form := forms.NewUserEmailLogin(api.app)
if readErr := c.Bind(form); readErr != nil { if readErr := c.Bind(form); readErr != nil {
return rest.NewBadRequestError("An error occurred while reading the submitted data.", readErr) return rest.NewBadRequestError("An error occurred while loading the submitted data.", readErr)
} }
user, submitErr := form.Submit() user, submitErr := form.Submit()
@@ -184,7 +184,7 @@ func (api *userApi) emailAuth(c echo.Context) error {
func (api *userApi) requestPasswordReset(c echo.Context) error { func (api *userApi) requestPasswordReset(c echo.Context) error {
form := forms.NewUserPasswordResetRequest(api.app) form := forms.NewUserPasswordResetRequest(api.app)
if err := c.Bind(form); err != nil { if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("An error occurred while reading the submitted data.", err) return rest.NewBadRequestError("An error occurred while loading the submitted data.", err)
} }
if err := form.Validate(); err != nil { if err := form.Validate(); err != nil {
@@ -205,7 +205,7 @@ func (api *userApi) requestPasswordReset(c echo.Context) error {
func (api *userApi) confirmPasswordReset(c echo.Context) error { func (api *userApi) confirmPasswordReset(c echo.Context) error {
form := forms.NewUserPasswordResetConfirm(api.app) form := forms.NewUserPasswordResetConfirm(api.app)
if readErr := c.Bind(form); readErr != nil { if readErr := c.Bind(form); readErr != nil {
return rest.NewBadRequestError("An error occurred while reading the submitted data.", readErr) return rest.NewBadRequestError("An error occurred while loading the submitted data.", readErr)
} }
user, submitErr := form.Submit() user, submitErr := form.Submit()
@@ -224,7 +224,7 @@ func (api *userApi) requestEmailChange(c echo.Context) error {
form := forms.NewUserEmailChangeRequest(api.app, loggedUser) form := forms.NewUserEmailChangeRequest(api.app, loggedUser)
if err := c.Bind(form); err != nil { if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("An error occurred while reading the submitted data.", err) return rest.NewBadRequestError("An error occurred while loading the submitted data.", err)
} }
if err := form.Submit(); err != nil { if err := form.Submit(); err != nil {
@@ -237,7 +237,7 @@ func (api *userApi) requestEmailChange(c echo.Context) error {
func (api *userApi) confirmEmailChange(c echo.Context) error { func (api *userApi) confirmEmailChange(c echo.Context) error {
form := forms.NewUserEmailChangeConfirm(api.app) form := forms.NewUserEmailChangeConfirm(api.app)
if readErr := c.Bind(form); readErr != nil { if readErr := c.Bind(form); readErr != nil {
return rest.NewBadRequestError("An error occurred while reading the submitted data.", readErr) return rest.NewBadRequestError("An error occurred while loading the submitted data.", readErr)
} }
user, submitErr := form.Submit() user, submitErr := form.Submit()
@@ -251,7 +251,7 @@ func (api *userApi) confirmEmailChange(c echo.Context) error {
func (api *userApi) requestVerification(c echo.Context) error { func (api *userApi) requestVerification(c echo.Context) error {
form := forms.NewUserVerificationRequest(api.app) form := forms.NewUserVerificationRequest(api.app)
if err := c.Bind(form); err != nil { if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("An error occurred while reading the submitted data.", err) return rest.NewBadRequestError("An error occurred while loading the submitted data.", err)
} }
if err := form.Validate(); err != nil { if err := form.Validate(); err != nil {
@@ -272,7 +272,7 @@ func (api *userApi) requestVerification(c echo.Context) error {
func (api *userApi) confirmVerification(c echo.Context) error { func (api *userApi) confirmVerification(c echo.Context) error {
form := forms.NewUserVerificationConfirm(api.app) form := forms.NewUserVerificationConfirm(api.app)
if readErr := c.Bind(form); readErr != nil { if readErr := c.Bind(form); readErr != nil {
return rest.NewBadRequestError("An error occurred while reading the submitted data.", readErr) return rest.NewBadRequestError("An error occurred while loading the submitted data.", readErr)
} }
user, submitErr := form.Submit() user, submitErr := form.Submit()
@@ -348,7 +348,7 @@ func (api *userApi) create(c echo.Context) error {
// load request // load request
if err := c.Bind(form); err != nil { if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("Failed to read the submitted data due to invalid formatting.", err) return rest.NewBadRequestError("Failed to load the submitted data due to invalid formatting.", err)
} }
event := &core.UserCreateEvent{ event := &core.UserCreateEvent{
@@ -356,20 +356,24 @@ func (api *userApi) create(c echo.Context) error {
User: user, User: user,
} }
handlerErr := api.app.OnUserBeforeCreateRequest().Trigger(event, func(e *core.UserCreateEvent) error { // create the user
// create the user submitErr := form.Submit(func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
if err := form.Submit(); err != nil { return func() error {
return rest.NewBadRequestError("Failed to create user.", err) return api.app.OnUserBeforeCreateRequest().Trigger(event, func(e *core.UserCreateEvent) error {
} if err := next(); err != nil {
return rest.NewBadRequestError("Failed to create user.", err)
}
return e.HttpContext.JSON(http.StatusOK, e.User) return e.HttpContext.JSON(http.StatusOK, e.User)
})
}
}) })
if handlerErr == nil { if submitErr == nil {
api.app.OnUserAfterCreateRequest().Trigger(event) api.app.OnUserAfterCreateRequest().Trigger(event)
} }
return handlerErr return submitErr
} }
func (api *userApi) update(c echo.Context) error { func (api *userApi) update(c echo.Context) error {
@@ -387,7 +391,7 @@ func (api *userApi) update(c echo.Context) error {
// load request // load request
if err := c.Bind(form); err != nil { if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("Failed to read the submitted data due to invalid formatting.", err) return rest.NewBadRequestError("Failed to load the submitted data due to invalid formatting.", err)
} }
event := &core.UserUpdateEvent{ event := &core.UserUpdateEvent{
@@ -395,20 +399,24 @@ func (api *userApi) update(c echo.Context) error {
User: user, User: user,
} }
handlerErr := api.app.OnUserBeforeUpdateRequest().Trigger(event, func(e *core.UserUpdateEvent) error { // update the user
// update the user submitErr := form.Submit(func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
if err := form.Submit(); err != nil { return func() error {
return rest.NewBadRequestError("Failed to update user.", err) return api.app.OnUserBeforeUpdateRequest().Trigger(event, func(e *core.UserUpdateEvent) error {
} if err := next(); err != nil {
return rest.NewBadRequestError("Failed to update user.", err)
}
return e.HttpContext.JSON(http.StatusOK, e.User) return e.HttpContext.JSON(http.StatusOK, e.User)
})
}
}) })
if handlerErr == nil { if submitErr == nil {
api.app.OnUserAfterUpdateRequest().Trigger(event) api.app.OnUserAfterUpdateRequest().Trigger(event)
} }
return handlerErr return submitErr
} }
func (api *userApi) delete(c echo.Context) error { func (api *userApi) delete(c echo.Context) error {
+58 -30
View File
@@ -4,9 +4,12 @@ import (
"net/http" "net/http"
"strings" "strings"
"testing" "testing"
"time"
"github.com/labstack/echo/v5" "github.com/labstack/echo/v5"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/tests" "github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/types"
) )
func TestUsersAuthMethods(t *testing.T) { func TestUsersAuthMethods(t *testing.T) {
@@ -132,6 +135,7 @@ func TestUserRequestPasswordReset(t *testing.T) {
Method: http.MethodPost, Method: http.MethodPost,
Url: "/api/users/request-password-reset", Url: "/api/users/request-password-reset",
Body: strings.NewReader(`{"email":"missing@example.com"}`), Body: strings.NewReader(`{"email":"missing@example.com"}`),
Delay: 100 * time.Millisecond,
ExpectedStatus: 204, ExpectedStatus: 204,
}, },
{ {
@@ -139,22 +143,34 @@ func TestUserRequestPasswordReset(t *testing.T) {
Method: http.MethodPost, Method: http.MethodPost,
Url: "/api/users/request-password-reset", Url: "/api/users/request-password-reset",
Body: strings.NewReader(`{"email":"test@example.com"}`), Body: strings.NewReader(`{"email":"test@example.com"}`),
Delay: 100 * time.Millisecond,
ExpectedStatus: 204, ExpectedStatus: 204,
// usually this events are fired but since the submit is ExpectedEvents: map[string]int{
// executed in a separate go routine they are fired async "OnModelBeforeUpdate": 1,
// ExpectedEvents: map[string]int{ "OnModelAfterUpdate": 1,
// "OnModelBeforeUpdate": 1, "OnMailerBeforeUserResetPasswordSend": 1,
// "OnModelAfterUpdate": 1, "OnMailerAfterUserResetPasswordSend": 1,
// "OnMailerBeforeUserResetPasswordSend": 1, },
// "OnMailerAfterUserResetPasswordSend": 1,
// },
}, },
{ {
Name: "existing user (after already sent)", Name: "existing user (after already sent)",
Method: http.MethodPost, Method: http.MethodPost,
Url: "/api/users/request-password-reset", Url: "/api/users/request-password-reset",
Body: strings.NewReader(`{"email":"test@example.com"}`), Body: strings.NewReader(`{"email":"test@example.com"}`),
Delay: 100 * time.Millisecond,
ExpectedStatus: 204, ExpectedStatus: 204,
BeforeFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) {
// simulate recent password request
user, err := app.Dao().FindUserByEmail("test@example.com")
if err != nil {
t.Fatal(err)
}
user.LastResetSentAt = types.NowDateTime()
dao := daos.New(app.Dao().DB()) // new dao to ignore hooks
if err := dao.Save(user); err != nil {
t.Fatal(err)
}
},
}, },
} }
@@ -216,50 +232,71 @@ func TestUserConfirmPasswordReset(t *testing.T) {
func TestUserRequestVerification(t *testing.T) { func TestUserRequestVerification(t *testing.T) {
scenarios := []tests.ApiScenario{ scenarios := []tests.ApiScenario{
// empty data
{ {
Name: "empty data",
Method: http.MethodPost, Method: http.MethodPost,
Url: "/api/users/request-verification", Url: "/api/users/request-verification",
Body: strings.NewReader(``), Body: strings.NewReader(``),
ExpectedStatus: 400, ExpectedStatus: 400,
ExpectedContent: []string{`"data":{"email":{"code":"validation_required","message":"Cannot be blank."}}`}, ExpectedContent: []string{`"data":{"email":{"code":"validation_required","message":"Cannot be blank."}}`},
}, },
// invalid data
{ {
Name: "invalid data",
Method: http.MethodPost, Method: http.MethodPost,
Url: "/api/users/request-verification", Url: "/api/users/request-verification",
Body: strings.NewReader(`{"email`), Body: strings.NewReader(`{"email`),
ExpectedStatus: 400, ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`}, ExpectedContent: []string{`"data":{}`},
}, },
// missing user
{ {
Name: "missing user",
Method: http.MethodPost, Method: http.MethodPost,
Url: "/api/users/request-verification", Url: "/api/users/request-verification",
Body: strings.NewReader(`{"email":"missing@example.com"}`), Body: strings.NewReader(`{"email":"missing@example.com"}`),
Delay: 100 * time.Millisecond,
ExpectedStatus: 204, ExpectedStatus: 204,
}, },
// existing already verified user
{ {
Name: "existing already verified user",
Method: http.MethodPost, Method: http.MethodPost,
Url: "/api/users/request-verification", Url: "/api/users/request-verification",
Body: strings.NewReader(`{"email":"test@example.com"}`), Body: strings.NewReader(`{"email":"test@example.com"}`),
Delay: 100 * time.Millisecond,
ExpectedStatus: 204, ExpectedStatus: 204,
}, },
// existing unverified user
{ {
Name: "existing unverified user",
Method: http.MethodPost, Method: http.MethodPost,
Url: "/api/users/request-verification", Url: "/api/users/request-verification",
Body: strings.NewReader(`{"email":"test2@example.com"}`), Body: strings.NewReader(`{"email":"test2@example.com"}`),
Delay: 100 * time.Millisecond,
ExpectedStatus: 204, ExpectedStatus: 204,
// usually this events are fired but since the submit is ExpectedEvents: map[string]int{
// executed in a separate go routine they are fired async "OnModelBeforeUpdate": 1,
// ExpectedEvents: map[string]int{ "OnModelAfterUpdate": 1,
// "OnModelBeforeUpdate": 1, "OnMailerBeforeUserVerificationSend": 1,
// "OnModelAfterUpdate": 1, "OnMailerAfterUserVerificationSend": 1,
// "OnMailerBeforeUserVerificationSend": 1, },
// "OnMailerAfterUserVerificationSend": 1, },
// }, {
Name: "existing unverified user (after already sent)",
Method: http.MethodPost,
Url: "/api/users/request-verification",
Body: strings.NewReader(`{"email":"test2@example.com"}`),
Delay: 100 * time.Millisecond,
ExpectedStatus: 204,
BeforeFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) {
// simulate recent verification sent
user, err := app.Dao().FindUserByEmail("test2@example.com")
if err != nil {
t.Fatal(err)
}
user.LastVerificationSentAt = types.NowDateTime()
dao := daos.New(app.Dao().DB()) // new dao to ignore hooks
if err := dao.Save(user); err != nil {
t.Fatal(err)
}
},
}, },
} }
@@ -748,9 +785,6 @@ func TestUserCreate(t *testing.T) {
`"email":{"code":"validation_required"`, `"email":{"code":"validation_required"`,
`"password":{"code":"validation_required"`, `"password":{"code":"validation_required"`,
}, },
ExpectedEvents: map[string]int{
"OnUserBeforeCreateRequest": 1,
},
}, },
{ {
Name: "invalid data", Name: "invalid data",
@@ -764,9 +798,6 @@ func TestUserCreate(t *testing.T) {
`"password":{"code":"validation_length_out_of_range"`, `"password":{"code":"validation_length_out_of_range"`,
`"passwordConfirm":{"code":"validation_values_mismatch"`, `"passwordConfirm":{"code":"validation_values_mismatch"`,
}, },
ExpectedEvents: map[string]int{
"OnUserBeforeCreateRequest": 1,
},
}, },
{ {
Name: "valid data but with disabled email/pass auth", Name: "valid data but with disabled email/pass auth",
@@ -868,9 +899,6 @@ func TestUserUpdate(t *testing.T) {
`"data":{`, `"data":{`,
`"email":{"code":"validation_user_email_exists"`, `"email":{"code":"validation_user_email_exists"`,
}, },
ExpectedEvents: map[string]int{
"OnUserBeforeUpdateRequest": 1,
},
}, },
{ {
Name: "authorized as admin - valid data", Name: "authorized as admin - valid data",
+168 -4
View File
@@ -1,12 +1,21 @@
package cmd package cmd
import ( import (
"encoding/json"
"fmt"
"log" "log"
"os"
"path"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/pocketbase/dbx" "github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/migrations" "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/migrations/logs" "github.com/pocketbase/pocketbase/migrations/logs"
"github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/tools/inflector"
"github.com/pocketbase/pocketbase/tools/migrate" "github.com/pocketbase/pocketbase/tools/migrate"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@@ -15,18 +24,40 @@ import (
func NewMigrateCommand(app core.App) *cobra.Command { func NewMigrateCommand(app core.App) *cobra.Command {
desc := ` desc := `
Supported arguments are: Supported arguments are:
- up - runs all available migrations. - up - runs all available migrations.
- down [number] - reverts the last [number] applied migrations. - down [number] - reverts the last [number] applied migrations.
- create folder name - creates new migration template file. - create name [folder] - creates new migration template file.
- collections [folder] - (Experimental) creates new migration file with the most recent local collections configuration.
` `
var databaseFlag string var databaseFlag string
command := &cobra.Command{ command := &cobra.Command{
Use: "migrate", Use: "migrate",
Short: "Executes DB migration scripts", Short: "Executes DB migration scripts",
ValidArgs: []string{"up", "down", "create"}, ValidArgs: []string{"up", "down", "create", "collections"},
Long: desc, Long: desc,
Run: func(command *cobra.Command, args []string) { Run: func(command *cobra.Command, args []string) {
cmd := ""
if len(args) > 0 {
cmd = args[0]
}
// additional commands
// ---
if cmd == "create" {
if err := migrateCreateHandler(defaultMigrateCreateTemplate, args[1:]); err != nil {
log.Fatal(err)
}
return
}
if cmd == "collections" {
if err := migrateCollectionsHandler(app, args[1:]); err != nil {
log.Fatal(err)
}
return
}
// ---
// normalize // normalize
if databaseFlag != "logs" { if databaseFlag != "logs" {
databaseFlag = "db" databaseFlag = "db"
@@ -75,3 +106,136 @@ func migrationsConnectionsMap(app core.App) map[string]migrationsConnection {
}, },
} }
} }
// -------------------------------------------------------------------
// migrate create
// -------------------------------------------------------------------
const defaultMigrateCreateTemplate = `package migrations
import (
"github.com/pocketbase/dbx"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(db dbx.Builder) error {
// add up queries...
return nil
}, func(db dbx.Builder) error {
// add down queries...
return nil
})
}
`
func migrateCreateHandler(template string, args []string) error {
if len(args) < 1 {
return fmt.Errorf("Missing migration file name")
}
name := args[0]
var dir string
if len(args) == 2 {
dir = args[1]
}
if dir == "" {
// If not specified, auto point to the default migrations folder.
//
// NB!
// Since the create command makes sense only during development,
// it is expected the user to be in the app working directory
// and to be using `go run`
wd, err := os.Getwd()
if err != nil {
return err
}
dir = path.Join(wd, "migrations")
}
resultFilePath := path.Join(
dir,
fmt.Sprintf("%d_%s.go", time.Now().Unix(), inflector.Snakecase(name)),
)
confirm := false
prompt := &survey.Confirm{
Message: fmt.Sprintf("Do you really want to create migration %q?", resultFilePath),
}
survey.AskOne(prompt, &confirm)
if !confirm {
fmt.Println("The command has been cancelled")
return nil
}
// ensure that migrations dir exist
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return err
}
if err := os.WriteFile(resultFilePath, []byte(template), 0644); err != nil {
return fmt.Errorf("Failed to save migration file %q\n", resultFilePath)
}
fmt.Printf("Successfully created file %q\n", resultFilePath)
return nil
}
// -------------------------------------------------------------------
// migrate collections
// -------------------------------------------------------------------
const collectionsMigrateCreateTemplate = `package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models"
)
// Auto generated migration with the most recent collections configuration.
func init() {
m.Register(func(db dbx.Builder) error {
jsonData := ` + "`" + `%s` + "`" + `
collections := []*models.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collections); err != nil {
return err
}
return daos.New(db).ImportCollections(collections, true, nil)
}, func(db dbx.Builder) error {
// no revert since the configuration on the environment, on which
// the migration was executed, could have changed via the UI/API
return nil
})
}
`
func migrateCollectionsHandler(app core.App, args []string) error {
createArgs := []string{"collections_snapshot"}
createArgs = append(createArgs, args...)
dao := daos.New(app.DB())
collections := []*models.Collection{}
if err := dao.CollectionQuery().OrderBy("created ASC").All(&collections); err != nil {
return fmt.Errorf("Failed to fetch migrations list: %v", err)
}
serialized, err := json.MarshalIndent(collections, "\t\t", "\t")
if err != nil {
return fmt.Errorf("Failed to serialize collections list: %v", err)
}
return migrateCreateHandler(
fmt.Sprintf(collectionsMigrateCreateTemplate, string(serialized)),
createArgs,
)
}
+2 -2
View File
@@ -28,7 +28,7 @@ func NewServeCommand(app core.App, showStartBanner bool) *cobra.Command {
command := &cobra.Command{ command := &cobra.Command{
Use: "serve", Use: "serve",
Short: "Starts the web server (default to localhost:8090)", Short: "Starts the web server (default to 127.0.0.1:8090)",
Run: func(command *cobra.Command, args []string) { Run: func(command *cobra.Command, args []string) {
// ensure that the latest migrations are applied before starting the server // ensure that the latest migrations are applied before starting the server
if err := runMigrations(app); err != nil { if err := runMigrations(app); err != nil {
@@ -123,7 +123,7 @@ func NewServeCommand(app core.App, showStartBanner bool) *cobra.Command {
command.PersistentFlags().StringVar( command.PersistentFlags().StringVar(
&httpAddr, &httpAddr,
"http", "http",
"localhost:8090", "127.0.0.1:8090",
"api HTTP server address", "api HTTP server address",
) )
-21
View File
@@ -1,21 +0,0 @@
// Package cmd implements various PocketBase system commands.
package cmd
import (
"fmt"
"github.com/pocketbase/pocketbase/core"
"github.com/spf13/cobra"
)
// NewVersionCommand creates and returns new command that prints
// the current PocketBase version.
func NewVersionCommand(app core.App, version string) *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "Prints the current PocketBase app version",
Run: func(command *cobra.Command, args []string) {
fmt.Printf("PocketBase v%s\n", version)
},
}
}
+28 -17
View File
@@ -119,7 +119,7 @@ type App interface {
// sending a password reset email to an admin. // sending a password reset email to an admin.
// //
// Could be used to send your own custom email template if // Could be used to send your own custom email template if
// hook.StopPropagation is returned in one of its listeners. // [hook.StopPropagation] is returned in one of its listeners.
OnMailerBeforeAdminResetPasswordSend() *hook.Hook[*MailerAdminEvent] OnMailerBeforeAdminResetPasswordSend() *hook.Hook[*MailerAdminEvent]
// OnMailerAfterAdminResetPasswordSend hook is triggered after // OnMailerAfterAdminResetPasswordSend hook is triggered after
@@ -130,7 +130,7 @@ type App interface {
// sending a password reset email to a user. // sending a password reset email to a user.
// //
// Could be used to send your own custom email template if // Could be used to send your own custom email template if
// hook.StopPropagation is returned in one of its listeners. // [hook.StopPropagation] is returned in one of its listeners.
OnMailerBeforeUserResetPasswordSend() *hook.Hook[*MailerUserEvent] OnMailerBeforeUserResetPasswordSend() *hook.Hook[*MailerUserEvent]
// OnMailerAfterUserResetPasswordSend hook is triggered after // OnMailerAfterUserResetPasswordSend hook is triggered after
@@ -141,7 +141,7 @@ type App interface {
// sending a verification email to a user. // sending a verification email to a user.
// //
// Could be used to send your own custom email template if // Could be used to send your own custom email template if
// hook.StopPropagation is returned in one of its listeners. // [hook.StopPropagation] is returned in one of its listeners.
OnMailerBeforeUserVerificationSend() *hook.Hook[*MailerUserEvent] OnMailerBeforeUserVerificationSend() *hook.Hook[*MailerUserEvent]
// OnMailerAfterUserVerificationSend hook is triggered after a user // OnMailerAfterUserVerificationSend hook is triggered after a user
@@ -152,7 +152,7 @@ type App interface {
// sending a confirmation new address email to a a user. // sending a confirmation new address email to a a user.
// //
// Could be used to send your own custom email template if // Could be used to send your own custom email template if
// hook.StopPropagation is returned in one of its listeners. // [hook.StopPropagation] is returned in one of its listeners.
OnMailerBeforeUserChangeEmailSend() *hook.Hook[*MailerUserEvent] OnMailerBeforeUserChangeEmailSend() *hook.Hook[*MailerUserEvent]
// OnMailerAfterUserChangeEmailSend hook is triggered after a user // OnMailerAfterUserChangeEmailSend hook is triggered after a user
@@ -192,7 +192,7 @@ type App interface {
// //
// Could be used to additionally validate the request data or // Could be used to additionally validate the request data or
// implement completely different persistence behavior // implement completely different persistence behavior
// (returning hook.StopPropagation). // (returning [hook.StopPropagation]).
OnSettingsBeforeUpdateRequest() *hook.Hook[*SettingsUpdateEvent] OnSettingsBeforeUpdateRequest() *hook.Hook[*SettingsUpdateEvent]
// OnSettingsAfterUpdateRequest hook is triggered after each // OnSettingsAfterUpdateRequest hook is triggered after each
@@ -227,7 +227,7 @@ type App interface {
// Admin create request (after request data load and before model persistence). // Admin create request (after request data load and before model persistence).
// //
// Could be used to additionally validate the request data or implement // Could be used to additionally validate the request data or implement
// completely different persistence behavior (returning hook.StopPropagation). // completely different persistence behavior (returning [hook.StopPropagation]).
OnAdminBeforeCreateRequest() *hook.Hook[*AdminCreateEvent] OnAdminBeforeCreateRequest() *hook.Hook[*AdminCreateEvent]
// OnAdminAfterCreateRequest hook is triggered after each // OnAdminAfterCreateRequest hook is triggered after each
@@ -238,7 +238,7 @@ type App interface {
// Admin update request (after request data load and before model persistence). // Admin update request (after request data load and before model persistence).
// //
// Could be used to additionally validate the request data or implement // Could be used to additionally validate the request data or implement
// completely different persistence behavior (returning hook.StopPropagation). // completely different persistence behavior (returning [hook.StopPropagation]).
OnAdminBeforeUpdateRequest() *hook.Hook[*AdminUpdateEvent] OnAdminBeforeUpdateRequest() *hook.Hook[*AdminUpdateEvent]
// OnAdminAfterUpdateRequest hook is triggered after each // OnAdminAfterUpdateRequest hook is triggered after each
@@ -249,7 +249,7 @@ type App interface {
// Admin delete request (after model load and before actual deletion). // Admin delete request (after model load and before actual deletion).
// //
// Could be used to additionally validate the request data or implement // Could be used to additionally validate the request data or implement
// completely different delete behavior (returning hook.StopPropagation). // completely different delete behavior (returning [hook.StopPropagation]).
OnAdminBeforeDeleteRequest() *hook.Hook[*AdminDeleteEvent] OnAdminBeforeDeleteRequest() *hook.Hook[*AdminDeleteEvent]
// OnAdminAfterDeleteRequest hook is triggered after each // OnAdminAfterDeleteRequest hook is triggered after each
@@ -281,7 +281,7 @@ type App interface {
// create request (after request data load and before model persistence). // create request (after request data load and before model persistence).
// //
// Could be used to additionally validate the request data or implement // Could be used to additionally validate the request data or implement
// completely different persistence behavior (returning hook.StopPropagation). // completely different persistence behavior (returning [hook.StopPropagation]).
OnUserBeforeCreateRequest() *hook.Hook[*UserCreateEvent] OnUserBeforeCreateRequest() *hook.Hook[*UserCreateEvent]
// OnUserAfterCreateRequest hook is triggered after each // OnUserAfterCreateRequest hook is triggered after each
@@ -292,7 +292,7 @@ type App interface {
// update request (after request data load and before model persistence). // update request (after request data load and before model persistence).
// //
// Could be used to additionally validate the request data or implement // Could be used to additionally validate the request data or implement
// completely different persistence behavior (returning hook.StopPropagation). // completely different persistence behavior (returning [hook.StopPropagation]).
OnUserBeforeUpdateRequest() *hook.Hook[*UserUpdateEvent] OnUserBeforeUpdateRequest() *hook.Hook[*UserUpdateEvent]
// OnUserAfterUpdateRequest hook is triggered after each // OnUserAfterUpdateRequest hook is triggered after each
@@ -303,7 +303,7 @@ type App interface {
// delete request (after model load and before actual deletion). // delete request (after model load and before actual deletion).
// //
// Could be used to additionally validate the request data or implement // Could be used to additionally validate the request data or implement
// completely different delete behavior (returning hook.StopPropagation). // completely different delete behavior (returning [hook.StopPropagation]).
OnUserBeforeDeleteRequest() *hook.Hook[*UserDeleteEvent] OnUserBeforeDeleteRequest() *hook.Hook[*UserDeleteEvent]
// OnUserAfterDeleteRequest hook is triggered after each // OnUserAfterDeleteRequest hook is triggered after each
@@ -346,7 +346,7 @@ type App interface {
// create request (after request data load and before model persistence). // create request (after request data load and before model persistence).
// //
// Could be used to additionally validate the request data or implement // Could be used to additionally validate the request data or implement
// completely different persistence behavior (returning hook.StopPropagation). // completely different persistence behavior (returning [hook.StopPropagation]).
OnRecordBeforeCreateRequest() *hook.Hook[*RecordCreateEvent] OnRecordBeforeCreateRequest() *hook.Hook[*RecordCreateEvent]
// OnRecordAfterCreateRequest hook is triggered after each // OnRecordAfterCreateRequest hook is triggered after each
@@ -357,7 +357,7 @@ type App interface {
// update request (after request data load and before model persistence). // update request (after request data load and before model persistence).
// //
// Could be used to additionally validate the request data or implement // Could be used to additionally validate the request data or implement
// completely different persistence behavior (returning hook.StopPropagation). // completely different persistence behavior (returning [hook.StopPropagation]).
OnRecordBeforeUpdateRequest() *hook.Hook[*RecordUpdateEvent] OnRecordBeforeUpdateRequest() *hook.Hook[*RecordUpdateEvent]
// OnRecordAfterUpdateRequest hook is triggered after each // OnRecordAfterUpdateRequest hook is triggered after each
@@ -368,7 +368,7 @@ type App interface {
// delete request (after model load and before actual deletion). // delete request (after model load and before actual deletion).
// //
// Could be used to additionally validate the request data or implement // Could be used to additionally validate the request data or implement
// completely different delete behavior (returning hook.StopPropagation). // completely different delete behavior (returning [hook.StopPropagation]).
OnRecordBeforeDeleteRequest() *hook.Hook[*RecordDeleteEvent] OnRecordBeforeDeleteRequest() *hook.Hook[*RecordDeleteEvent]
// OnRecordAfterDeleteRequest hook is triggered after each // OnRecordAfterDeleteRequest hook is triggered after each
@@ -393,7 +393,7 @@ type App interface {
// create request (after request data load and before model persistence). // create request (after request data load and before model persistence).
// //
// Could be used to additionally validate the request data or implement // Could be used to additionally validate the request data or implement
// completely different persistence behavior (returning hook.StopPropagation). // completely different persistence behavior (returning [hook.StopPropagation]).
OnCollectionBeforeCreateRequest() *hook.Hook[*CollectionCreateEvent] OnCollectionBeforeCreateRequest() *hook.Hook[*CollectionCreateEvent]
// OnCollectionAfterCreateRequest hook is triggered after each // OnCollectionAfterCreateRequest hook is triggered after each
@@ -404,7 +404,7 @@ type App interface {
// update request (after request data load and before model persistence). // update request (after request data load and before model persistence).
// //
// Could be used to additionally validate the request data or implement // Could be used to additionally validate the request data or implement
// completely different persistence behavior (returning hook.StopPropagation). // completely different persistence behavior (returning [hook.StopPropagation]).
OnCollectionBeforeUpdateRequest() *hook.Hook[*CollectionUpdateEvent] OnCollectionBeforeUpdateRequest() *hook.Hook[*CollectionUpdateEvent]
// OnCollectionAfterUpdateRequest hook is triggered after each // OnCollectionAfterUpdateRequest hook is triggered after each
@@ -415,10 +415,21 @@ type App interface {
// Collection delete request (after model load and before actual deletion). // Collection delete request (after model load and before actual deletion).
// //
// Could be used to additionally validate the request data or implement // Could be used to additionally validate the request data or implement
// completely different delete behavior (returning hook.StopPropagation). // completely different delete behavior (returning [hook.StopPropagation]).
OnCollectionBeforeDeleteRequest() *hook.Hook[*CollectionDeleteEvent] OnCollectionBeforeDeleteRequest() *hook.Hook[*CollectionDeleteEvent]
// OnCollectionAfterDeleteRequest hook is triggered after each // OnCollectionAfterDeleteRequest hook is triggered after each
// successful API Collection delete request. // successful API Collection delete request.
OnCollectionAfterDeleteRequest() *hook.Hook[*CollectionDeleteEvent] OnCollectionAfterDeleteRequest() *hook.Hook[*CollectionDeleteEvent]
// OnCollectionsBeforeImportRequest hook is triggered before each API
// collections import request (after request data load and before the actual import).
//
// Could be used to additionally validate the imported collections or
// to implement completely different import behavior (returning [hook.StopPropagation]).
OnCollectionsBeforeImportRequest() *hook.Hook[*CollectionsImportEvent]
// OnCollectionsAfterImportRequest hook is triggered after each
// successful API collections import request.
OnCollectionsAfterImportRequest() *hook.Hook[*CollectionsImportEvent]
} }
+65 -17
View File
@@ -5,6 +5,7 @@ import (
"database/sql" "database/sql"
"encoding/json" "encoding/json"
"errors" "errors"
"log"
"os" "os"
"path/filepath" "path/filepath"
"time" "time"
@@ -108,14 +109,16 @@ type BaseApp struct {
onRecordAfterDeleteRequest *hook.Hook[*RecordDeleteEvent] onRecordAfterDeleteRequest *hook.Hook[*RecordDeleteEvent]
// collection api event hooks // collection api event hooks
onCollectionsListRequest *hook.Hook[*CollectionsListEvent] onCollectionsListRequest *hook.Hook[*CollectionsListEvent]
onCollectionViewRequest *hook.Hook[*CollectionViewEvent] onCollectionViewRequest *hook.Hook[*CollectionViewEvent]
onCollectionBeforeCreateRequest *hook.Hook[*CollectionCreateEvent] onCollectionBeforeCreateRequest *hook.Hook[*CollectionCreateEvent]
onCollectionAfterCreateRequest *hook.Hook[*CollectionCreateEvent] onCollectionAfterCreateRequest *hook.Hook[*CollectionCreateEvent]
onCollectionBeforeUpdateRequest *hook.Hook[*CollectionUpdateEvent] onCollectionBeforeUpdateRequest *hook.Hook[*CollectionUpdateEvent]
onCollectionAfterUpdateRequest *hook.Hook[*CollectionUpdateEvent] onCollectionAfterUpdateRequest *hook.Hook[*CollectionUpdateEvent]
onCollectionBeforeDeleteRequest *hook.Hook[*CollectionDeleteEvent] onCollectionBeforeDeleteRequest *hook.Hook[*CollectionDeleteEvent]
onCollectionAfterDeleteRequest *hook.Hook[*CollectionDeleteEvent] onCollectionAfterDeleteRequest *hook.Hook[*CollectionDeleteEvent]
onCollectionsBeforeImportRequest *hook.Hook[*CollectionsImportEvent]
onCollectionsAfterImportRequest *hook.Hook[*CollectionsImportEvent]
} }
// NewBaseApp creates and returns a new BaseApp instance // NewBaseApp creates and returns a new BaseApp instance
@@ -123,7 +126,7 @@ type BaseApp struct {
// //
// To initialize the app, you need to call `app.Bootsrap()`. // To initialize the app, you need to call `app.Bootsrap()`.
func NewBaseApp(dataDir string, encryptionEnv string, isDebug bool) *BaseApp { func NewBaseApp(dataDir string, encryptionEnv string, isDebug bool) *BaseApp {
return &BaseApp{ app := &BaseApp{
dataDir: dataDir, dataDir: dataDir,
isDebug: isDebug, isDebug: isDebug,
encryptionEnv: encryptionEnv, encryptionEnv: encryptionEnv,
@@ -200,15 +203,21 @@ func NewBaseApp(dataDir string, encryptionEnv string, isDebug bool) *BaseApp {
onRecordAfterDeleteRequest: &hook.Hook[*RecordDeleteEvent]{}, onRecordAfterDeleteRequest: &hook.Hook[*RecordDeleteEvent]{},
// collection API event hooks // collection API event hooks
onCollectionsListRequest: &hook.Hook[*CollectionsListEvent]{}, onCollectionsListRequest: &hook.Hook[*CollectionsListEvent]{},
onCollectionViewRequest: &hook.Hook[*CollectionViewEvent]{}, onCollectionViewRequest: &hook.Hook[*CollectionViewEvent]{},
onCollectionBeforeCreateRequest: &hook.Hook[*CollectionCreateEvent]{}, onCollectionBeforeCreateRequest: &hook.Hook[*CollectionCreateEvent]{},
onCollectionAfterCreateRequest: &hook.Hook[*CollectionCreateEvent]{}, onCollectionAfterCreateRequest: &hook.Hook[*CollectionCreateEvent]{},
onCollectionBeforeUpdateRequest: &hook.Hook[*CollectionUpdateEvent]{}, onCollectionBeforeUpdateRequest: &hook.Hook[*CollectionUpdateEvent]{},
onCollectionAfterUpdateRequest: &hook.Hook[*CollectionUpdateEvent]{}, onCollectionAfterUpdateRequest: &hook.Hook[*CollectionUpdateEvent]{},
onCollectionBeforeDeleteRequest: &hook.Hook[*CollectionDeleteEvent]{}, onCollectionBeforeDeleteRequest: &hook.Hook[*CollectionDeleteEvent]{},
onCollectionAfterDeleteRequest: &hook.Hook[*CollectionDeleteEvent]{}, onCollectionAfterDeleteRequest: &hook.Hook[*CollectionDeleteEvent]{},
onCollectionsBeforeImportRequest: &hook.Hook[*CollectionsImportEvent]{},
onCollectionsAfterImportRequest: &hook.Hook[*CollectionsImportEvent]{},
} }
app.registerDefaultHooks()
return app
} }
// Bootstrap initializes the application // Bootstrap initializes the application
@@ -342,6 +351,7 @@ func (app *BaseApp) NewFilesystem() (*filesystem.System, error) {
app.settings.S3.Endpoint, app.settings.S3.Endpoint,
app.settings.S3.AccessKey, app.settings.S3.AccessKey,
app.settings.S3.Secret, app.settings.S3.Secret,
app.settings.S3.ForcePathStyle,
) )
} }
@@ -681,6 +691,14 @@ func (app *BaseApp) OnCollectionAfterDeleteRequest() *hook.Hook[*CollectionDelet
return app.onCollectionAfterDeleteRequest return app.onCollectionAfterDeleteRequest
} }
func (app *BaseApp) OnCollectionsBeforeImportRequest() *hook.Hook[*CollectionsImportEvent] {
return app.onCollectionsBeforeImportRequest
}
func (app *BaseApp) OnCollectionsAfterImportRequest() *hook.Hook[*CollectionsImportEvent] {
return app.onCollectionsAfterImportRequest
}
// ------------------------------------------------------------------- // -------------------------------------------------------------------
// Helpers // Helpers
// ------------------------------------------------------------------- // -------------------------------------------------------------------
@@ -750,3 +768,33 @@ func (app *BaseApp) createDao(db dbx.Builder) *daos.Dao {
return dao return dao
} }
func (app *BaseApp) registerDefaultHooks() {
deletePrefix := func(prefix string) error {
fs, err := app.NewFilesystem()
if err != nil {
return err
}
defer fs.Close()
failed := fs.DeletePrefix(prefix)
if len(failed) > 0 {
return errors.New("Failed to delete the files at " + prefix)
}
return nil
}
// delete storage files from deleted Collection, Records, etc.
app.OnModelAfterDelete().Add(func(e *ModelEvent) error {
if m, ok := e.Model.(models.FilesManager); ok && m.BaseFilesPath() != "" {
if err := deletePrefix(m.BaseFilesPath()); err != nil && app.IsDebug() {
// non critical error - only log for debug
// (usually could happen because of S3 api limits)
log.Println(err)
}
}
return nil
})
}
+5
View File
@@ -216,6 +216,11 @@ type CollectionDeleteEvent struct {
Collection *models.Collection Collection *models.Collection
} }
type CollectionsImportEvent struct {
HttpContext echo.Context
Collections []*models.Collection
}
// ------------------------------------------------------------------- // -------------------------------------------------------------------
// File API events data // File API events data
// ------------------------------------------------------------------- // -------------------------------------------------------------------
+144 -85
View File
@@ -10,48 +10,47 @@ import (
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is" "github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/tools/auth" "github.com/pocketbase/pocketbase/tools/auth"
"github.com/pocketbase/pocketbase/tools/rest"
"github.com/pocketbase/pocketbase/tools/security" "github.com/pocketbase/pocketbase/tools/security"
) )
// Common settings placeholder tokens
const (
EmailPlaceholderAppUrl string = "%APP_URL%"
EmailPlaceholderToken string = "%TOKEN%"
)
// Settings defines common app configuration options. // Settings defines common app configuration options.
type Settings struct { type Settings struct {
mux sync.RWMutex mux sync.RWMutex
Meta MetaConfig `form:"meta" json:"meta"` Meta MetaConfig `form:"meta" json:"meta"`
Logs LogsConfig `form:"logs" json:"logs"` Logs LogsConfig `form:"logs" json:"logs"`
Smtp SmtpConfig `form:"smtp" json:"smtp"` Smtp SmtpConfig `form:"smtp" json:"smtp"`
S3 S3Config `form:"s3" json:"s3"` S3 S3Config `form:"s3" json:"s3"`
AdminAuthToken TokenConfig `form:"adminAuthToken" json:"adminAuthToken"`
AdminPasswordResetToken TokenConfig `form:"adminPasswordResetToken" json:"adminPasswordResetToken"` AdminAuthToken TokenConfig `form:"adminAuthToken" json:"adminAuthToken"`
UserAuthToken TokenConfig `form:"userAuthToken" json:"userAuthToken"` AdminPasswordResetToken TokenConfig `form:"adminPasswordResetToken" json:"adminPasswordResetToken"`
UserPasswordResetToken TokenConfig `form:"userPasswordResetToken" json:"userPasswordResetToken"` UserAuthToken TokenConfig `form:"userAuthToken" json:"userAuthToken"`
UserEmailChangeToken TokenConfig `form:"userEmailChangeToken" json:"userEmailChangeToken"` UserPasswordResetToken TokenConfig `form:"userPasswordResetToken" json:"userPasswordResetToken"`
UserVerificationToken TokenConfig `form:"userVerificationToken" json:"userVerificationToken"` UserEmailChangeToken TokenConfig `form:"userEmailChangeToken" json:"userEmailChangeToken"`
EmailAuth EmailAuthConfig `form:"emailAuth" json:"emailAuth"` UserVerificationToken TokenConfig `form:"userVerificationToken" json:"userVerificationToken"`
GoogleAuth AuthProviderConfig `form:"googleAuth" json:"googleAuth"`
FacebookAuth AuthProviderConfig `form:"facebookAuth" json:"facebookAuth"` EmailAuth EmailAuthConfig `form:"emailAuth" json:"emailAuth"`
GithubAuth AuthProviderConfig `form:"githubAuth" json:"githubAuth"` GoogleAuth AuthProviderConfig `form:"googleAuth" json:"googleAuth"`
GitlabAuth AuthProviderConfig `form:"gitlabAuth" json:"gitlabAuth"` FacebookAuth AuthProviderConfig `form:"facebookAuth" json:"facebookAuth"`
GithubAuth AuthProviderConfig `form:"githubAuth" json:"githubAuth"`
GitlabAuth AuthProviderConfig `form:"gitlabAuth" json:"gitlabAuth"`
} }
// NewSettings creates and returns a new default Settings instance. // NewSettings creates and returns a new default Settings instance.
func NewSettings() *Settings { func NewSettings() *Settings {
return &Settings{ return &Settings{
Meta: MetaConfig{ Meta: MetaConfig{
AppName: "Acme", AppName: "Acme",
AppUrl: "http://localhost:8090", AppUrl: "http://localhost:8090",
SenderName: "Support", HideControls: false,
SenderAddress: "support@example.com", SenderName: "Support",
UserVerificationUrl: EmailPlaceholderAppUrl + "/_/#/users/confirm-verification/" + EmailPlaceholderToken, SenderAddress: "support@example.com",
UserResetPasswordUrl: EmailPlaceholderAppUrl + "/_/#/users/confirm-password-reset/" + EmailPlaceholderToken, VerificationTemplate: defaultVerificationTemplate,
UserConfirmEmailChangeUrl: EmailPlaceholderAppUrl + "/_/#/users/confirm-email-change/" + EmailPlaceholderToken, ResetPasswordTemplate: defaultResetPasswordTemplate,
ConfirmEmailChangeTemplate: defaultConfirmEmailChangeTemplate,
}, },
Logs: LogsConfig{ Logs: LogsConfig{
MaxDays: 7, MaxDays: 7,
}, },
@@ -194,6 +193,9 @@ func (s *Settings) RedactClone() (*Settings, error) {
// NamedAuthProviderConfigs returns a map with all registered OAuth2 // NamedAuthProviderConfigs returns a map with all registered OAuth2
// provider configurations (indexed by their name identifier). // provider configurations (indexed by their name identifier).
func (s *Settings) NamedAuthProviderConfigs() map[string]AuthProviderConfig { func (s *Settings) NamedAuthProviderConfigs() map[string]AuthProviderConfig {
s.mux.RLock()
defer s.mux.RUnlock()
return map[string]AuthProviderConfig{ return map[string]AuthProviderConfig{
auth.NameGoogle: s.GoogleAuth, auth.NameGoogle: s.GoogleAuth,
auth.NameFacebook: s.FacebookAuth, auth.NameFacebook: s.FacebookAuth,
@@ -244,18 +246,19 @@ func (c SmtpConfig) Validate() error {
// ------------------------------------------------------------------- // -------------------------------------------------------------------
type S3Config struct { type S3Config struct {
Enabled bool `form:"enabled" json:"enabled"` Enabled bool `form:"enabled" json:"enabled"`
Bucket string `form:"bucket" json:"bucket"` Bucket string `form:"bucket" json:"bucket"`
Region string `form:"region" json:"region"` Region string `form:"region" json:"region"`
Endpoint string `form:"endpoint" json:"endpoint"` Endpoint string `form:"endpoint" json:"endpoint"`
AccessKey string `form:"accessKey" json:"accessKey"` AccessKey string `form:"accessKey" json:"accessKey"`
Secret string `form:"secret" json:"secret"` Secret string `form:"secret" json:"secret"`
ForcePathStyle bool `form:"forcePathStyle" json:"forcePathStyle"`
} }
// Validate makes S3Config validatable by implementing [validation.Validatable] interface. // Validate makes S3Config validatable by implementing [validation.Validatable] interface.
func (c S3Config) Validate() error { func (c S3Config) Validate() error {
return validation.ValidateStruct(&c, return validation.ValidateStruct(&c,
validation.Field(&c.Endpoint, is.Host, validation.When(c.Enabled, validation.Required)), validation.Field(&c.Endpoint, is.URL, validation.When(c.Enabled, validation.Required)),
validation.Field(&c.Bucket, validation.When(c.Enabled, validation.Required)), validation.Field(&c.Bucket, validation.When(c.Enabled, validation.Required)),
validation.Field(&c.Region, validation.When(c.Enabled, validation.Required)), validation.Field(&c.Region, validation.When(c.Enabled, validation.Required)),
validation.Field(&c.AccessKey, validation.When(c.Enabled, validation.Required)), validation.Field(&c.AccessKey, validation.When(c.Enabled, validation.Required)),
@@ -266,13 +269,14 @@ func (c S3Config) Validate() error {
// ------------------------------------------------------------------- // -------------------------------------------------------------------
type MetaConfig struct { type MetaConfig struct {
AppName string `form:"appName" json:"appName"` AppName string `form:"appName" json:"appName"`
AppUrl string `form:"appUrl" json:"appUrl"` AppUrl string `form:"appUrl" json:"appUrl"`
SenderName string `form:"senderName" json:"senderName"` HideControls bool `form:"hideControls" json:"hideControls"`
SenderAddress string `form:"senderAddress" json:"senderAddress"` SenderName string `form:"senderName" json:"senderName"`
UserVerificationUrl string `form:"userVerificationUrl" json:"userVerificationUrl"` SenderAddress string `form:"senderAddress" json:"senderAddress"`
UserResetPasswordUrl string `form:"userResetPasswordUrl" json:"userResetPasswordUrl"` VerificationTemplate EmailTemplate `form:"verificationTemplate" json:"verificationTemplate"`
UserConfirmEmailChangeUrl string `form:"userConfirmEmailChangeUrl" json:"userConfirmEmailChangeUrl"` ResetPasswordTemplate EmailTemplate `form:"resetPasswordTemplate" json:"resetPasswordTemplate"`
ConfirmEmailChangeTemplate EmailTemplate `form:"confirmEmailChangeTemplate" json:"confirmEmailChangeTemplate"`
} }
// Validate makes MetaConfig validatable by implementing [validation.Validatable] interface. // Validate makes MetaConfig validatable by implementing [validation.Validatable] interface.
@@ -282,34 +286,45 @@ func (c MetaConfig) Validate() error {
validation.Field(&c.AppUrl, validation.Required, is.URL), validation.Field(&c.AppUrl, validation.Required, is.URL),
validation.Field(&c.SenderName, validation.Required, validation.Length(1, 255)), validation.Field(&c.SenderName, validation.Required, validation.Length(1, 255)),
validation.Field(&c.SenderAddress, is.Email, validation.Required), validation.Field(&c.SenderAddress, is.Email, validation.Required),
validation.Field(&c.VerificationTemplate, validation.Required),
validation.Field(&c.ResetPasswordTemplate, validation.Required),
validation.Field(&c.ConfirmEmailChangeTemplate, validation.Required),
)
}
type EmailTemplate struct {
Body string `form:"body" json:"body"`
Subject string `form:"subject" json:"subject"`
ActionUrl string `form:"actionUrl" json:"actionUrl"`
}
// Validate makes EmailTemplate validatable by implementing [validation.Validatable] interface.
func (t EmailTemplate) Validate() error {
return validation.ValidateStruct(&t,
validation.Field(&t.Subject, validation.Required),
validation.Field( validation.Field(
&c.UserVerificationUrl, &t.Body,
validation.Required, validation.Required,
validation.By(c.checkPlaceholders(EmailPlaceholderToken)), validation.By(checkPlaceholderParams(EmailPlaceholderActionUrl)),
), ),
validation.Field( validation.Field(
&c.UserResetPasswordUrl, &t.ActionUrl,
validation.Required, validation.Required,
validation.By(c.checkPlaceholders(EmailPlaceholderToken)), validation.By(checkPlaceholderParams(EmailPlaceholderToken)),
),
validation.Field(
&c.UserConfirmEmailChangeUrl,
validation.Required,
validation.By(c.checkPlaceholders(EmailPlaceholderToken)),
), ),
) )
} }
func (c *MetaConfig) checkPlaceholders(params ...string) validation.RuleFunc { func checkPlaceholderParams(params ...string) validation.RuleFunc {
return func(value any) error { return func(value any) error {
v, _ := value.(string) v, _ := value.(string)
if v == "" {
return nil // nothing to check
}
for _, param := range params { for _, param := range params {
if !strings.Contains(v, param) { if !strings.Contains(v, param) {
return validation.NewError("validation_missing_required_param", fmt.Sprintf("Missing required parameter %q", param)) return validation.NewError(
"validation_missing_required_param",
fmt.Sprintf("Missing required parameter %q", param),
)
} }
} }
@@ -317,6 +332,50 @@ func (c *MetaConfig) checkPlaceholders(params ...string) validation.RuleFunc {
} }
} }
// Resolve replaces the placeholder parameters in the current email
// template and returns its components as ready-to-use strings.
func (t EmailTemplate) Resolve(
appName string,
appUrl,
token string,
) (subject, body, actionUrl string) {
// replace action url placeholder params (if any)
actionUrlParams := map[string]string{
EmailPlaceholderAppName: appName,
EmailPlaceholderAppUrl: appUrl,
EmailPlaceholderToken: token,
}
actionUrl = t.ActionUrl
for k, v := range actionUrlParams {
actionUrl = strings.ReplaceAll(actionUrl, k, v)
}
actionUrl, _ = rest.NormalizeUrl(actionUrl)
// replace body placeholder params (if any)
bodyParams := map[string]string{
EmailPlaceholderAppName: appName,
EmailPlaceholderAppUrl: appUrl,
EmailPlaceholderToken: token,
EmailPlaceholderActionUrl: actionUrl,
}
body = t.Body
for k, v := range bodyParams {
body = strings.ReplaceAll(body, k, v)
}
// replace subject placeholder params (if any)
subjectParams := map[string]string{
EmailPlaceholderAppName: appName,
EmailPlaceholderAppUrl: appUrl,
}
subject = t.Subject
for k, v := range subjectParams {
subject = strings.ReplaceAll(subject, k, v)
}
return subject, body, actionUrl
}
// ------------------------------------------------------------------- // -------------------------------------------------------------------
type LogsConfig struct { type LogsConfig struct {
@@ -332,6 +391,35 @@ func (c LogsConfig) Validate() error {
// ------------------------------------------------------------------- // -------------------------------------------------------------------
type EmailAuthConfig struct {
Enabled bool `form:"enabled" json:"enabled"`
ExceptDomains []string `form:"exceptDomains" json:"exceptDomains"`
OnlyDomains []string `form:"onlyDomains" json:"onlyDomains"`
MinPasswordLength int `form:"minPasswordLength" json:"minPasswordLength"`
}
// Validate makes `EmailAuthConfig` validatable by implementing [validation.Validatable] interface.
func (c EmailAuthConfig) Validate() error {
return validation.ValidateStruct(&c,
validation.Field(
&c.ExceptDomains,
validation.When(len(c.OnlyDomains) > 0, validation.Empty).Else(validation.Each(is.Domain)),
),
validation.Field(
&c.OnlyDomains,
validation.When(len(c.ExceptDomains) > 0, validation.Empty).Else(validation.Each(is.Domain)),
),
validation.Field(
&c.MinPasswordLength,
validation.When(c.Enabled, validation.Required),
validation.Min(5),
validation.Max(100),
),
)
}
// -------------------------------------------------------------------
type AuthProviderConfig struct { type AuthProviderConfig struct {
Enabled bool `form:"enabled" json:"enabled"` Enabled bool `form:"enabled" json:"enabled"`
AllowRegistrations bool `form:"allowRegistrations" json:"allowRegistrations"` AllowRegistrations bool `form:"allowRegistrations" json:"allowRegistrations"`
@@ -381,32 +469,3 @@ func (c AuthProviderConfig) SetupProvider(provider auth.Provider) error {
return nil return nil
} }
// -------------------------------------------------------------------
type EmailAuthConfig struct {
Enabled bool `form:"enabled" json:"enabled"`
ExceptDomains []string `form:"exceptDomains" json:"exceptDomains"`
OnlyDomains []string `form:"onlyDomains" json:"onlyDomains"`
MinPasswordLength int `form:"minPasswordLength" json:"minPasswordLength"`
}
// Validate makes `EmailAuthConfig` validatable by implementing [validation.Validatable] interface.
func (c EmailAuthConfig) Validate() error {
return validation.ValidateStruct(&c,
validation.Field(
&c.ExceptDomains,
validation.When(len(c.OnlyDomains) > 0, validation.Empty).Else(validation.Each(is.Domain)),
),
validation.Field(
&c.OnlyDomains,
validation.When(len(c.ExceptDomains) > 0, validation.Empty).Else(validation.Each(is.Domain)),
),
validation.Field(
&c.MinPasswordLength,
validation.When(c.Enabled, validation.Required),
validation.Min(5),
validation.Max(100),
),
)
}
+54
View File
@@ -0,0 +1,54 @@
package core
// Common settings placeholder tokens
const (
EmailPlaceholderAppName string = "{APP_NAME}"
EmailPlaceholderAppUrl string = "{APP_URL}"
EmailPlaceholderToken string = "{TOKEN}"
EmailPlaceholderActionUrl string = "{ACTION_URL}"
)
var defaultVerificationTemplate = EmailTemplate{
Subject: "Verify your " + EmailPlaceholderAppName + " email",
Body: `<p>Hello,</p>
<p>Thank you for joining us at ` + EmailPlaceholderAppName + `.</p>
<p>Click on the button below to verify your email address.</p>
<p>
<a class="btn" href="` + EmailPlaceholderActionUrl + `" target="_blank" rel="noopener">Verify</a>
</p>
<p>
Thanks,<br/>
` + EmailPlaceholderAppName + ` team
</p>`,
ActionUrl: EmailPlaceholderAppUrl + "/_/#/users/confirm-verification/" + EmailPlaceholderToken,
}
var defaultResetPasswordTemplate = EmailTemplate{
Subject: "Reset your " + EmailPlaceholderAppName + " password",
Body: `<p>Hello,</p>
<p>Click on the button below to reset your password.</p>
<p>
<a class="btn" href="` + EmailPlaceholderActionUrl + `" target="_blank" rel="noopener">Reset password</a>
</p>
<p><i>If you didn't ask to reset your password, you can ignore this email.</i></p>
<p>
Thanks,<br/>
` + EmailPlaceholderAppName + ` team
</p>`,
ActionUrl: EmailPlaceholderAppUrl + "/_/#/users/confirm-password-reset/" + EmailPlaceholderToken,
}
var defaultConfirmEmailChangeTemplate = EmailTemplate{
Subject: "Confirm your " + EmailPlaceholderAppName + " new email address",
Body: `<p>Hello,</p>
<p>Click on the button below to confirm your new email address.</p>
<p>
<a class="btn" href="` + EmailPlaceholderActionUrl + `" target="_blank" rel="noopener">Confirm new email</a>
</p>
<p><i>If you didn't ask to change your email address, you can ignore this email.</i></p>
<p>
Thanks,<br/>
` + EmailPlaceholderAppName + ` team
</p>`,
ActionUrl: EmailPlaceholderAppUrl + "/_/#/users/confirm-email-change/" + EmailPlaceholderToken,
}
+179 -23
View File
@@ -2,9 +2,11 @@ package core_test
import ( import (
"encoding/json" "encoding/json"
"fmt"
"strings" "strings"
"testing" "testing"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/auth" "github.com/pocketbase/pocketbase/tools/auth"
) )
@@ -172,7 +174,7 @@ func TestSettingsRedactClone(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
expected := `{"meta":{"appName":"test123","appUrl":"http://localhost:8090","senderName":"Support","senderAddress":"support@example.com","userVerificationUrl":"%APP_URL%/_/#/users/confirm-verification/%TOKEN%","userResetPasswordUrl":"%APP_URL%/_/#/users/confirm-password-reset/%TOKEN%","userConfirmEmailChangeUrl":"%APP_URL%/_/#/users/confirm-email-change/%TOKEN%"},"logs":{"maxDays":7},"smtp":{"enabled":false,"host":"smtp.example.com","port":587,"username":"","password":"******","tls":true},"s3":{"enabled":false,"bucket":"","region":"","endpoint":"","accessKey":"","secret":"******"},"adminAuthToken":{"secret":"******","duration":1209600},"adminPasswordResetToken":{"secret":"******","duration":1800},"userAuthToken":{"secret":"******","duration":1209600},"userPasswordResetToken":{"secret":"******","duration":1800},"userEmailChangeToken":{"secret":"******","duration":1800},"userVerificationToken":{"secret":"******","duration":604800},"emailAuth":{"enabled":true,"exceptDomains":null,"onlyDomains":null,"minPasswordLength":8},"googleAuth":{"enabled":false,"allowRegistrations":true,"clientSecret":"******"},"facebookAuth":{"enabled":false,"allowRegistrations":true,"clientSecret":"******"},"githubAuth":{"enabled":false,"allowRegistrations":true,"clientSecret":"******"},"gitlabAuth":{"enabled":false,"allowRegistrations":true,"clientSecret":"******"}}` expected := `{"meta":{"appName":"test123","appUrl":"http://localhost:8090","hideControls":false,"senderName":"Support","senderAddress":"support@example.com","verificationTemplate":{"body":"\u003cp\u003eHello,\u003c/p\u003e\n\u003cp\u003eThank you for joining us at {APP_NAME}.\u003c/p\u003e\n\u003cp\u003eClick on the button below to verify your email address.\u003c/p\u003e\n\u003cp\u003e\n \u003ca class=\"btn\" href=\"{ACTION_URL}\" target=\"_blank\" rel=\"noopener\"\u003eVerify\u003c/a\u003e\n\u003c/p\u003e\n\u003cp\u003e\n Thanks,\u003cbr/\u003e\n {APP_NAME} team\n\u003c/p\u003e","subject":"Verify your {APP_NAME} email","actionUrl":"{APP_URL}/_/#/users/confirm-verification/{TOKEN}"},"resetPasswordTemplate":{"body":"\u003cp\u003eHello,\u003c/p\u003e\n\u003cp\u003eClick on the button below to reset your password.\u003c/p\u003e\n\u003cp\u003e\n \u003ca class=\"btn\" href=\"{ACTION_URL}\" target=\"_blank\" rel=\"noopener\"\u003eReset password\u003c/a\u003e\n\u003c/p\u003e\n\u003cp\u003e\u003ci\u003eIf you didn't ask to reset your password, you can ignore this email.\u003c/i\u003e\u003c/p\u003e\n\u003cp\u003e\n Thanks,\u003cbr/\u003e\n {APP_NAME} team\n\u003c/p\u003e","subject":"Reset your {APP_NAME} password","actionUrl":"{APP_URL}/_/#/users/confirm-password-reset/{TOKEN}"},"confirmEmailChangeTemplate":{"body":"\u003cp\u003eHello,\u003c/p\u003e\n\u003cp\u003eClick on the button below to confirm your new email address.\u003c/p\u003e\n\u003cp\u003e\n \u003ca class=\"btn\" href=\"{ACTION_URL}\" target=\"_blank\" rel=\"noopener\"\u003eConfirm new email\u003c/a\u003e\n\u003c/p\u003e\n\u003cp\u003e\u003ci\u003eIf you didn't ask to change your email address, you can ignore this email.\u003c/i\u003e\u003c/p\u003e\n\u003cp\u003e\n Thanks,\u003cbr/\u003e\n {APP_NAME} team\n\u003c/p\u003e","subject":"Confirm your {APP_NAME} new email address","actionUrl":"{APP_URL}/_/#/users/confirm-email-change/{TOKEN}"}},"logs":{"maxDays":7},"smtp":{"enabled":false,"host":"smtp.example.com","port":587,"username":"","password":"******","tls":true},"s3":{"enabled":false,"bucket":"","region":"","endpoint":"","accessKey":"","secret":"******","forcePathStyle":false},"adminAuthToken":{"secret":"******","duration":1209600},"adminPasswordResetToken":{"secret":"******","duration":1800},"userAuthToken":{"secret":"******","duration":1209600},"userPasswordResetToken":{"secret":"******","duration":1800},"userEmailChangeToken":{"secret":"******","duration":1800},"userVerificationToken":{"secret":"******","duration":604800},"emailAuth":{"enabled":true,"exceptDomains":null,"onlyDomains":null,"minPasswordLength":8},"googleAuth":{"enabled":false,"allowRegistrations":true,"clientSecret":"******"},"facebookAuth":{"enabled":false,"allowRegistrations":true,"clientSecret":"******"},"githubAuth":{"enabled":false,"allowRegistrations":true,"clientSecret":"******"},"gitlabAuth":{"enabled":false,"allowRegistrations":true,"clientSecret":"******"}}`
if encodedStr := string(encoded); encodedStr != expected { if encodedStr := string(encoded); encodedStr != expected {
t.Fatalf("Expected %v, got \n%v", expected, encodedStr) t.Fatalf("Expected %v, got \n%v", expected, encodedStr)
@@ -315,7 +317,19 @@ func TestS3ConfigValidate(t *testing.T) {
}, },
true, true,
}, },
// valid data // valid data (url endpoint)
{
core.S3Config{
Enabled: true,
Endpoint: "https://localhost:8090",
Bucket: "test",
Region: "test",
AccessKey: "test",
Secret: "test",
},
false,
},
// valid data (hostname endpoint)
{ {
core.S3Config{ core.S3Config{
Enabled: true, Enabled: true,
@@ -343,6 +357,24 @@ func TestS3ConfigValidate(t *testing.T) {
} }
func TestMetaConfigValidate(t *testing.T) { func TestMetaConfigValidate(t *testing.T) {
invalidTemplate := core.EmailTemplate{
Subject: "test",
ActionUrl: "test",
Body: "test",
}
noPlaceholdersTemplate := core.EmailTemplate{
Subject: "test",
ActionUrl: "http://example.com",
Body: "test",
}
withPlaceholdersTemplate := core.EmailTemplate{
Subject: "test",
ActionUrl: "http://example.com" + core.EmailPlaceholderToken,
Body: "test" + core.EmailPlaceholderActionUrl,
}
scenarios := []struct { scenarios := []struct {
config core.MetaConfig config core.MetaConfig
expectError bool expectError bool
@@ -355,39 +387,39 @@ func TestMetaConfigValidate(t *testing.T) {
// invalid data // invalid data
{ {
core.MetaConfig{ core.MetaConfig{
AppName: strings.Repeat("a", 300), AppName: strings.Repeat("a", 300),
AppUrl: "test", AppUrl: "test",
SenderName: strings.Repeat("a", 300), SenderName: strings.Repeat("a", 300),
SenderAddress: "invalid_email", SenderAddress: "invalid_email",
UserVerificationUrl: "test", VerificationTemplate: invalidTemplate,
UserResetPasswordUrl: "test", ResetPasswordTemplate: invalidTemplate,
UserConfirmEmailChangeUrl: "test", ConfirmEmailChangeTemplate: invalidTemplate,
}, },
true, true,
}, },
// invalid data (missing required placeholders) // invalid data (missing required placeholders)
{ {
core.MetaConfig{ core.MetaConfig{
AppName: "test", AppName: "test",
AppUrl: "https://example.com", AppUrl: "https://example.com",
SenderName: "test", SenderName: "test",
SenderAddress: "test@example.com", SenderAddress: "test@example.com",
UserVerificationUrl: "https://example.com", VerificationTemplate: noPlaceholdersTemplate,
UserResetPasswordUrl: "https://example.com", ResetPasswordTemplate: noPlaceholdersTemplate,
UserConfirmEmailChangeUrl: "https://example.com", ConfirmEmailChangeTemplate: noPlaceholdersTemplate,
}, },
true, true,
}, },
// valid data // valid data
{ {
core.MetaConfig{ core.MetaConfig{
AppName: "test", AppName: "test",
AppUrl: "https://example.com", AppUrl: "https://example.com",
SenderName: "test", SenderName: "test",
SenderAddress: "test@example.com", SenderAddress: "test@example.com",
UserVerificationUrl: "https://example.com/" + core.EmailPlaceholderToken, VerificationTemplate: withPlaceholdersTemplate,
UserResetPasswordUrl: "https://example.com/" + core.EmailPlaceholderToken, ResetPasswordTemplate: withPlaceholdersTemplate,
UserConfirmEmailChangeUrl: "https://example.com/" + core.EmailPlaceholderToken, ConfirmEmailChangeTemplate: withPlaceholdersTemplate,
}, },
false, false,
}, },
@@ -406,6 +438,130 @@ func TestMetaConfigValidate(t *testing.T) {
} }
} }
func TestEmailTemplateValidate(t *testing.T) {
scenarios := []struct {
emailTemplate core.EmailTemplate
expectedErrors []string
}{
// require values
{
core.EmailTemplate{},
[]string{"subject", "actionUrl", "body"},
},
// missing placeholders
{
core.EmailTemplate{
Subject: "test",
ActionUrl: "test",
Body: "test",
},
[]string{"actionUrl", "body"},
},
// valid data
{
core.EmailTemplate{
Subject: "test",
ActionUrl: "test" + core.EmailPlaceholderToken,
Body: "test" + core.EmailPlaceholderActionUrl,
},
[]string{},
},
}
for i, s := range scenarios {
result := s.emailTemplate.Validate()
// parse errors
errs, ok := result.(validation.Errors)
if !ok && result != nil {
t.Errorf("(%d) Failed to parse errors %v", i, result)
continue
}
// check errors
if len(errs) > len(s.expectedErrors) {
t.Errorf("(%d) Expected error keys %v, got %v", i, s.expectedErrors, errs)
}
for _, k := range s.expectedErrors {
if _, ok := errs[k]; !ok {
t.Errorf("(%d) Missing expected error key %q in %v", i, k, errs)
}
}
}
}
func TestEmailTemplateResolve(t *testing.T) {
allPlaceholders := core.EmailPlaceholderActionUrl + core.EmailPlaceholderToken + core.EmailPlaceholderAppName + core.EmailPlaceholderAppUrl
scenarios := []struct {
emailTemplate core.EmailTemplate
expectedSubject string
expectedBody string
expectedActionUrl string
}{
// no placeholders
{
emailTemplate: core.EmailTemplate{
Subject: "subject:",
Body: "body:",
ActionUrl: "/actionUrl////",
},
expectedSubject: "subject:",
expectedActionUrl: "/actionUrl/",
expectedBody: "body:",
},
// with placeholders
{
emailTemplate: core.EmailTemplate{
ActionUrl: "/actionUrl////" + allPlaceholders,
Subject: "subject:" + allPlaceholders,
Body: "body:" + allPlaceholders,
},
expectedActionUrl: fmt.Sprintf(
"/actionUrl/%%7BACTION_URL%%7D%s%s%s",
"token_test",
"name_test",
"url_test",
),
expectedSubject: fmt.Sprintf(
"subject:%s%s%s%s",
core.EmailPlaceholderActionUrl,
core.EmailPlaceholderToken,
"name_test",
"url_test",
),
expectedBody: fmt.Sprintf(
"body:%s%s%s%s",
fmt.Sprintf(
"/actionUrl/%%7BACTION_URL%%7D%s%s%s",
"token_test",
"name_test",
"url_test",
),
"token_test",
"name_test",
"url_test",
),
},
}
for i, s := range scenarios {
subject, body, actionUrl := s.emailTemplate.Resolve("name_test", "url_test", "token_test")
if s.expectedSubject != subject {
t.Errorf("(%d) Expected subject %q got %q", i, s.expectedSubject, subject)
}
if s.expectedBody != body {
t.Errorf("(%d) Expected body \n%v got \n%v", i, s.expectedBody, body)
}
if s.expectedActionUrl != actionUrl {
t.Errorf("(%d) Expected actionUrl \n%v got \n%v", i, s.expectedActionUrl, actionUrl)
}
}
}
func TestLogsConfigValidate(t *testing.T) { func TestLogsConfigValidate(t *testing.T) {
scenarios := []struct { scenarios := []struct {
config core.LogsConfig config core.LogsConfig
+65 -33
View File
@@ -49,6 +49,12 @@ func (dao *Dao) FindById(m models.Model, id string) error {
return dao.ModelQuery(m).Where(dbx.HashExp{"id": id}).Limit(1).One(m) return dao.ModelQuery(m).Where(dbx.HashExp{"id": id}).Limit(1).One(m)
} }
type afterCallGroup struct {
Action string
EventDao *Dao
Model models.Model
}
// RunInTransaction wraps fn into a transaction. // RunInTransaction wraps fn into a transaction.
// //
// It is safe to nest RunInTransaction calls. // It is safe to nest RunInTransaction calls.
@@ -59,45 +65,61 @@ func (dao *Dao) RunInTransaction(fn func(txDao *Dao) error) error {
// so execute the function within the current transaction // so execute the function within the current transaction
return fn(dao) return fn(dao)
case *dbx.DB: case *dbx.DB:
return txOrDB.Transactional(func(tx *dbx.Tx) error { afterCalls := []afterCallGroup{}
txError := txOrDB.Transactional(func(tx *dbx.Tx) error {
txDao := New(tx) txDao := New(tx)
txDao.BeforeCreateFunc = func(eventDao *Dao, m models.Model) error { if dao.BeforeCreateFunc != nil {
if dao.BeforeCreateFunc != nil { txDao.BeforeCreateFunc = func(eventDao *Dao, m models.Model) error {
return dao.BeforeCreateFunc(eventDao, m) return dao.BeforeCreateFunc(eventDao, m)
} }
return nil
} }
txDao.AfterCreateFunc = func(eventDao *Dao, m models.Model) { if dao.BeforeUpdateFunc != nil {
if dao.AfterCreateFunc != nil { txDao.BeforeUpdateFunc = func(eventDao *Dao, m models.Model) error {
dao.AfterCreateFunc(eventDao, m)
}
}
txDao.BeforeUpdateFunc = func(eventDao *Dao, m models.Model) error {
if dao.BeforeUpdateFunc != nil {
return dao.BeforeUpdateFunc(eventDao, m) return dao.BeforeUpdateFunc(eventDao, m)
} }
return nil
} }
txDao.AfterUpdateFunc = func(eventDao *Dao, m models.Model) { if dao.BeforeDeleteFunc != nil {
if dao.AfterUpdateFunc != nil { txDao.BeforeDeleteFunc = func(eventDao *Dao, m models.Model) error {
dao.AfterUpdateFunc(eventDao, m)
}
}
txDao.BeforeDeleteFunc = func(eventDao *Dao, m models.Model) error {
if dao.BeforeDeleteFunc != nil {
return dao.BeforeDeleteFunc(eventDao, m) return dao.BeforeDeleteFunc(eventDao, m)
} }
return nil
} }
txDao.AfterDeleteFunc = func(eventDao *Dao, m models.Model) {
if dao.AfterDeleteFunc != nil { if dao.AfterCreateFunc != nil {
dao.AfterDeleteFunc(eventDao, m) txDao.AfterCreateFunc = func(eventDao *Dao, m models.Model) {
afterCalls = append(afterCalls, afterCallGroup{"create", eventDao, m})
}
}
if dao.AfterUpdateFunc != nil {
txDao.AfterUpdateFunc = func(eventDao *Dao, m models.Model) {
afterCalls = append(afterCalls, afterCallGroup{"update", eventDao, m})
}
}
if dao.AfterDeleteFunc != nil {
txDao.AfterDeleteFunc = func(eventDao *Dao, m models.Model) {
afterCalls = append(afterCalls, afterCallGroup{"delete", eventDao, m})
} }
} }
return fn(txDao) return fn(txDao)
}) })
if txError == nil {
// execute after event calls on successful transaction
for _, call := range afterCalls {
switch call.Action {
case "create":
dao.AfterCreateFunc(call.EventDao, call.Model)
case "update":
dao.AfterUpdateFunc(call.EventDao, call.Model)
case "delete":
dao.AfterDeleteFunc(call.EventDao, call.Model)
}
}
}
return txError
} }
return errors.New("Failed to start transaction (unknown dao.db)") return errors.New("Failed to start transaction (unknown dao.db)")
@@ -115,9 +137,8 @@ func (dao *Dao) Delete(m models.Model) error {
} }
} }
deleteErr := dao.db.Model(m).Delete() if err := dao.db.Model(m).Delete(); err != nil {
if deleteErr != nil { return err
return deleteErr
} }
if dao.AfterDeleteFunc != nil { if dao.AfterDeleteFunc != nil {
@@ -129,11 +150,11 @@ func (dao *Dao) Delete(m models.Model) error {
// Save upserts (update or create if primary key is not set) the provided model. // Save upserts (update or create if primary key is not set) the provided model.
func (dao *Dao) Save(m models.Model) error { func (dao *Dao) Save(m models.Model) error {
if m.HasId() { if m.IsNew() {
return dao.update(m) return dao.create(m)
} }
return dao.create(m) return dao.update(m)
} }
func (dao *Dao) update(m models.Model) error { func (dao *Dao) update(m models.Model) error {
@@ -141,6 +162,10 @@ func (dao *Dao) update(m models.Model) error {
return errors.New("ID is not set") return errors.New("ID is not set")
} }
if m.GetCreated().IsZero() {
m.RefreshCreated()
}
m.RefreshUpdated() m.RefreshUpdated()
if dao.BeforeUpdateFunc != nil { if dao.BeforeUpdateFunc != nil {
@@ -162,8 +187,7 @@ func (dao *Dao) update(m models.Model) error {
return err return err
} }
} else { } else {
err := dao.db.Model(m).Update() if err := dao.db.Model(m).Update(); err != nil {
if err != nil {
return err return err
} }
} }
@@ -181,6 +205,9 @@ func (dao *Dao) create(m models.Model) error {
m.RefreshId() m.RefreshId()
} }
// mark the model as "new" since the model now always has an ID
m.MarkAsNew()
if m.GetCreated().IsZero() { if m.GetCreated().IsZero() {
m.RefreshCreated() m.RefreshCreated()
} }
@@ -197,18 +224,23 @@ func (dao *Dao) create(m models.Model) error {
if v, ok := any(m).(models.ColumnValueMapper); ok { if v, ok := any(m).(models.ColumnValueMapper); ok {
dataMap := v.ColumnValueMap() dataMap := v.ColumnValueMap()
if _, ok := dataMap["id"]; !ok {
dataMap["id"] = m.GetId()
}
_, err := dao.db.Insert(m.TableName(), dataMap).Execute() _, err := dao.db.Insert(m.TableName(), dataMap).Execute()
if err != nil { if err != nil {
return err return err
} }
} else { } else {
err := dao.db.Model(m).Insert() if err := dao.db.Model(m).Insert(); err != nil {
if err != nil {
return err return err
} }
} }
// clears the "new" model flag
m.UnmarkAsNew()
if dao.AfterCreateFunc != nil { if dao.AfterCreateFunc != nil {
dao.AfterCreateFunc(dao, m) dao.AfterCreateFunc(dao, m)
} }
+269 -10
View File
@@ -158,6 +158,33 @@ func TestDaoSaveCreate(t *testing.T) {
} }
} }
func TestDaoSaveWithInsertId(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
model := &models.Admin{}
model.Id = "test"
model.Email = "test_new@example.com"
model.MarkAsNew()
if err := testApp.Dao().Save(model); err != nil {
t.Fatal(err)
}
// refresh
model, _ = testApp.Dao().FindAdminById("test")
if model == nil {
t.Fatal("Failed to find admin with id 'test'")
}
expectedHooks := []string{"OnModelBeforeCreate", "OnModelAfterCreate"}
for _, h := range expectedHooks {
if v, ok := testApp.EventCalls[h]; !ok || v != 1 {
t.Fatalf("Expected event %s to be called exactly one time, got %d", h, v)
}
}
}
func TestDaoSaveUpdate(t *testing.T) { func TestDaoSaveUpdate(t *testing.T) {
testApp, _ := tests.NewTestApp() testApp, _ := tests.NewTestApp()
defer testApp.Cleanup() defer testApp.Cleanup()
@@ -184,6 +211,61 @@ func TestDaoSaveUpdate(t *testing.T) {
} }
} }
type dummyColumnValueMapper struct {
models.Admin
}
func (a *dummyColumnValueMapper) ColumnValueMap() map[string]any {
return map[string]any{
"email": a.Email,
"passwordHash": a.PasswordHash,
"tokenKey": "custom_token_key",
}
}
func TestDaoSaveWithColumnValueMapper(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
model := &dummyColumnValueMapper{}
model.Id = "test_mapped_id" // explicitly set an id
model.Email = "test_mapped_create@example.com"
model.TokenKey = "test_unmapped_token_key" // not used in the map
model.SetPassword("123456")
model.MarkAsNew()
if err := testApp.Dao().Save(model); err != nil {
t.Fatal(err)
}
createdModel, _ := testApp.Dao().FindAdminById("test_mapped_id")
if createdModel == nil {
t.Fatal("[create] Failed to find model with id 'test_mapped_id'")
}
if createdModel.Email != model.Email {
t.Fatalf("Expected model with email %q, got %q", model.Email, createdModel.Email)
}
if createdModel.TokenKey != "custom_token_key" {
t.Fatalf("Expected model with tokenKey %q, got %q", "custom_token_key", createdModel.TokenKey)
}
model.Email = "test_mapped_update@example.com"
model.Avatar = 9 // not mapped and expect to be ignored
if err := testApp.Dao().Save(model); err != nil {
t.Fatal(err)
}
updatedModel, _ := testApp.Dao().FindAdminById("test_mapped_id")
if updatedModel == nil {
t.Fatal("[update] Failed to find model with id 'test_mapped_id'")
}
if updatedModel.Email != model.Email {
t.Fatalf("Expected model with email %q, got %q", model.Email, createdModel.Email)
}
if updatedModel.Avatar != 0 {
t.Fatalf("Expected model avatar 0, got %v", updatedModel.Avatar)
}
}
func TestDaoDelete(t *testing.T) { func TestDaoDelete(t *testing.T) {
testApp, _ := tests.NewTestApp() testApp, _ := tests.NewTestApp()
defer testApp.Cleanup() defer testApp.Cleanup()
@@ -211,35 +293,212 @@ func TestDaoBeforeHooksError(t *testing.T) {
testApp, _ := tests.NewTestApp() testApp, _ := tests.NewTestApp()
defer testApp.Cleanup() defer testApp.Cleanup()
testApp.Dao().BeforeCreateFunc = func(eventDao *daos.Dao, m models.Model) error { baseDao := testApp.Dao()
baseDao.BeforeCreateFunc = func(eventDao *daos.Dao, m models.Model) error {
return errors.New("before_create") return errors.New("before_create")
} }
testApp.Dao().BeforeUpdateFunc = func(eventDao *daos.Dao, m models.Model) error { baseDao.BeforeUpdateFunc = func(eventDao *daos.Dao, m models.Model) error {
return errors.New("before_update") return errors.New("before_update")
} }
testApp.Dao().BeforeDeleteFunc = func(eventDao *daos.Dao, m models.Model) error { baseDao.BeforeDeleteFunc = func(eventDao *daos.Dao, m models.Model) error {
return errors.New("before_delete") return errors.New("before_delete")
} }
existingModel, _ := testApp.Dao().FindAdminByEmail("test@example.com") existingModel, _ := testApp.Dao().FindAdminByEmail("test@example.com")
// try to create // test create error
// --- // ---
newModel := &models.Admin{} newModel := &models.Admin{}
newModel.Email = "test_new@example.com" if err := baseDao.Save(newModel); err.Error() != "before_create" {
if err := testApp.Dao().Save(newModel); err.Error() != "before_create" {
t.Fatalf("Expected before_create error, got %v", err) t.Fatalf("Expected before_create error, got %v", err)
} }
// try to update // test update error
// --- // ---
if err := testApp.Dao().Save(existingModel); err.Error() != "before_update" { if err := baseDao.Save(existingModel); err.Error() != "before_update" {
t.Fatalf("Expected before_update error, got %v", err) t.Fatalf("Expected before_update error, got %v", err)
} }
// try to delete // test delete error
// --- // ---
if err := testApp.Dao().Delete(existingModel); err.Error() != "before_delete" { if err := baseDao.Delete(existingModel); err.Error() != "before_delete" {
t.Fatalf("Expected before_delete error, got %v", err) t.Fatalf("Expected before_delete error, got %v", err)
} }
} }
func TestDaoTransactionHooksCallsOnFailure(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
beforeCreateFuncCalls := 0
beforeUpdateFuncCalls := 0
beforeDeleteFuncCalls := 0
afterCreateFuncCalls := 0
afterUpdateFuncCalls := 0
afterDeleteFuncCalls := 0
baseDao := testApp.Dao()
baseDao.BeforeCreateFunc = func(eventDao *daos.Dao, m models.Model) error {
beforeCreateFuncCalls++
return nil
}
baseDao.BeforeUpdateFunc = func(eventDao *daos.Dao, m models.Model) error {
beforeUpdateFuncCalls++
return nil
}
baseDao.BeforeDeleteFunc = func(eventDao *daos.Dao, m models.Model) error {
beforeDeleteFuncCalls++
return nil
}
baseDao.AfterCreateFunc = func(eventDao *daos.Dao, m models.Model) {
afterCreateFuncCalls++
}
baseDao.AfterUpdateFunc = func(eventDao *daos.Dao, m models.Model) {
afterUpdateFuncCalls++
}
baseDao.AfterDeleteFunc = func(eventDao *daos.Dao, m models.Model) {
afterDeleteFuncCalls++
}
existingModel, _ := testApp.Dao().FindAdminByEmail("test@example.com")
baseDao.RunInTransaction(func(txDao1 *daos.Dao) error {
return txDao1.RunInTransaction(func(txDao2 *daos.Dao) error {
// test create
// ---
newModel := &models.Admin{}
newModel.Email = "test_new1@example.com"
newModel.SetPassword("123456")
if err := txDao2.Save(newModel); err != nil {
t.Fatal(err)
}
// test update (twice)
// ---
if err := txDao2.Save(existingModel); err != nil {
t.Fatal(err)
}
if err := txDao2.Save(existingModel); err != nil {
t.Fatal(err)
}
// test delete
// ---
if err := txDao2.Delete(existingModel); err != nil {
t.Fatal(err)
}
return errors.New("test_tx_error")
})
})
if beforeCreateFuncCalls != 1 {
t.Fatalf("Expected beforeCreateFuncCalls to be called 1 times, got %d", beforeCreateFuncCalls)
}
if beforeUpdateFuncCalls != 2 {
t.Fatalf("Expected beforeUpdateFuncCalls to be called 2 times, got %d", beforeUpdateFuncCalls)
}
if beforeDeleteFuncCalls != 1 {
t.Fatalf("Expected beforeDeleteFuncCalls to be called 1 times, got %d", beforeDeleteFuncCalls)
}
if afterCreateFuncCalls != 0 {
t.Fatalf("Expected afterCreateFuncCalls to be called 0 times, got %d", afterCreateFuncCalls)
}
if afterUpdateFuncCalls != 0 {
t.Fatalf("Expected afterUpdateFuncCalls to be called 0 times, got %d", afterUpdateFuncCalls)
}
if afterDeleteFuncCalls != 0 {
t.Fatalf("Expected afterDeleteFuncCalls to be called 0 times, got %d", afterDeleteFuncCalls)
}
}
func TestDaoTransactionHooksCallsOnSuccess(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
beforeCreateFuncCalls := 0
beforeUpdateFuncCalls := 0
beforeDeleteFuncCalls := 0
afterCreateFuncCalls := 0
afterUpdateFuncCalls := 0
afterDeleteFuncCalls := 0
baseDao := testApp.Dao()
baseDao.BeforeCreateFunc = func(eventDao *daos.Dao, m models.Model) error {
beforeCreateFuncCalls++
return nil
}
baseDao.BeforeUpdateFunc = func(eventDao *daos.Dao, m models.Model) error {
beforeUpdateFuncCalls++
return nil
}
baseDao.BeforeDeleteFunc = func(eventDao *daos.Dao, m models.Model) error {
beforeDeleteFuncCalls++
return nil
}
baseDao.AfterCreateFunc = func(eventDao *daos.Dao, m models.Model) {
afterCreateFuncCalls++
}
baseDao.AfterUpdateFunc = func(eventDao *daos.Dao, m models.Model) {
afterUpdateFuncCalls++
}
baseDao.AfterDeleteFunc = func(eventDao *daos.Dao, m models.Model) {
afterDeleteFuncCalls++
}
existingModel, _ := testApp.Dao().FindAdminByEmail("test@example.com")
baseDao.RunInTransaction(func(txDao1 *daos.Dao) error {
return txDao1.RunInTransaction(func(txDao2 *daos.Dao) error {
// test create
// ---
newModel := &models.Admin{}
newModel.Email = "test_new1@example.com"
newModel.SetPassword("123456")
if err := txDao2.Save(newModel); err != nil {
t.Fatal(err)
}
// test update (twice)
// ---
if err := txDao2.Save(existingModel); err != nil {
t.Fatal(err)
}
if err := txDao2.Save(existingModel); err != nil {
t.Fatal(err)
}
// test delete
// ---
if err := txDao2.Delete(existingModel); err != nil {
t.Fatal(err)
}
return nil
})
})
if beforeCreateFuncCalls != 1 {
t.Fatalf("Expected beforeCreateFuncCalls to be called 1 times, got %d", beforeCreateFuncCalls)
}
if beforeUpdateFuncCalls != 2 {
t.Fatalf("Expected beforeUpdateFuncCalls to be called 2 times, got %d", beforeUpdateFuncCalls)
}
if beforeDeleteFuncCalls != 1 {
t.Fatalf("Expected beforeDeleteFuncCalls to be called 1 times, got %d", beforeDeleteFuncCalls)
}
if afterCreateFuncCalls != 1 {
t.Fatalf("Expected afterCreateFuncCalls to be called 1 times, got %d", afterCreateFuncCalls)
}
if afterUpdateFuncCalls != 2 {
t.Fatalf("Expected afterUpdateFuncCalls to be called 2 times, got %d", afterUpdateFuncCalls)
}
if afterDeleteFuncCalls != 1 {
t.Fatalf("Expected afterDeleteFuncCalls to be called 1 times, got %d", afterDeleteFuncCalls)
}
}
+115 -3
View File
@@ -113,7 +113,7 @@ func (dao *Dao) FindCollectionReferences(collection *models.Collection, excludeI
// - is referenced as part of a relation field in another collection // - is referenced as part of a relation field in another collection
func (dao *Dao) DeleteCollection(collection *models.Collection) error { func (dao *Dao) DeleteCollection(collection *models.Collection) error {
if collection.System { if collection.System {
return errors.New("System collections cannot be deleted.") return fmt.Errorf("System collection %q cannot be deleted.", collection.Name)
} }
// ensure that there aren't any existing references. // ensure that there aren't any existing references.
@@ -123,7 +123,7 @@ func (dao *Dao) DeleteCollection(collection *models.Collection) error {
return err return err
} }
if total := len(result); total > 0 { if total := len(result); total > 0 {
return fmt.Errorf("The collection has external relation field references (%d).", total) return fmt.Errorf("The collection %q has external relation field references (%d).", collection.Name, total)
} }
return dao.RunInTransaction(func(txDao *Dao) error { return dao.RunInTransaction(func(txDao *Dao) error {
@@ -141,7 +141,7 @@ func (dao *Dao) DeleteCollection(collection *models.Collection) error {
func (dao *Dao) SaveCollection(collection *models.Collection) error { func (dao *Dao) SaveCollection(collection *models.Collection) error {
var oldCollection *models.Collection var oldCollection *models.Collection
if collection.HasId() { if !collection.IsNew() {
// get the existing collection state to compare with the new one // get the existing collection state to compare with the new one
// note: the select is outside of the transaction to prevent SQLITE_LOCKED error when mixing read&write in a single transaction // note: the select is outside of the transaction to prevent SQLITE_LOCKED error when mixing read&write in a single transaction
var findErr error var findErr error
@@ -161,3 +161,115 @@ func (dao *Dao) SaveCollection(collection *models.Collection) error {
return txDao.SyncRecordTableSchema(collection, oldCollection) return txDao.SyncRecordTableSchema(collection, oldCollection)
}) })
} }
// ImportCollections imports the provided collections list within a single transaction.
//
// NB1! If deleteMissing is set, all local collections and schema fields, that are not present
// in the imported configuration, WILL BE DELETED (including their related records data).
//
// NB2! This method doesn't perform validations on the imported collections data!
// If you need validations, use [forms.CollectionsImport].
func (dao *Dao) ImportCollections(
importedCollections []*models.Collection,
deleteMissing bool,
beforeRecordsSync func(txDao *Dao, mappedImported, mappedExisting map[string]*models.Collection) error,
) error {
if len(importedCollections) == 0 {
return errors.New("No collections to import")
}
return dao.RunInTransaction(func(txDao *Dao) error {
existingCollections := []*models.Collection{}
if err := txDao.CollectionQuery().OrderBy("created ASC").All(&existingCollections); err != nil {
return err
}
mappedExisting := make(map[string]*models.Collection, len(existingCollections))
for _, existing := range existingCollections {
mappedExisting[existing.GetId()] = existing
}
mappedImported := make(map[string]*models.Collection, len(importedCollections))
for _, imported := range importedCollections {
// generate id if not set
if !imported.HasId() {
imported.MarkAsNew()
imported.RefreshId()
}
if existing, ok := mappedExisting[imported.GetId()]; ok {
// preserve original created date
if !existing.Created.IsZero() {
imported.Created = existing.Created
}
// extend existing schema
if !deleteMissing {
schema, _ := existing.Schema.Clone()
for _, f := range imported.Schema.Fields() {
schema.AddField(f) // add or replace
}
imported.Schema = *schema
}
} else {
imported.MarkAsNew()
}
mappedImported[imported.GetId()] = imported
}
// delete old collections not available in the new configuration
// (before saving the imports in case a deleted collection name is being reused)
if deleteMissing {
for _, existing := range existingCollections {
if mappedImported[existing.GetId()] != nil {
continue // exist
}
if existing.System {
return fmt.Errorf("System collection %q cannot be deleted.", existing.Name)
}
// delete the collection
if err := txDao.Delete(existing); err != nil {
return err
}
}
}
// upsert imported collections
for _, imported := range importedCollections {
if err := txDao.Save(imported); err != nil {
return err
}
}
if beforeRecordsSync != nil {
if err := beforeRecordsSync(txDao, mappedImported, mappedExisting); err != nil {
return err
}
}
// delete the record tables of the deleted collections
if deleteMissing {
for _, existing := range existingCollections {
if mappedImported[existing.GetId()] != nil {
continue // exist
}
if err := txDao.DeleteTable(existing.Name); err != nil {
return err
}
}
}
// sync the upserted collections with the related records table
for _, imported := range importedCollections {
existing := mappedExisting[imported.GetId()]
if err := txDao.SyncRecordTableSchema(imported, existing); err != nil {
return err
}
}
return nil
})
}
+315 -1
View File
@@ -1,8 +1,11 @@
package daos_test package daos_test
import ( import (
"encoding/json"
"errors"
"testing" "testing"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/models/schema" "github.com/pocketbase/pocketbase/models/schema"
"github.com/pocketbase/pocketbase/tests" "github.com/pocketbase/pocketbase/tests"
@@ -113,7 +116,7 @@ func TestFindCollectionReferences(t *testing.T) {
t.Fatalf("Expected 1 collection, got %d: %v", len(result), result) t.Fatalf("Expected 1 collection, got %d: %v", len(result), result)
} }
expectedFields := []string{"onerel", "manyrels", "rel_cascade"} expectedFields := []string{"onerel", "manyrels", "cascaderel"}
for col, fields := range result { for col, fields := range result {
if col.Name != "demo2" { if col.Name != "demo2" {
@@ -250,3 +253,314 @@ func TestSaveCollectionUpdate(t *testing.T) {
} }
} }
} }
func TestImportCollections(t *testing.T) {
scenarios := []struct {
name string
jsonData string
deleteMissing bool
beforeRecordsSync func(txDao *daos.Dao, mappedImported, mappedExisting map[string]*models.Collection) error
expectError bool
expectCollectionsCount int
afterTestFunc func(testApp *tests.TestApp, resultCollections []*models.Collection)
}{
{
name: "empty collections",
jsonData: `[]`,
expectError: true,
expectCollectionsCount: 5,
},
{
name: "check db constraints",
jsonData: `[
{"name": "import_test", "schema": []}
]`,
deleteMissing: false,
expectError: true,
expectCollectionsCount: 5,
},
{
name: "minimal collection import",
jsonData: `[
{"name": "import_test", "schema": [{"name":"test", "type": "text"}]}
]`,
deleteMissing: false,
expectError: false,
expectCollectionsCount: 6,
},
{
name: "minimal collection import + failed beforeRecordsSync",
jsonData: `[
{"name": "import_test", "schema": [{"name":"test", "type": "text"}]}
]`,
beforeRecordsSync: func(txDao *daos.Dao, mappedImported, mappedExisting map[string]*models.Collection) error {
return errors.New("test_error")
},
deleteMissing: false,
expectError: true,
expectCollectionsCount: 5,
},
{
name: "minimal collection import + successful beforeRecordsSync",
jsonData: `[
{"name": "import_test", "schema": [{"name":"test", "type": "text"}]}
]`,
beforeRecordsSync: func(txDao *daos.Dao, mappedImported, mappedExisting map[string]*models.Collection) error {
return nil
},
deleteMissing: false,
expectError: false,
expectCollectionsCount: 6,
},
{
name: "new + update + delete system collection",
jsonData: `[
{
"id":"3f2888f8-075d-49fe-9d09-ea7e951000dc",
"name":"demo",
"schema":[
{
"id":"_2hlxbmp",
"name":"title",
"type":"text",
"system":false,
"required":true,
"unique":false,
"options":{
"min":3,
"max":null,
"pattern":""
}
}
]
},
{
"name": "import1",
"schema": [
{
"name":"active",
"type":"bool"
}
]
}
]`,
deleteMissing: true,
expectError: true,
expectCollectionsCount: 5,
},
{
name: "new + update + delete non-system collection",
jsonData: `[
{
"id":"abe78266-fd4d-4aea-962d-8c0138ac522b",
"name":"profiles",
"system":true,
"listRule":"userId = @request.user.id",
"viewRule":"created > 'test_change'",
"createRule":"userId = @request.user.id",
"updateRule":"userId = @request.user.id",
"deleteRule":"userId = @request.user.id",
"schema":[
{
"id":"koih1lqx",
"name":"userId",
"type":"user",
"system":true,
"required":true,
"unique":true,
"options":{
"maxSelect":1,
"cascadeDelete":true
}
},
{
"id":"69ycbg3q",
"name":"rel",
"type":"relation",
"system":false,
"required":false,
"unique":false,
"options":{
"maxSelect":2,
"collectionId":"abe78266-fd4d-4aea-962d-8c0138ac522b",
"cascadeDelete":false
}
}
]
},
{
"id":"3f2888f8-075d-49fe-9d09-ea7e951000dc",
"name":"demo",
"schema":[
{
"id":"_2hlxbmp",
"name":"title",
"type":"text",
"system":false,
"required":true,
"unique":false,
"options":{
"min":3,
"max":null,
"pattern":""
}
}
]
},
{
"id": "test_deleted_collection_name_reuse",
"name": "demo2",
"schema": [
{
"id":"fz6iql2m",
"name":"active",
"type":"bool"
}
]
}
]`,
deleteMissing: true,
expectError: false,
expectCollectionsCount: 3,
},
{
name: "test with deleteMissing: false",
jsonData: `[
{
"id":"abe78266-fd4d-4aea-962d-8c0138ac522b",
"name":"profiles",
"system":true,
"listRule":"userId = @request.user.id",
"viewRule":"created > 'test_change'",
"createRule":"userId = @request.user.id",
"updateRule":"userId = @request.user.id",
"deleteRule":"userId = @request.user.id",
"schema":[
{
"id":"69ycbg3q",
"name":"rel",
"type":"relation",
"system":false,
"required":false,
"unique":false,
"options":{
"maxSelect":2,
"collectionId":"abe78266-fd4d-4aea-962d-8c0138ac522b",
"cascadeDelete":true
}
},
{
"id":"abcd_import",
"name":"new_field",
"type":"bool"
}
]
},
{
"id":"3f2888f8-075d-49fe-9d09-ea7e951000dc",
"name":"demo",
"schema":[
{
"id":"_2hlxbmp",
"name":"title",
"type":"text",
"system":false,
"required":true,
"unique":false,
"options":{
"min":3,
"max":null,
"pattern":""
}
},
{
"id":"_2hlxbmp",
"name":"field_with_duplicate_id",
"type":"text",
"system":false,
"required":true,
"unique":false,
"options":{
"min":3,
"max":null,
"pattern":""
}
},
{
"id":"abcd_import",
"name":"new_field",
"type":"text"
}
]
},
{
"name": "new_import",
"schema": [
{
"id":"abcd_import",
"name":"active",
"type":"bool"
}
]
}
]`,
deleteMissing: false,
expectError: false,
expectCollectionsCount: 6,
afterTestFunc: func(testApp *tests.TestApp, resultCollections []*models.Collection) {
expectedCollectionFields := map[string]int{
"profiles": 6,
"demo": 3,
"demo2": 14,
"demo3": 1,
"demo4": 6,
"new_import": 1,
}
for name, expectedCount := range expectedCollectionFields {
collection, err := testApp.Dao().FindCollectionByNameOrId(name)
if err != nil {
t.Fatal(err)
}
if totalFields := len(collection.Schema.Fields()); totalFields != expectedCount {
t.Errorf("Expected %d %q fields, got %d", expectedCount, collection.Name, totalFields)
}
}
},
},
}
for _, scenario := range scenarios {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
importedCollections := []*models.Collection{}
// load data
loadErr := json.Unmarshal([]byte(scenario.jsonData), &importedCollections)
if loadErr != nil {
t.Fatalf("[%s] Failed to load data: %v", scenario.name, loadErr)
continue
}
err := testApp.Dao().ImportCollections(importedCollections, scenario.deleteMissing, scenario.beforeRecordsSync)
hasErr := err != nil
if hasErr != scenario.expectError {
t.Errorf("[%s] Expected hasErr to be %v, got %v (%v)", scenario.name, scenario.expectError, hasErr, err)
}
// check collections count
collections := []*models.Collection{}
if err := testApp.Dao().CollectionQuery().All(&collections); err != nil {
t.Fatal(err)
}
if len(collections) != scenario.expectCollectionsCount {
t.Errorf("[%s] Expected %d collections, got %d", scenario.name, scenario.expectCollectionsCount, len(collections))
}
if scenario.afterTestFunc != nil {
scenario.afterTestFunc(testApp, collections)
}
}
}
+1 -3
View File
@@ -40,7 +40,7 @@ func (dao *Dao) SaveParam(key string, value any, optEncryptionKey ...string) err
param = &models.Param{Key: key} param = &models.Param{Key: key}
} }
var normalizedValue any normalizedValue := value
// encrypt if optEncryptionKey is set // encrypt if optEncryptionKey is set
if len(optEncryptionKey) > 0 && optEncryptionKey[0] != "" { if len(optEncryptionKey) > 0 && optEncryptionKey[0] != "" {
@@ -55,8 +55,6 @@ func (dao *Dao) SaveParam(key string, value any, optEncryptionKey ...string) err
} }
normalizedValue = encryptVal normalizedValue = encryptVal
} else {
normalizedValue = value
} }
encodedValue := types.JsonRaw{} encodedValue := types.JsonRaw{}
+32 -6
View File
@@ -9,6 +9,7 @@ import (
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/models/schema" "github.com/pocketbase/pocketbase/models/schema"
"github.com/pocketbase/pocketbase/tools/list" "github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/pocketbase/pocketbase/tools/types" "github.com/pocketbase/pocketbase/tools/types"
) )
@@ -149,6 +150,10 @@ func (dao *Dao) IsRecordValueUnique(
// FindUserRelatedRecords returns all records that has a reference // FindUserRelatedRecords returns all records that has a reference
// to the provided User model (via the user shema field). // to the provided User model (via the user shema field).
func (dao *Dao) FindUserRelatedRecords(user *models.User) ([]*models.Record, error) { func (dao *Dao) FindUserRelatedRecords(user *models.User) ([]*models.Record, error) {
if user.Id == "" {
return []*models.Record{}, nil
}
collections, err := dao.FindCollectionsWithUserFields() collections, err := dao.FindCollectionsWithUserFields()
if err != nil { if err != nil {
return nil, err return nil, err
@@ -329,23 +334,44 @@ func (dao *Dao) SyncRecordTableSchema(newCollection *models.Collection, oldColle
} }
// check for new or renamed columns // check for new or renamed columns
toRename := map[string]string{}
for _, field := range newSchema.Fields() { for _, field := range newSchema.Fields() {
oldField := oldSchema.GetFieldById(field.Id) oldField := oldSchema.GetFieldById(field.Id)
if oldField != nil { // Note:
// rename // We are using a temporary column name when adding or renaming columns
_, err := txDao.DB().RenameColumn(newTableName, oldField.Name, field.Name).Execute() // to ensure that there are no name collisions in case there is
// names switch/reuse of existing columns (eg. name, title -> title, name).
// This way we are always doing 1 more rename operation but it provides better dev experience.
if oldField == nil {
tempName := field.Name + security.RandomString(5)
toRename[tempName] = field.Name
// add
_, err := txDao.DB().AddColumn(newTableName, tempName, field.ColDefinition()).Execute()
if err != nil { if err != nil {
return err return err
} }
} else { } else if oldField.Name != field.Name {
// add tempName := field.Name + security.RandomString(5)
_, err := txDao.DB().AddColumn(newTableName, field.Name, field.ColDefinition()).Execute() toRename[tempName] = field.Name
// rename
_, err := txDao.DB().RenameColumn(newTableName, oldField.Name, tempName).Execute()
if err != nil { if err != nil {
return err return err
} }
} }
} }
// set the actual columns name
for tempName, actualName := range toRename {
_, err := txDao.DB().RenameColumn(newTableName, tempName, actualName).Execute()
if err != nil {
return err
}
}
return nil return nil
}) })
} }
+24 -17
View File
@@ -17,21 +17,27 @@ const MaxExpandDepth = 6
type ExpandFetchFunc func(relCollection *models.Collection, relIds []string) ([]*models.Record, error) type ExpandFetchFunc func(relCollection *models.Collection, relIds []string) ([]*models.Record, error)
// ExpandRecord expands the relations of a single Record model. // ExpandRecord expands the relations of a single Record model.
func (dao *Dao) ExpandRecord(record *models.Record, expands []string, fetchFunc ExpandFetchFunc) error { //
// Returns a map with the failed expand parameters and their errors.
func (dao *Dao) ExpandRecord(record *models.Record, expands []string, fetchFunc ExpandFetchFunc) map[string]error {
return dao.ExpandRecords([]*models.Record{record}, expands, fetchFunc) return dao.ExpandRecords([]*models.Record{record}, expands, fetchFunc)
} }
// ExpandRecords expands the relations of the provided Record models list. // ExpandRecords expands the relations of the provided Record models list.
func (dao *Dao) ExpandRecords(records []*models.Record, expands []string, fetchFunc ExpandFetchFunc) error { //
// Returns a map with the failed expand parameters and their errors.
func (dao *Dao) ExpandRecords(records []*models.Record, expands []string, fetchFunc ExpandFetchFunc) map[string]error {
normalized := normalizeExpands(expands) normalized := normalizeExpands(expands)
failed := map[string]error{}
for _, expand := range normalized { for _, expand := range normalized {
if err := dao.expandRecords(records, expand, fetchFunc, 1); err != nil { if err := dao.expandRecords(records, expand, fetchFunc, 1); err != nil {
return err failed[expand] = err
} }
} }
return nil return failed
} }
// notes: // notes:
@@ -52,11 +58,14 @@ func (dao *Dao) expandRecords(records []*models.Record, expandPath string, fetch
// extract the relation field (if exist) // extract the relation field (if exist)
mainCollection := records[0].Collection() mainCollection := records[0].Collection()
relField := mainCollection.Schema.GetFieldByName(parts[0]) relField := mainCollection.Schema.GetFieldByName(parts[0])
if relField == nil { if relField == nil || relField.Type != schema.FieldTypeRelation {
return fmt.Errorf("Couldn't find field %q in collection %q.", parts[0], mainCollection.Name) return fmt.Errorf("Couldn't find relation field %q in collection %q.", parts[0], mainCollection.Name)
} }
relField.InitOptions() relField.InitOptions()
relFieldOptions, _ := relField.Options.(*schema.RelationOptions) relFieldOptions, ok := relField.Options.(*schema.RelationOptions)
if !ok {
return fmt.Errorf("Cannot initialize the options of relation field %q.", parts[0])
}
relCollection, err := dao.FindCollectionByNameOrId(relFieldOptions.CollectionId) relCollection, err := dao.FindCollectionByNameOrId(relFieldOptions.CollectionId)
if err != nil { if err != nil {
@@ -64,7 +73,7 @@ func (dao *Dao) expandRecords(records []*models.Record, expandPath string, fetch
} }
// extract the id of the relations to expand // extract the id of the relations to expand
relIds := []string{} relIds := make([]string, 0, len(records))
for _, record := range records { for _, record := range records {
relIds = append(relIds, record.GetStringSliceDataValue(relField.Name)...) relIds = append(relIds, record.GetStringSliceDataValue(relField.Name)...)
} }
@@ -92,7 +101,7 @@ func (dao *Dao) expandRecords(records []*models.Record, expandPath string, fetch
for _, model := range records { for _, model := range records {
relIds := model.GetStringSliceDataValue(relField.Name) relIds := model.GetStringSliceDataValue(relField.Name)
validRels := []*models.Record{} validRels := make([]*models.Record, 0, len(relIds))
for _, id := range relIds { for _, id := range relIds {
if rel, ok := indexedRels[id]; ok { if rel, ok := indexedRels[id]; ok {
validRels = append(validRels, rel) validRels = append(validRels, rel)
@@ -120,20 +129,18 @@ func (dao *Dao) expandRecords(records []*models.Record, expandPath string, fetch
// normalizeExpands normalizes expand strings and merges self containing paths // normalizeExpands normalizes expand strings and merges self containing paths
// (eg. ["a.b.c", "a.b", " test ", " ", "test"] -> ["a.b.c", "test"]). // (eg. ["a.b.c", "a.b", " test ", " ", "test"] -> ["a.b.c", "test"]).
func normalizeExpands(paths []string) []string { func normalizeExpands(paths []string) []string {
result := []string{}
// normalize paths // normalize paths
normalized := []string{} normalized := make([]string, 0, len(paths))
for _, p := range paths { for _, p := range paths {
p := strings.ReplaceAll(p, " ", "") // replace spaces p = strings.ReplaceAll(p, " ", "") // replace spaces
p = strings.Trim(p, ".") // trim incomplete paths p = strings.Trim(p, ".") // trim incomplete paths
if p == "" { if p != "" {
continue normalized = append(normalized, p)
} }
normalized = append(normalized, p)
} }
// merge containing paths // merge containing paths
result := make([]string, 0, len(normalized))
for i, p1 := range normalized { for i, p1 := range normalized {
var skip bool var skip bool
for j, p2 := range normalized { for j, p2 := range normalized {
+47 -39
View File
@@ -19,11 +19,11 @@ func TestExpandRecords(t *testing.T) {
col, _ := app.Dao().FindCollectionByNameOrId("demo4") col, _ := app.Dao().FindCollectionByNameOrId("demo4")
scenarios := []struct { scenarios := []struct {
recordIds []string recordIds []string
expands []string expands []string
fetchFunc daos.ExpandFetchFunc fetchFunc daos.ExpandFetchFunc
expectExpandProps int expectExpandProps int
expectError bool expectExpandFailures int
}{ }{
// empty records // empty records
{ {
@@ -33,7 +33,7 @@ func TestExpandRecords(t *testing.T) {
return app.Dao().FindRecordsByIds(c, ids, nil) return app.Dao().FindRecordsByIds(c, ids, nil)
}, },
0, 0,
false, 0,
}, },
// empty expand // empty expand
{ {
@@ -43,7 +43,7 @@ func TestExpandRecords(t *testing.T) {
return app.Dao().FindRecordsByIds(c, ids, nil) return app.Dao().FindRecordsByIds(c, ids, nil)
}, },
0, 0,
false, 0,
}, },
// empty fetchFunc // empty fetchFunc
{ {
@@ -51,7 +51,7 @@ func TestExpandRecords(t *testing.T) {
[]string{"onerel", "manyrels.onerel.manyrels"}, []string{"onerel", "manyrels.onerel.manyrels"},
nil, nil,
0, 0,
true, 2,
}, },
// fetchFunc with error // fetchFunc with error
{ {
@@ -61,9 +61,9 @@ func TestExpandRecords(t *testing.T) {
return nil, errors.New("test error") return nil, errors.New("test error")
}, },
0, 0,
true, 2,
}, },
// invalid missing first level expand // missing relation field
{ {
[]string{"b8ba58f9-e2d7-42a0-b0e7-a11efd98236b", "df55c8ff-45ef-4c82-8aed-6e2183fe1125"}, []string{"b8ba58f9-e2d7-42a0-b0e7-a11efd98236b", "df55c8ff-45ef-4c82-8aed-6e2183fe1125"},
[]string{"invalid"}, []string{"invalid"},
@@ -71,9 +71,19 @@ func TestExpandRecords(t *testing.T) {
return app.Dao().FindRecordsByIds(c, ids, nil) return app.Dao().FindRecordsByIds(c, ids, nil)
}, },
0, 0,
true, 1,
}, },
// invalid missing second level expand // existing, but non-relation type field
{
[]string{"b8ba58f9-e2d7-42a0-b0e7-a11efd98236b", "df55c8ff-45ef-4c82-8aed-6e2183fe1125"},
[]string{"title"},
func(c *models.Collection, ids []string) ([]*models.Record, error) {
return app.Dao().FindRecordsByIds(c, ids, nil)
},
0,
1,
},
// invalid/missing second level expand
{ {
[]string{"b8ba58f9-e2d7-42a0-b0e7-a11efd98236b", "df55c8ff-45ef-4c82-8aed-6e2183fe1125"}, []string{"b8ba58f9-e2d7-42a0-b0e7-a11efd98236b", "df55c8ff-45ef-4c82-8aed-6e2183fe1125"},
[]string{"manyrels.invalid"}, []string{"manyrels.invalid"},
@@ -81,7 +91,7 @@ func TestExpandRecords(t *testing.T) {
return app.Dao().FindRecordsByIds(c, ids, nil) return app.Dao().FindRecordsByIds(c, ids, nil)
}, },
0, 0,
true, 1,
}, },
// expand normalizations // expand normalizations
{ {
@@ -96,7 +106,7 @@ func TestExpandRecords(t *testing.T) {
return app.Dao().FindRecordsByIds(c, ids, nil) return app.Dao().FindRecordsByIds(c, ids, nil)
}, },
9, 9,
false, 0,
}, },
// single expand // single expand
{ {
@@ -111,7 +121,7 @@ func TestExpandRecords(t *testing.T) {
return app.Dao().FindRecordsByIds(c, ids, nil) return app.Dao().FindRecordsByIds(c, ids, nil)
}, },
2, 2,
false, 0,
}, },
// maxExpandDepth reached // maxExpandDepth reached
{ {
@@ -121,18 +131,17 @@ func TestExpandRecords(t *testing.T) {
return app.Dao().FindRecordsByIds(c, ids, nil) return app.Dao().FindRecordsByIds(c, ids, nil)
}, },
6, 6,
false, 0,
}, },
} }
for i, s := range scenarios { for i, s := range scenarios {
ids := list.ToUniqueStringSlice(s.recordIds) ids := list.ToUniqueStringSlice(s.recordIds)
records, _ := app.Dao().FindRecordsByIds(col, ids, nil) records, _ := app.Dao().FindRecordsByIds(col, ids, nil)
err := app.Dao().ExpandRecords(records, s.expands, s.fetchFunc) failed := app.Dao().ExpandRecords(records, s.expands, s.fetchFunc)
hasErr := err != nil if len(failed) != s.expectExpandFailures {
if hasErr != s.expectError { t.Errorf("(%d) Expected %d failures, got %d: \n%v", i, s.expectExpandFailures, len(failed), failed)
t.Errorf("(%d) Expected hasErr to be %v, got %v (%v)", i, s.expectError, hasErr, err)
} }
encoded, _ := json.Marshal(records) encoded, _ := json.Marshal(records)
@@ -140,7 +149,7 @@ func TestExpandRecords(t *testing.T) {
totalExpandProps := strings.Count(encodedStr, "@expand") totalExpandProps := strings.Count(encodedStr, "@expand")
if s.expectExpandProps != totalExpandProps { if s.expectExpandProps != totalExpandProps {
t.Errorf("(%d) Expected %d @expand props in %v, got %d", i, s.expectExpandProps, encodedStr, totalExpandProps) t.Errorf("(%d) Expected %d @expand props, got %d: \n%v", i, s.expectExpandProps, totalExpandProps, encodedStr)
} }
} }
} }
@@ -152,11 +161,11 @@ func TestExpandRecord(t *testing.T) {
col, _ := app.Dao().FindCollectionByNameOrId("demo4") col, _ := app.Dao().FindCollectionByNameOrId("demo4")
scenarios := []struct { scenarios := []struct {
recordId string recordId string
expands []string expands []string
fetchFunc daos.ExpandFetchFunc fetchFunc daos.ExpandFetchFunc
expectExpandProps int expectExpandProps int
expectError bool expectExpandFailures int
}{ }{
// empty expand // empty expand
{ {
@@ -166,7 +175,7 @@ func TestExpandRecord(t *testing.T) {
return app.Dao().FindRecordsByIds(c, ids, nil) return app.Dao().FindRecordsByIds(c, ids, nil)
}, },
0, 0,
false, 0,
}, },
// empty fetchFunc // empty fetchFunc
{ {
@@ -174,7 +183,7 @@ func TestExpandRecord(t *testing.T) {
[]string{"onerel", "manyrels.onerel.manyrels"}, []string{"onerel", "manyrels.onerel.manyrels"},
nil, nil,
0, 0,
true, 2,
}, },
// fetchFunc with error // fetchFunc with error
{ {
@@ -184,7 +193,7 @@ func TestExpandRecord(t *testing.T) {
return nil, errors.New("test error") return nil, errors.New("test error")
}, },
0, 0,
true, 2,
}, },
// invalid missing first level expand // invalid missing first level expand
{ {
@@ -194,7 +203,7 @@ func TestExpandRecord(t *testing.T) {
return app.Dao().FindRecordsByIds(c, ids, nil) return app.Dao().FindRecordsByIds(c, ids, nil)
}, },
0, 0,
true, 1,
}, },
// invalid missing second level expand // invalid missing second level expand
{ {
@@ -204,7 +213,7 @@ func TestExpandRecord(t *testing.T) {
return app.Dao().FindRecordsByIds(c, ids, nil) return app.Dao().FindRecordsByIds(c, ids, nil)
}, },
0, 0,
true, 1,
}, },
// expand normalizations // expand normalizations
{ {
@@ -214,7 +223,7 @@ func TestExpandRecord(t *testing.T) {
return app.Dao().FindRecordsByIds(c, ids, nil) return app.Dao().FindRecordsByIds(c, ids, nil)
}, },
3, 3,
false, 0,
}, },
// single expand // single expand
{ {
@@ -224,7 +233,7 @@ func TestExpandRecord(t *testing.T) {
return app.Dao().FindRecordsByIds(c, ids, nil) return app.Dao().FindRecordsByIds(c, ids, nil)
}, },
1, 1,
false, 0,
}, },
// maxExpandDepth reached // maxExpandDepth reached
{ {
@@ -234,17 +243,16 @@ func TestExpandRecord(t *testing.T) {
return app.Dao().FindRecordsByIds(c, ids, nil) return app.Dao().FindRecordsByIds(c, ids, nil)
}, },
6, 6,
false, 0,
}, },
} }
for i, s := range scenarios { for i, s := range scenarios {
record, _ := app.Dao().FindFirstRecordByData(col, "id", s.recordId) record, _ := app.Dao().FindFirstRecordByData(col, "id", s.recordId)
err := app.Dao().ExpandRecord(record, s.expands, s.fetchFunc) failed := app.Dao().ExpandRecord(record, s.expands, s.fetchFunc)
hasErr := err != nil if len(failed) != s.expectExpandFailures {
if hasErr != s.expectError { t.Errorf("(%d) Expected %d failures, got %d: \n%v", i, s.expectExpandFailures, len(failed), failed)
t.Errorf("(%d) Expected hasErr to be %v, got %v (%v)", i, s.expectError, hasErr, err)
} }
encoded, _ := json.Marshal(record) encoded, _ := json.Marshal(record)
@@ -252,7 +260,7 @@ func TestExpandRecord(t *testing.T) {
totalExpandProps := strings.Count(encodedStr, "@expand") totalExpandProps := strings.Count(encodedStr, "@expand")
if s.expectExpandProps != totalExpandProps { if s.expectExpandProps != totalExpandProps {
t.Errorf("(%d) Expected %d @expand props in %v, got %d", i, s.expectExpandProps, encodedStr, totalExpandProps) t.Errorf("(%d) Expected %d @expand props, got %d: \n%v", i, s.expectExpandProps, totalExpandProps, encodedStr)
} }
} }
} }
+3 -3
View File
@@ -43,10 +43,10 @@ func (dao *Dao) LoadProfiles(users []*models.User) error {
} }
// extract user ids // extract user ids
ids := []string{} ids := make([]string, len(users))
usersMap := map[string]*models.User{} usersMap := map[string]*models.User{}
for _, user := range users { for i, user := range users {
ids = append(ids, user.Id) ids[i] = user.Id
usersMap[user.Id] = user usersMap[user.Id] = user
} }
+37 -6
View File
@@ -6,26 +6,57 @@ import (
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is" "github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
) )
// AdminLogin defines an admin email/pass login form. // AdminLogin specifies an admin email/pass login form.
type AdminLogin struct { type AdminLogin struct {
app core.App config AdminLoginConfig
Email string `form:"email" json:"email"` Email string `form:"email" json:"email"`
Password string `form:"password" json:"password"` Password string `form:"password" json:"password"`
} }
// NewAdminLogin creates new admin login form for the provided app. // AdminLoginConfig is the [AdminLogin] factory initializer config.
//
// NB! App is a required struct member.
type AdminLoginConfig struct {
App core.App
TxDao *daos.Dao
}
// NewAdminLogin creates a new [AdminLogin] form with initializer
// config created from the provided [core.App] instance.
//
// If you want to submit the form as part of another transaction, use
// [NewAdminLoginWithConfig] with explicitly set TxDao.
func NewAdminLogin(app core.App) *AdminLogin { func NewAdminLogin(app core.App) *AdminLogin {
return &AdminLogin{app: app} return NewAdminLoginWithConfig(AdminLoginConfig{
App: app,
})
}
// NewAdminLoginWithConfig creates a new [AdminLogin] form
// with the provided config or panics on invalid configuration.
func NewAdminLoginWithConfig(config AdminLoginConfig) *AdminLogin {
form := &AdminLogin{config: config}
if form.config.App == nil {
panic("Missing required config.App instance.")
}
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
}
return form
} }
// Validate makes the form validatable by implementing [validation.Validatable] interface. // Validate makes the form validatable by implementing [validation.Validatable] interface.
func (form *AdminLogin) Validate() error { func (form *AdminLogin) Validate() error {
return validation.ValidateStruct(form, return validation.ValidateStruct(form,
validation.Field(&form.Email, validation.Required, validation.Length(1, 255), is.Email), validation.Field(&form.Email, validation.Required, validation.Length(1, 255), is.EmailFormat),
validation.Field(&form.Password, validation.Required, validation.Length(1, 255)), validation.Field(&form.Password, validation.Required, validation.Length(1, 255)),
) )
} }
@@ -37,7 +68,7 @@ func (form *AdminLogin) Submit() (*models.Admin, error) {
return nil, err return nil, err
} }
admin, err := form.app.Dao().FindAdminByEmail(form.Email) admin, err := form.config.TxDao.FindAdminByEmail(form.Email)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+10
View File
@@ -7,6 +7,16 @@ import (
"github.com/pocketbase/pocketbase/tests" "github.com/pocketbase/pocketbase/tests"
) )
func TestAdminLoginPanic(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewAdminLogin(nil)
}
func TestAdminLoginValidate(t *testing.T) { func TestAdminLoginValidate(t *testing.T) {
app, _ := tests.NewTestApp() app, _ := tests.NewTestApp()
defer app.Cleanup() defer app.Cleanup()
+39 -10
View File
@@ -3,24 +3,53 @@ package forms
import ( import (
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/forms/validators" "github.com/pocketbase/pocketbase/forms/validators"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
) )
// AdminPasswordResetConfirm defines an admin password reset confirmation form. // AdminPasswordResetConfirm specifies an admin password reset confirmation form.
type AdminPasswordResetConfirm struct { type AdminPasswordResetConfirm struct {
app core.App config AdminPasswordResetConfirmConfig
Token string `form:"token" json:"token"` Token string `form:"token" json:"token"`
Password string `form:"password" json:"password"` Password string `form:"password" json:"password"`
PasswordConfirm string `form:"passwordConfirm" json:"passwordConfirm"` PasswordConfirm string `form:"passwordConfirm" json:"passwordConfirm"`
} }
// NewAdminPasswordResetConfirm creates new admin password reset confirmation form. // AdminPasswordResetConfirmConfig is the [AdminPasswordResetConfirm] factory initializer config.
//
// NB! App is required struct member.
type AdminPasswordResetConfirmConfig struct {
App core.App
TxDao *daos.Dao
}
// NewAdminPasswordResetConfirm creates a new [AdminPasswordResetConfirm]
// form with initializer config created from the provided [core.App] instance.
//
// If you want to submit the form as part of another transaction, use
// [NewAdminPasswordResetConfirmWithConfig] with explicitly set TxDao.
func NewAdminPasswordResetConfirm(app core.App) *AdminPasswordResetConfirm { func NewAdminPasswordResetConfirm(app core.App) *AdminPasswordResetConfirm {
return &AdminPasswordResetConfirm{ return NewAdminPasswordResetConfirmWithConfig(AdminPasswordResetConfirmConfig{
app: app, App: app,
})
}
// NewAdminPasswordResetConfirmWithConfig creates a new [AdminPasswordResetConfirm]
// form with the provided config or panics on invalid configuration.
func NewAdminPasswordResetConfirmWithConfig(config AdminPasswordResetConfirmConfig) *AdminPasswordResetConfirm {
form := &AdminPasswordResetConfirm{config: config}
if form.config.App == nil {
panic("Missing required config.App instance.")
} }
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
}
return form
} }
// Validate makes the form validatable by implementing [validation.Validatable] interface. // Validate makes the form validatable by implementing [validation.Validatable] interface.
@@ -38,9 +67,9 @@ func (form *AdminPasswordResetConfirm) checkToken(value any) error {
return nil // nothing to check return nil // nothing to check
} }
admin, err := form.app.Dao().FindAdminByToken( admin, err := form.config.TxDao.FindAdminByToken(
v, v,
form.app.Settings().AdminPasswordResetToken.Secret, form.config.App.Settings().AdminPasswordResetToken.Secret,
) )
if err != nil || admin == nil { if err != nil || admin == nil {
return validation.NewError("validation_invalid_token", "Invalid or expired token.") return validation.NewError("validation_invalid_token", "Invalid or expired token.")
@@ -56,9 +85,9 @@ func (form *AdminPasswordResetConfirm) Submit() (*models.Admin, error) {
return nil, err return nil, err
} }
admin, err := form.app.Dao().FindAdminByToken( admin, err := form.config.TxDao.FindAdminByToken(
form.Token, form.Token,
form.app.Settings().AdminPasswordResetToken.Secret, form.config.App.Settings().AdminPasswordResetToken.Secret,
) )
if err != nil { if err != nil {
return nil, err return nil, err
@@ -68,7 +97,7 @@ func (form *AdminPasswordResetConfirm) Submit() (*models.Admin, error) {
return nil, err return nil, err
} }
if err := form.app.Dao().SaveAdmin(admin); err != nil { if err := form.config.TxDao.SaveAdmin(admin); err != nil {
return nil, err return nil, err
} }
@@ -8,6 +8,16 @@ import (
"github.com/pocketbase/pocketbase/tools/security" "github.com/pocketbase/pocketbase/tools/security"
) )
func TestAdminPasswordResetPanic(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewAdminPasswordResetConfirm(nil)
}
func TestAdminPasswordResetConfirmValidate(t *testing.T) { func TestAdminPasswordResetConfirmValidate(t *testing.T) {
app, _ := tests.NewTestApp() app, _ := tests.NewTestApp()
defer app.Cleanup() defer app.Cleanup()
+40 -11
View File
@@ -7,24 +7,53 @@ import (
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is" "github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/mails" "github.com/pocketbase/pocketbase/mails"
"github.com/pocketbase/pocketbase/tools/types" "github.com/pocketbase/pocketbase/tools/types"
) )
// AdminPasswordResetRequest defines an admin password reset request form. // AdminPasswordResetRequest specifies an admin password reset request form.
type AdminPasswordResetRequest struct { type AdminPasswordResetRequest struct {
app core.App config AdminPasswordResetRequestConfig
resendThreshold float64
Email string `form:"email" json:"email"` Email string `form:"email" json:"email"`
} }
// NewAdminPasswordResetRequest creates new admin password reset request form. // AdminPasswordResetRequestConfig is the [AdminPasswordResetRequest] factory initializer config.
//
// NB! App is required struct member.
type AdminPasswordResetRequestConfig struct {
App core.App
TxDao *daos.Dao
ResendThreshold float64 // in seconds
}
// NewAdminPasswordResetRequest creates a new [AdminPasswordResetRequest]
// form with initializer config created from the provided [core.App] instance.
//
// If you want to submit the form as part of another transaction, use
// [NewAdminPasswordResetRequestWithConfig] with explicitly set TxDao.
func NewAdminPasswordResetRequest(app core.App) *AdminPasswordResetRequest { func NewAdminPasswordResetRequest(app core.App) *AdminPasswordResetRequest {
return &AdminPasswordResetRequest{ return NewAdminPasswordResetRequestWithConfig(AdminPasswordResetRequestConfig{
app: app, App: app,
resendThreshold: 120, // 2 min ResendThreshold: 120, // 2min
})
}
// NewAdminPasswordResetRequestWithConfig creates a new [AdminPasswordResetRequest]
// form with the provided config or panics on invalid configuration.
func NewAdminPasswordResetRequestWithConfig(config AdminPasswordResetRequestConfig) *AdminPasswordResetRequest {
form := &AdminPasswordResetRequest{config: config}
if form.config.App == nil {
panic("Missing required config.App instance.")
} }
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
}
return form
} }
// Validate makes the form validatable by implementing [validation.Validatable] interface. // Validate makes the form validatable by implementing [validation.Validatable] interface.
@@ -48,23 +77,23 @@ func (form *AdminPasswordResetRequest) Submit() error {
return err return err
} }
admin, err := form.app.Dao().FindAdminByEmail(form.Email) admin, err := form.config.TxDao.FindAdminByEmail(form.Email)
if err != nil { if err != nil {
return err return err
} }
now := time.Now().UTC() now := time.Now().UTC()
lastResetSentAt := admin.LastResetSentAt.Time() lastResetSentAt := admin.LastResetSentAt.Time()
if now.Sub(lastResetSentAt).Seconds() < form.resendThreshold { if now.Sub(lastResetSentAt).Seconds() < form.config.ResendThreshold {
return errors.New("You have already requested a password reset.") return errors.New("You have already requested a password reset.")
} }
if err := mails.SendAdminPasswordReset(form.app, admin); err != nil { if err := mails.SendAdminPasswordReset(form.config.App, admin); err != nil {
return err return err
} }
// update last sent timestamp // update last sent timestamp
admin.LastResetSentAt = types.NowDateTime() admin.LastResetSentAt = types.NowDateTime()
return form.app.Dao().SaveAdmin(admin) return form.config.TxDao.SaveAdmin(admin)
} }
@@ -7,6 +7,16 @@ import (
"github.com/pocketbase/pocketbase/tests" "github.com/pocketbase/pocketbase/tests"
) )
func TestAdminPasswordResetRequestPanic(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewAdminPasswordResetRequest(nil)
}
func TestAdminPasswordResetRequestValidate(t *testing.T) { func TestAdminPasswordResetRequestValidate(t *testing.T) {
testApp, _ := tests.NewTestApp() testApp, _ := tests.NewTestApp()
defer testApp.Cleanup() defer testApp.Cleanup()
+63 -14
View File
@@ -4,32 +4,62 @@ import (
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is" "github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/forms/validators" "github.com/pocketbase/pocketbase/forms/validators"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
) )
// AdminUpsert defines an admin upsert (create/update) form. // AdminUpsert specifies a [models.Admin] upsert (create/update) form.
type AdminUpsert struct { type AdminUpsert struct {
app core.App config AdminUpsertConfig
admin *models.Admin admin *models.Admin
isCreate bool
Id string `form:"id" json:"id"`
Avatar int `form:"avatar" json:"avatar"` Avatar int `form:"avatar" json:"avatar"`
Email string `form:"email" json:"email"` Email string `form:"email" json:"email"`
Password string `form:"password" json:"password"` Password string `form:"password" json:"password"`
PasswordConfirm string `form:"passwordConfirm" json:"passwordConfirm"` PasswordConfirm string `form:"passwordConfirm" json:"passwordConfirm"`
} }
// NewAdminUpsert creates new upsert form for the provided admin model // AdminUpsertConfig is the [AdminUpsert] factory initializer config.
// (pass an empty admin model instance (`&models.Admin{}`) for create). //
// NB! App is a required struct member.
type AdminUpsertConfig struct {
App core.App
TxDao *daos.Dao
}
// NewAdminUpsert creates a new [AdminUpsert] form with initializer
// config created from the provided [core.App] and [models.Admin] instances
// (for create you could pass a pointer to an empty Admin - `&models.Admin{}`).
//
// If you want to submit the form as part of another transaction, use
// [NewAdminUpsertWithConfig] with explicitly set TxDao.
func NewAdminUpsert(app core.App, admin *models.Admin) *AdminUpsert { func NewAdminUpsert(app core.App, admin *models.Admin) *AdminUpsert {
return NewAdminUpsertWithConfig(AdminUpsertConfig{
App: app,
}, admin)
}
// NewAdminUpsertWithConfig creates a new [AdminUpsert] form
// with the provided config and [models.Admin] instance or panics on invalid configuration
// (for create you could pass a pointer to an empty Admin - `&models.Admin{}`).
func NewAdminUpsertWithConfig(config AdminUpsertConfig, admin *models.Admin) *AdminUpsert {
form := &AdminUpsert{ form := &AdminUpsert{
app: app, config: config,
admin: admin, admin: admin,
isCreate: !admin.HasId(), }
if form.config.App == nil || form.admin == nil {
panic("Invalid initializer config or nil upsert model.")
}
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
} }
// load defaults // load defaults
form.Id = admin.Id
form.Avatar = admin.Avatar form.Avatar = admin.Avatar
form.Email = admin.Email form.Email = admin.Email
@@ -39,6 +69,14 @@ func NewAdminUpsert(app core.App, admin *models.Admin) *AdminUpsert {
// Validate makes the form validatable by implementing [validation.Validatable] interface. // Validate makes the form validatable by implementing [validation.Validatable] interface.
func (form *AdminUpsert) Validate() error { func (form *AdminUpsert) Validate() error {
return validation.ValidateStruct(form, return validation.ValidateStruct(form,
validation.Field(
&form.Id,
validation.When(
form.admin.IsNew(),
validation.Length(models.DefaultIdLength, models.DefaultIdLength),
validation.Match(idRegex),
).Else(validation.In(form.admin.Id)),
),
validation.Field( validation.Field(
&form.Avatar, &form.Avatar,
validation.Min(0), validation.Min(0),
@@ -53,7 +91,7 @@ func (form *AdminUpsert) Validate() error {
), ),
validation.Field( validation.Field(
&form.Password, &form.Password,
validation.When(form.isCreate, validation.Required), validation.When(form.admin.IsNew(), validation.Required),
validation.Length(10, 100), validation.Length(10, 100),
), ),
validation.Field( validation.Field(
@@ -67,19 +105,28 @@ func (form *AdminUpsert) Validate() error {
func (form *AdminUpsert) checkUniqueEmail(value any) error { func (form *AdminUpsert) checkUniqueEmail(value any) error {
v, _ := value.(string) v, _ := value.(string)
if form.app.Dao().IsAdminEmailUnique(v, form.admin.Id) { if form.config.TxDao.IsAdminEmailUnique(v, form.admin.Id) {
return nil return nil
} }
return validation.NewError("validation_admin_email_exists", "Admin email already exists.") return validation.NewError("validation_admin_email_exists", "Admin email already exists.")
} }
// Submit validates the form and upserts the form's admin model. // Submit validates the form and upserts the form admin model.
func (form *AdminUpsert) Submit() error { //
// You can optionally provide a list of InterceptorFunc to further
// modify the form behavior before persisting it.
func (form *AdminUpsert) Submit(interceptors ...InterceptorFunc) error {
if err := form.Validate(); err != nil { if err := form.Validate(); err != nil {
return err return err
} }
// custom insertion id can be set only on create
if form.admin.IsNew() && form.Id != "" {
form.admin.MarkAsNew()
form.admin.SetId(form.Id)
}
form.admin.Avatar = form.Avatar form.admin.Avatar = form.Avatar
form.admin.Email = form.Email form.admin.Email = form.Email
@@ -87,5 +134,7 @@ func (form *AdminUpsert) Submit() error {
form.admin.SetPassword(form.Password) form.admin.SetPassword(form.Password)
} }
return form.app.Dao().SaveAdmin(form.admin) return runInterceptors(func() error {
return form.config.TxDao.SaveAdmin(form.admin)
}, interceptors...)
} }
+191 -1
View File
@@ -2,6 +2,8 @@ package forms_test
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt"
"testing" "testing"
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
@@ -10,6 +12,29 @@ import (
"github.com/pocketbase/pocketbase/tests" "github.com/pocketbase/pocketbase/tests"
) )
func TestAdminUpsertPanic1(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewAdminUpsert(nil, nil)
}
func TestAdminUpsertPanic2(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewAdminUpsert(app, nil)
}
func TestNewAdminUpsert(t *testing.T) { func TestNewAdminUpsert(t *testing.T) {
app, _ := tests.NewTestApp() app, _ := tests.NewTestApp()
defer app.Cleanup() defer app.Cleanup()
@@ -252,7 +277,14 @@ func TestAdminUpsertSubmit(t *testing.T) {
continue continue
} }
err := form.Submit() interceptorCalls := 0
err := form.Submit(func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptorCalls++
return next()
}
})
hasErr := err != nil hasErr := err != nil
if hasErr != s.expectError { if hasErr != s.expectError {
@@ -266,6 +298,14 @@ func TestAdminUpsertSubmit(t *testing.T) {
continue continue
} }
expectInterceptorCall := 1
if s.expectError {
expectInterceptorCall = 0
}
if interceptorCalls != expectInterceptorCall {
t.Errorf("(%d) Expected interceptor to be called %d, got %d", i, expectInterceptorCall, interceptorCalls)
}
if s.expectError { if s.expectError {
continue // skip persistence check continue // skip persistence check
} }
@@ -283,3 +323,153 @@ func TestAdminUpsertSubmit(t *testing.T) {
} }
} }
} }
func TestAdminUpsertSubmitInterceptors(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
admin := &models.Admin{}
form := forms.NewAdminUpsert(app, admin)
form.Email = "test_new@example.com"
form.Password = "1234567890"
form.PasswordConfirm = form.Password
testErr := errors.New("test_error")
interceptorAdminEmail := ""
interceptor1Called := false
interceptor1 := func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptor1Called = true
return next()
}
}
interceptor2Called := false
interceptor2 := func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptorAdminEmail = admin.Email // to check if the record was filled
interceptor2Called = true
return testErr
}
}
err := form.Submit(interceptor1, interceptor2)
if err != testErr {
t.Fatalf("Expected error %v, got %v", testErr, err)
}
if !interceptor1Called {
t.Fatalf("Expected interceptor1 to be called")
}
if !interceptor2Called {
t.Fatalf("Expected interceptor2 to be called")
}
if interceptorAdminEmail != form.Email {
t.Fatalf("Expected the form model to be filled before calling the interceptors")
}
}
func TestAdminUpsertWithCustomId(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
existingAdmin, err := app.Dao().FindAdminByEmail("test@example.com")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
jsonData string
collection *models.Admin
expectError bool
}{
{
"empty data",
"{}",
&models.Admin{},
false,
},
{
"empty id",
`{"id":""}`,
&models.Admin{},
false,
},
{
"id < 15 chars",
`{"id":"a23"}`,
&models.Admin{},
true,
},
{
"id > 15 chars",
`{"id":"a234567890123456"}`,
&models.Admin{},
true,
},
{
"id = 15 chars (invalid chars)",
`{"id":"a@3456789012345"}`,
&models.Admin{},
true,
},
{
"id = 15 chars (valid chars)",
`{"id":"a23456789012345"}`,
&models.Admin{},
false,
},
{
"changing the id of an existing item",
`{"id":"b23456789012345"}`,
existingAdmin,
true,
},
{
"using the same existing item id",
`{"id":"` + existingAdmin.Id + `"}`,
existingAdmin,
false,
},
{
"skipping the id for existing item",
`{}`,
existingAdmin,
false,
},
}
for i, scenario := range scenarios {
form := forms.NewAdminUpsert(app, scenario.collection)
if form.Email == "" {
form.Email = fmt.Sprintf("test_id_%d@example.com", i)
}
form.Password = "1234567890"
form.PasswordConfirm = form.Password
// load data
loadErr := json.Unmarshal([]byte(scenario.jsonData), form)
if loadErr != nil {
t.Errorf("[%s] Failed to load form data: %v", scenario.name, loadErr)
continue
}
submitErr := form.Submit()
hasErr := submitErr != nil
if hasErr != scenario.expectError {
t.Errorf("[%s] Expected hasErr to be %v, got %v (%v)", scenario.name, scenario.expectError, hasErr, submitErr)
}
if !hasErr && form.Id != "" {
_, err := app.Dao().FindAdminById(form.Id)
if err != nil {
t.Errorf("[%s] Expected to find record with id %s, got %v", scenario.name, form.Id, err)
}
}
}
}
+24
View File
@@ -0,0 +1,24 @@
// Package models implements various services used for request data
// validation and applying changes to existing DB models through the app Dao.
package forms
import "regexp"
// base ID value regex pattern
var idRegex = regexp.MustCompile(`^[^\@\#\$\&\|\.\,\'\"\\\/\s]+$`)
// InterceptorNextFunc is a interceptor handler function.
// Usually used in combination with InterceptorFunc.
type InterceptorNextFunc = func() error
// InterceptorFunc defines a single interceptor function that will execute the provided next func handler.
type InterceptorFunc func(next InterceptorNextFunc) InterceptorNextFunc
// runInterceptors executes the provided list of interceptors.
func runInterceptors(next InterceptorNextFunc, interceptors ...InterceptorFunc) error {
for i := len(interceptors) - 1; i >= 0; i-- {
next = interceptors[i](next)
}
return next()
}
+105 -42
View File
@@ -1,11 +1,13 @@
package forms package forms
import ( import (
"fmt"
"regexp" "regexp"
"strings" "strings"
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/models/schema" "github.com/pocketbase/pocketbase/models/schema"
"github.com/pocketbase/pocketbase/resolvers" "github.com/pocketbase/pocketbase/resolvers"
@@ -14,12 +16,12 @@ import (
var collectionNameRegex = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_]*$`) var collectionNameRegex = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_]*$`)
// CollectionUpsert defines a collection upsert (create/update) form. // CollectionUpsert specifies a [models.Collection] upsert (create/update) form.
type CollectionUpsert struct { type CollectionUpsert struct {
app core.App config CollectionUpsertConfig
collection *models.Collection collection *models.Collection
isCreate bool
Id string `form:"id" json:"id"`
Name string `form:"name" json:"name"` Name string `form:"name" json:"name"`
System bool `form:"system" json:"system"` System bool `form:"system" json:"system"`
Schema schema.Schema `form:"schema" json:"schema"` Schema schema.Schema `form:"schema" json:"schema"`
@@ -30,25 +32,54 @@ type CollectionUpsert struct {
DeleteRule *string `form:"deleteRule" json:"deleteRule"` DeleteRule *string `form:"deleteRule" json:"deleteRule"`
} }
// NewCollectionUpsert creates new collection upsert form for the provided Collection model // CollectionUpsertConfig is the [CollectionUpsert] factory initializer config.
// (pass an empty Collection model instance (`&models.Collection{}`) for create). //
// NB! App is a required struct member.
type CollectionUpsertConfig struct {
App core.App
TxDao *daos.Dao
}
// NewCollectionUpsert creates a new [CollectionUpsert] form with initializer
// config created from the provided [core.App] and [models.Collection] instances
// (for create you could pass a pointer to an empty Collection - `&models.Collection{}`).
//
// If you want to submit the form as part of another transaction, use
// [NewCollectionUpsertWithConfig] with explicitly set TxDao.
func NewCollectionUpsert(app core.App, collection *models.Collection) *CollectionUpsert { func NewCollectionUpsert(app core.App, collection *models.Collection) *CollectionUpsert {
return NewCollectionUpsertWithConfig(CollectionUpsertConfig{
App: app,
}, collection)
}
// NewCollectionUpsertWithConfig creates a new [CollectionUpsert] form
// with the provided config and [models.Collection] instance or panics on invalid configuration
// (for create you could pass a pointer to an empty Collection - `&models.Collection{}`).
func NewCollectionUpsertWithConfig(config CollectionUpsertConfig, collection *models.Collection) *CollectionUpsert {
form := &CollectionUpsert{ form := &CollectionUpsert{
app: app, config: config,
collection: collection, collection: collection,
isCreate: !collection.HasId(), }
if form.config.App == nil || form.collection == nil {
panic("Invalid initializer config or nil upsert model.")
}
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
} }
// load defaults // load defaults
form.Name = collection.Name form.Id = form.collection.Id
form.System = collection.System form.Name = form.collection.Name
form.ListRule = collection.ListRule form.System = form.collection.System
form.ViewRule = collection.ViewRule form.ListRule = form.collection.ListRule
form.CreateRule = collection.CreateRule form.ViewRule = form.collection.ViewRule
form.UpdateRule = collection.UpdateRule form.CreateRule = form.collection.CreateRule
form.DeleteRule = collection.DeleteRule form.UpdateRule = form.collection.UpdateRule
form.DeleteRule = form.collection.DeleteRule
clone, _ := collection.Schema.Clone() clone, _ := form.collection.Schema.Clone()
if clone != nil { if clone != nil {
form.Schema = *clone form.Schema = *clone
} else { } else {
@@ -61,6 +92,14 @@ func NewCollectionUpsert(app core.App, collection *models.Collection) *Collectio
// Validate makes the form validatable by implementing [validation.Validatable] interface. // Validate makes the form validatable by implementing [validation.Validatable] interface.
func (form *CollectionUpsert) Validate() error { func (form *CollectionUpsert) Validate() error {
return validation.ValidateStruct(form, return validation.ValidateStruct(form,
validation.Field(
&form.Id,
validation.When(
form.collection.IsNew(),
validation.Length(models.DefaultIdLength, models.DefaultIdLength),
validation.Match(idRegex),
).Else(validation.In(form.collection.Id)),
),
validation.Field( validation.Field(
&form.System, &form.System,
validation.By(form.ensureNoSystemFlagChange), validation.By(form.ensureNoSystemFlagChange),
@@ -78,7 +117,7 @@ func (form *CollectionUpsert) Validate() error {
&form.Schema, &form.Schema,
validation.By(form.ensureNoSystemFieldsChange), validation.By(form.ensureNoSystemFieldsChange),
validation.By(form.ensureNoFieldsTypeChange), validation.By(form.ensureNoFieldsTypeChange),
validation.By(form.ensureNoFieldsNameReuse), validation.By(form.ensureExistingRelationCollectionId),
), ),
validation.Field(&form.ListRule, validation.By(form.checkRule)), validation.Field(&form.ListRule, validation.By(form.checkRule)),
validation.Field(&form.ViewRule, validation.By(form.checkRule)), validation.Field(&form.ViewRule, validation.By(form.checkRule)),
@@ -91,11 +130,11 @@ func (form *CollectionUpsert) Validate() error {
func (form *CollectionUpsert) checkUniqueName(value any) error { func (form *CollectionUpsert) checkUniqueName(value any) error {
v, _ := value.(string) v, _ := value.(string)
if !form.app.Dao().IsCollectionNameUnique(v, form.collection.Id) { if !form.config.TxDao.IsCollectionNameUnique(v, form.collection.Id) {
return validation.NewError("validation_collection_name_exists", "Collection name must be unique (case insensitive).") return validation.NewError("validation_collection_name_exists", "Collection name must be unique (case insensitive).")
} }
if (form.isCreate || !strings.EqualFold(v, form.collection.Name)) && form.app.Dao().HasTable(v) { if (form.collection.IsNew() || !strings.EqualFold(v, form.collection.Name)) && form.config.TxDao.HasTable(v) {
return validation.NewError("validation_collection_name_table_exists", "The collection name must be also unique table name.") return validation.NewError("validation_collection_name_table_exists", "The collection name must be also unique table name.")
} }
@@ -105,7 +144,7 @@ func (form *CollectionUpsert) checkUniqueName(value any) error {
func (form *CollectionUpsert) ensureNoSystemNameChange(value any) error { func (form *CollectionUpsert) ensureNoSystemNameChange(value any) error {
v, _ := value.(string) v, _ := value.(string)
if form.isCreate || !form.collection.System || v == form.collection.Name { if form.collection.IsNew() || !form.collection.System || v == form.collection.Name {
return nil return nil
} }
@@ -115,7 +154,7 @@ func (form *CollectionUpsert) ensureNoSystemNameChange(value any) error {
func (form *CollectionUpsert) ensureNoSystemFlagChange(value any) error { func (form *CollectionUpsert) ensureNoSystemFlagChange(value any) error {
v, _ := value.(bool) v, _ := value.(bool)
if form.isCreate || v == form.collection.System { if form.collection.IsNew() || v == form.collection.System {
return nil return nil
} }
@@ -125,11 +164,38 @@ func (form *CollectionUpsert) ensureNoSystemFlagChange(value any) error {
func (form *CollectionUpsert) ensureNoFieldsTypeChange(value any) error { func (form *CollectionUpsert) ensureNoFieldsTypeChange(value any) error {
v, _ := value.(schema.Schema) v, _ := value.(schema.Schema)
for _, field := range v.Fields() { for i, field := range v.Fields() {
oldField := form.collection.Schema.GetFieldById(field.Id) oldField := form.collection.Schema.GetFieldById(field.Id)
if oldField != nil && oldField.Type != field.Type { if oldField != nil && oldField.Type != field.Type {
return validation.NewError("validation_field_type_change", "Field type cannot be changed.") return validation.Errors{fmt.Sprint(i): validation.NewError(
"validation_field_type_change",
"Field type cannot be changed.",
)}
}
}
return nil
}
func (form *CollectionUpsert) ensureExistingRelationCollectionId(value any) error {
v, _ := value.(schema.Schema)
for i, field := range v.Fields() {
if field.Type != schema.FieldTypeRelation {
continue
}
options, _ := field.Options.(*schema.RelationOptions)
if options == nil {
continue
}
if _, err := form.config.TxDao.FindCollectionByNameOrId(options.CollectionId); err != nil {
return validation.Errors{fmt.Sprint(i): validation.NewError(
"validation_field_invalid_relation",
"The relation collection doesn't exist.",
)}
} }
} }
@@ -154,20 +220,6 @@ func (form *CollectionUpsert) ensureNoSystemFieldsChange(value any) error {
return nil return nil
} }
func (form *CollectionUpsert) ensureNoFieldsNameReuse(value any) error {
v, _ := value.(schema.Schema)
for _, field := range v.Fields() {
oldField := form.collection.Schema.GetFieldByName(field.Name)
if oldField != nil && oldField.Id != field.Id {
return validation.NewError("validation_field_old_field_exist", "Cannot use existing schema field names when renaming fields.")
}
}
return nil
}
func (form *CollectionUpsert) checkRule(value any) error { func (form *CollectionUpsert) checkRule(value any) error {
v, _ := value.(*string) v, _ := value.(*string)
@@ -176,7 +228,7 @@ func (form *CollectionUpsert) checkRule(value any) error {
} }
dummy := &models.Collection{Schema: form.Schema} dummy := &models.Collection{Schema: form.Schema}
r := resolvers.NewRecordFieldResolver(form.app.Dao(), dummy, nil) r := resolvers.NewRecordFieldResolver(form.config.TxDao, dummy, nil)
_, err := search.FilterData(*v).BuildExpr(r) _, err := search.FilterData(*v).BuildExpr(r)
if err != nil { if err != nil {
@@ -189,18 +241,27 @@ func (form *CollectionUpsert) checkRule(value any) error {
// Submit validates the form and upserts the form's Collection model. // Submit validates the form and upserts the form's Collection model.
// //
// On success the related record table schema will be auto updated. // On success the related record table schema will be auto updated.
func (form *CollectionUpsert) Submit() error { //
// You can optionally provide a list of InterceptorFunc to further
// modify the form behavior before persisting it.
func (form *CollectionUpsert) Submit(interceptors ...InterceptorFunc) error {
if err := form.Validate(); err != nil { if err := form.Validate(); err != nil {
return err return err
} }
// system flag can be set only for create if form.collection.IsNew() {
if form.isCreate { // system flag can be set only on create
form.collection.System = form.System form.collection.System = form.System
// custom insertion id can be set only on create
if form.Id != "" {
form.collection.MarkAsNew()
form.collection.SetId(form.Id)
}
} }
// system collections cannot be renamed // system collections cannot be renamed
if form.isCreate || !form.collection.System { if form.collection.IsNew() || !form.collection.System {
form.collection.Name = form.Name form.collection.Name = form.Name
} }
@@ -211,5 +272,7 @@ func (form *CollectionUpsert) Submit() error {
form.collection.UpdateRule = form.UpdateRule form.collection.UpdateRule = form.UpdateRule
form.collection.DeleteRule = form.DeleteRule form.collection.DeleteRule = form.DeleteRule
return form.app.Dao().SaveCollection(form.collection) return runInterceptors(func() error {
return form.config.TxDao.SaveCollection(form.collection)
}, interceptors...)
} }
+199 -3
View File
@@ -2,6 +2,7 @@ package forms_test
import ( import (
"encoding/json" "encoding/json"
"errors"
"testing" "testing"
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
@@ -9,9 +10,33 @@ import (
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/models/schema" "github.com/pocketbase/pocketbase/models/schema"
"github.com/pocketbase/pocketbase/tests" "github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/spf13/cast" "github.com/spf13/cast"
) )
func TestCollectionUpsertPanic1(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewCollectionUpsert(nil, nil)
}
func TestCollectionUpsertPanic2(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewCollectionUpsert(app, nil)
}
func TestNewCollectionUpsert(t *testing.T) { func TestNewCollectionUpsert(t *testing.T) {
app, _ := tests.NewTestApp() app, _ := tests.NewTestApp()
defer app.Cleanup() defer app.Cleanup()
@@ -260,7 +285,7 @@ func TestCollectionUpsertSubmit(t *testing.T) {
}`, }`,
[]string{"schema"}, []string{"schema"},
}, },
// update failure - rename fields to existing field names (aka. reusing field names) // update success - rename fields to existing field names (aka. reusing field names)
{ {
"test_new", "test_new",
`{ `{
@@ -269,7 +294,7 @@ func TestCollectionUpsertSubmit(t *testing.T) {
{"id":"b123456","name":"test1","type":"email"} {"id":"b123456","name":"test1","type":"email"}
] ]
}`, }`,
[]string{"schema"}, []string{},
}, },
// update failure - existing name // update failure - existing name
{ {
@@ -387,14 +412,31 @@ func TestCollectionUpsertSubmit(t *testing.T) {
continue continue
} }
interceptorCalls := 0
interceptor := func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptorCalls++
return next()
}
}
// parse errors // parse errors
result := form.Submit() result := form.Submit(interceptor)
errs, ok := result.(validation.Errors) errs, ok := result.(validation.Errors)
if !ok && result != nil { if !ok && result != nil {
t.Errorf("(%d) Failed to parse errors %v", i, result) t.Errorf("(%d) Failed to parse errors %v", i, result)
continue continue
} }
// check interceptor calls
expectInterceptorCall := 1
if len(s.expectedErrors) > 0 {
expectInterceptorCall = 0
}
if interceptorCalls != expectInterceptorCall {
t.Errorf("(%d) Expected interceptor to be called %d, got %d", i, expectInterceptorCall, interceptorCalls)
}
// check errors // check errors
if len(errs) > len(s.expectedErrors) { if len(errs) > len(s.expectedErrors) {
t.Errorf("(%d) Expected error keys %v, got %v", i, s.expectedErrors, errs) t.Errorf("(%d) Expected error keys %v, got %v", i, s.expectedErrors, errs)
@@ -450,3 +492,157 @@ func TestCollectionUpsertSubmit(t *testing.T) {
} }
} }
} }
func TestCollectionUpsertSubmitInterceptors(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, err := app.Dao().FindCollectionByNameOrId("demo")
if err != nil {
t.Fatal(err)
}
form := forms.NewCollectionUpsert(app, collection)
form.Name = "test_new"
testErr := errors.New("test_error")
interceptorCollectionName := ""
interceptor1Called := false
interceptor1 := func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptor1Called = true
return next()
}
}
interceptor2Called := false
interceptor2 := func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptorCollectionName = collection.Name // to check if the record was filled
interceptor2Called = true
return testErr
}
}
submitErr := form.Submit(interceptor1, interceptor2)
if submitErr != testErr {
t.Fatalf("Expected submitError %v, got %v", testErr, submitErr)
}
if !interceptor1Called {
t.Fatalf("Expected interceptor1 to be called")
}
if !interceptor2Called {
t.Fatalf("Expected interceptor2 to be called")
}
if interceptorCollectionName != form.Name {
t.Fatalf("Expected the form model to be filled before calling the interceptors")
}
}
func TestCollectionUpsertWithCustomId(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
existingCollection, err := app.Dao().FindCollectionByNameOrId("demo3")
if err != nil {
t.Fatal(err)
}
newCollection := func() *models.Collection {
return &models.Collection{
Name: "c_" + security.RandomString(4),
Schema: existingCollection.Schema,
}
}
scenarios := []struct {
name string
jsonData string
collection *models.Collection
expectError bool
}{
{
"empty data",
"{}",
newCollection(),
false,
},
{
"empty id",
`{"id":""}`,
newCollection(),
false,
},
{
"id < 15 chars",
`{"id":"a23"}`,
newCollection(),
true,
},
{
"id > 15 chars",
`{"id":"a234567890123456"}`,
newCollection(),
true,
},
{
"id = 15 chars (invalid chars)",
`{"id":"a@3456789012345"}`,
newCollection(),
true,
},
{
"id = 15 chars (valid chars)",
`{"id":"a23456789012345"}`,
newCollection(),
false,
},
{
"changing the id of an existing item",
`{"id":"b23456789012345"}`,
existingCollection,
true,
},
{
"using the same existing item id",
`{"id":"` + existingCollection.Id + `"}`,
existingCollection,
false,
},
{
"skipping the id for existing item",
`{}`,
existingCollection,
false,
},
}
for _, scenario := range scenarios {
form := forms.NewCollectionUpsert(app, scenario.collection)
// load data
loadErr := json.Unmarshal([]byte(scenario.jsonData), form)
if loadErr != nil {
t.Errorf("[%s] Failed to load form data: %v", scenario.name, loadErr)
continue
}
submitErr := form.Submit()
hasErr := submitErr != nil
if hasErr != scenario.expectError {
t.Errorf("[%s] Expected hasErr to be %v, got %v (%v)", scenario.name, scenario.expectError, hasErr, submitErr)
}
if !hasErr && form.Id != "" {
_, err := app.Dao().FindCollectionByNameOrId(form.Id)
if err != nil {
t.Errorf("[%s] Expected to find record with id %s, got %v", scenario.name, form.Id, err)
}
}
}
}
+152
View File
@@ -0,0 +1,152 @@
package forms
import (
"encoding/json"
"fmt"
"log"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/models"
)
// CollectionsImport specifies a form model to bulk import
// (create, replace and delete) collections from a user provided list.
type CollectionsImport struct {
config CollectionsImportConfig
Collections []*models.Collection `form:"collections" json:"collections"`
DeleteMissing bool `form:"deleteMissing" json:"deleteMissing"`
}
// CollectionsImportConfig is the [CollectionsImport] factory initializer config.
//
// NB! App is a required struct member.
type CollectionsImportConfig struct {
App core.App
TxDao *daos.Dao
}
// NewCollectionsImport creates a new [CollectionsImport] form with
// initializer config created from the provided [core.App] instance.
//
// If you want to submit the form as part of another transaction, use
// [NewCollectionsImportWithConfig] with explicitly set TxDao.
func NewCollectionsImport(app core.App) *CollectionsImport {
return NewCollectionsImportWithConfig(CollectionsImportConfig{
App: app,
})
}
// NewCollectionsImportWithConfig creates a new [CollectionsImport]
// form with the provided config or panics on invalid configuration.
func NewCollectionsImportWithConfig(config CollectionsImportConfig) *CollectionsImport {
form := &CollectionsImport{config: config}
if form.config.App == nil {
panic("Missing required config.App instance.")
}
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
}
return form
}
// Validate makes the form validatable by implementing [validation.Validatable] interface.
func (form *CollectionsImport) Validate() error {
return validation.ValidateStruct(form,
validation.Field(&form.Collections, validation.Required),
)
}
// Submit applies the import, aka.:
// - imports the form collections (create or replace)
// - sync the collection changes with their related records table
// - ensures the integrity of the imported structure (aka. run validations for each collection)
// - if [form.DeleteMissing] is set, deletes all local collections that are not found in the imports list
//
// All operations are wrapped in a single transaction that are
// rollbacked on the first encountered error.
//
// You can optionally provide a list of InterceptorFunc to further
// modify the form behavior before persisting it.
func (form *CollectionsImport) Submit(interceptors ...InterceptorFunc) error {
if err := form.Validate(); err != nil {
return err
}
return runInterceptors(func() error {
return form.config.TxDao.RunInTransaction(func(txDao *daos.Dao) error {
importErr := txDao.ImportCollections(
form.Collections,
form.DeleteMissing,
form.beforeRecordsSync,
)
if importErr == nil {
return nil
}
// validation failure
if err, ok := importErr.(validation.Errors); ok {
return err
}
// generic/db failure
if form.config.App.IsDebug() {
log.Println("Internal import failure:", importErr)
}
return validation.Errors{"collections": validation.NewError(
"collections_import_failure",
"Failed to import the collections configuration.",
)}
})
}, interceptors...)
}
func (form *CollectionsImport) beforeRecordsSync(txDao *daos.Dao, mappedNew, mappedOld map[string]*models.Collection) error {
// refresh the actual persisted collections list
refreshedCollections := []*models.Collection{}
if err := txDao.CollectionQuery().OrderBy("created ASC").All(&refreshedCollections); err != nil {
return err
}
// trigger the validator for each existing collection to
// ensure that the app is not left in a broken state
for _, collection := range refreshedCollections {
upsertModel := mappedOld[collection.GetId()]
if upsertModel == nil {
upsertModel = collection
}
upsertForm := NewCollectionUpsertWithConfig(CollectionUpsertConfig{
App: form.config.App,
TxDao: txDao,
}, upsertModel)
// load form fields with the refreshed collection state
upsertForm.Id = collection.Id
upsertForm.Name = collection.Name
upsertForm.System = collection.System
upsertForm.ListRule = collection.ListRule
upsertForm.ViewRule = collection.ViewRule
upsertForm.CreateRule = collection.CreateRule
upsertForm.UpdateRule = collection.UpdateRule
upsertForm.DeleteRule = collection.DeleteRule
upsertForm.Schema = collection.Schema
if err := upsertForm.Validate(); err != nil {
// serialize the validation error(s)
serializedErr, _ := json.MarshalIndent(err, "", " ")
return validation.Errors{"collections": validation.NewError(
"collections_import_validate_failure",
fmt.Sprintf("Data validations failed for collection %q (%s):\n%s", collection.Name, collection.Id, serializedErr),
)}
}
}
return nil
}
+419
View File
@@ -0,0 +1,419 @@
package forms_test
import (
"encoding/json"
"errors"
"testing"
"github.com/pocketbase/pocketbase/forms"
"github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/tests"
)
func TestCollectionsImportPanic(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewCollectionsImport(nil)
}
func TestCollectionsImportValidate(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
form := forms.NewCollectionsImport(app)
scenarios := []struct {
collections []*models.Collection
expectError bool
}{
{nil, true},
{[]*models.Collection{}, true},
{[]*models.Collection{{}}, false},
}
for i, s := range scenarios {
form.Collections = s.collections
err := form.Validate()
hasErr := err != nil
if hasErr != s.expectError {
t.Errorf("(%d) Expected hasErr to be %v, got %v (%v)", i, s.expectError, hasErr, err)
}
}
}
func TestCollectionsImportSubmit(t *testing.T) {
scenarios := []struct {
name string
jsonData string
expectError bool
expectCollectionsCount int
expectEvents map[string]int
}{
{
name: "empty collections",
jsonData: `{
"deleteMissing": true,
"collections": []
}`,
expectError: true,
expectCollectionsCount: 5,
expectEvents: nil,
},
{
name: "one of the collections has invalid data",
jsonData: `{
"collections": [
{
"name": "import1",
"schema": [
{
"id":"fz6iql2m",
"name":"active",
"type":"bool"
}
]
},
{
"name": "import 2",
"schema": [
{
"id":"fz6iql2m",
"name":"active",
"type":"bool"
}
]
}
]
}`,
expectError: true,
expectCollectionsCount: 5,
expectEvents: map[string]int{
"OnModelBeforeCreate": 2,
},
},
{
name: "all imported collections has valid data",
jsonData: `{
"collections": [
{
"name": "import1",
"schema": [
{
"id":"fz6iql2m",
"name":"active",
"type":"bool"
}
]
},
{
"name": "import2",
"schema": [
{
"id":"fz6iql2m",
"name":"active",
"type":"bool"
}
]
}
]
}`,
expectError: false,
expectCollectionsCount: 7,
expectEvents: map[string]int{
"OnModelBeforeCreate": 2,
"OnModelAfterCreate": 2,
},
},
{
name: "new collection with existing name",
jsonData: `{
"collections": [
{
"name": "demo2",
"schema": [
{
"id":"fz6iql2m",
"name":"active",
"type":"bool"
}
]
}
]
}`,
expectError: true,
expectCollectionsCount: 5,
expectEvents: map[string]int{
"OnModelBeforeCreate": 1,
},
},
{
name: "delete system + modified + new collection",
jsonData: `{
"deleteMissing": true,
"collections": [
{
"id":"3f2888f8-075d-49fe-9d09-ea7e951000dc",
"name":"demo",
"schema":[
{
"id":"_2hlxbmp",
"name":"title",
"type":"text",
"system":false,
"required":true,
"unique":false,
"options":{
"min":3,
"max":null,
"pattern":""
}
}
]
},
{
"name": "import1",
"schema": [
{
"id":"fz6iql2m",
"name":"active",
"type":"bool"
}
]
}
]
}`,
expectError: true,
expectCollectionsCount: 5,
},
{
name: "modified + new collection",
jsonData: `{
"collections": [
{
"id":"3f2888f8-075d-49fe-9d09-ea7e951000dc",
"name":"demo",
"schema":[
{
"id":"_2hlxbmp",
"name":"title",
"type":"text",
"system":false,
"required":true,
"unique":false,
"options":{
"min":3,
"max":null,
"pattern":""
}
}
]
},
{
"name": "import1",
"schema": [
{
"id":"fz6iql2m",
"name":"active",
"type":"bool"
}
]
},
{
"name": "import2",
"schema": [
{
"id":"fz6iql2m",
"name":"active",
"type":"bool"
}
]
}
]
}`,
expectError: false,
expectCollectionsCount: 7,
expectEvents: map[string]int{
"OnModelBeforeUpdate": 1,
"OnModelAfterUpdate": 1,
"OnModelBeforeCreate": 2,
"OnModelAfterCreate": 2,
},
},
{
name: "delete non-system + modified + new collection",
jsonData: `{
"deleteMissing": true,
"collections": [
{
"id":"abe78266-fd4d-4aea-962d-8c0138ac522b",
"name":"profiles",
"system":true,
"listRule":"userId = @request.user.id",
"viewRule":"created > 'test_change'",
"createRule":"userId = @request.user.id",
"updateRule":"userId = @request.user.id",
"deleteRule":"userId = @request.user.id",
"schema":[
{
"id":"koih1lqx",
"name":"userId",
"type":"user",
"system":true,
"required":true,
"unique":true,
"options":{
"maxSelect":1,
"cascadeDelete":true
}
},
{
"id":"69ycbg3q",
"name":"rel",
"type":"relation",
"system":false,
"required":false,
"unique":false,
"options":{
"maxSelect":2,
"collectionId":"abe78266-fd4d-4aea-962d-8c0138ac522b",
"cascadeDelete":false
}
}
]
},
{
"id":"3f2888f8-075d-49fe-9d09-ea7e951000dc",
"name":"demo",
"schema":[
{
"id":"_2hlxbmp",
"name":"title",
"type":"text",
"system":false,
"required":true,
"unique":false,
"options":{
"min":3,
"max":null,
"pattern":""
}
}
]
},
{
"id": "test_deleted_collection_name_reuse",
"name": "demo2",
"schema": [
{
"id":"fz6iql2m",
"name":"active",
"type":"bool"
}
]
}
]
}`,
expectError: false,
expectCollectionsCount: 3,
expectEvents: map[string]int{
"OnModelBeforeUpdate": 2,
"OnModelAfterUpdate": 2,
"OnModelBeforeCreate": 1,
"OnModelAfterCreate": 1,
"OnModelBeforeDelete": 3,
"OnModelAfterDelete": 3,
},
},
}
for _, s := range scenarios {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
form := forms.NewCollectionsImport(testApp)
// load data
loadErr := json.Unmarshal([]byte(s.jsonData), form)
if loadErr != nil {
t.Errorf("[%s] Failed to load form data: %v", s.name, loadErr)
continue
}
err := form.Submit()
hasErr := err != nil
if hasErr != s.expectError {
t.Errorf("[%s] Expected hasErr to be %v, got %v (%v)", s.name, s.expectError, hasErr, err)
}
// check collections count
collections := []*models.Collection{}
if err := testApp.Dao().CollectionQuery().All(&collections); err != nil {
t.Fatal(err)
}
if len(collections) != s.expectCollectionsCount {
t.Errorf("[%s] Expected %d collections, got %d", s.name, s.expectCollectionsCount, len(collections))
}
// check events
if len(testApp.EventCalls) > len(s.expectEvents) {
t.Errorf("[%s] Expected events %v, got %v", s.name, s.expectEvents, testApp.EventCalls)
}
for event, expectedCalls := range s.expectEvents {
actualCalls := testApp.EventCalls[event]
if actualCalls != expectedCalls {
t.Errorf("[%s] Expected event %s to be called %d, got %d", s.name, event, expectedCalls, actualCalls)
}
}
}
}
func TestCollectionsImportSubmitInterceptors(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collections := []*models.Collection{}
if err := app.Dao().CollectionQuery().All(&collections); err != nil {
t.Fatal(err)
}
form := forms.NewCollectionsImport(app)
form.Collections = collections
testErr := errors.New("test_error")
interceptor1Called := false
interceptor1 := func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptor1Called = true
return next()
}
}
interceptor2Called := false
interceptor2 := func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptor2Called = true
return testErr
}
}
submitErr := form.Submit(interceptor1, interceptor2)
if submitErr != testErr {
t.Fatalf("Expected submitError %v, got %v", testErr, submitErr)
}
if !interceptor1Called {
t.Fatalf("Expected interceptor1 to be called")
}
if !interceptor2Called {
t.Fatalf("Expected interceptor2 to be called")
}
}
+1 -1
View File
@@ -4,7 +4,7 @@ import (
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
) )
// RealtimeSubscribe defines a RealtimeSubscribe request form. // RealtimeSubscribe is a realtime subscriptions request form.
type RealtimeSubscribe struct { type RealtimeSubscribe struct {
ClientId string `form:"clientId" json:"clientId"` ClientId string `form:"clientId" json:"clientId"`
Subscriptions []string `form:"subscriptions" json:"subscriptions"` Subscriptions []string `form:"subscriptions" json:"subscriptions"`
+188 -91
View File
@@ -3,10 +3,13 @@ package forms
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt"
"log"
"net/http" "net/http"
"regexp" "regexp"
"strconv" "strconv"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx" "github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos" "github.com/pocketbase/pocketbase/daos"
@@ -18,29 +21,59 @@ import (
"github.com/spf13/cast" "github.com/spf13/cast"
) )
// RecordUpsert defines a Record upsert form. // RecordUpsert specifies a [models.Record] upsert (create/update) form.
type RecordUpsert struct { type RecordUpsert struct {
app core.App config RecordUpsertConfig
record *models.Record record *models.Record
isCreate bool
filesToDelete []string // names list filesToDelete []string // names list
filesToUpload []*rest.UploadedFile filesToUpload []*rest.UploadedFile
Id string `form:"id" json:"id"`
Data map[string]any `json:"data"` Data map[string]any `json:"data"`
} }
// NewRecordUpsert creates a new Record upsert form. // RecordUpsertConfig is the [RecordUpsert] factory initializer config.
// (pass a new Record model instance (`models.NewRecord(...)`) for create). //
// NB! App is required struct member.
type RecordUpsertConfig struct {
App core.App
TxDao *daos.Dao
}
// NewRecordUpsert creates a new [RecordUpsert] form with initializer
// config created from the provided [core.App] and [models.Record] instances
// (for create you could pass a pointer to an empty Record - `models.NewRecord(collection)`).
//
// If you want to submit the form as part of another transaction, use
// [NewRecordUpsertWithConfig] with explicitly set TxDao.
func NewRecordUpsert(app core.App, record *models.Record) *RecordUpsert { func NewRecordUpsert(app core.App, record *models.Record) *RecordUpsert {
return NewRecordUpsertWithConfig(RecordUpsertConfig{
App: app,
}, record)
}
// NewRecordUpsertWithConfig creates a new [RecordUpsert] form
// with the provided config and [models.Record] instance or panics on invalid configuration
// (for create you could pass a pointer to an empty Record - `models.NewRecord(collection)`).
func NewRecordUpsertWithConfig(config RecordUpsertConfig, record *models.Record) *RecordUpsert {
form := &RecordUpsert{ form := &RecordUpsert{
app: app, config: config,
record: record, record: record,
isCreate: !record.HasId(),
filesToDelete: []string{}, filesToDelete: []string{},
filesToUpload: []*rest.UploadedFile{}, filesToUpload: []*rest.UploadedFile{},
} }
if form.config.App == nil || form.record == nil {
panic("Invalid initializer config or nil upsert model.")
}
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
}
form.Id = record.Id
form.Data = map[string]any{} form.Data = map[string]any{}
for _, field := range record.Collection().Schema.Fields() { for _, field := range record.Collection().Schema.Fields() {
form.Data[field.Name] = record.GetDataValue(field.Name) form.Data[field.Name] = record.GetDataValue(field.Name)
@@ -134,6 +167,10 @@ func (form *RecordUpsert) LoadData(r *http.Request) error {
return err return err
} }
if id, ok := requestData["id"]; ok {
form.Id = cast.ToString(id)
}
// extend base data with the extracted one // extend base data with the extracted one
extendedData := form.record.Data() extendedData := form.record.Data()
rawData, err := json.Marshal(requestData) rawData, err := json.Marshal(requestData)
@@ -149,76 +186,81 @@ func (form *RecordUpsert) LoadData(r *http.Request) error {
value := extendedData[key] value := extendedData[key]
value = field.PrepareValue(value) value = field.PrepareValue(value)
if field.Type == schema.FieldTypeFile { if field.Type != schema.FieldTypeFile {
options, _ := field.Options.(*schema.FileOptions) form.Data[key] = value
oldNames := list.ToUniqueStringSlice(form.Data[key]) continue
}
// delete previously uploaded file(s) options, _ := field.Options.(*schema.FileOptions)
if options.MaxSelect == 1 { oldNames := list.ToUniqueStringSlice(form.Data[key])
// search for unset zero indexed key as a fallback
indexedKeyValue, hasIndexedKey := extendedData[key+".0"]
if cast.ToString(value) == "" || (hasIndexedKey && cast.ToString(indexedKeyValue) == "") { // delete previously uploaded file(s)
if len(oldNames) > 0 { if options.MaxSelect == 1 {
form.filesToDelete = append(form.filesToDelete, oldNames...) // search for unset zero indexed key as a fallback
} indexedKeyValue, hasIndexedKey := extendedData[key+".0"]
form.Data[key] = nil
if cast.ToString(value) == "" || (hasIndexedKey && cast.ToString(indexedKeyValue) == "") {
if len(oldNames) > 0 {
form.filesToDelete = append(form.filesToDelete, oldNames...)
} }
} else if options.MaxSelect > 1 { form.Data[key] = ""
// search for individual file index to delete (eg. "file.0") }
keyExp, _ := regexp.Compile(`^` + regexp.QuoteMeta(key) + `\.\d+$`) } else if options.MaxSelect > 1 {
indexesToDelete := []int{} // search for individual file index to delete (eg. "file.0")
for indexedKey := range extendedData { keyExp, _ := regexp.Compile(`^` + regexp.QuoteMeta(key) + `\.\d+$`)
if keyExp.MatchString(indexedKey) && cast.ToString(extendedData[indexedKey]) == "" { indexesToDelete := make([]int, 0, len(extendedData))
index, indexErr := strconv.Atoi(indexedKey[len(key)+1:]) for indexedKey := range extendedData {
if indexErr != nil || index >= len(oldNames) { if keyExp.MatchString(indexedKey) && cast.ToString(extendedData[indexedKey]) == "" {
continue index, indexErr := strconv.Atoi(indexedKey[len(key)+1:])
} if indexErr != nil || index >= len(oldNames) {
indexesToDelete = append(indexesToDelete, index)
}
}
// slice to fill only with the non-deleted indexes
nonDeleted := []string{}
for i, name := range oldNames {
// not marked for deletion
if !list.ExistInSlice(i, indexesToDelete) {
nonDeleted = append(nonDeleted, name)
continue continue
} }
indexesToDelete = append(indexesToDelete, index)
// store the id to actually delete the file later
form.filesToDelete = append(form.filesToDelete, name)
} }
form.Data[key] = nonDeleted
} }
// check if there are any new uploaded form files // slice to fill only with the non-deleted indexes
files, err := rest.FindUploadedFiles(r, key) nonDeleted := make([]string, 0, len(oldNames))
if err != nil { for i, name := range oldNames {
continue // skip invalid or missing file(s) // not marked for deletion
if !list.ExistInSlice(i, indexesToDelete) {
nonDeleted = append(nonDeleted, name)
continue
}
// store the id to actually delete the file later
form.filesToDelete = append(form.filesToDelete, name)
}
form.Data[key] = nonDeleted
}
// check if there are any new uploaded form files
files, err := rest.FindUploadedFiles(r, key)
if err != nil {
if form.config.App.IsDebug() {
log.Printf("%q uploaded file error: %v\n", key, err)
} }
// refresh oldNames list continue // skip invalid or missing file(s)
oldNames = list.ToUniqueStringSlice(form.Data[key]) }
if options.MaxSelect == 1 { // refresh oldNames list
// delete previous file(s) before replacing oldNames = list.ToUniqueStringSlice(form.Data[key])
if len(oldNames) > 0 {
form.filesToDelete = list.ToUniqueStringSlice(append(form.filesToDelete, oldNames...)) if options.MaxSelect == 1 {
} // delete previous file(s) before replacing
form.filesToUpload = append(form.filesToUpload, files[0]) if len(oldNames) > 0 {
form.Data[key] = files[0].Name() form.filesToDelete = list.ToUniqueStringSlice(append(form.filesToDelete, oldNames...))
} else if options.MaxSelect > 1 {
// append the id of each uploaded file instance
form.filesToUpload = append(form.filesToUpload, files...)
for _, file := range files {
oldNames = append(oldNames, file.Name())
}
form.Data[key] = oldNames
} }
} else { form.filesToUpload = append(form.filesToUpload, files[0])
form.Data[key] = value form.Data[key] = files[0].Name()
} else if options.MaxSelect > 1 {
// append the id of each uploaded file instance
form.filesToUpload = append(form.filesToUpload, files...)
for _, file := range files {
oldNames = append(oldNames, file.Name())
}
form.Data[key] = oldNames
} }
} }
@@ -227,8 +269,24 @@ func (form *RecordUpsert) LoadData(r *http.Request) error {
// Validate makes the form validatable by implementing [validation.Validatable] interface. // Validate makes the form validatable by implementing [validation.Validatable] interface.
func (form *RecordUpsert) Validate() error { func (form *RecordUpsert) Validate() error {
// base form fields validator
baseFieldsErrors := validation.ValidateStruct(form,
validation.Field(
&form.Id,
validation.When(
form.record.IsNew(),
validation.Length(models.DefaultIdLength, models.DefaultIdLength),
validation.Match(idRegex),
).Else(validation.In(form.record.Id)),
),
)
if baseFieldsErrors != nil {
return baseFieldsErrors
}
// record data validator
dataValidator := validators.NewRecordDataValidator( dataValidator := validators.NewRecordDataValidator(
form.app.Dao(), form.config.TxDao,
form.record, form.record,
form.filesToUpload, form.filesToUpload,
) )
@@ -245,17 +303,26 @@ func (form *RecordUpsert) DrySubmit(callback func(txDao *daos.Dao) error) error
return err return err
} }
isNew := form.record.IsNew()
// custom insertion id can be set only on create
if isNew && form.Id != "" {
form.record.MarkAsNew()
form.record.SetId(form.Id)
}
// bulk load form data // bulk load form data
if err := form.record.Load(form.Data); err != nil { if err := form.record.Load(form.Data); err != nil {
return err return err
} }
return form.app.Dao().RunInTransaction(func(txDao *daos.Dao) error { return form.config.TxDao.RunInTransaction(func(txDao *daos.Dao) error {
tx, ok := txDao.DB().(*dbx.Tx) tx, ok := txDao.DB().(*dbx.Tx)
if !ok { if !ok {
return errors.New("failed to get transaction db") return errors.New("failed to get transaction db")
} }
defer tx.Rollback() defer tx.Rollback()
txDao.BeforeCreateFunc = nil txDao.BeforeCreateFunc = nil
txDao.AfterCreateFunc = nil txDao.AfterCreateFunc = nil
txDao.BeforeUpdateFunc = nil txDao.BeforeUpdateFunc = nil
@@ -265,40 +332,60 @@ func (form *RecordUpsert) DrySubmit(callback func(txDao *daos.Dao) error) error
return err return err
} }
return callback(txDao) // restore record isNew state
if isNew {
form.record.MarkAsNew()
}
if callback != nil {
return callback(txDao)
}
return nil
}) })
} }
// Submit validates the form and upserts the form Record model. // Submit validates the form and upserts the form Record model.
func (form *RecordUpsert) Submit() error { //
// You can optionally provide a list of InterceptorFunc to further
// modify the form behavior before persisting it.
func (form *RecordUpsert) Submit(interceptors ...InterceptorFunc) error {
if err := form.Validate(); err != nil { if err := form.Validate(); err != nil {
return err return err
} }
// custom insertion id can be set only on create
if form.record.IsNew() && form.Id != "" {
form.record.MarkAsNew()
form.record.SetId(form.Id)
}
// bulk load form data // bulk load form data
if err := form.record.Load(form.Data); err != nil { if err := form.record.Load(form.Data); err != nil {
return err return err
} }
return form.app.Dao().RunInTransaction(func(txDao *daos.Dao) error { return runInterceptors(func() error {
// persist record model return form.config.TxDao.RunInTransaction(func(txDao *daos.Dao) error {
if err := txDao.SaveRecord(form.record); err != nil { // persist record model
return err if err := txDao.SaveRecord(form.record); err != nil {
} return err
}
// upload new files (if any) // upload new files (if any)
if err := form.processFilesToUpload(); err != nil { if err := form.processFilesToUpload(); err != nil {
return err return err
} }
// delete old files (if any) // delete old files (if any)
if err := form.processFilesToDelete(); err != nil { if err := form.processFilesToDelete(); err != nil { //nolint:staticcheck
// for now fail silently to avoid reupload when `form.Submit()` // for now fail silently to avoid reupload when `form.Submit()`
// is called manually (aka. not from an api request)... // is called manually (aka. not from an api request)...
} }
return nil return nil
}) })
}, interceptors...)
} }
func (form *RecordUpsert) processFilesToUpload() error { func (form *RecordUpsert) processFilesToUpload() error {
@@ -310,23 +397,28 @@ func (form *RecordUpsert) processFilesToUpload() error {
return errors.New("The record is not persisted yet.") return errors.New("The record is not persisted yet.")
} }
fs, err := form.app.NewFilesystem() fs, err := form.config.App.NewFilesystem()
if err != nil { if err != nil {
return err return err
} }
defer fs.Close() defer fs.Close()
var uploadErrors []error
for i := len(form.filesToUpload) - 1; i >= 0; i-- { for i := len(form.filesToUpload) - 1; i >= 0; i-- {
file := form.filesToUpload[i] file := form.filesToUpload[i]
path := form.record.BaseFilesPath() + "/" + file.Name() path := form.record.BaseFilesPath() + "/" + file.Name()
if err := fs.Upload(file.Bytes(), path); err == nil { if err := fs.Upload(file.Bytes(), path); err == nil {
// remove the uploaded file from the list
form.filesToUpload = append(form.filesToUpload[:i], form.filesToUpload[i+1:]...) form.filesToUpload = append(form.filesToUpload[:i], form.filesToUpload[i+1:]...)
} else {
// store the upload error
uploadErrors = append(uploadErrors, fmt.Errorf("File %d: %v", i, err))
} }
} }
if len(form.filesToUpload) > 0 { if len(uploadErrors) > 0 {
return errors.New("Failed to upload all files.") return fmt.Errorf("Failed to upload all files: %v", uploadErrors)
} }
return nil return nil
@@ -341,26 +433,31 @@ func (form *RecordUpsert) processFilesToDelete() error {
return errors.New("The record is not persisted yet.") return errors.New("The record is not persisted yet.")
} }
fs, err := form.app.NewFilesystem() fs, err := form.config.App.NewFilesystem()
if err != nil { if err != nil {
return err return err
} }
defer fs.Close() defer fs.Close()
var deleteErrors []error
for i := len(form.filesToDelete) - 1; i >= 0; i-- { for i := len(form.filesToDelete) - 1; i >= 0; i-- {
filename := form.filesToDelete[i] filename := form.filesToDelete[i]
path := form.record.BaseFilesPath() + "/" + filename path := form.record.BaseFilesPath() + "/" + filename
if err := fs.Delete(path); err == nil { if err := fs.Delete(path); err == nil {
// remove the deleted file from the list
form.filesToDelete = append(form.filesToDelete[:i], form.filesToDelete[i+1:]...) form.filesToDelete = append(form.filesToDelete[:i], form.filesToDelete[i+1:]...)
} else {
// store the delete error
deleteErrors = append(deleteErrors, fmt.Errorf("File %d: %v", i, err))
} }
// try to delete the related file thumbs (if any) // try to delete the related file thumbs (if any)
fs.DeletePrefix(form.record.BaseFilesPath() + "/thumbs_" + filename + "/") fs.DeletePrefix(form.record.BaseFilesPath() + "/thumbs_" + filename + "/")
} }
if len(form.filesToDelete) > 0 { if len(deleteErrors) > 0 {
return errors.New("Failed to delete all files.") return fmt.Errorf("Failed to delete all files: %v", deleteErrors)
} }
return nil return nil
+228 -7
View File
@@ -3,6 +3,7 @@ package forms_test
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"errors"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"path/filepath" "path/filepath"
@@ -19,6 +20,29 @@ import (
"github.com/pocketbase/pocketbase/tools/list" "github.com/pocketbase/pocketbase/tools/list"
) )
func TestRecordUpsertPanic1(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewRecordUpsert(nil, nil)
}
func TestRecordUpsertPanic2(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewRecordUpsert(app, nil)
}
func TestNewRecordUpsert(t *testing.T) { func TestNewRecordUpsert(t *testing.T) {
app, _ := tests.NewTestApp() app, _ := tests.NewTestApp()
defer app.Cleanup() defer app.Cleanup()
@@ -31,7 +55,7 @@ func TestNewRecordUpsert(t *testing.T) {
val := form.Data["title"] val := form.Data["title"]
if val != "test_value" { if val != "test_value" {
t.Errorf("Expected record data to be load, got %v", form.Data) t.Errorf("Expected record data to be loaded, got %v", form.Data)
} }
} }
@@ -67,6 +91,7 @@ func TestRecordUpsertLoadDataJson(t *testing.T) {
} }
testData := map[string]any{ testData := map[string]any{
"id": "test_id",
"title": "test123", "title": "test123",
"unknown": "test456", "unknown": "test456",
// file fields unset/delete // file fields unset/delete
@@ -85,6 +110,10 @@ func TestRecordUpsertLoadDataJson(t *testing.T) {
t.Fatal(loadErr) t.Fatal(loadErr)
} }
if form.Id != "test_id" {
t.Fatalf("Expect id field to be %q, got %q", "test_id", form.Id)
}
if v, ok := form.Data["title"]; !ok || v != "test123" { if v, ok := form.Data["title"]; !ok || v != "test123" {
t.Fatalf("Expect title field to be %q, got %q", "test123", v) t.Fatalf("Expect title field to be %q, got %q", "test123", v)
} }
@@ -97,8 +126,8 @@ func TestRecordUpsertLoadDataJson(t *testing.T) {
if !ok { if !ok {
t.Fatal("Expect onefile field to be set") t.Fatal("Expect onefile field to be set")
} }
if onefile != nil { if onefile != "" {
t.Fatalf("Expect onefile field to be nil, got %v", onefile) t.Fatalf("Expect onefile field to be empty string, got %v", onefile)
} }
manyfiles, ok := form.Data["manyfiles"] manyfiles, ok := form.Data["manyfiles"]
@@ -133,6 +162,7 @@ func TestRecordUpsertLoadDataMultipart(t *testing.T) {
} }
formData, mp, err := tests.MockMultipartData(map[string]string{ formData, mp, err := tests.MockMultipartData(map[string]string{
"id": "test_id",
"title": "test123", "title": "test123",
"unknown": "test456", "unknown": "test456",
// file fields unset/delete // file fields unset/delete
@@ -153,6 +183,10 @@ func TestRecordUpsertLoadDataMultipart(t *testing.T) {
t.Fatal(loadErr) t.Fatal(loadErr)
} }
if form.Id != "test_id" {
t.Fatalf("Expect id field to be %q, got %q", "test_id", form.Id)
}
if v, ok := form.Data["title"]; !ok || v != "test123" { if v, ok := form.Data["title"]; !ok || v != "test123" {
t.Fatalf("Expect title field to be %q, got %q", "test123", v) t.Fatalf("Expect title field to be %q, got %q", "test123", v)
} }
@@ -165,8 +199,8 @@ func TestRecordUpsertLoadDataMultipart(t *testing.T) {
if !ok { if !ok {
t.Fatal("Expect onefile field to be set") t.Fatal("Expect onefile field to be set")
} }
if onefile != nil { if onefile != "" {
t.Fatalf("Expect onefile field to be nil, got %v", onefile) t.Fatalf("Expect onefile field to be empty string, got %v", onefile)
} }
manyfiles, ok := form.Data["manyfiles"] manyfiles, ok := form.Data["manyfiles"]
@@ -201,6 +235,7 @@ func TestRecordUpsertValidateFailure(t *testing.T) {
// try with invalid test data to check whether the RecordDataValidator is triggered // try with invalid test data to check whether the RecordDataValidator is triggered
formData, mp, err := tests.MockMultipartData(map[string]string{ formData, mp, err := tests.MockMultipartData(map[string]string{
"id": "",
"unknown": "test456", // should be ignored "unknown": "test456", // should be ignored
"title": "a", "title": "a",
"onerel": "00000000-84ab-4057-a592-4604a731f78f", "onerel": "00000000-84ab-4057-a592-4604a731f78f",
@@ -246,6 +281,7 @@ func TestRecordUpsertValidateSuccess(t *testing.T) {
} }
formData, mp, err := tests.MockMultipartData(map[string]string{ formData, mp, err := tests.MockMultipartData(map[string]string{
"id": record.Id,
"unknown": "test456", // should be ignored "unknown": "test456", // should be ignored
"title": "abc", "title": "abc",
"onerel": "054f9f24-0a0a-4e09-87b1-bc7ff2b336a2", "onerel": "054f9f24-0a0a-4e09-87b1-bc7ff2b336a2",
@@ -400,13 +436,27 @@ func TestRecordUpsertSubmitFailure(t *testing.T) {
req.Header.Set(echo.HeaderContentType, mp.FormDataContentType()) req.Header.Set(echo.HeaderContentType, mp.FormDataContentType())
form.LoadData(req) form.LoadData(req)
interceptorCalls := 0
interceptor := func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptorCalls++
return next()
}
}
// ensure that validate is triggered // ensure that validate is triggered
// --- // ---
result := form.Submit() result := form.Submit(interceptor)
if result == nil { if result == nil {
t.Fatal("Expected error, got nil") t.Fatal("Expected error, got nil")
} }
// check interceptor calls
// ---
if interceptorCalls != 0 {
t.Fatalf("Expected interceptor to be called 0 times, got %d", interceptorCalls)
}
// ensure that the record changes weren't persisted // ensure that the record changes weren't persisted
// --- // ---
recordAfter, err := app.Dao().FindFirstRecordByData(collection, "id", recordBefore.Id) recordAfter, err := app.Dao().FindFirstRecordByData(collection, "id", recordBefore.Id)
@@ -451,11 +501,25 @@ func TestRecordUpsertSubmitSuccess(t *testing.T) {
req.Header.Set(echo.HeaderContentType, mp.FormDataContentType()) req.Header.Set(echo.HeaderContentType, mp.FormDataContentType())
form.LoadData(req) form.LoadData(req)
result := form.Submit() interceptorCalls := 0
interceptor := func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptorCalls++
return next()
}
}
result := form.Submit(interceptor)
if result != nil { if result != nil {
t.Fatalf("Expected nil, got error %v", result) t.Fatalf("Expected nil, got error %v", result)
} }
// check interceptor calls
// ---
if interceptorCalls != 1 {
t.Fatalf("Expected interceptor to be called 1 time, got %d", interceptorCalls)
}
// ensure that the record changes were persisted // ensure that the record changes were persisted
// --- // ---
recordAfter, err := app.Dao().FindFirstRecordByData(collection, "id", recordBefore.Id) recordAfter, err := app.Dao().FindFirstRecordByData(collection, "id", recordBefore.Id)
@@ -482,6 +546,57 @@ func TestRecordUpsertSubmitSuccess(t *testing.T) {
} }
} }
func TestRecordUpsertSubmitInterceptors(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, _ := app.Dao().FindCollectionByNameOrId("demo4")
record, err := app.Dao().FindFirstRecordByData(collection, "id", "054f9f24-0a0a-4e09-87b1-bc7ff2b336a2")
if err != nil {
t.Fatal(err)
}
form := forms.NewRecordUpsert(app, record)
form.Data["title"] = "test_new"
testErr := errors.New("test_error")
interceptorRecordTitle := ""
interceptor1Called := false
interceptor1 := func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptor1Called = true
return next()
}
}
interceptor2Called := false
interceptor2 := func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptorRecordTitle = record.GetStringDataValue("title") // to check if the record was filled
interceptor2Called = true
return testErr
}
}
submitErr := form.Submit(interceptor1, interceptor2)
if submitErr != testErr {
t.Fatalf("Expected submitError %v, got %v", testErr, submitErr)
}
if !interceptor1Called {
t.Fatalf("Expected interceptor1 to be called")
}
if !interceptor2Called {
t.Fatalf("Expected interceptor2 to be called")
}
if interceptorRecordTitle != form.Data["title"].(string) {
t.Fatalf("Expected the form model to be filled before calling the interceptors")
}
}
func hasRecordFile(app core.App, record *models.Record, filename string) bool { func hasRecordFile(app core.App, record *models.Record, filename string) bool {
fs, _ := app.NewFilesystem() fs, _ := app.NewFilesystem()
defer fs.Close() defer fs.Close()
@@ -496,3 +611,109 @@ func hasRecordFile(app core.App, record *models.Record, filename string) bool {
return exists return exists
} }
func TestRecordUpsertWithCustomId(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, _ := app.Dao().FindCollectionByNameOrId("demo3")
existingRecord, err := app.Dao().FindFirstRecordByData(collection, "id", "2c542824-9de1-42fe-8924-e57c86267760")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
data map[string]string
record *models.Record
expectError bool
}{
{
"empty data",
map[string]string{},
models.NewRecord(collection),
false,
},
{
"empty id",
map[string]string{"id": ""},
models.NewRecord(collection),
false,
},
{
"id < 15 chars",
map[string]string{"id": "a23"},
models.NewRecord(collection),
true,
},
{
"id > 15 chars",
map[string]string{"id": "a234567890123456"},
models.NewRecord(collection),
true,
},
{
"id = 15 chars (invalid chars)",
map[string]string{"id": "a@3456789012345"},
models.NewRecord(collection),
true,
},
{
"id = 15 chars (valid chars)",
map[string]string{"id": "a23456789012345"},
models.NewRecord(collection),
false,
},
{
"changing the id of an existing record",
map[string]string{"id": "b23456789012345"},
existingRecord,
true,
},
{
"using the same existing record id",
map[string]string{"id": existingRecord.Id},
existingRecord,
false,
},
{
"skipping the id for existing record",
map[string]string{},
existingRecord,
false,
},
}
for _, scenario := range scenarios {
formData, mp, err := tests.MockMultipartData(scenario.data)
if err != nil {
t.Fatal(err)
}
form := forms.NewRecordUpsert(app, scenario.record)
req := httptest.NewRequest(http.MethodGet, "/", formData)
req.Header.Set(echo.HeaderContentType, mp.FormDataContentType())
form.LoadData(req)
dryErr := form.DrySubmit(nil)
hasDryErr := dryErr != nil
submitErr := form.Submit()
hasSubmitErr := submitErr != nil
if hasDryErr != hasSubmitErr {
t.Errorf("[%s] Expected hasDryErr and hasSubmitErr to have the same value, got %v vs %v", scenario.name, hasDryErr, hasSubmitErr)
}
if hasSubmitErr != scenario.expectError {
t.Errorf("[%s] Expected hasSubmitErr to be %v, got %v (%v)", scenario.name, scenario.expectError, hasSubmitErr, submitErr)
}
if id, ok := scenario.data["id"]; ok && id != "" && !hasSubmitErr {
_, err := app.Dao().FindRecordById(collection, id, nil)
if err != nil {
t.Errorf("[%s] Expected to find record with id %s, got %v", scenario.name, id, err)
}
}
}
}
+60 -21
View File
@@ -5,22 +5,56 @@ import (
"time" "time"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
) )
// SettingsUpsert defines app settings upsert form. // SettingsUpsert specifies a [core.Settings] upsert (create/update) form.
type SettingsUpsert struct { type SettingsUpsert struct {
*core.Settings *core.Settings
app core.App config SettingsUpsertConfig
} }
// NewSettingsUpsert creates new settings upsert form from the provided app. // SettingsUpsertConfig is the [SettingsUpsert] factory initializer config.
//
// NB! App is required struct member.
type SettingsUpsertConfig struct {
App core.App
TxDao *daos.Dao
TxLogsDao *daos.Dao
}
// NewSettingsUpsert creates a new [SettingsUpsert] form with initializer
// config created from the provided [core.App] instance.
//
// If you want to submit the form as part of another transaction, use
// [NewSettingsUpsertWithConfig] with explicitly set TxDao.
func NewSettingsUpsert(app core.App) *SettingsUpsert { func NewSettingsUpsert(app core.App) *SettingsUpsert {
form := &SettingsUpsert{app: app} return NewSettingsUpsertWithConfig(SettingsUpsertConfig{
App: app,
})
}
// NewSettingsUpsertWithConfig creates a new [SettingsUpsert] form
// with the provided config or panics on invalid configuration.
func NewSettingsUpsertWithConfig(config SettingsUpsertConfig) *SettingsUpsert {
form := &SettingsUpsert{config: config}
if form.config.App == nil {
panic("Missing required config.App instance.")
}
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
}
if form.config.TxLogsDao == nil {
form.config.TxLogsDao = form.config.App.LogsDao()
}
// load the application settings into the form // load the application settings into the form
form.Settings, _ = app.Settings().Clone() form.Settings, _ = config.App.Settings().Clone()
return form return form
} }
@@ -33,27 +67,32 @@ func (form *SettingsUpsert) Validate() error {
// Submit validates the form and upserts the loaded settings. // Submit validates the form and upserts the loaded settings.
// //
// On success the app settings will be refreshed with the form ones. // On success the app settings will be refreshed with the form ones.
func (form *SettingsUpsert) Submit() error { //
// You can optionally provide a list of InterceptorFunc to further
// modify the form behavior before persisting it.
func (form *SettingsUpsert) Submit(interceptors ...InterceptorFunc) error {
if err := form.Validate(); err != nil { if err := form.Validate(); err != nil {
return err return err
} }
encryptionKey := os.Getenv(form.app.EncryptionEnv()) encryptionKey := os.Getenv(form.config.App.EncryptionEnv())
saveErr := form.app.Dao().SaveParam( return runInterceptors(func() error {
models.ParamAppSettings, saveErr := form.config.TxDao.SaveParam(
form.Settings, models.ParamAppSettings,
encryptionKey, form.Settings,
) encryptionKey,
if saveErr != nil { )
return saveErr if saveErr != nil {
} return saveErr
}
// explicitly trigger old logs deletion // explicitly trigger old logs deletion
form.app.LogsDao().DeleteOldRequests( form.config.TxLogsDao.DeleteOldRequests(
time.Now().AddDate(0, 0, -1*form.Settings.Logs.MaxDays), time.Now().AddDate(0, 0, -1*form.Settings.Logs.MaxDays),
) )
// merge the application settings with the form ones // merge the application settings with the form ones
return form.app.Settings().Merge(form.Settings) return form.config.App.Settings().Merge(form.Settings)
}, interceptors...)
} }
+68 -1
View File
@@ -2,6 +2,7 @@ package forms_test
import ( import (
"encoding/json" "encoding/json"
"errors"
"os" "os"
"testing" "testing"
@@ -11,6 +12,16 @@ import (
"github.com/pocketbase/pocketbase/tools/security" "github.com/pocketbase/pocketbase/tools/security"
) )
func TestSettingsUpsertPanic(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewSettingsUpsert(nil)
}
func TestNewSettingsUpsert(t *testing.T) { func TestNewSettingsUpsert(t *testing.T) {
app, _ := tests.NewTestApp() app, _ := tests.NewTestApp()
defer app.Cleanup() defer app.Cleanup()
@@ -98,14 +109,31 @@ func TestSettingsUpsertSubmit(t *testing.T) {
continue continue
} }
interceptorCalls := 0
interceptor := func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptorCalls++
return next()
}
}
// parse errors // parse errors
result := form.Submit() result := form.Submit(interceptor)
errs, ok := result.(validation.Errors) errs, ok := result.(validation.Errors)
if !ok && result != nil { if !ok && result != nil {
t.Errorf("(%d) Failed to parse errors %v", i, result) t.Errorf("(%d) Failed to parse errors %v", i, result)
continue continue
} }
// check interceptor calls
expectInterceptorCall := 1
if len(s.expectedErrors) > 0 {
expectInterceptorCall = 0
}
if interceptorCalls != expectInterceptorCall {
t.Errorf("(%d) Expected interceptor to be called %d, got %d", i, expectInterceptorCall, interceptorCalls)
}
// check errors // check errors
if len(errs) > len(s.expectedErrors) { if len(errs) > len(s.expectedErrors) {
t.Errorf("(%d) Expected error keys %v, got %v", i, s.expectedErrors, errs) t.Errorf("(%d) Expected error keys %v, got %v", i, s.expectedErrors, errs)
@@ -128,3 +156,42 @@ func TestSettingsUpsertSubmit(t *testing.T) {
} }
} }
} }
func TestSettingsUpsertSubmitInterceptors(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
form := forms.NewSettingsUpsert(app)
form.Meta.AppName = "test_new"
testErr := errors.New("test_error")
interceptor1Called := false
interceptor1 := func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptor1Called = true
return next()
}
}
interceptor2Called := false
interceptor2 := func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptor2Called = true
return testErr
}
}
submitErr := form.Submit(interceptor1, interceptor2)
if submitErr != testErr {
t.Fatalf("Expected submitError %v, got %v", testErr, submitErr)
}
if !interceptor1Called {
t.Fatalf("Expected interceptor1 to be called")
}
if !interceptor2Called {
t.Fatalf("Expected interceptor2 to be called")
}
}
+69
View File
@@ -0,0 +1,69 @@
package forms
import (
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/mails"
"github.com/pocketbase/pocketbase/models"
)
const (
templateVerification = "verification"
templatePasswordReset = "password-reset"
templateEmailChange = "email-change"
)
// TestEmailSend is a email template test request form.
type TestEmailSend struct {
app core.App
Template string `form:"template" json:"template"`
Email string `form:"email" json:"email"`
}
// NewTestEmailSend creates and initializes new TestEmailSend form.
func NewTestEmailSend(app core.App) *TestEmailSend {
return &TestEmailSend{app: app}
}
// Validate makes the form validatable by implementing [validation.Validatable] interface.
func (form *TestEmailSend) Validate() error {
return validation.ValidateStruct(form,
validation.Field(
&form.Email,
validation.Required,
validation.Length(1, 255),
is.Email,
),
validation.Field(
&form.Template,
validation.Required,
validation.In(templateVerification, templateEmailChange, templatePasswordReset),
),
)
}
// Submit validates and sends a test email to the form.Email address.
func (form *TestEmailSend) Submit() error {
if err := form.Validate(); err != nil {
return err
}
// create a test user
user := &models.User{}
user.Id = "__pb_test_id__"
user.Email = form.Email
user.RefreshTokenKey()
switch form.Template {
case templateVerification:
return mails.SendUserVerification(form.app, user)
case templatePasswordReset:
return mails.SendUserPasswordReset(form.app, user)
case templateEmailChange:
return mails.SendUserChangeEmail(form.app, user, form.Email)
}
return nil
}
+103
View File
@@ -0,0 +1,103 @@
package forms_test
import (
"strings"
"testing"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/forms"
"github.com/pocketbase/pocketbase/tests"
)
func TestEmailSendValidate(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
template string
email string
expectedErrors []string
}{
{"", "", []string{"template", "email"}},
{"invalid", "test@example.com", []string{"template"}},
{"verification", "invalid", []string{"email"}},
{"verification", "test@example.com", nil},
{"password-reset", "test@example.com", nil},
{"email-change", "test@example.com", nil},
}
for i, s := range scenarios {
form := forms.NewTestEmailSend(app)
form.Email = s.email
form.Template = s.template
result := form.Validate()
// parse errors
errs, ok := result.(validation.Errors)
if !ok && result != nil {
t.Errorf("(%d) Failed to parse errors %v", i, result)
continue
}
// check errors
if len(errs) > len(s.expectedErrors) {
t.Errorf("(%d) Expected error keys %v, got %v", i, s.expectedErrors, errs)
}
for _, k := range s.expectedErrors {
if _, ok := errs[k]; !ok {
t.Errorf("(%d) Missing expected error key %q in %v", i, k, errs)
}
}
}
}
func TestEmailSendSubmit(t *testing.T) {
scenarios := []struct {
template string
email string
expectError bool
}{
{"", "", true},
{"invalid", "test@example.com", true},
{"verification", "invalid", true},
{"verification", "test@example.com", false},
{"password-reset", "test@example.com", false},
{"email-change", "test@example.com", false},
}
for i, s := range scenarios {
app, _ := tests.NewTestApp()
defer app.Cleanup()
form := forms.NewTestEmailSend(app)
form.Email = s.email
form.Template = s.template
err := form.Submit()
hasErr := err != nil
if hasErr != s.expectError {
t.Errorf("(%d) Expected hasErr to be %v, got %v (%v)", i, s.expectError, hasErr, err)
}
if hasErr {
continue
}
if app.TestMailer.TotalSend != 1 {
t.Errorf("(%d) Expected one email to be sent, got %d", i, app.TestMailer.TotalSend)
}
expectedContent := "Verify"
if s.template == "password-reset" {
expectedContent = "Reset password"
} else if s.template == "email-change" {
expectedContent = "Confirm new email"
}
if !strings.Contains(app.TestMailer.LastHtmlBody, expectedContent) {
t.Errorf("(%d) Expected the email to contains %s, got \n%v", i, expectedContent, app.TestMailer.LastHtmlBody)
}
}
}
+40 -10
View File
@@ -3,23 +3,53 @@ package forms
import ( import (
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/tools/security" "github.com/pocketbase/pocketbase/tools/security"
) )
// UserEmailChangeConfirm defines a user email change confirmation form. // UserEmailChangeConfirm specifies a user email change confirmation form.
type UserEmailChangeConfirm struct { type UserEmailChangeConfirm struct {
app core.App config UserEmailChangeConfirmConfig
Token string `form:"token" json:"token"` Token string `form:"token" json:"token"`
Password string `form:"password" json:"password"` Password string `form:"password" json:"password"`
} }
// NewUserEmailChangeConfirm creates new user email change confirmation form. // UserEmailChangeConfirmConfig is the [UserEmailChangeConfirm] factory initializer config.
//
// NB! App is required struct member.
type UserEmailChangeConfirmConfig struct {
App core.App
TxDao *daos.Dao
}
// NewUserEmailChangeConfirm creates a new [UserEmailChangeConfirm]
// form with initializer config created from the provided [core.App] instance.
//
// This factory method is used primarily for convenience (and backward compatibility).
// If you want to submit the form as part of another transaction, use
// [NewUserEmailChangeConfirmWithConfig] with explicitly set TxDao.
func NewUserEmailChangeConfirm(app core.App) *UserEmailChangeConfirm { func NewUserEmailChangeConfirm(app core.App) *UserEmailChangeConfirm {
return &UserEmailChangeConfirm{ return NewUserEmailChangeConfirmWithConfig(UserEmailChangeConfirmConfig{
app: app, App: app,
})
}
// NewUserEmailChangeConfirmWithConfig creates a new [UserEmailChangeConfirm]
// form with the provided config or panics on invalid configuration.
func NewUserEmailChangeConfirmWithConfig(config UserEmailChangeConfirmConfig) *UserEmailChangeConfirm {
form := &UserEmailChangeConfirm{config: config}
if form.config.App == nil {
panic("Missing required config.App instance.")
} }
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
}
return form
} }
// Validate makes the form validatable by implementing [validation.Validatable] interface. // Validate makes the form validatable by implementing [validation.Validatable] interface.
@@ -73,14 +103,14 @@ func (form *UserEmailChangeConfirm) parseToken(token string) (*models.User, stri
} }
// ensure that there aren't other users with the new email // ensure that there aren't other users with the new email
if !form.app.Dao().IsUserEmailUnique(newEmail, "") { if !form.config.TxDao.IsUserEmailUnique(newEmail, "") {
return nil, "", validation.NewError("validation_existing_token_email", "The new email address is already registered: "+newEmail) return nil, "", validation.NewError("validation_existing_token_email", "The new email address is already registered: "+newEmail)
} }
// verify that the token is not expired and its signiture is valid // verify that the token is not expired and its signature is valid
user, err := form.app.Dao().FindUserByToken( user, err := form.config.TxDao.FindUserByToken(
token, token,
form.app.Settings().UserEmailChangeToken.Secret, form.config.App.Settings().UserEmailChangeToken.Secret,
) )
if err != nil || user == nil { if err != nil || user == nil {
return nil, "", validation.NewError("validation_invalid_token", "Invalid or expired token.") return nil, "", validation.NewError("validation_invalid_token", "Invalid or expired token.")
@@ -105,7 +135,7 @@ func (form *UserEmailChangeConfirm) Submit() (*models.User, error) {
user.Verified = true user.Verified = true
user.RefreshTokenKey() // invalidate old tokens user.RefreshTokenKey() // invalidate old tokens
if err := form.app.Dao().SaveUser(user); err != nil { if err := form.config.TxDao.SaveUser(user); err != nil {
return nil, err return nil, err
} }
+10
View File
@@ -10,6 +10,16 @@ import (
"github.com/pocketbase/pocketbase/tools/security" "github.com/pocketbase/pocketbase/tools/security"
) )
func TestUserEmailChangeConfirmPanic(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewUserEmailChangeConfirm(nil)
}
func TestUserEmailChangeConfirmValidateAndSubmit(t *testing.T) { func TestUserEmailChangeConfirmValidateAndSubmit(t *testing.T) {
app, _ := tests.NewTestApp() app, _ := tests.NewTestApp()
defer app.Cleanup() defer app.Cleanup()
+39 -8
View File
@@ -4,24 +4,55 @@ import (
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is" "github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/mails" "github.com/pocketbase/pocketbase/mails"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
) )
// UserEmailChangeRequest defines a user email change request form. // UserEmailChangeRequest defines a user email change request form.
type UserEmailChangeRequest struct { type UserEmailChangeRequest struct {
app core.App config UserEmailChangeRequestConfig
user *models.User user *models.User
NewEmail string `form:"newEmail" json:"newEmail"` NewEmail string `form:"newEmail" json:"newEmail"`
} }
// NewUserEmailChangeRequest creates a new user email change request form. // UserEmailChangeRequestConfig is the [UserEmailChangeRequest] factory initializer config.
//
// NB! App is required struct member.
type UserEmailChangeRequestConfig struct {
App core.App
TxDao *daos.Dao
}
// NewUserEmailChangeRequest creates a new [UserEmailChangeRequest]
// form with initializer config created from the provided [core.App] instance.
//
// If you want to submit the form as part of another transaction, use
// [NewUserEmailChangeConfirmWithConfig] with explicitly set TxDao.
func NewUserEmailChangeRequest(app core.App, user *models.User) *UserEmailChangeRequest { func NewUserEmailChangeRequest(app core.App, user *models.User) *UserEmailChangeRequest {
return &UserEmailChangeRequest{ return NewUserEmailChangeRequestWithConfig(UserEmailChangeRequestConfig{
app: app, App: app,
user: user, }, user)
}
// NewUserEmailChangeRequestWithConfig creates a new [UserEmailChangeRequest]
// form with the provided config or panics on invalid configuration.
func NewUserEmailChangeRequestWithConfig(config UserEmailChangeRequestConfig, user *models.User) *UserEmailChangeRequest {
form := &UserEmailChangeRequest{
config: config,
user: user,
} }
if form.config.App == nil || form.user == nil {
panic("Invalid initializer config or nil user model.")
}
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
}
return form
} }
// Validate makes the form validatable by implementing [validation.Validatable] interface. // Validate makes the form validatable by implementing [validation.Validatable] interface.
@@ -40,7 +71,7 @@ func (form *UserEmailChangeRequest) Validate() error {
func (form *UserEmailChangeRequest) checkUniqueEmail(value any) error { func (form *UserEmailChangeRequest) checkUniqueEmail(value any) error {
v, _ := value.(string) v, _ := value.(string)
if !form.app.Dao().IsUserEmailUnique(v, "") { if !form.config.TxDao.IsUserEmailUnique(v, "") {
return validation.NewError("validation_user_email_exists", "User email already exists.") return validation.NewError("validation_user_email_exists", "User email already exists.")
} }
@@ -53,5 +84,5 @@ func (form *UserEmailChangeRequest) Submit() error {
return err return err
} }
return mails.SendUserChangeEmail(form.app, form.user, form.NewEmail) return mails.SendUserChangeEmail(form.config.App, form.user, form.NewEmail)
} }
+23
View File
@@ -9,6 +9,29 @@ import (
"github.com/pocketbase/pocketbase/tests" "github.com/pocketbase/pocketbase/tests"
) )
func TestUserEmailChangeRequestPanic1(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewUserEmailChangeRequest(nil, nil)
}
func TestUserEmailChangeRequestPanic2(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewUserEmailChangeRequest(testApp, nil)
}
func TestUserEmailChangeRequestValidateAndSubmit(t *testing.T) { func TestUserEmailChangeRequestValidateAndSubmit(t *testing.T) {
testApp, _ := tests.NewTestApp() testApp, _ := tests.NewTestApp()
defer testApp.Cleanup() defer testApp.Cleanup()
+35 -7
View File
@@ -4,21 +4,49 @@ import (
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is" "github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
) )
// UserEmailLogin defines a user email/pass login form. // UserEmailLogin specifies a user email/pass login form.
type UserEmailLogin struct { type UserEmailLogin struct {
app core.App config UserEmailLoginConfig
Email string `form:"email" json:"email"` Email string `form:"email" json:"email"`
Password string `form:"password" json:"password"` Password string `form:"password" json:"password"`
} }
// NewUserEmailLogin creates a new user email/pass login form. // UserEmailLoginConfig is the [UserEmailLogin] factory initializer config.
//
// NB! App is required struct member.
type UserEmailLoginConfig struct {
App core.App
TxDao *daos.Dao
}
// NewUserEmailLogin creates a new [UserEmailLogin] form with
// initializer config created from the provided [core.App] instance.
//
// This factory method is used primarily for convenience (and backward compatibility).
// If you want to submit the form as part of another transaction, use
// [NewUserEmailLoginWithConfig] with explicitly set TxDao.
func NewUserEmailLogin(app core.App) *UserEmailLogin { func NewUserEmailLogin(app core.App) *UserEmailLogin {
form := &UserEmailLogin{ return NewUserEmailLoginWithConfig(UserEmailLoginConfig{
app: app, App: app,
})
}
// NewUserEmailLoginWithConfig creates a new [UserEmailLogin]
// form with the provided config or panics on invalid configuration.
func NewUserEmailLoginWithConfig(config UserEmailLoginConfig) *UserEmailLogin {
form := &UserEmailLogin{config: config}
if form.config.App == nil {
panic("Missing required config.App instance.")
}
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
} }
return form return form
@@ -27,7 +55,7 @@ func NewUserEmailLogin(app core.App) *UserEmailLogin {
// Validate makes the form validatable by implementing [validation.Validatable] interface. // Validate makes the form validatable by implementing [validation.Validatable] interface.
func (form *UserEmailLogin) Validate() error { func (form *UserEmailLogin) Validate() error {
return validation.ValidateStruct(form, return validation.ValidateStruct(form,
validation.Field(&form.Email, validation.Required, validation.Length(1, 255), is.Email), validation.Field(&form.Email, validation.Required, validation.Length(1, 255), is.EmailFormat),
validation.Field(&form.Password, validation.Required, validation.Length(1, 255)), validation.Field(&form.Password, validation.Required, validation.Length(1, 255)),
) )
} }
@@ -39,7 +67,7 @@ func (form *UserEmailLogin) Submit() (*models.User, error) {
return nil, err return nil, err
} }
user, err := form.app.Dao().FindUserByEmail(form.Email) user, err := form.config.TxDao.FindUserByEmail(form.Email)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+10
View File
@@ -9,6 +9,16 @@ import (
"github.com/pocketbase/pocketbase/tests" "github.com/pocketbase/pocketbase/tests"
) )
func TestUserEmailLoginPanic(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewUserEmailLogin(nil)
}
func TestUserEmailLoginValidate(t *testing.T) { func TestUserEmailLoginValidate(t *testing.T) {
app, _ := tests.NewTestApp() app, _ := tests.NewTestApp()
defer app.Cleanup() defer app.Cleanup()
+67 -32
View File
@@ -7,15 +7,16 @@ import (
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is" "github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/tools/auth" "github.com/pocketbase/pocketbase/tools/auth"
"github.com/pocketbase/pocketbase/tools/security" "github.com/pocketbase/pocketbase/tools/security"
"golang.org/x/oauth2" "golang.org/x/oauth2"
) )
// UserOauth2Login defines a user Oauth2 login form. // UserOauth2Login specifies a user Oauth2 login form.
type UserOauth2Login struct { type UserOauth2Login struct {
app core.App config UserOauth2LoginConfig
// The name of the OAuth2 client provider (eg. "google") // The name of the OAuth2 client provider (eg. "google")
Provider string `form:"provider" json:"provider"` Provider string `form:"provider" json:"provider"`
@@ -30,9 +31,39 @@ type UserOauth2Login struct {
RedirectUrl string `form:"redirectUrl" json:"redirectUrl"` RedirectUrl string `form:"redirectUrl" json:"redirectUrl"`
} }
// NewUserOauth2Login creates a new user Oauth2 login form. // UserOauth2LoginConfig is the [UserOauth2Login] factory initializer config.
//
// NB! App is required struct member.
type UserOauth2LoginConfig struct {
App core.App
TxDao *daos.Dao
}
// NewUserOauth2Login creates a new [UserOauth2Login] form with
// initializer config created from the provided [core.App] instance.
//
// If you want to submit the form as part of another transaction, use
// [NewUserOauth2LoginWithConfig] with explicitly set TxDao.
func NewUserOauth2Login(app core.App) *UserOauth2Login { func NewUserOauth2Login(app core.App) *UserOauth2Login {
return &UserOauth2Login{app: app} return NewUserOauth2LoginWithConfig(UserOauth2LoginConfig{
App: app,
})
}
// NewUserOauth2LoginWithConfig creates a new [UserOauth2Login]
// form with the provided config or panics on invalid configuration.
func NewUserOauth2LoginWithConfig(config UserOauth2LoginConfig) *UserOauth2Login {
form := &UserOauth2Login{config: config}
if form.config.App == nil {
panic("Missing required config.App instance.")
}
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
}
return form
} }
// Validate makes the form validatable by implementing [validation.Validatable] interface. // Validate makes the form validatable by implementing [validation.Validatable] interface.
@@ -48,7 +79,7 @@ func (form *UserOauth2Login) Validate() error {
func (form *UserOauth2Login) checkProviderName(value any) error { func (form *UserOauth2Login) checkProviderName(value any) error {
name, _ := value.(string) name, _ := value.(string)
config, ok := form.app.Settings().NamedAuthProviderConfigs()[name] config, ok := form.config.App.Settings().NamedAuthProviderConfigs()[name]
if !ok || !config.Enabled { if !ok || !config.Enabled {
return validation.NewError("validation_invalid_provider", fmt.Sprintf("%q is missing or is not enabled.", name)) return validation.NewError("validation_invalid_provider", fmt.Sprintf("%q is missing or is not enabled.", name))
} }
@@ -68,7 +99,7 @@ func (form *UserOauth2Login) Submit() (*models.User, *auth.AuthUser, error) {
return nil, nil, err return nil, nil, err
} }
config := form.app.Settings().NamedAuthProviderConfigs()[form.Provider] config := form.config.App.Settings().NamedAuthProviderConfigs()[form.Provider]
config.SetupProvider(provider) config.SetupProvider(provider)
provider.SetRedirectUrl(form.RedirectUrl) provider.SetRedirectUrl(form.RedirectUrl)
@@ -89,44 +120,48 @@ func (form *UserOauth2Login) Submit() (*models.User, *auth.AuthUser, error) {
} }
// login/register the auth user // login/register the auth user
user, _ := form.app.Dao().FindUserByEmail(authData.Email) user, _ := form.config.TxDao.FindUserByEmail(authData.Email)
if user != nil { if user != nil {
// update the existing user's verified state // update the existing user's verified state
if !user.Verified { if !user.Verified {
user.Verified = true user.Verified = true
if err := form.app.Dao().SaveUser(user); err != nil { if err := form.config.TxDao.SaveUser(user); err != nil {
return nil, authData, err return nil, authData, err
} }
} }
} else { return user, authData, nil
if !config.AllowRegistrations { }
// registration of new users is not allowed via the Oauth2 provider
return nil, authData, errors.New("Cannot find user with the authorized email.")
}
// create new user if !config.AllowRegistrations {
user = &models.User{Verified: true} // registration of new users is not allowed via the Oauth2 provider
upsertForm := NewUserUpsert(form.app, user) return nil, authData, errors.New("Cannot find user with the authorized email.")
upsertForm.Email = authData.Email }
upsertForm.Password = security.RandomString(30)
upsertForm.PasswordConfirm = upsertForm.Password
event := &core.UserOauth2RegisterEvent{ // create new user
User: user, user = &models.User{Verified: true}
AuthData: authData, upsertForm := NewUserUpsertWithConfig(UserUpsertConfig{
} App: form.config.App,
TxDao: form.config.TxDao,
}, user)
upsertForm.Email = authData.Email
upsertForm.Password = security.RandomString(30)
upsertForm.PasswordConfirm = upsertForm.Password
if err := form.app.OnUserBeforeOauth2Register().Trigger(event); err != nil { event := &core.UserOauth2RegisterEvent{
return nil, authData, err User: user,
} AuthData: authData,
}
if err := upsertForm.Submit(); err != nil { if err := form.config.App.OnUserBeforeOauth2Register().Trigger(event); err != nil {
return nil, authData, err return nil, authData, err
} }
if err := form.app.OnUserAfterOauth2Register().Trigger(event); err != nil { if err := upsertForm.Submit(); err != nil {
return nil, authData, err return nil, authData, err
} }
if err := form.config.App.OnUserAfterOauth2Register().Trigger(event); err != nil {
return nil, authData, err
} }
return user, authData, nil return user, authData, nil
+10
View File
@@ -9,6 +9,16 @@ import (
"github.com/pocketbase/pocketbase/tests" "github.com/pocketbase/pocketbase/tests"
) )
func TestUserOauth2LoginPanic(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewUserOauth2Login(nil)
}
func TestUserOauth2LoginValidate(t *testing.T) { func TestUserOauth2LoginValidate(t *testing.T) {
app, _ := tests.NewTestApp() app, _ := tests.NewTestApp()
defer app.Cleanup() defer app.Cleanup()
+41 -11
View File
@@ -3,29 +3,59 @@ package forms
import ( import (
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/forms/validators" "github.com/pocketbase/pocketbase/forms/validators"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
) )
// UserPasswordResetConfirm defines a user password reset confirmation form. // UserPasswordResetConfirm specifies a user password reset confirmation form.
type UserPasswordResetConfirm struct { type UserPasswordResetConfirm struct {
app core.App config UserPasswordResetConfirmConfig
Token string `form:"token" json:"token"` Token string `form:"token" json:"token"`
Password string `form:"password" json:"password"` Password string `form:"password" json:"password"`
PasswordConfirm string `form:"passwordConfirm" json:"passwordConfirm"` PasswordConfirm string `form:"passwordConfirm" json:"passwordConfirm"`
} }
// NewUserPasswordResetConfirm creates new user password reset confirmation form. // UserPasswordResetConfirmConfig is the [UserPasswordResetConfirm]
// factory initializer config.
//
// NB! App is required struct member.
type UserPasswordResetConfirmConfig struct {
App core.App
TxDao *daos.Dao
}
// NewUserPasswordResetConfirm creates a new [UserPasswordResetConfirm]
// form with initializer config created from the provided [core.App] instance.
//
// If you want to submit the form as part of another transaction, use
// [NewUserPasswordResetConfirmWithConfig] with explicitly set TxDao.
func NewUserPasswordResetConfirm(app core.App) *UserPasswordResetConfirm { func NewUserPasswordResetConfirm(app core.App) *UserPasswordResetConfirm {
return &UserPasswordResetConfirm{ return NewUserPasswordResetConfirmWithConfig(UserPasswordResetConfirmConfig{
app: app, App: app,
})
}
// NewUserPasswordResetConfirmWithConfig creates a new [UserPasswordResetConfirm]
// form with the provided config or panics on invalid configuration.
func NewUserPasswordResetConfirmWithConfig(config UserPasswordResetConfirmConfig) *UserPasswordResetConfirm {
form := &UserPasswordResetConfirm{config: config}
if form.config.App == nil {
panic("Missing required config.App instance.")
} }
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
}
return form
} }
// Validate makes the form validatable by implementing [validation.Validatable] interface. // Validate makes the form validatable by implementing [validation.Validatable] interface.
func (form *UserPasswordResetConfirm) Validate() error { func (form *UserPasswordResetConfirm) Validate() error {
minPasswordLength := form.app.Settings().EmailAuth.MinPasswordLength minPasswordLength := form.config.App.Settings().EmailAuth.MinPasswordLength
return validation.ValidateStruct(form, return validation.ValidateStruct(form,
validation.Field(&form.Token, validation.Required, validation.By(form.checkToken)), validation.Field(&form.Token, validation.Required, validation.By(form.checkToken)),
@@ -40,9 +70,9 @@ func (form *UserPasswordResetConfirm) checkToken(value any) error {
return nil // nothing to check return nil // nothing to check
} }
user, err := form.app.Dao().FindUserByToken( user, err := form.config.TxDao.FindUserByToken(
v, v,
form.app.Settings().UserPasswordResetToken.Secret, form.config.App.Settings().UserPasswordResetToken.Secret,
) )
if err != nil || user == nil { if err != nil || user == nil {
return validation.NewError("validation_invalid_token", "Invalid or expired token.") return validation.NewError("validation_invalid_token", "Invalid or expired token.")
@@ -58,9 +88,9 @@ func (form *UserPasswordResetConfirm) Submit() (*models.User, error) {
return nil, err return nil, err
} }
user, err := form.app.Dao().FindUserByToken( user, err := form.config.TxDao.FindUserByToken(
form.Token, form.Token,
form.app.Settings().UserPasswordResetToken.Secret, form.config.App.Settings().UserPasswordResetToken.Secret,
) )
if err != nil { if err != nil {
return nil, err return nil, err
@@ -70,7 +100,7 @@ func (form *UserPasswordResetConfirm) Submit() (*models.User, error) {
return nil, err return nil, err
} }
if err := form.app.Dao().SaveUser(user); err != nil { if err := form.config.TxDao.SaveUser(user); err != nil {
return nil, err return nil, err
} }
+10
View File
@@ -10,6 +10,16 @@ import (
"github.com/pocketbase/pocketbase/tools/security" "github.com/pocketbase/pocketbase/tools/security"
) )
func TestUserPasswordResetConfirmPanic(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewUserPasswordResetConfirm(nil)
}
func TestUserPasswordResetConfirmValidate(t *testing.T) { func TestUserPasswordResetConfirmValidate(t *testing.T) {
app, _ := tests.NewTestApp() app, _ := tests.NewTestApp()
defer app.Cleanup() defer app.Cleanup()
+41 -11
View File
@@ -7,24 +7,54 @@ import (
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is" "github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/mails" "github.com/pocketbase/pocketbase/mails"
"github.com/pocketbase/pocketbase/tools/types" "github.com/pocketbase/pocketbase/tools/types"
) )
// UserPasswordResetRequest defines a user password reset request form. // UserPasswordResetRequest specifies a user password reset request form.
type UserPasswordResetRequest struct { type UserPasswordResetRequest struct {
app core.App config UserPasswordResetRequestConfig
resendThreshold float64
Email string `form:"email" json:"email"` Email string `form:"email" json:"email"`
} }
// NewUserPasswordResetRequest creates new user password reset request form. // UserPasswordResetRequestConfig is the [UserPasswordResetRequest]
// factory initializer config.
//
// NB! App is required struct member.
type UserPasswordResetRequestConfig struct {
App core.App
TxDao *daos.Dao
ResendThreshold float64 // in seconds
}
// NewUserPasswordResetRequest creates a new [UserPasswordResetRequest]
// form with initializer config created from the provided [core.App] instance.
//
// If you want to submit the form as part of another transaction, use
// [NewUserPasswordResetRequestWithConfig] with explicitly set TxDao.
func NewUserPasswordResetRequest(app core.App) *UserPasswordResetRequest { func NewUserPasswordResetRequest(app core.App) *UserPasswordResetRequest {
return &UserPasswordResetRequest{ return NewUserPasswordResetRequestWithConfig(UserPasswordResetRequestConfig{
app: app, App: app,
resendThreshold: 120, // 2 min ResendThreshold: 120, // 2 min
})
}
// NewUserPasswordResetRequestWithConfig creates a new [UserPasswordResetRequest]
// form with the provided config or panics on invalid configuration.
func NewUserPasswordResetRequestWithConfig(config UserPasswordResetRequestConfig) *UserPasswordResetRequest {
form := &UserPasswordResetRequest{config: config}
if form.config.App == nil {
panic("Missing required config.App instance.")
} }
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
}
return form
} }
// Validate makes the form validatable by implementing [validation.Validatable] interface. // Validate makes the form validatable by implementing [validation.Validatable] interface.
@@ -48,23 +78,23 @@ func (form *UserPasswordResetRequest) Submit() error {
return err return err
} }
user, err := form.app.Dao().FindUserByEmail(form.Email) user, err := form.config.TxDao.FindUserByEmail(form.Email)
if err != nil { if err != nil {
return err return err
} }
now := time.Now().UTC() now := time.Now().UTC()
lastResetSentAt := user.LastResetSentAt.Time() lastResetSentAt := user.LastResetSentAt.Time()
if now.Sub(lastResetSentAt).Seconds() < form.resendThreshold { if now.Sub(lastResetSentAt).Seconds() < form.config.ResendThreshold {
return errors.New("You've already requested a password reset.") return errors.New("You've already requested a password reset.")
} }
if err := mails.SendUserPasswordReset(form.app, user); err != nil { if err := mails.SendUserPasswordReset(form.config.App, user); err != nil {
return err return err
} }
// update last sent timestamp // update last sent timestamp
user.LastResetSentAt = types.NowDateTime() user.LastResetSentAt = types.NowDateTime()
return form.app.Dao().SaveUser(user) return form.config.TxDao.SaveUser(user)
} }
+10
View File
@@ -11,6 +11,16 @@ import (
"github.com/pocketbase/pocketbase/tools/types" "github.com/pocketbase/pocketbase/tools/types"
) )
func TestUserPasswordResetRequestPanic(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewUserPasswordResetRequest(nil)
}
func TestUserPasswordResetRequestValidate(t *testing.T) { func TestUserPasswordResetRequestValidate(t *testing.T) {
testApp, _ := tests.NewTestApp() testApp, _ := tests.NewTestApp()
defer testApp.Cleanup() defer testApp.Cleanup()
+67 -20
View File
@@ -6,33 +6,63 @@ import (
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is" "github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/forms/validators" "github.com/pocketbase/pocketbase/forms/validators"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/tools/list" "github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/types" "github.com/pocketbase/pocketbase/tools/types"
) )
// UserUpsert defines a user upsert (create/update) form. // UserUpsert specifies a [models.User] upsert (create/update) form.
type UserUpsert struct { type UserUpsert struct {
app core.App config UserUpsertConfig
user *models.User user *models.User
isCreate bool
Id string `form:"id" json:"id"`
Email string `form:"email" json:"email"` Email string `form:"email" json:"email"`
Password string `form:"password" json:"password"` Password string `form:"password" json:"password"`
PasswordConfirm string `form:"passwordConfirm" json:"passwordConfirm"` PasswordConfirm string `form:"passwordConfirm" json:"passwordConfirm"`
} }
// NewUserUpsert creates new upsert form for the provided user model // UserUpsertConfig is the [UserUpsert] factory initializer config.
// (pass an empty user model instance (`&models.User{}`) for create). //
// NB! App is required struct member.
type UserUpsertConfig struct {
App core.App
TxDao *daos.Dao
}
// NewUserUpsert creates a new [UserUpsert] form with initializer
// config created from the provided [core.App] instance
// (for create you could pass a pointer to an empty User - `&models.User{}`).
//
// If you want to submit the form as part of another transaction, use
// [NewUserEmailChangeConfirmWithConfig] with explicitly set TxDao.
func NewUserUpsert(app core.App, user *models.User) *UserUpsert { func NewUserUpsert(app core.App, user *models.User) *UserUpsert {
return NewUserUpsertWithConfig(UserUpsertConfig{
App: app,
}, user)
}
// NewUserUpsertWithConfig creates a new [UserUpsert] form with the provided
// config and [models.User] instance or panics on invalid configuration
// (for create you could pass a pointer to an empty User - `&models.User{}`).
func NewUserUpsertWithConfig(config UserUpsertConfig, user *models.User) *UserUpsert {
form := &UserUpsert{ form := &UserUpsert{
app: app, config: config,
user: user, user: user,
isCreate: !user.HasId(), }
if form.config.App == nil || form.user == nil {
panic("Invalid initializer config or nil upsert model.")
}
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
} }
// load defaults // load defaults
form.Id = user.Id
form.Email = user.Email form.Email = user.Email
return form return form
@@ -40,9 +70,15 @@ func NewUserUpsert(app core.App, user *models.User) *UserUpsert {
// Validate makes the form validatable by implementing [validation.Validatable] interface. // Validate makes the form validatable by implementing [validation.Validatable] interface.
func (form *UserUpsert) Validate() error { func (form *UserUpsert) Validate() error {
config := form.app.Settings()
return validation.ValidateStruct(form, return validation.ValidateStruct(form,
validation.Field(
&form.Id,
validation.When(
form.user.IsNew(),
validation.Length(models.DefaultIdLength, models.DefaultIdLength),
validation.Match(idRegex),
).Else(validation.In(form.user.Id)),
),
validation.Field( validation.Field(
&form.Email, &form.Email,
validation.Required, validation.Required,
@@ -53,12 +89,12 @@ func (form *UserUpsert) Validate() error {
), ),
validation.Field( validation.Field(
&form.Password, &form.Password,
validation.When(form.isCreate, validation.Required), validation.When(form.user.IsNew(), validation.Required),
validation.Length(config.EmailAuth.MinPasswordLength, 100), validation.Length(form.config.App.Settings().EmailAuth.MinPasswordLength, 100),
), ),
validation.Field( validation.Field(
&form.PasswordConfirm, &form.PasswordConfirm,
validation.When(form.isCreate || form.Password != "", validation.Required), validation.When(form.user.IsNew() || form.Password != "", validation.Required),
validation.By(validators.Compare(form.Password)), validation.By(validators.Compare(form.Password)),
), ),
) )
@@ -67,7 +103,7 @@ func (form *UserUpsert) Validate() error {
func (form *UserUpsert) checkUniqueEmail(value any) error { func (form *UserUpsert) checkUniqueEmail(value any) error {
v, _ := value.(string) v, _ := value.(string)
if v == "" || form.app.Dao().IsUserEmailUnique(v, form.user.Id) { if v == "" || form.config.TxDao.IsUserEmailUnique(v, form.user.Id) {
return nil return nil
} }
@@ -81,8 +117,8 @@ func (form *UserUpsert) checkEmailDomain(value any) error {
} }
domain := val[strings.LastIndex(val, "@")+1:] domain := val[strings.LastIndex(val, "@")+1:]
only := form.app.Settings().EmailAuth.OnlyDomains only := form.config.App.Settings().EmailAuth.OnlyDomains
except := form.app.Settings().EmailAuth.ExceptDomains except := form.config.App.Settings().EmailAuth.ExceptDomains
// only domains check // only domains check
if len(only) > 0 && !list.ExistInSlice(domain, only) { if len(only) > 0 && !list.ExistInSlice(domain, only) {
@@ -98,7 +134,10 @@ func (form *UserUpsert) checkEmailDomain(value any) error {
} }
// Submit validates the form and upserts the form user model. // Submit validates the form and upserts the form user model.
func (form *UserUpsert) Submit() error { //
// You can optionally provide a list of InterceptorFunc to further
// modify the form behavior before persisting it.
func (form *UserUpsert) Submit(interceptors ...InterceptorFunc) error {
if err := form.Validate(); err != nil { if err := form.Validate(); err != nil {
return err return err
} }
@@ -107,12 +146,20 @@ func (form *UserUpsert) Submit() error {
form.user.SetPassword(form.Password) form.user.SetPassword(form.Password)
} }
if !form.isCreate && form.Email != form.user.Email { // custom insertion id can be set only on create
if form.user.IsNew() && form.Id != "" {
form.user.MarkAsNew()
form.user.SetId(form.Id)
}
if !form.user.IsNew() && form.Email != form.user.Email {
form.user.Verified = false form.user.Verified = false
form.user.LastVerificationSentAt = types.DateTime{} // reset form.user.LastVerificationSentAt = types.DateTime{} // reset
} }
form.user.Email = form.Email form.user.Email = form.Email
return form.app.Dao().SaveUser(form.user) return runInterceptors(func() error {
return form.config.TxDao.SaveUser(form.user)
}, interceptors...)
} }
+191 -1
View File
@@ -2,6 +2,8 @@ package forms_test
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt"
"testing" "testing"
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
@@ -10,6 +12,29 @@ import (
"github.com/pocketbase/pocketbase/tests" "github.com/pocketbase/pocketbase/tests"
) )
func TestUserUpsertPanic1(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewUserUpsert(nil, nil)
}
func TestUserUpsertPanic2(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewUserUpsert(app, nil)
}
func TestNewUserUpsert(t *testing.T) { func TestNewUserUpsert(t *testing.T) {
app, _ := tests.NewTestApp() app, _ := tests.NewTestApp()
defer app.Cleanup() defer app.Cleanup()
@@ -212,13 +237,28 @@ func TestUserUpsertSubmit(t *testing.T) {
continue continue
} }
err := form.Submit() interceptorCalls := 0
err := form.Submit(func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptorCalls++
return next()
}
})
hasErr := err != nil hasErr := err != nil
if hasErr != s.expectError { if hasErr != s.expectError {
t.Errorf("(%d) Expected hasErr to be %v, got %v (%v)", i, s.expectError, hasErr, err) t.Errorf("(%d) Expected hasErr to be %v, got %v (%v)", i, s.expectError, hasErr, err)
} }
expectInterceptorCall := 1
if s.expectError {
expectInterceptorCall = 0
}
if interceptorCalls != expectInterceptorCall {
t.Errorf("(%d) Expected interceptor to be called %d, got %d", i, expectInterceptorCall, interceptorCalls)
}
if s.expectError { if s.expectError {
continue continue
} }
@@ -240,3 +280,153 @@ func TestUserUpsertSubmit(t *testing.T) {
} }
} }
} }
func TestUserUpsertSubmitInterceptors(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
user := &models.User{}
form := forms.NewUserUpsert(app, user)
form.Email = "test_new@example.com"
form.Password = "1234567890"
form.PasswordConfirm = form.Password
testErr := errors.New("test_error")
interceptorUserEmail := ""
interceptor1Called := false
interceptor1 := func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptor1Called = true
return next()
}
}
interceptor2Called := false
interceptor2 := func(next forms.InterceptorNextFunc) forms.InterceptorNextFunc {
return func() error {
interceptorUserEmail = user.Email // to check if the record was filled
interceptor2Called = true
return testErr
}
}
err := form.Submit(interceptor1, interceptor2)
if err != testErr {
t.Fatalf("Expected error %v, got %v", testErr, err)
}
if !interceptor1Called {
t.Fatalf("Expected interceptor1 to be called")
}
if !interceptor2Called {
t.Fatalf("Expected interceptor2 to be called")
}
if interceptorUserEmail != form.Email {
t.Fatalf("Expected the form model to be filled before calling the interceptors")
}
}
func TestUserUpsertWithCustomId(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
existingUser, err := app.Dao().FindUserByEmail("test@example.com")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
jsonData string
collection *models.User
expectError bool
}{
{
"empty data",
"{}",
&models.User{},
false,
},
{
"empty id",
`{"id":""}`,
&models.User{},
false,
},
{
"id < 15 chars",
`{"id":"a23"}`,
&models.User{},
true,
},
{
"id > 15 chars",
`{"id":"a234567890123456"}`,
&models.User{},
true,
},
{
"id = 15 chars (invalid chars)",
`{"id":"a@3456789012345"}`,
&models.User{},
true,
},
{
"id = 15 chars (valid chars)",
`{"id":"a23456789012345"}`,
&models.User{},
false,
},
{
"changing the id of an existing item",
`{"id":"b23456789012345"}`,
existingUser,
true,
},
{
"using the same existing item id",
`{"id":"` + existingUser.Id + `"}`,
existingUser,
false,
},
{
"skipping the id for existing item",
`{}`,
existingUser,
false,
},
}
for i, scenario := range scenarios {
form := forms.NewUserUpsert(app, scenario.collection)
if form.Email == "" {
form.Email = fmt.Sprintf("test_id_%d@example.com", i)
}
form.Password = "1234567890"
form.PasswordConfirm = form.Password
// load data
loadErr := json.Unmarshal([]byte(scenario.jsonData), form)
if loadErr != nil {
t.Errorf("[%s] Failed to load form data: %v", scenario.name, loadErr)
continue
}
submitErr := form.Submit()
hasErr := submitErr != nil
if hasErr != scenario.expectError {
t.Errorf("[%s] Expected hasErr to be %v, got %v (%v)", scenario.name, scenario.expectError, hasErr, submitErr)
}
if !hasErr && form.Id != "" {
_, err := app.Dao().FindUserById(form.Id)
if err != nil {
t.Errorf("[%s] Expected to find record with id %s, got %v", scenario.name, form.Id, err)
}
}
}
}
+40 -10
View File
@@ -3,21 +3,51 @@ package forms
import ( import (
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
) )
// UserVerificationConfirm defines a user email confirmation form. // UserVerificationConfirm specifies a user email verification confirmation form.
type UserVerificationConfirm struct { type UserVerificationConfirm struct {
app core.App config UserVerificationConfirmConfig
Token string `form:"token" json:"token"` Token string `form:"token" json:"token"`
} }
// NewUserVerificationConfirm creates a new user email confirmation form. // UserVerificationConfirmConfig is the [UserVerificationConfirm]
// factory initializer config.
//
// NB! App is required struct member.
type UserVerificationConfirmConfig struct {
App core.App
TxDao *daos.Dao
}
// NewUserVerificationConfirm creates a new [UserVerificationConfirm]
// form with initializer config created from the provided [core.App] instance.
//
// If you want to submit the form as part of another transaction, use
// [NewUserVerificationConfirmWithConfig] with explicitly set TxDao.
func NewUserVerificationConfirm(app core.App) *UserVerificationConfirm { func NewUserVerificationConfirm(app core.App) *UserVerificationConfirm {
return &UserVerificationConfirm{ return NewUserVerificationConfirmWithConfig(UserVerificationConfirmConfig{
app: app, App: app,
})
}
// NewUserVerificationConfirmWithConfig creates a new [UserVerificationConfirmConfig]
// form with the provided config or panics on invalid configuration.
func NewUserVerificationConfirmWithConfig(config UserVerificationConfirmConfig) *UserVerificationConfirm {
form := &UserVerificationConfirm{config: config}
if form.config.App == nil {
panic("Missing required config.App instance.")
} }
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
}
return form
} }
// Validate makes the form validatable by implementing [validation.Validatable] interface. // Validate makes the form validatable by implementing [validation.Validatable] interface.
@@ -33,9 +63,9 @@ func (form *UserVerificationConfirm) checkToken(value any) error {
return nil // nothing to check return nil // nothing to check
} }
user, err := form.app.Dao().FindUserByToken( user, err := form.config.TxDao.FindUserByToken(
v, v,
form.app.Settings().UserVerificationToken.Secret, form.config.App.Settings().UserVerificationToken.Secret,
) )
if err != nil || user == nil { if err != nil || user == nil {
return validation.NewError("validation_invalid_token", "Invalid or expired token.") return validation.NewError("validation_invalid_token", "Invalid or expired token.")
@@ -51,9 +81,9 @@ func (form *UserVerificationConfirm) Submit() (*models.User, error) {
return nil, err return nil, err
} }
user, err := form.app.Dao().FindUserByToken( user, err := form.config.TxDao.FindUserByToken(
form.Token, form.Token,
form.app.Settings().UserVerificationToken.Secret, form.config.App.Settings().UserVerificationToken.Secret,
) )
if err != nil { if err != nil {
return nil, err return nil, err
@@ -65,7 +95,7 @@ func (form *UserVerificationConfirm) Submit() (*models.User, error) {
user.Verified = true user.Verified = true
if err := form.app.Dao().SaveUser(user); err != nil { if err := form.config.TxDao.SaveUser(user); err != nil {
return nil, err return nil, err
} }
+10
View File
@@ -10,6 +10,16 @@ import (
"github.com/pocketbase/pocketbase/tools/security" "github.com/pocketbase/pocketbase/tools/security"
) )
func TestUserVerificationConfirmPanic(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewUserVerificationConfirm(nil)
}
func TestUserVerificationConfirmValidate(t *testing.T) { func TestUserVerificationConfirmValidate(t *testing.T) {
app, _ := tests.NewTestApp() app, _ := tests.NewTestApp()
defer app.Cleanup() defer app.Cleanup()
+40 -10
View File
@@ -7,24 +7,54 @@ import (
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is" "github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/mails" "github.com/pocketbase/pocketbase/mails"
"github.com/pocketbase/pocketbase/tools/types" "github.com/pocketbase/pocketbase/tools/types"
) )
// UserVerificationRequest defines a user email verification request form. // UserVerificationRequest defines a user email verification request form.
type UserVerificationRequest struct { type UserVerificationRequest struct {
app core.App config UserVerificationRequestConfig
resendThreshold float64
Email string `form:"email" json:"email"` Email string `form:"email" json:"email"`
} }
// NewUserVerificationRequest creates a new user email verification request form. // UserVerificationRequestConfig is the [UserVerificationRequest]
// factory initializer config.
//
// NB! App is required struct member.
type UserVerificationRequestConfig struct {
App core.App
TxDao *daos.Dao
ResendThreshold float64 // in seconds
}
// NewUserVerificationRequest creates a new [UserVerificationRequest]
// form with initializer config created from the provided [core.App] instance.
//
// If you want to submit the form as part of another transaction, use
// [NewUserVerificationRequestWithConfig] with explicitly set TxDao.
func NewUserVerificationRequest(app core.App) *UserVerificationRequest { func NewUserVerificationRequest(app core.App) *UserVerificationRequest {
return &UserVerificationRequest{ return NewUserVerificationRequestWithConfig(UserVerificationRequestConfig{
app: app, App: app,
resendThreshold: 120, // 2 min ResendThreshold: 120, // 2 min
})
}
// NewUserVerificationRequestWithConfig creates a new [UserVerificationRequest]
// form with the provided config or panics on invalid configuration.
func NewUserVerificationRequestWithConfig(config UserVerificationRequestConfig) *UserVerificationRequest {
form := &UserVerificationRequest{config: config}
if form.config.App == nil {
panic("Missing required config.App instance.")
} }
if form.config.TxDao == nil {
form.config.TxDao = form.config.App.Dao()
}
return form
} }
// Validate makes the form validatable by implementing [validation.Validatable] interface. // Validate makes the form validatable by implementing [validation.Validatable] interface.
@@ -48,7 +78,7 @@ func (form *UserVerificationRequest) Submit() error {
return err return err
} }
user, err := form.app.Dao().FindUserByEmail(form.Email) user, err := form.config.TxDao.FindUserByEmail(form.Email)
if err != nil { if err != nil {
return err return err
} }
@@ -59,16 +89,16 @@ func (form *UserVerificationRequest) Submit() error {
now := time.Now().UTC() now := time.Now().UTC()
lastVerificationSentAt := user.LastVerificationSentAt.Time() lastVerificationSentAt := user.LastVerificationSentAt.Time()
if (now.Sub(lastVerificationSentAt)).Seconds() < form.resendThreshold { if (now.Sub(lastVerificationSentAt)).Seconds() < form.config.ResendThreshold {
return errors.New("A verification email was already sent.") return errors.New("A verification email was already sent.")
} }
if err := mails.SendUserVerification(form.app, user); err != nil { if err := mails.SendUserVerification(form.config.App, user); err != nil {
return err return err
} }
// update last sent timestamp // update last sent timestamp
user.LastVerificationSentAt = types.NowDateTime() user.LastVerificationSentAt = types.NowDateTime()
return form.app.Dao().SaveUser(user) return form.config.TxDao.SaveUser(user)
} }
+10
View File
@@ -11,6 +11,16 @@ import (
"github.com/pocketbase/pocketbase/tools/types" "github.com/pocketbase/pocketbase/tools/types"
) )
func TestUserVerificationRequestPanic(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("The form did not panic")
}
}()
forms.NewUserVerificationRequest(nil)
}
func TestUserVerificationRequestValidate(t *testing.T) { func TestUserVerificationRequestValidate(t *testing.T) {
testApp, _ := tests.NewTestApp() testApp, _ := tests.NewTestApp()
defer testApp.Cleanup() defer testApp.Cleanup()
+18 -32
View File
@@ -240,7 +240,6 @@ func (validator *RecordDataValidator) checkUrlValue(field *schema.SchemaField, v
func (validator *RecordDataValidator) checkDateValue(field *schema.SchemaField, value any) error { func (validator *RecordDataValidator) checkDateValue(field *schema.SchemaField, value any) error {
val, _ := value.(types.DateTime) val, _ := value.(types.DateTime)
if val.IsZero() { if val.IsZero() {
if field.Required { if field.Required {
return requiredErr return requiredErr
@@ -268,6 +267,9 @@ func (validator *RecordDataValidator) checkDateValue(field *schema.SchemaField,
func (validator *RecordDataValidator) checkSelectValue(field *schema.SchemaField, value any) error { func (validator *RecordDataValidator) checkSelectValue(field *schema.SchemaField, value any) error {
normalizedVal := list.ToUniqueStringSlice(value) normalizedVal := list.ToUniqueStringSlice(value)
if len(normalizedVal) == 0 { if len(normalizedVal) == 0 {
if field.Required {
return requiredErr
}
return nil // nothing to check return nil // nothing to check
} }
@@ -302,13 +304,9 @@ func (validator *RecordDataValidator) checkJsonValue(field *schema.SchemaField,
} }
func (validator *RecordDataValidator) checkFileValue(field *schema.SchemaField, value any) error { func (validator *RecordDataValidator) checkFileValue(field *schema.SchemaField, value any) error {
// normalize value access names := list.ToUniqueStringSlice(value)
var names []string if len(names) == 0 && field.Required {
switch v := value.(type) { return requiredErr
case []string:
names = v
case string:
names = []string{v}
} }
options, _ := field.Options.(*schema.FileOptions) options, _ := field.Options.(*schema.FileOptions)
@@ -318,12 +316,10 @@ func (validator *RecordDataValidator) checkFileValue(field *schema.SchemaField,
} }
// extract the uploaded files // extract the uploaded files
files := []*rest.UploadedFile{} files := make([]*rest.UploadedFile, 0, len(validator.uploadedFiles))
if len(validator.uploadedFiles) > 0 { for _, file := range validator.uploadedFiles {
for _, file := range validator.uploadedFiles { if list.ExistInSlice(file.Name(), names) {
if list.ExistInSlice(file.Name(), names) { files = append(files, file)
files = append(files, file)
}
} }
} }
@@ -345,16 +341,11 @@ func (validator *RecordDataValidator) checkFileValue(field *schema.SchemaField,
} }
func (validator *RecordDataValidator) checkRelationValue(field *schema.SchemaField, value any) error { func (validator *RecordDataValidator) checkRelationValue(field *schema.SchemaField, value any) error {
// normalize value access ids := list.ToUniqueStringSlice(value)
var ids []string
switch v := value.(type) {
case []string:
ids = v
case string:
ids = []string{v}
}
if len(ids) == 0 { if len(ids) == 0 {
if field.Required {
return requiredErr
}
return nil // nothing to check return nil // nothing to check
} }
@@ -385,16 +376,11 @@ func (validator *RecordDataValidator) checkRelationValue(field *schema.SchemaFie
} }
func (validator *RecordDataValidator) checkUserValue(field *schema.SchemaField, value any) error { func (validator *RecordDataValidator) checkUserValue(field *schema.SchemaField, value any) error {
// normalize value access ids := list.ToUniqueStringSlice(value)
var ids []string
switch v := value.(type) {
case []string:
ids = v
case string:
ids = []string{v}
}
if len(ids) == 0 { if len(ids) == 0 {
if field.Required {
return requiredErr
}
return nil // nothing to check return nil // nothing to check
} }
+62 -62
View File
@@ -89,7 +89,7 @@ func TestRecordDataValidatorValidateText(t *testing.T) {
scenarios := []testDataFieldScenario{ scenarios := []testDataFieldScenario{
{ {
"check required constraint", "(text) check required constraint",
map[string]any{ map[string]any{
"field1": nil, "field1": nil,
"field2": nil, "field2": nil,
@@ -99,7 +99,7 @@ func TestRecordDataValidatorValidateText(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"check unique constraint", "(text) check unique constraint",
map[string]any{ map[string]any{
"field1": "test", "field1": "test",
"field2": "test", "field2": "test",
@@ -109,7 +109,7 @@ func TestRecordDataValidatorValidateText(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"check min constraint", "(text) check min constraint",
map[string]any{ map[string]any{
"field1": "test", "field1": "test",
"field2": "test", "field2": "test",
@@ -119,7 +119,7 @@ func TestRecordDataValidatorValidateText(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"check max constraint", "(text) check max constraint",
map[string]any{ map[string]any{
"field1": "test", "field1": "test",
"field2": "test", "field2": "test",
@@ -129,7 +129,7 @@ func TestRecordDataValidatorValidateText(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"check pattern constraint", "(text) check pattern constraint",
map[string]any{ map[string]any{
"field1": nil, "field1": nil,
"field2": "test", "field2": "test",
@@ -139,7 +139,7 @@ func TestRecordDataValidatorValidateText(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"valid data (only required)", "(text) valid data (only required)",
map[string]any{ map[string]any{
"field2": "test", "field2": "test",
}, },
@@ -147,7 +147,7 @@ func TestRecordDataValidatorValidateText(t *testing.T) {
[]string{}, []string{},
}, },
{ {
"valid data (all)", "(text) valid data (all)",
map[string]any{ map[string]any{
"field1": "test", "field1": "test",
"field2": 12345, // test value cast "field2": 12345, // test value cast
@@ -168,7 +168,7 @@ func TestRecordDataValidatorValidateNumber(t *testing.T) {
// create new test collection // create new test collection
collection := &models.Collection{} collection := &models.Collection{}
collection.Name = "validate_test" collection.Name = "validate_test"
min := 1.0 min := 0.0
max := 150.0 max := 150.0
collection.Schema = schema.NewSchema( collection.Schema = schema.NewSchema(
&schema.SchemaField{ &schema.SchemaField{
@@ -205,7 +205,7 @@ func TestRecordDataValidatorValidateNumber(t *testing.T) {
scenarios := []testDataFieldScenario{ scenarios := []testDataFieldScenario{
{ {
"check required constraint", "(number) check required constraint",
map[string]any{ map[string]any{
"field1": nil, "field1": nil,
"field2": nil, "field2": nil,
@@ -215,17 +215,17 @@ func TestRecordDataValidatorValidateNumber(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"check required constraint + casting", "(number) check required constraint + casting",
map[string]any{ map[string]any{
"field1": "invalid", "field1": "invalid",
"field2": "invalid", "field2": "invalid",
"field3": "invalid", "field3": "invalid",
}, },
nil, nil,
[]string{"field2", "field3"}, []string{"field2"},
}, },
{ {
"check unique constraint", "(number) check unique constraint",
map[string]any{ map[string]any{
"field1": 123, "field1": 123,
"field2": 123, "field2": 123,
@@ -235,7 +235,7 @@ func TestRecordDataValidatorValidateNumber(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"check min constraint", "(number) check min constraint",
map[string]any{ map[string]any{
"field1": 0.5, "field1": 0.5,
"field2": 1, "field2": 1,
@@ -245,7 +245,7 @@ func TestRecordDataValidatorValidateNumber(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"check max constraint", "(number) check max constraint",
map[string]any{ map[string]any{
"field1": nil, "field1": nil,
"field2": max, "field2": max,
@@ -255,7 +255,7 @@ func TestRecordDataValidatorValidateNumber(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"valid data (only required)", "(number) valid data (only required)",
map[string]any{ map[string]any{
"field2": 1, "field2": 1,
}, },
@@ -263,7 +263,7 @@ func TestRecordDataValidatorValidateNumber(t *testing.T) {
[]string{}, []string{},
}, },
{ {
"valid data (all)", "(number) valid data (all)",
map[string]any{ map[string]any{
"field1": nil, "field1": nil,
"field2": 123, // test value cast "field2": 123, // test value cast
@@ -316,7 +316,7 @@ func TestRecordDataValidatorValidateBool(t *testing.T) {
scenarios := []testDataFieldScenario{ scenarios := []testDataFieldScenario{
{ {
"check required constraint", "(bool) check required constraint",
map[string]any{ map[string]any{
"field1": nil, "field1": nil,
"field2": nil, "field2": nil,
@@ -326,7 +326,7 @@ func TestRecordDataValidatorValidateBool(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"check required constraint + casting", "(bool) check required constraint + casting",
map[string]any{ map[string]any{
"field1": "invalid", "field1": "invalid",
"field2": "invalid", "field2": "invalid",
@@ -336,7 +336,7 @@ func TestRecordDataValidatorValidateBool(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"check unique constraint", "(bool) check unique constraint",
map[string]any{ map[string]any{
"field1": true, "field1": true,
"field2": true, "field2": true,
@@ -346,7 +346,7 @@ func TestRecordDataValidatorValidateBool(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"valid data (only required)", "(bool) valid data (only required)",
map[string]any{ map[string]any{
"field2": 1, "field2": 1,
}, },
@@ -354,7 +354,7 @@ func TestRecordDataValidatorValidateBool(t *testing.T) {
[]string{}, []string{},
}, },
{ {
"valid data (all)", "(bool) valid data (all)",
map[string]any{ map[string]any{
"field1": false, "field1": false,
"field2": true, "field2": true,
@@ -412,7 +412,7 @@ func TestRecordDataValidatorValidateEmail(t *testing.T) {
scenarios := []testDataFieldScenario{ scenarios := []testDataFieldScenario{
{ {
"check required constraint", "(email) check required constraint",
map[string]any{ map[string]any{
"field1": nil, "field1": nil,
"field2": nil, "field2": nil,
@@ -422,7 +422,7 @@ func TestRecordDataValidatorValidateEmail(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"check email format validator", "(email) check email format validator",
map[string]any{ map[string]any{
"field1": "test", "field1": "test",
"field2": "test.com", "field2": "test.com",
@@ -432,7 +432,7 @@ func TestRecordDataValidatorValidateEmail(t *testing.T) {
[]string{"field1", "field2", "field3"}, []string{"field1", "field2", "field3"},
}, },
{ {
"check unique constraint", "(email) check unique constraint",
map[string]any{ map[string]any{
"field1": "test@example.com", "field1": "test@example.com",
"field2": "test@test.com", "field2": "test@test.com",
@@ -442,7 +442,7 @@ func TestRecordDataValidatorValidateEmail(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"check ExceptDomains constraint", "(email) check ExceptDomains constraint",
map[string]any{ map[string]any{
"field1": "test@example.com", "field1": "test@example.com",
"field2": "test@example.com", "field2": "test@example.com",
@@ -452,7 +452,7 @@ func TestRecordDataValidatorValidateEmail(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"check OnlyDomains constraint", "(email) check OnlyDomains constraint",
map[string]any{ map[string]any{
"field1": "test@test.com", "field1": "test@test.com",
"field2": "test@test.com", "field2": "test@test.com",
@@ -462,7 +462,7 @@ func TestRecordDataValidatorValidateEmail(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"valid data (only required)", "(email) valid data (only required)",
map[string]any{ map[string]any{
"field2": "test@test.com", "field2": "test@test.com",
}, },
@@ -470,7 +470,7 @@ func TestRecordDataValidatorValidateEmail(t *testing.T) {
[]string{}, []string{},
}, },
{ {
"valid data (all)", "(email) valid data (all)",
map[string]any{ map[string]any{
"field1": "123@example.com", "field1": "123@example.com",
"field2": "test@test.com", "field2": "test@test.com",
@@ -528,7 +528,7 @@ func TestRecordDataValidatorValidateUrl(t *testing.T) {
scenarios := []testDataFieldScenario{ scenarios := []testDataFieldScenario{
{ {
"check required constraint", "(url) check required constraint",
map[string]any{ map[string]any{
"field1": nil, "field1": nil,
"field2": nil, "field2": nil,
@@ -538,7 +538,7 @@ func TestRecordDataValidatorValidateUrl(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"check url format validator", "(url) check url format validator",
map[string]any{ map[string]any{
"field1": "/abc", "field1": "/abc",
"field2": "test.com", // valid "field2": "test.com", // valid
@@ -548,7 +548,7 @@ func TestRecordDataValidatorValidateUrl(t *testing.T) {
[]string{"field1", "field3"}, []string{"field1", "field3"},
}, },
{ {
"check unique constraint", "(url) check unique constraint",
map[string]any{ map[string]any{
"field1": "http://example.com", "field1": "http://example.com",
"field2": "http://test.com", "field2": "http://test.com",
@@ -558,7 +558,7 @@ func TestRecordDataValidatorValidateUrl(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"check ExceptDomains constraint", "(url) check ExceptDomains constraint",
map[string]any{ map[string]any{
"field1": "http://example.com", "field1": "http://example.com",
"field2": "http://example.com", "field2": "http://example.com",
@@ -568,7 +568,7 @@ func TestRecordDataValidatorValidateUrl(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"check OnlyDomains constraint", "(url) check OnlyDomains constraint",
map[string]any{ map[string]any{
"field1": "http://test.com/abc", "field1": "http://test.com/abc",
"field2": "http://test.com/abc", "field2": "http://test.com/abc",
@@ -578,7 +578,7 @@ func TestRecordDataValidatorValidateUrl(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"check subdomains constraint", "(url) check subdomains constraint",
map[string]any{ map[string]any{
"field1": "http://test.test.com", "field1": "http://test.test.com",
"field2": "http://test.example.com", "field2": "http://test.example.com",
@@ -588,7 +588,7 @@ func TestRecordDataValidatorValidateUrl(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"valid data (only required)", "(url) valid data (only required)",
map[string]any{ map[string]any{
"field2": "http://sub.test.com/abc", "field2": "http://sub.test.com/abc",
}, },
@@ -596,7 +596,7 @@ func TestRecordDataValidatorValidateUrl(t *testing.T) {
[]string{}, []string{},
}, },
{ {
"valid data (all)", "(url) valid data (all)",
map[string]any{ map[string]any{
"field1": "http://example.com/123", "field1": "http://example.com/123",
"field2": "http://test.com/", "field2": "http://test.com/",
@@ -656,7 +656,7 @@ func TestRecordDataValidatorValidateDate(t *testing.T) {
scenarios := []testDataFieldScenario{ scenarios := []testDataFieldScenario{
{ {
"check required constraint", "(date) check required constraint",
map[string]any{ map[string]any{
"field1": nil, "field1": nil,
"field2": nil, "field2": nil,
@@ -666,7 +666,7 @@ func TestRecordDataValidatorValidateDate(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"check required constraint + cast", "(date) check required constraint + cast",
map[string]any{ map[string]any{
"field1": "invalid", "field1": "invalid",
"field2": "invalid", "field2": "invalid",
@@ -676,7 +676,7 @@ func TestRecordDataValidatorValidateDate(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"check required constraint + zero datetime", "(date) check required constraint + zero datetime",
map[string]any{ map[string]any{
"field1": "January 1, year 1, 00:00:00 UTC", "field1": "January 1, year 1, 00:00:00 UTC",
"field2": "0001-01-01 00:00:00", "field2": "0001-01-01 00:00:00",
@@ -686,7 +686,7 @@ func TestRecordDataValidatorValidateDate(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"check unique constraint", "(date) check unique constraint",
map[string]any{ map[string]any{
"field1": "2029-01-01 01:01:01.123", "field1": "2029-01-01 01:01:01.123",
"field2": "2029-01-01 01:01:01.123", "field2": "2029-01-01 01:01:01.123",
@@ -696,7 +696,7 @@ func TestRecordDataValidatorValidateDate(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"check min date constraint", "(date) check min date constraint",
map[string]any{ map[string]any{
"field1": "2021-01-01 01:01:01", "field1": "2021-01-01 01:01:01",
"field2": "2021-01-01 01:01:01", "field2": "2021-01-01 01:01:01",
@@ -706,7 +706,7 @@ func TestRecordDataValidatorValidateDate(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"check max date constraint", "(date) check max date constraint",
map[string]any{ map[string]any{
"field1": "2030-02-01 01:01:01", "field1": "2030-02-01 01:01:01",
"field2": "2030-02-01 01:01:01", "field2": "2030-02-01 01:01:01",
@@ -716,7 +716,7 @@ func TestRecordDataValidatorValidateDate(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"valid data (only required)", "(date) valid data (only required)",
map[string]any{ map[string]any{
"field2": "2029-01-01 01:01:01", "field2": "2029-01-01 01:01:01",
}, },
@@ -724,7 +724,7 @@ func TestRecordDataValidatorValidateDate(t *testing.T) {
[]string{}, []string{},
}, },
{ {
"valid data (all)", "(date) valid data (all)",
map[string]any{ map[string]any{
"field1": "2029-01-01 01:01:01.000", "field1": "2029-01-01 01:01:01.000",
"field2": "2029-01-01 01:01:01", "field2": "2029-01-01 01:01:01",
@@ -788,7 +788,7 @@ func TestRecordDataValidatorValidateSelect(t *testing.T) {
scenarios := []testDataFieldScenario{ scenarios := []testDataFieldScenario{
{ {
"check required constraint", "(select) check required constraint",
map[string]any{ map[string]any{
"field1": nil, "field1": nil,
"field2": nil, "field2": nil,
@@ -798,7 +798,7 @@ func TestRecordDataValidatorValidateSelect(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"check required constraint - empty values", "(select) check required constraint - empty values",
map[string]any{ map[string]any{
"field1": "", "field1": "",
"field2": "", "field2": "",
@@ -808,7 +808,7 @@ func TestRecordDataValidatorValidateSelect(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"check required constraint - multiple select cast", "(select) check required constraint - multiple select cast",
map[string]any{ map[string]any{
"field1": "a", "field1": "a",
"field2": "a", "field2": "a",
@@ -818,7 +818,7 @@ func TestRecordDataValidatorValidateSelect(t *testing.T) {
[]string{}, []string{},
}, },
{ {
"check unique constraint", "(select) check unique constraint",
map[string]any{ map[string]any{
"field1": "a", "field1": "a",
"field2": "b", "field2": "b",
@@ -828,7 +828,7 @@ func TestRecordDataValidatorValidateSelect(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"check unique constraint - same elements but different order", "(select) check unique constraint - same elements but different order",
map[string]any{ map[string]any{
"field1": "a", "field1": "a",
"field2": "b", "field2": "b",
@@ -838,7 +838,7 @@ func TestRecordDataValidatorValidateSelect(t *testing.T) {
[]string{}, []string{},
}, },
{ {
"check Values constraint", "(select) check Values constraint",
map[string]any{ map[string]any{
"field1": 1, "field1": 1,
"field2": "d", "field2": "d",
@@ -848,7 +848,7 @@ func TestRecordDataValidatorValidateSelect(t *testing.T) {
[]string{"field2", "field3"}, []string{"field2", "field3"},
}, },
{ {
"check MaxSelect constraint", "(select) check MaxSelect constraint",
map[string]any{ map[string]any{
"field1": []string{"a", "b"}, // this will be normalized to a single string value "field1": []string{"a", "b"}, // this will be normalized to a single string value
"field2": []string{"a", "b", "c"}, "field2": []string{"a", "b", "c"},
@@ -858,7 +858,7 @@ func TestRecordDataValidatorValidateSelect(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"valid data - only required fields", "(select) valid data - only required fields",
map[string]any{ map[string]any{
"field2": []string{"a", "b"}, "field2": []string{"a", "b"},
}, },
@@ -866,7 +866,7 @@ func TestRecordDataValidatorValidateSelect(t *testing.T) {
[]string{}, []string{},
}, },
{ {
"valid data - all fields with normalizations", "(select) valid data - all fields with normalizations",
map[string]any{ map[string]any{
"field1": "a", "field1": "a",
"field2": []string{"a", "b", "b"}, // will be collapsed "field2": []string{"a", "b", "b"}, // will be collapsed
@@ -918,7 +918,7 @@ func TestRecordDataValidatorValidateJson(t *testing.T) {
scenarios := []testDataFieldScenario{ scenarios := []testDataFieldScenario{
{ {
"check required constraint - nil", "(json) check required constraint - nil",
map[string]any{ map[string]any{
"field1": nil, "field1": nil,
"field2": nil, "field2": nil,
@@ -928,7 +928,7 @@ func TestRecordDataValidatorValidateJson(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"check required constraint - zero string", "(json) check required constraint - zero string",
map[string]any{ map[string]any{
"field1": "", "field1": "",
"field2": "", "field2": "",
@@ -938,7 +938,7 @@ func TestRecordDataValidatorValidateJson(t *testing.T) {
[]string{"field2"}, []string{"field2"},
}, },
{ {
"check required constraint - zero number", "(json) check required constraint - zero number",
map[string]any{ map[string]any{
"field1": 0, "field1": 0,
"field2": 0, "field2": 0,
@@ -948,7 +948,7 @@ func TestRecordDataValidatorValidateJson(t *testing.T) {
[]string{}, []string{},
}, },
{ {
"check required constraint - zero slice", "(json) check required constraint - zero slice",
map[string]any{ map[string]any{
"field1": []string{}, "field1": []string{},
"field2": []string{}, "field2": []string{},
@@ -958,7 +958,7 @@ func TestRecordDataValidatorValidateJson(t *testing.T) {
[]string{}, []string{},
}, },
{ {
"check required constraint - zero map", "(json) check required constraint - zero map",
map[string]any{ map[string]any{
"field1": map[string]string{}, "field1": map[string]string{},
"field2": map[string]string{}, "field2": map[string]string{},
@@ -968,7 +968,7 @@ func TestRecordDataValidatorValidateJson(t *testing.T) {
[]string{}, []string{},
}, },
{ {
"check unique constraint", "(json) check unique constraint",
map[string]any{ map[string]any{
"field1": `{"test":123}`, "field1": `{"test":123}`,
"field2": `{"test":123}`, "field2": `{"test":123}`,
@@ -978,7 +978,7 @@ func TestRecordDataValidatorValidateJson(t *testing.T) {
[]string{"field3"}, []string{"field3"},
}, },
{ {
"check json text validator", "(json) check json text validator",
map[string]any{ map[string]any{
"field1": `[1, 2, 3`, "field1": `[1, 2, 3`,
"field2": `invalid`, "field2": `invalid`,
@@ -988,7 +988,7 @@ func TestRecordDataValidatorValidateJson(t *testing.T) {
[]string{"field1", "field2"}, []string{"field1", "field2"},
}, },
{ {
"valid data - only required fields", "(json) valid data - only required fields",
map[string]any{ map[string]any{
"field2": `{"test":123}`, "field2": `{"test":123}`,
}, },
@@ -996,7 +996,7 @@ func TestRecordDataValidatorValidateJson(t *testing.T) {
[]string{}, []string{},
}, },
{ {
"valid data - all fields with normalizations", "(json) valid data - all fields with normalizations",
map[string]any{ map[string]any{
"field1": []string{"a", "b", "c"}, "field1": []string{"a", "b", "c"},
"field2": 123, "field2": 123,
+42 -45
View File
@@ -4,81 +4,78 @@ go 1.18
require ( require (
github.com/AlecAivazis/survey/v2 v2.3.5 github.com/AlecAivazis/survey/v2 v2.3.5
github.com/aws/aws-sdk-go v1.44.48 github.com/aws/aws-sdk-go v1.44.81
github.com/disintegration/imaging v1.6.2 github.com/disintegration/imaging v1.6.2
github.com/domodwyer/mailyak/v3 v3.3.3 github.com/domodwyer/mailyak/v3 v3.3.4
github.com/fatih/color v1.13.0 github.com/fatih/color v1.13.0
github.com/ganigeorgiev/fexpr v0.1.1 github.com/ganigeorgiev/fexpr v0.1.1
github.com/go-ozzo/ozzo-validation/v4 v4.3.0 github.com/go-ozzo/ozzo-validation/v4 v4.3.0
github.com/golang-jwt/jwt/v4 v4.4.2 github.com/golang-jwt/jwt/v4 v4.4.2
github.com/labstack/echo/v5 v5.0.0-20220201181537-ed2888cfa198 github.com/labstack/echo/v5 v5.0.0-20220201181537-ed2888cfa198
github.com/mattn/go-sqlite3 v1.14.14 github.com/mattn/go-sqlite3 v1.14.15
github.com/microcosm-cc/bluemonday v1.0.19
github.com/pocketbase/dbx v1.6.0 github.com/pocketbase/dbx v1.6.0
github.com/spf13/cast v1.5.0 github.com/spf13/cast v1.5.0
github.com/spf13/cobra v1.5.0 github.com/spf13/cobra v1.5.0
gocloud.dev v0.25.0 gocloud.dev v0.26.0
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d golang.org/x/crypto v0.0.0-20220817201139-bc19a97f63c8
golang.org/x/oauth2 v0.0.0-20220630143837-2104d58473e0 golang.org/x/oauth2 v0.0.0-20220808172628-8227340efae7
modernc.org/sqlite v1.17.3 modernc.org/sqlite v1.18.1
) )
require ( require (
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect
github.com/aws/aws-sdk-go-v2 v1.16.7 // indirect github.com/aws/aws-sdk-go-v2 v1.16.11 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.3 // indirect github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.4 // indirect
github.com/aws/aws-sdk-go-v2/config v1.15.13 // indirect github.com/aws/aws-sdk-go-v2/config v1.17.1 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.12.8 // indirect github.com/aws/aws-sdk-go-v2/credentials v1.12.14 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.8 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.12 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.19 // indirect github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.27 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.14 // indirect github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.18 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.8 // indirect github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.12 // indirect
github.com/aws/aws-sdk-go-v2/internal/ini v1.3.15 // indirect github.com/aws/aws-sdk-go-v2/internal/ini v1.3.19 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.0.5 // indirect github.com/aws/aws-sdk-go-v2/internal/v4a v1.0.9 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.3 // indirect github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.5 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.9 // indirect github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.13 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.8 // indirect github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.12 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.13.8 // indirect github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.13.12 // indirect
github.com/aws/aws-sdk-go-v2/service/s3 v1.27.1 // indirect github.com/aws/aws-sdk-go-v2/service/s3 v1.27.5 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.11.11 // indirect github.com/aws/aws-sdk-go-v2/service/sso v1.11.17 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.16.9 // indirect github.com/aws/aws-sdk-go-v2/service/sts v1.16.13 // indirect
github.com/aws/smithy-go v1.12.0 // indirect github.com/aws/smithy-go v1.12.1 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.2 // indirect github.com/golang/protobuf v1.5.2 // indirect
github.com/google/uuid v1.3.0 // indirect github.com/google/uuid v1.3.0 // indirect
github.com/google/wire v0.5.0 // indirect github.com/google/wire v0.5.0 // indirect
github.com/googleapis/gax-go/v2 v2.4.0 // indirect github.com/googleapis/gax-go/v2 v2.5.1 // indirect
github.com/gorilla/css v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.0.1 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
github.com/mattn/go-colorable v0.1.12 // indirect github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect github.com/mattn/go-isatty v0.0.16 // indirect
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 // indirect
github.com/spf13/pflag v1.0.5 // indirect github.com/spf13/pflag v1.0.5 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.1 // indirect github.com/valyala/fasttemplate v1.2.1 // indirect
go.opencensus.io v0.23.0 // indirect go.opencensus.io v0.23.0 // indirect
golang.org/x/image v0.0.0-20220617043117-41969df76e82 // indirect golang.org/x/image v0.0.0-20220722155232-062f8c9fd539 // indirect
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect
golang.org/x/net v0.0.0-20220706163947-c90051bbdb60 // indirect golang.org/x/net v0.0.0-20220812174116-3211cb980234 // indirect
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e // indirect golang.org/x/sys v0.0.0-20220818161305-2296e01440c6 // indirect
golang.org/x/term v0.0.0-20220526004731-065cf7ba2467 // indirect golang.org/x/term v0.0.0-20220722155259-a9ba230a4035 // indirect
golang.org/x/text v0.3.7 // indirect golang.org/x/text v0.3.7 // indirect
golang.org/x/time v0.0.0-20220609170525-579cf78fd858 // indirect golang.org/x/time v0.0.0-20220722155302-e5dcc9cfc0b9 // indirect
golang.org/x/tools v0.1.11 // indirect golang.org/x/tools v0.1.12 // indirect
golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f // indirect golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f // indirect
google.golang.org/api v0.86.0 // indirect google.golang.org/api v0.93.0 // indirect
google.golang.org/appengine v1.6.7 // indirect google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20220706132729-d86698d07c53 // indirect google.golang.org/genproto v0.0.0-20220819174105-e9f053255caa // indirect
google.golang.org/grpc v1.47.0 // indirect google.golang.org/grpc v1.48.0 // indirect
google.golang.org/protobuf v1.28.0 // indirect google.golang.org/protobuf v1.28.1 // indirect
lukechampine.com/uint128 v1.2.0 // indirect lukechampine.com/uint128 v1.2.0 // indirect
modernc.org/cc/v3 v3.36.0 // indirect modernc.org/cc/v3 v3.36.1 // indirect
modernc.org/ccgo/v3 v3.16.6 // indirect modernc.org/ccgo/v3 v3.16.8 // indirect
modernc.org/libc v1.16.14 // indirect modernc.org/libc v1.16.19 // indirect
modernc.org/mathutil v1.4.1 // indirect modernc.org/mathutil v1.4.1 // indirect
modernc.org/memory v1.1.1 // indirect modernc.org/memory v1.1.1 // indirect
modernc.org/opt v0.1.3 // indirect modernc.org/opt v0.1.3 // indirect
+87 -93
View File
@@ -122,68 +122,66 @@ github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d/go.mod h1:W
github.com/aws/aws-sdk-go v1.15.27/go.mod h1:mFuSZ37Z9YOHbQEwBWztmVzqXrEkub65tZoCYDt7FT0= github.com/aws/aws-sdk-go v1.15.27/go.mod h1:mFuSZ37Z9YOHbQEwBWztmVzqXrEkub65tZoCYDt7FT0=
github.com/aws/aws-sdk-go v1.37.0/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro= github.com/aws/aws-sdk-go v1.37.0/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro=
github.com/aws/aws-sdk-go v1.43.31/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= github.com/aws/aws-sdk-go v1.43.31/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo=
github.com/aws/aws-sdk-go v1.44.48 h1:jLDC9RsNoYMLFlKpB8LdqUnoDdC2yvkS4QbuyPQJ8+M= github.com/aws/aws-sdk-go v1.44.81 h1:C8oBZ+a+ka0qk3Q24MohQIFq0tkbO8IAu5tfpAMKVWE=
github.com/aws/aws-sdk-go v1.44.48/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= github.com/aws/aws-sdk-go v1.44.81/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo=
github.com/aws/aws-sdk-go-v2 v1.16.2/go.mod h1:ytwTPBG6fXTZLxxeeCCWj2/EMYp/xDUgX+OET6TLNNU= github.com/aws/aws-sdk-go-v2 v1.16.2/go.mod h1:ytwTPBG6fXTZLxxeeCCWj2/EMYp/xDUgX+OET6TLNNU=
github.com/aws/aws-sdk-go-v2 v1.16.7 h1:zfBwXus3u14OszRxGcqCDS4MfMCv10e8SMJ2r8Xm0Ns= github.com/aws/aws-sdk-go-v2 v1.16.11 h1:xM1ZPSvty3xVmdxiGr7ay/wlqv+MWhH0rMlyLdbC0YQ=
github.com/aws/aws-sdk-go-v2 v1.16.7/go.mod h1:6CpKuLXg2w7If3ABZCl/qZ6rEgwtjZTn4eAf4RcEyuw= github.com/aws/aws-sdk-go-v2 v1.16.11/go.mod h1:WTACcleLz6VZTp7fak4EO5b9Q4foxbn+8PIz3PmyKlo=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.1/go.mod h1:n8Bs1ElDD2wJ9kCRTczA83gYbBmjSwZp3umc6zF4EeM= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.1/go.mod h1:n8Bs1ElDD2wJ9kCRTczA83gYbBmjSwZp3umc6zF4EeM=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.3 h1:S/ZBwevQkr7gv5YxONYpGQxlMFFYSRfz3RMcjsC9Qhk= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.4 h1:zfT11pa7ifu/VlLDpmc5OY2W4nYmnKkFDGeMVnmqAI0=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.3/go.mod h1:gNsR5CaXKmQSSzrmGxmwmct/r+ZBfbxorAuXYsj/M5Y= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.4/go.mod h1:ES0I1GBs+YYgcDS1ek47Erbn4TOL811JKqBXtgzqyZ8=
github.com/aws/aws-sdk-go-v2/config v1.15.3/go.mod h1:9YL3v07Xc/ohTsxFXzan9ZpFpdTOFl4X65BAKYaz8jg= github.com/aws/aws-sdk-go-v2/config v1.15.3/go.mod h1:9YL3v07Xc/ohTsxFXzan9ZpFpdTOFl4X65BAKYaz8jg=
github.com/aws/aws-sdk-go-v2/config v1.15.13 h1:CJH9zn/Enst7lDiGpoguVt0lZr5HcpNVlRJWbJ6qreo= github.com/aws/aws-sdk-go-v2/config v1.17.1 h1:BWxTjokU/69BZ4DnLrZco6OvBDii6ToEdfBL/y5I1nA=
github.com/aws/aws-sdk-go-v2/config v1.15.13/go.mod h1:AcMu50uhV6wMBUlURnEXhr9b3fX6FLSTlEV89krTEGk= github.com/aws/aws-sdk-go-v2/config v1.17.1/go.mod h1:uOxDHjBemNTF2Zos+fgG0NNfE86wn1OAHDTGxjMEYi0=
github.com/aws/aws-sdk-go-v2/credentials v1.11.2/go.mod h1:j8YsY9TXTm31k4eFhspiQicfXPLZ0gYXA50i4gxPE8g= github.com/aws/aws-sdk-go-v2/credentials v1.11.2/go.mod h1:j8YsY9TXTm31k4eFhspiQicfXPLZ0gYXA50i4gxPE8g=
github.com/aws/aws-sdk-go-v2/credentials v1.12.8 h1:niTa7zc7uyOP2ufri0jPESBt1h9yP3Zc0q+xzih3h8o= github.com/aws/aws-sdk-go-v2/credentials v1.12.14 h1:AtVG/amkjbDBfnPr/tuW2IG18HGNznP6L12Dx0rLz+Q=
github.com/aws/aws-sdk-go-v2/credentials v1.12.8/go.mod h1:P2Hd4Sy7mXRxPNcQMPBmqszSJoDXexX8XEDaT6lucO0= github.com/aws/aws-sdk-go-v2/credentials v1.12.14/go.mod h1:opAndTyq+YN7IpVG57z2CeNuXSQMqTYxGGlYH0m0RMY=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.3/go.mod h1:uk1vhHHERfSVCUnqSqz8O48LBYDSC+k6brng09jcMOk= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.3/go.mod h1:uk1vhHHERfSVCUnqSqz8O48LBYDSC+k6brng09jcMOk=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.8 h1:VfBdn2AxwMbFyJN/lF/xuT3SakomJ86PZu3rCxb5K0s= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.12 h1:wgJBHO58Pc1V1QAnzdVM3JK3WbE/6eUF0JxCZ+/izz0=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.8/go.mod h1:oL1Q3KuCq1D4NykQnIvtRiBGLUXhcpY5pl6QZB2XEPU= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.12/go.mod h1:aZ4vZnyUuxedC7eD4JyEHpGnCz+O2sHQEx3VvAwklSE=
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.3/go.mod h1:0dHuD2HZZSiwfJSy1FO5bX1hQ1TxVV1QXXjpn3XUE44= github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.3/go.mod h1:0dHuD2HZZSiwfJSy1FO5bX1hQ1TxVV1QXXjpn3XUE44=
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.19 h1:WfCYqsAADDRNCQQ5LGcrlqbR7SK3PYrP/UCh7qNGBQM= github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.27 h1:xFXIMBci0UXStoOHq/8w0XIZPB2hgb9CD7uATJhqt10=
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.19/go.mod h1:koLPv2oF6ksE3zBKLDP0GFmKfaCmYwVHqGIbaPrHIRg= github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.27/go.mod h1:+tj2cHQkChanggNZn1J2fJ1Cv6RO1TV0AA3472do31I=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.9/go.mod h1:AnVH5pvai0pAF4lXRq0bmhbes1u9R8wTE+g+183bZNM= github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.9/go.mod h1:AnVH5pvai0pAF4lXRq0bmhbes1u9R8wTE+g+183bZNM=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.14 h1:2C0pYHcUBmdzPj+EKNC4qj97oK6yjrUhc1KoSodglvk= github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.18 h1:OmiwoVyLKEqqD5GvB683dbSqxiOfvx4U2lDZhG2Esc4=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.14/go.mod h1:kdjrMwHwrC3+FsKhNcCMJ7tUVj/8uSD5CZXeQ4wV6fM= github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.18/go.mod h1:348MLhzV1GSlZSMusdwQpXKbhD7X2gbI/TxwAPKkYZQ=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.3/go.mod h1:ssOhaLpRlh88H3UmEcsBoVKq309quMvm3Ds8e9d4eJM= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.3/go.mod h1:ssOhaLpRlh88H3UmEcsBoVKq309quMvm3Ds8e9d4eJM=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.8 h1:2J+jdlBJWEmTyAwC82Ym68xCykIvnSnIN18b8xHGlcc= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.12 h1:5mvQDtNWtI6H56+E4LUnLWEmATMB7oEh+Z9RurtIuC0=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.8/go.mod h1:ZIV8GYoC6WLBW5KGs+o4rsc65/ozd+eQ0L31XF5VDwk= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.12/go.mod h1:ckaCVTEdGAxO6KwTGzgskxR1xM+iJW4lxMyDFVda2Fc=
github.com/aws/aws-sdk-go-v2/internal/ini v1.3.10/go.mod h1:8DcYQcz0+ZJaSxANlHIsbbi6S+zMwjwdDqwW3r9AzaE= github.com/aws/aws-sdk-go-v2/internal/ini v1.3.10/go.mod h1:8DcYQcz0+ZJaSxANlHIsbbi6S+zMwjwdDqwW3r9AzaE=
github.com/aws/aws-sdk-go-v2/internal/ini v1.3.15 h1:QquxR7NH3ULBsKC+NoTpilzbKKS+5AELfNREInbhvas= github.com/aws/aws-sdk-go-v2/internal/ini v1.3.19 h1:g5qq9sgtEzt2szMaDqQO6fqKe026T6dHTFJp5NsPzkQ=
github.com/aws/aws-sdk-go-v2/internal/ini v1.3.15/go.mod h1:Tkrthp/0sNBShQQsamR7j/zY4p19tVTAs+nnqhH6R3c= github.com/aws/aws-sdk-go-v2/internal/ini v1.3.19/go.mod h1:cVHo8KTuHjShb9V8/VjH3S/8+xPu16qx8fdGwmotJhE=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.0.5 h1:tEEHn+PGAxRVqMPEhtU8oCSW/1Ge3zP5nUgPrGQNUPs= github.com/aws/aws-sdk-go-v2/internal/v4a v1.0.9 h1:agLpf3vtYX1rtKTrOGpevdP3iC2W0hKDmzmhhxJzL+A=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.0.5/go.mod h1:aIwFF3dUk95ocCcA3zfk3nhz0oLkpzHFWuMp8l/4nNs= github.com/aws/aws-sdk-go-v2/internal/v4a v1.0.9/go.mod h1:cv+n1mdyh+0B8tAtlEBzTYFA2Uv15SISEn6kabYhIgE=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.1/go.mod h1:GeUru+8VzrTXV/83XyMJ80KpH8xO89VPoUileyNQ+tc= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.1/go.mod h1:GeUru+8VzrTXV/83XyMJ80KpH8xO89VPoUileyNQ+tc=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.3 h1:4n4KCtv5SUoT5Er5XV41huuzrCqepxlW3SDI9qHQebc= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.5 h1:g1ITJ9i9ixa+/WVggLNK20KyliAA8ltnuxfZEDfo2hM=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.3/go.mod h1:gkb2qADY+OHaGLKNTYxMaQNacfeyQpZ4csDTQMeFmcw= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.5/go.mod h1:oehQLbMQkppKLXvpx/1Eo0X47Fe+0971DXC9UjGnKcI=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.3/go.mod h1:Seb8KNmD6kVTjwRjVEgOT5hPin6sq+v4C2ycJQDwuH8= github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.3/go.mod h1:Seb8KNmD6kVTjwRjVEgOT5hPin6sq+v4C2ycJQDwuH8=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.9 h1:gVv2vXOMqJeR4ZHHV32K7LElIJIIzyw/RU1b0lSfWTQ= github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.13 h1:3GamN8jcdz/a3nvL/ZVtoH/6xxeshfsiXj5O+6GW4Rg=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.9/go.mod h1:EF5RLnD9l0xvEWwMRcktIS/dI6lF8lU5eV3B13k6sWo= github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.13/go.mod h1:89CSPn69UECDLVn0H6FwKNgbtirksl8C8i3aBeeeihw=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.3/go.mod h1:wlY6SVjuwvh3TVRpTqdy4I1JpBFLX4UGeKZdWntaocw= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.3/go.mod h1:wlY6SVjuwvh3TVRpTqdy4I1JpBFLX4UGeKZdWntaocw=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.8 h1:oKnAXxSF2FUvfgw8uzU/v9OTYorJJZ8eBmWhr9TWVVQ= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.12 h1:7iPTTX4SAI2U2VOogD7/gmHlsgnYSgoNHt7MSQXtG2M=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.8/go.mod h1:rDVhIMAX9N2r8nWxDUlbubvvaFMnfsm+3jAV7q+rpM4= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.12/go.mod h1:1TODGhheLWjpQWSuhYuAUWYTCKwEjx2iblIFKDHjeTc=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.13.3/go.mod h1:Bm/v2IaN6rZ+Op7zX+bOUMdL4fsrYZiD0dsjLhNKwZc= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.13.3/go.mod h1:Bm/v2IaN6rZ+Op7zX+bOUMdL4fsrYZiD0dsjLhNKwZc=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.13.8 h1:TlN1UC39A0LUNoD51ubO5h32haznA+oVe15jO9O4Lj0= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.13.12 h1:QFjSOmHSb77qRTv7KI9UFon9X5wLWY5/M+6la3dTcZc=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.13.8/go.mod h1:JlVwmWtT/1c5W+6oUsjXjAJ0iJZ+hlghdrDy/8JxGCU= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.13.12/go.mod h1:MADjAN0GHFDuc5lRa5Y5ki+oIO/w7X4qczHy+OUx0IA=
github.com/aws/aws-sdk-go-v2/service/kms v1.16.3/go.mod h1:QuiHPBqlOFCi4LqdSskYYAWpQlx3PKmohy+rE2F+o5g= github.com/aws/aws-sdk-go-v2/service/kms v1.16.3/go.mod h1:QuiHPBqlOFCi4LqdSskYYAWpQlx3PKmohy+rE2F+o5g=
github.com/aws/aws-sdk-go-v2/service/s3 v1.26.3/go.mod h1:g1qvDuRsJY+XghsV6zg00Z4KJ7DtFFCx8fJD2a491Ak= github.com/aws/aws-sdk-go-v2/service/s3 v1.26.3/go.mod h1:g1qvDuRsJY+XghsV6zg00Z4KJ7DtFFCx8fJD2a491Ak=
github.com/aws/aws-sdk-go-v2/service/s3 v1.27.1 h1:OKQIQ0QhEBmGr2LfT952meIZz3ujrPYnxH+dO/5ldnI= github.com/aws/aws-sdk-go-v2/service/s3 v1.27.5 h1:h9qqTedYnA9JcWjKyLV6UYIMSdp91ExLCUbjbpDLH7A=
github.com/aws/aws-sdk-go-v2/service/s3 v1.27.1/go.mod h1:NffjpNsMUFXp6Ok/PahrktAncoekWrywvmIK83Q2raE= github.com/aws/aws-sdk-go-v2/service/s3 v1.27.5/go.mod h1:J8SS5Tp/zeLxaubB0xGfKnVrvssNBNLwTipreTKLhjQ=
github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.15.4/go.mod h1:PJc8s+lxyU8rrre0/4a0pn2wgwiDvOEzoOjcJUBr67o= github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.15.4/go.mod h1:PJc8s+lxyU8rrre0/4a0pn2wgwiDvOEzoOjcJUBr67o=
github.com/aws/aws-sdk-go-v2/service/sns v1.17.4/go.mod h1:kElt+uCcXxcqFyc+bQqZPFD9DME/eC6oHBXvFzQ9Bcw= github.com/aws/aws-sdk-go-v2/service/sns v1.17.4/go.mod h1:kElt+uCcXxcqFyc+bQqZPFD9DME/eC6oHBXvFzQ9Bcw=
github.com/aws/aws-sdk-go-v2/service/sqs v1.18.3/go.mod h1:skmQo0UPvsjsuYYSYMVmrPc1HWCbHUJyrCEp+ZaLzqM= github.com/aws/aws-sdk-go-v2/service/sqs v1.18.3/go.mod h1:skmQo0UPvsjsuYYSYMVmrPc1HWCbHUJyrCEp+ZaLzqM=
github.com/aws/aws-sdk-go-v2/service/ssm v1.24.1/go.mod h1:NR/xoKjdbRJ+qx0pMR4mI+N/H1I1ynHwXnO6FowXJc0= github.com/aws/aws-sdk-go-v2/service/ssm v1.24.1/go.mod h1:NR/xoKjdbRJ+qx0pMR4mI+N/H1I1ynHwXnO6FowXJc0=
github.com/aws/aws-sdk-go-v2/service/sso v1.11.3/go.mod h1:7UQ/e69kU7LDPtY40OyoHYgRmgfGM4mgsLYtcObdveU= github.com/aws/aws-sdk-go-v2/service/sso v1.11.3/go.mod h1:7UQ/e69kU7LDPtY40OyoHYgRmgfGM4mgsLYtcObdveU=
github.com/aws/aws-sdk-go-v2/service/sso v1.11.11 h1:XOJWXNFXJyapJqQuCIPfftsOf0XZZioM0kK6OPRt9MY= github.com/aws/aws-sdk-go-v2/service/sso v1.11.17 h1:pXxu9u2z1UqSbjO9YA8kmFJBhFc1EVTDaf7A+S+Ivq8=
github.com/aws/aws-sdk-go-v2/service/sso v1.11.11/go.mod h1:MO4qguFjs3wPGcCSpQ7kOFTwRvb+eu+fn+1vKleGHUk= github.com/aws/aws-sdk-go-v2/service/sso v1.11.17/go.mod h1:mS5xqLZc/6kc06IpXn5vRxdLaED+jEuaSRv5BxtnsiY=
github.com/aws/aws-sdk-go-v2/service/sts v1.16.3/go.mod h1:bfBj0iVmsUyUg4weDB4NxktD9rDGeKSVWnjTnwbx9b8= github.com/aws/aws-sdk-go-v2/service/sts v1.16.3/go.mod h1:bfBj0iVmsUyUg4weDB4NxktD9rDGeKSVWnjTnwbx9b8=
github.com/aws/aws-sdk-go-v2/service/sts v1.16.9 h1:yOfILxyjmtr2ubRkRJldlHDFBhf5vw4CzhbwWIBmimQ= github.com/aws/aws-sdk-go-v2/service/sts v1.16.13 h1:dl8T0PJlN92rvEGOEUiD0+YPYdPEaCZK0TqHukvSfII=
github.com/aws/aws-sdk-go-v2/service/sts v1.16.9/go.mod h1:O1IvkYxr+39hRf960Us6j0x1P8pDqhTX+oXM5kQNl/Y= github.com/aws/aws-sdk-go-v2/service/sts v1.16.13/go.mod h1:Ru3QVMLygVs/07UQ3YDur1AQZZp2tUNje8wfloFttC0=
github.com/aws/smithy-go v1.11.2/go.mod h1:3xHYmszWVx2c0kIwQeEVf9uSm4fYZt67FBJnwub1bgM= github.com/aws/smithy-go v1.11.2/go.mod h1:3xHYmszWVx2c0kIwQeEVf9uSm4fYZt67FBJnwub1bgM=
github.com/aws/smithy-go v1.12.0 h1:gXpeZel/jPoWQ7OEmLIgCUnhkFftqNfwWUwAHSlp1v0= github.com/aws/smithy-go v1.12.1 h1:yQRC55aXN/y1W10HgwHle01DRuV9Dpf31iGkotjt3Ag=
github.com/aws/smithy-go v1.12.0/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= github.com/aws/smithy-go v1.12.1/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA=
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/census-instrumentation/opencensus-proto v0.3.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.3.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
@@ -220,8 +218,8 @@ github.com/dimchansky/utfbom v1.1.1/go.mod h1:SxdoEBH5qIqFocHMyGOXVAybYJdr71b1Q/
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c= github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4= github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
github.com/domodwyer/mailyak/v3 v3.3.3 h1:E9cjqDUiwY1QSE5G2CbWHM7EJV5FybKPHnGovc2iaA8= github.com/domodwyer/mailyak/v3 v3.3.4 h1:AG/pvcz2/ocFqZkPEG7lPAa0MhCq1warfUEKJt6Fagk=
github.com/domodwyer/mailyak/v3 v3.3.3/go.mod h1:lOm/u9CyCVWHeaAmHIdF4RiKVxKUT/H5XX10lIKAL6c= github.com/domodwyer/mailyak/v3 v3.3.4/go.mod h1:lOm/u9CyCVWHeaAmHIdF4RiKVxKUT/H5XX10lIKAL6c=
github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
@@ -370,12 +368,11 @@ github.com/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pf
github.com/googleapis/gax-go/v2 v2.1.1/go.mod h1:hddJymUZASv3XPyGkUpKj8pPO47Rmb0eJc8R6ouapiM= github.com/googleapis/gax-go/v2 v2.1.1/go.mod h1:hddJymUZASv3XPyGkUpKj8pPO47Rmb0eJc8R6ouapiM=
github.com/googleapis/gax-go/v2 v2.2.0/go.mod h1:as02EH8zWkzwUoLbBaFeQ+arQaj/OthfcblKl4IGNaM= github.com/googleapis/gax-go/v2 v2.2.0/go.mod h1:as02EH8zWkzwUoLbBaFeQ+arQaj/OthfcblKl4IGNaM=
github.com/googleapis/gax-go/v2 v2.3.0/go.mod h1:b8LNqSzNabLiUpXKkY7HAR5jr6bIT99EXz9pXxye9YM= github.com/googleapis/gax-go/v2 v2.3.0/go.mod h1:b8LNqSzNabLiUpXKkY7HAR5jr6bIT99EXz9pXxye9YM=
github.com/googleapis/gax-go/v2 v2.4.0 h1:dS9eYAjhrE2RjmzYw2XAPvcXfmcQLtFEQWn0CR82awk=
github.com/googleapis/gax-go/v2 v2.4.0/go.mod h1:XOTVJ59hdnfJLIP/dh8n5CGryZR2LxK9wbMD5+iXC6c= github.com/googleapis/gax-go/v2 v2.4.0/go.mod h1:XOTVJ59hdnfJLIP/dh8n5CGryZR2LxK9wbMD5+iXC6c=
github.com/googleapis/gax-go/v2 v2.5.1 h1:kBRZU0PSuI7PspsSb/ChWoVResUcwNVIdpB049pKTiw=
github.com/googleapis/gax-go/v2 v2.5.1/go.mod h1:h6B0KMMFNtI2ddbGJn3T3ZbwkeT6yqEF02fYlzkUCyo=
github.com/googleapis/go-type-adapters v1.0.0 h1:9XdMn+d/G57qq1s8dNc5IesGCXHf6V2HZ2JwRxfA2tA= github.com/googleapis/go-type-adapters v1.0.0 h1:9XdMn+d/G57qq1s8dNc5IesGCXHf6V2HZ2JwRxfA2tA=
github.com/googleapis/go-type-adapters v1.0.0/go.mod h1:zHW75FOG2aur7gAO2B+MLby+cLsWGBF62rFAi7WjWO4= github.com/googleapis/go-type-adapters v1.0.0/go.mod h1:zHW75FOG2aur7gAO2B+MLby+cLsWGBF62rFAi7WjWO4=
github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY=
github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c=
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
github.com/hanwen/go-fuse v1.0.0/go.mod h1:unqXarDXqzAk0rt98O2tVndEPIpUgLD9+rwFisZH3Ok= github.com/hanwen/go-fuse v1.0.0/go.mod h1:unqXarDXqzAk0rt98O2tVndEPIpUgLD9+rwFisZH3Ok=
@@ -386,8 +383,9 @@ github.com/hinshun/vt10x v0.0.0-20220119200601-820417d04eec h1:qv2VnGeEQHchGaZ/u
github.com/hinshun/vt10x v0.0.0-20220119200601-820417d04eec/go.mod h1:Q48J4R4DvxnHolD5P8pOtXigYlRuPLGl6moFx3ulM68= github.com/hinshun/vt10x v0.0.0-20220119200601-820417d04eec/go.mod h1:Q48J4R4DvxnHolD5P8pOtXigYlRuPLGl6moFx3ulM68=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo= github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo=
github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk=
github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk=
@@ -462,25 +460,22 @@ github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcncea
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-ieproxy v0.0.1 h1:qiyop7gCflfhwCzGyeT0gro3sF9AIg9HU98JORTkqfI=
github.com/mattn/go-ieproxy v0.0.1/go.mod h1:pYabZ6IHcRpFh7vIaLfK7rdcWgFEb3SFJ6/gNWuh88E= github.com/mattn/go-ieproxy v0.0.1/go.mod h1:pYabZ6IHcRpFh7vIaLfK7rdcWgFEb3SFJ6/gNWuh88E=
github.com/mattn/go-ieproxy v0.0.3 h1:YkaHmK1CzE5C4O7A3hv3TCbfNDPSCf0RKZFX+VhBeYk=
github.com/mattn/go-ieproxy v0.0.3/go.mod h1:6ZpRmhBaYuBX1U2za+9rC9iCGLsSp2tftelZne7CPko=
github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-sqlite3 v1.14.12/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=
github.com/mattn/go-sqlite3 v1.14.14 h1:qZgc/Rwetq+MtyE18WhzjokPD93dNqLGNT3QJuLvBGw= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-sqlite3 v1.14.14/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= github.com/mattn/go-sqlite3 v1.14.15 h1:vfoHhTN1af61xCRSWzFIWzx2YskyMTwHLrExkBOjvxI=
github.com/mattn/go-sqlite3 v1.14.15/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI= github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI=
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
github.com/microcosm-cc/bluemonday v1.0.19 h1:OI7hoF5FY4pFz2VA//RN8TfM0YJ2dJcl4P4APrCWy6c=
github.com/microcosm-cc/bluemonday v1.0.19/go.mod h1:QNzV2UbLK2/53oIIwTOyLUSABMkjZ4tqiyC1g/DyqxE=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/mitchellh/mapstructure v1.4.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/mapstructure v1.4.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
@@ -565,8 +560,8 @@ go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM=
go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw=
gocloud.dev v0.25.0 h1:Y7vDq8xj7SyM848KXf32Krda2e6jQ4CLh/mTeCSqXtk= gocloud.dev v0.26.0 h1:4rM/SVL0lLs+rhC0Gmc+gt/82DBpb7nbpIZKXXnfMXg=
gocloud.dev v0.25.0/go.mod h1:7HegHVCYZrMiU3IE1qtnzf/vRrDwLYnRNR3EhWX8x9Y= gocloud.dev v0.26.0/go.mod h1:mkUgejbnbLotorqDyvedJO20XcZNTynmSeVSQS9btVg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
@@ -582,8 +577,8 @@ golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5y
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20211115234514-b4de73f9ece8/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211115234514-b4de73f9ece8/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d h1:sK3txAijHtOK88l68nt020reeT1ZdKLIYetKl95FzVY= golang.org/x/crypto v0.0.0-20220817201139-bc19a97f63c8 h1:GIAS/yBem/gq2MUqgNIzUHW7cJMmx3TGZOrnyYaNQ6c=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220817201139-bc19a97f63c8/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@@ -597,8 +592,8 @@ golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMk
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20220617043117-41969df76e82 h1:KpZB5pUSBvrHltNEdK/tw0xlPeD13M6M6aGP32gKqiw= golang.org/x/image v0.0.0-20220722155232-062f8c9fd539 h1:/eM0PCrQI2xd471rI+snWuu251/+/jpBpZqir2mPdnU=
golang.org/x/image v0.0.0-20220617043117-41969df76e82/go.mod h1:doUCurBvlfPMKfmIpRIywoHmhN3VyhnoFDbvIEWF4hY= golang.org/x/image v0.0.0-20220722155232-062f8c9fd539/go.mod h1:doUCurBvlfPMKfmIpRIywoHmhN3VyhnoFDbvIEWF4hY=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
@@ -665,7 +660,6 @@ golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qx
golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211020060615-d418f374d309/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211020060615-d418f374d309/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220107192237-5cfca573fb4d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.0.0-20220325170049-de3da57026de/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220325170049-de3da57026de/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
@@ -674,8 +668,8 @@ golang.org/x/net v0.0.0-20220412020605-290c469a71a5/go.mod h1:CfG3xpIq0wQ8r1q4Su
golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.0.0-20220706163947-c90051bbdb60 h1:8NSylCMxLW4JvserAndSgFL7aPli6A68yf0bYFTcWCM= golang.org/x/net v0.0.0-20220812174116-3211cb980234 h1:RDqmgfe7SvlMWoqC3xwQ2blLO3fcWcxMa3eBLRdRW7E=
golang.org/x/net v0.0.0-20220706163947-c90051bbdb60/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220812174116-3211cb980234/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@@ -699,8 +693,8 @@ golang.org/x/oauth2 v0.0.0-20220309155454-6242fa91716a/go.mod h1:DAh4E804XQdzx2j
golang.org/x/oauth2 v0.0.0-20220411215720-9780585627b5/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= golang.org/x/oauth2 v0.0.0-20220411215720-9780585627b5/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc=
golang.org/x/oauth2 v0.0.0-20220608161450-d0670ef3b1eb/go.mod h1:jaDAt6Dkxork7LmZnYtzbRWj0W47D86a3TGe0YHBvmE= golang.org/x/oauth2 v0.0.0-20220608161450-d0670ef3b1eb/go.mod h1:jaDAt6Dkxork7LmZnYtzbRWj0W47D86a3TGe0YHBvmE=
golang.org/x/oauth2 v0.0.0-20220622183110-fd043fe589d2/go.mod h1:jaDAt6Dkxork7LmZnYtzbRWj0W47D86a3TGe0YHBvmE= golang.org/x/oauth2 v0.0.0-20220622183110-fd043fe589d2/go.mod h1:jaDAt6Dkxork7LmZnYtzbRWj0W47D86a3TGe0YHBvmE=
golang.org/x/oauth2 v0.0.0-20220630143837-2104d58473e0 h1:VnGaRqoLmqZH/3TMLJwYCEWkR4j1nuIU1U9TvbqsDUw= golang.org/x/oauth2 v0.0.0-20220808172628-8227340efae7 h1:dtndE8FcEta75/4kHF3AbpuWzV6f1LjnLrM4pe2SZrw=
golang.org/x/oauth2 v0.0.0-20220630143837-2104d58473e0/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= golang.org/x/oauth2 v0.0.0-20220808172628-8227340efae7/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -770,13 +764,11 @@ golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210917161153-d61c044b1678/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210917161153-d61c044b1678/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211116061358-0a5406a5449c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211116061358-0a5406a5449c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220110181412-a018aaa089fe/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -791,14 +783,15 @@ golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220624220833-87e55d714810/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220624220833-87e55d714810/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e h1:CsOuNlbOuf0mzxJIefr6Q4uAUetRUwZE4qt7VfzP+xo= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220818161305-2296e01440c6 h1:Sx/u41w+OwrInGdEckYmEuU5gHoGSL4QbDz3S9s6j4U=
golang.org/x/sys v0.0.0-20220818161305-2296e01440c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210503060354-a79de5458b56/go.mod h1:tfny5GFUkzUvx4ps4ajbZsCe5lw1metzhBm9T3x7oIY= golang.org/x/term v0.0.0-20210503060354-a79de5458b56/go.mod h1:tfny5GFUkzUvx4ps4ajbZsCe5lw1metzhBm9T3x7oIY=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.0.0-20220526004731-065cf7ba2467 h1:CBpWXWQpIRjzmkkA+M7q9Fqnwd2mZr3AFqexg8YTfoM= golang.org/x/term v0.0.0-20220722155259-a9ba230a4035 h1:Q5284mrmYTpACcm+eAKjKJH48BBwSyfJqmmGDTtT8Vc=
golang.org/x/term v0.0.0-20220526004731-065cf7ba2467/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20220722155259-a9ba230a4035/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@@ -814,8 +807,8 @@ golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxb
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20220224211638-0e9765cccd65/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20220224211638-0e9765cccd65/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20220609170525-579cf78fd858 h1:Dpdu/EMxGMFgq0CeYMh4fazTD2vtlZRYE7wyynxJb9U= golang.org/x/time v0.0.0-20220722155302-e5dcc9cfc0b9 h1:ftMN5LMiBFjbzleLqtoBZk7KdJwhuybIU+FckUHgoyQ=
golang.org/x/time v0.0.0-20220609170525-579cf78fd858/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20220722155302-e5dcc9cfc0b9/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
@@ -874,8 +867,8 @@ golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.11 h1:loJ25fNOEhSXfHrpoGj91eCUThwdNX6u24rO1xnNteY= golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU=
golang.org/x/tools v0.1.11/go.mod h1:SgwaegtQh8clINPpECJMqnxLv9I09HLqnW3RMqW0CA4= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -932,8 +925,8 @@ google.golang.org/api v0.75.0/go.mod h1:pU9QmyHLnzlpar1Mjt4IbapUCy8J+6HD6GeELN69
google.golang.org/api v0.78.0/go.mod h1:1Sg78yoMLOhlQTeF+ARBoytAcH1NNyyl390YMy6rKmw= google.golang.org/api v0.78.0/go.mod h1:1Sg78yoMLOhlQTeF+ARBoytAcH1NNyyl390YMy6rKmw=
google.golang.org/api v0.80.0/go.mod h1:xY3nI94gbvBrE0J6NHXhxOmW97HG7Khjkku6AFB3Hyg= google.golang.org/api v0.80.0/go.mod h1:xY3nI94gbvBrE0J6NHXhxOmW97HG7Khjkku6AFB3Hyg=
google.golang.org/api v0.84.0/go.mod h1:NTsGnUFJMYROtiquksZHBWtHfeMC7iYthki7Eq3pa8o= google.golang.org/api v0.84.0/go.mod h1:NTsGnUFJMYROtiquksZHBWtHfeMC7iYthki7Eq3pa8o=
google.golang.org/api v0.86.0 h1:ZAnyOHQFIuWso1BodVfSaRyffD74T9ERGFa3k1fNk/U= google.golang.org/api v0.93.0 h1:T2xt9gi0gHdxdnRkVQhT8mIvPaXKNsDNWz+L696M66M=
google.golang.org/api v0.86.0/go.mod h1:+Sem1dnrKlrXMR/X0bPnMWyluQe4RsNoYfmNLhOIkzw= google.golang.org/api v0.93.0/go.mod h1:+Sem1dnrKlrXMR/X0bPnMWyluQe4RsNoYfmNLhOIkzw=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
@@ -1036,8 +1029,8 @@ google.golang.org/genproto v0.0.0-20220523171625-347a074981d8/go.mod h1:RAyBrSAP
google.golang.org/genproto v0.0.0-20220608133413-ed9918b62aac/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= google.golang.org/genproto v0.0.0-20220608133413-ed9918b62aac/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA=
google.golang.org/genproto v0.0.0-20220616135557-88e70c0c3a90/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= google.golang.org/genproto v0.0.0-20220616135557-88e70c0c3a90/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA=
google.golang.org/genproto v0.0.0-20220624142145-8cd45d7dbd1f/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= google.golang.org/genproto v0.0.0-20220624142145-8cd45d7dbd1f/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA=
google.golang.org/genproto v0.0.0-20220706132729-d86698d07c53 h1:liFd7OL799HvMNYG5xozhUoWDj944y+zXPDOhu4PyaM= google.golang.org/genproto v0.0.0-20220819174105-e9f053255caa h1:Ux9yJCyf598uEniFPSyp8g1jtGTt77m+lzYyVgrWQaQ=
google.golang.org/genproto v0.0.0-20220706132729-d86698d07c53/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= google.golang.org/genproto v0.0.0-20220819174105-e9f053255caa/go.mod h1:dbqgFATTzChvnt+ujMdZwITVAJHFtfyN1qUhDqEiIlk=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
@@ -1068,8 +1061,9 @@ google.golang.org/grpc v1.44.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ5
google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ=
google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk=
google.golang.org/grpc v1.46.2/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= google.golang.org/grpc v1.46.2/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk=
google.golang.org/grpc v1.47.0 h1:9n77onPX5F3qfFCqjy9dhn8PbNQsIKeVU04J9G7umt8=
google.golang.org/grpc v1.47.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= google.golang.org/grpc v1.47.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk=
google.golang.org/grpc v1.48.0 h1:rQOsyJ/8+ufEDJd/Gdsz7HG220Mh9HAhFHRGnIjda0w=
google.golang.org/grpc v1.48.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk=
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
@@ -1084,8 +1078,9 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw=
google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w=
google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
@@ -1109,13 +1104,14 @@ honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9
lukechampine.com/uint128 v1.1.1/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk= lukechampine.com/uint128 v1.1.1/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk=
lukechampine.com/uint128 v1.2.0 h1:mBi/5l91vocEN8otkC5bDLhi2KdCticRiwbdB0O+rjI= lukechampine.com/uint128 v1.2.0 h1:mBi/5l91vocEN8otkC5bDLhi2KdCticRiwbdB0O+rjI=
lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk= lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk=
modernc.org/cc/v3 v3.36.0 h1:0kmRkTmqNidmu3c7BNDSdVHCxXCkWLmWmCIVX4LUboo=
modernc.org/cc/v3 v3.36.0/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI= modernc.org/cc/v3 v3.36.0/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI=
modernc.org/cc/v3 v3.36.1 h1:CICrjwr/1M4+6OQ4HJZ/AHxjcwe67r5vPUF518MkO8A=
modernc.org/cc/v3 v3.36.1/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI=
modernc.org/ccgo/v3 v3.0.0-20220428102840-41399a37e894/go.mod h1:eI31LL8EwEBKPpNpA4bU1/i+sKOwOrQy8D87zWUcRZc= modernc.org/ccgo/v3 v3.0.0-20220428102840-41399a37e894/go.mod h1:eI31LL8EwEBKPpNpA4bU1/i+sKOwOrQy8D87zWUcRZc=
modernc.org/ccgo/v3 v3.0.0-20220430103911-bc99d88307be/go.mod h1:bwdAnOoaIt8Ax9YdWGjxWsdkPcZyRPHqrOvJxaKAKGw= modernc.org/ccgo/v3 v3.0.0-20220430103911-bc99d88307be/go.mod h1:bwdAnOoaIt8Ax9YdWGjxWsdkPcZyRPHqrOvJxaKAKGw=
modernc.org/ccgo/v3 v3.16.4/go.mod h1:tGtX0gE9Jn7hdZFeU88slbTh1UtCYKusWOoCJuvkWsQ=
modernc.org/ccgo/v3 v3.16.6 h1:3l18poV+iUemQ98O3X5OMr97LOqlzis+ytivU4NqGhA=
modernc.org/ccgo/v3 v3.16.6/go.mod h1:tGtX0gE9Jn7hdZFeU88slbTh1UtCYKusWOoCJuvkWsQ= modernc.org/ccgo/v3 v3.16.6/go.mod h1:tGtX0gE9Jn7hdZFeU88slbTh1UtCYKusWOoCJuvkWsQ=
modernc.org/ccgo/v3 v3.16.8 h1:G0QNlTqI5uVgczBWfGKs7B++EPwCfXPWGD2MdeKloDs=
modernc.org/ccgo/v3 v3.16.8/go.mod h1:zNjwkizS+fIFDrDjIAgBSCLkWbJuHF+ar3QRn+Z9aws=
modernc.org/ccorpus v1.11.6 h1:J16RXiiqiCgua6+ZvQot4yUuUy8zxgqbqEEUuGPlISk= modernc.org/ccorpus v1.11.6 h1:J16RXiiqiCgua6+ZvQot4yUuUy8zxgqbqEEUuGPlISk=
modernc.org/ccorpus v1.11.6/go.mod h1:2gEUTrWqdpH2pXsmTM1ZkjeSrUWDpjMu2T6m29L/ErQ= modernc.org/ccorpus v1.11.6/go.mod h1:2gEUTrWqdpH2pXsmTM1ZkjeSrUWDpjMu2T6m29L/ErQ=
modernc.org/httpfs v1.0.6 h1:AAgIpFZRXuYnkjftxTAZwMIiwEqAfk8aVB2/oA6nAeM= modernc.org/httpfs v1.0.6 h1:AAgIpFZRXuYnkjftxTAZwMIiwEqAfk8aVB2/oA6nAeM=
@@ -1123,9 +1119,9 @@ modernc.org/httpfs v1.0.6/go.mod h1:7dosgurJGp0sPaRanU53W4xZYKh14wfzX420oZADeHM=
modernc.org/libc v0.0.0-20220428101251-2d5f3daf273b/go.mod h1:p7Mg4+koNjc8jkqwcoFBJx7tXkpj00G77X7A72jXPXA= modernc.org/libc v0.0.0-20220428101251-2d5f3daf273b/go.mod h1:p7Mg4+koNjc8jkqwcoFBJx7tXkpj00G77X7A72jXPXA=
modernc.org/libc v1.16.0/go.mod h1:N4LD6DBE9cf+Dzf9buBlzVJndKr/iJHG97vGLHYnb5A= modernc.org/libc v1.16.0/go.mod h1:N4LD6DBE9cf+Dzf9buBlzVJndKr/iJHG97vGLHYnb5A=
modernc.org/libc v1.16.1/go.mod h1:JjJE0eu4yeK7tab2n4S1w8tlWd9MxXLRzheaRnAKymU= modernc.org/libc v1.16.1/go.mod h1:JjJE0eu4yeK7tab2n4S1w8tlWd9MxXLRzheaRnAKymU=
modernc.org/libc v1.16.7/go.mod h1:hYIV5VZczAmGZAnG15Vdngn5HSF5cSkbvfz2B7GRuVU= modernc.org/libc v1.16.17/go.mod h1:hYIV5VZczAmGZAnG15Vdngn5HSF5cSkbvfz2B7GRuVU=
modernc.org/libc v1.16.14 h1:MUIjk9Xwlkrp0BqGhMfRkiq0EkZsqfNiP4eixL3YiPk= modernc.org/libc v1.16.19 h1:S8flPn5ZeXx6iw/8yNa986hwTQDrY8RXU7tObZuAozo=
modernc.org/libc v1.16.14/go.mod h1:hYIV5VZczAmGZAnG15Vdngn5HSF5cSkbvfz2B7GRuVU= modernc.org/libc v1.16.19/go.mod h1:p7Mg4+koNjc8jkqwcoFBJx7tXkpj00G77X7A72jXPXA=
modernc.org/mathutil v1.2.2/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= modernc.org/mathutil v1.2.2/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
modernc.org/mathutil v1.4.1 h1:ij3fYGe8zBF4Vu+g0oT7mB06r8sqGWKuJu1yXeR4by8= modernc.org/mathutil v1.4.1 h1:ij3fYGe8zBF4Vu+g0oT7mB06r8sqGWKuJu1yXeR4by8=
modernc.org/mathutil v1.4.1/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= modernc.org/mathutil v1.4.1/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
@@ -1134,17 +1130,15 @@ modernc.org/memory v1.1.1/go.mod h1:/0wo5ibyrQiaoUoH7f9D8dnglAmILJ5/cxZlRECf+Nw=
modernc.org/opt v0.1.1/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= modernc.org/opt v0.1.1/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
modernc.org/sqlite v1.17.3 h1:iE+coC5g17LtByDYDWKpR6m2Z9022YrSh3bumwOnIrI= modernc.org/sqlite v1.18.1 h1:ko32eKt3jf7eqIkCgPAeHMBXw3riNSLhl2f3loEF7o8=
modernc.org/sqlite v1.17.3/go.mod h1:10hPVYar9C0kfXuTWGz8s0XtB8uAGymUy51ZzStYe3k= modernc.org/sqlite v1.18.1/go.mod h1:6ho+Gow7oX5V+OiOQ6Tr4xeqbx13UZ6t+Fw9IRUG4d4=
modernc.org/strutil v1.1.1/go.mod h1:DE+MQQ/hjKBZS2zNInV5hhcipt5rLPWkmpbGeW5mmdw= modernc.org/strutil v1.1.1/go.mod h1:DE+MQQ/hjKBZS2zNInV5hhcipt5rLPWkmpbGeW5mmdw=
modernc.org/strutil v1.1.2 h1:iFBDH6j1Z0bN/Q9udJnnFoFpENA4252qe/7/5woE5MI= modernc.org/strutil v1.1.2 h1:iFBDH6j1Z0bN/Q9udJnnFoFpENA4252qe/7/5woE5MI=
modernc.org/strutil v1.1.2/go.mod h1:OYajnUAcI/MX+XD/Wx7v1bbdvcQSvxgtb0gC+u3d3eg= modernc.org/strutil v1.1.2/go.mod h1:OYajnUAcI/MX+XD/Wx7v1bbdvcQSvxgtb0gC+u3d3eg=
modernc.org/tcl v1.13.1 h1:npxzTwFTZYM8ghWicVIX1cRWzj7Nd8i6AqqX2p+IYao= modernc.org/tcl v1.13.1 h1:npxzTwFTZYM8ghWicVIX1cRWzj7Nd8i6AqqX2p+IYao=
modernc.org/tcl v1.13.1/go.mod h1:XOLfOwzhkljL4itZkK6T72ckMgvj0BDsnKNdZVUOecw=
modernc.org/token v1.0.0 h1:a0jaWiNMDhDUtqOj09wvjWWAqd3q7WpBulmL9H2egsk= modernc.org/token v1.0.0 h1:a0jaWiNMDhDUtqOj09wvjWWAqd3q7WpBulmL9H2egsk=
modernc.org/token v1.0.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= modernc.org/token v1.0.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
modernc.org/z v1.5.1 h1:RTNHdsrOpeoSeOF4FbzTo8gBYByaJ5xT7NgZ9ZqRiJM= modernc.org/z v1.5.1 h1:RTNHdsrOpeoSeOF4FbzTo8gBYByaJ5xT7NgZ9ZqRiJM=
modernc.org/z v1.5.1/go.mod h1:eWFB510QWW5Th9YGZT81s+LwvaAs3Q2yr4sP0rmLkv8=
nhooyr.io/websocket v1.8.7/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0= nhooyr.io/websocket v1.8.7/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0=
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0=
+4 -4
View File
@@ -3,12 +3,12 @@ package mails
import ( import (
"fmt" "fmt"
"net/mail" "net/mail"
"strings"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/mails/templates" "github.com/pocketbase/pocketbase/mails/templates"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/tokens" "github.com/pocketbase/pocketbase/tokens"
"github.com/pocketbase/pocketbase/tools/rest"
) )
// SendAdminPasswordReset sends a password reset request email to the specified admin. // SendAdminPasswordReset sends a password reset request email to the specified admin.
@@ -18,9 +18,9 @@ func SendAdminPasswordReset(app core.App, admin *models.Admin) error {
return tokenErr return tokenErr
} }
actionUrl, urlErr := normalizeUrl(fmt.Sprintf( actionUrl, urlErr := rest.NormalizeUrl(fmt.Sprintf(
"%s/#/confirm-password-reset/%s", "%s/_/#/confirm-password-reset/%s",
strings.TrimSuffix(app.Settings().Meta.AppUrl, "/"), app.Settings().Meta.AppUrl,
token, token,
)) ))
if urlErr != nil { if urlErr != nil {
+1 -1
View File
@@ -27,7 +27,7 @@ func TestSendAdminPasswordReset(t *testing.T) {
} }
expectedParts := []string{ expectedParts := []string{
"http://localhost:8090/#/confirm-password-reset/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.", "http://localhost:8090/_/#/confirm-password-reset/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.",
} }
for _, part := range expectedParts { for _, part := range expectedParts {
if !strings.Contains(testApp.TestMailer.LastHtmlBody, part) { if !strings.Contains(testApp.TestMailer.LastHtmlBody, part) {
-25
View File
@@ -4,34 +4,9 @@ package mails
import ( import (
"bytes" "bytes"
"net/url"
"path"
"strings"
"text/template" "text/template"
) )
// normalizeUrl removes duplicated slashes from a url path.
func normalizeUrl(originalUrl string) (string, error) {
u, err := url.Parse(originalUrl)
if err != nil {
return "", err
}
hasSlash := strings.HasSuffix(u.Path, "/")
// clean up path by removing duplicated /
u.Path = path.Clean(u.Path)
u.RawPath = path.Clean(u.RawPath)
// restore original trailing slash
if hasSlash && !strings.HasSuffix(u.Path, "/") {
u.Path += "/"
u.RawPath += "/"
}
return u.String(), nil
}
// resolveTemplateContent resolves inline html template strings. // resolveTemplateContent resolves inline html template strings.
func resolveTemplateContent(data any, content ...string) (string, error) { func resolveTemplateContent(data any, content ...string) (string, error) {
if len(content) == 0 { if len(content) == 0 {
+1 -2
View File
@@ -16,8 +16,7 @@ const AdminPasswordResetBody = `
<p>Follow this link to reset your admin password for {{.AppName}}.</p> <p>Follow this link to reset your admin password for {{.AppName}}.</p>
<p> <p>
<a class="btn" href="{{.ActionUrl}}">Reset password</a> <a class="btn" href="{{.ActionUrl}}" target="_blank" rel="noopener">Reset password</a>
<a class="fallback-link" href="{{.ActionUrl}}">{{.ActionUrl}}</a>
</p> </p>
<p><i>If you did not request to reset your password, please ignore this email and the link will expire on its own.</i></p> <p><i>If you did not request to reset your password, please ignore this email and the link will expire on its own.</i></p>
-6
View File
@@ -50,12 +50,6 @@ const Layout = `
.hidden { .hidden {
display: none !important; display: none !important;
} }
.fallback-link {
display: none !important;
word-break: break-all;
font-size: 11px;
color: #666f75;
}
.btn { .btn {
display: inline-block; display: inline-block;
vertical-align: top; vertical-align: top;
@@ -1,26 +0,0 @@
package templates
// Available variables:
//
// ```
// User *models.User
// AppName string
// AppUrl string
// Token string
// ActionUrl string
// ```
const UserConfirmEmailChangeBody = `
{{define "content"}}
<p>Hello,</p>
<p>Click on the button below to confirm your new email address.</p>
<p>
<a class="btn" href="{{.ActionUrl}}">Confirm new email</a>
<a class="fallback-link" href="{{.ActionUrl}}">{{.ActionUrl}}</a>
</p>
<p><i>If you didn’t ask to change your email address, you can ignore this email.</i></p>
<p>
Thanks,<br/>
{{.AppName}} team
</p>
{{end}}
`
-26
View File
@@ -1,26 +0,0 @@
package templates
// Available variables:
//
// ```
// User *models.User
// AppName string
// AppUrl string
// Token string
// ActionUrl string
// ```
const UserPasswordResetBody = `
{{define "content"}}
<p>Hello,</p>
<p>Click on the button below to reset your password.</p>
<p>
<a class="btn" href="{{.ActionUrl}}">Reset password</a>
<a class="fallback-link" href="{{.ActionUrl}}">{{.ActionUrl}}</a>
</p>
<p><i>If you didn’t ask to reset your password, you can ignore this email.</i></p>
<p>
Thanks,<br/>
{{.AppName}} team
</p>
{{end}}
`
-26
View File
@@ -1,26 +0,0 @@
package templates
// Available variables:
//
// ```
// User *models.User
// AppName string
// AppUrl string
// Token string
// ActionUrl string
// ```
const UserVerificationBody = `
{{define "content"}}
<p>Hello,</p>
<p>Thank you for joining us at {{.AppName}}.</p>
<p>Click on the button below to verify your email address.</p>
<p>
<a class="btn" href="{{.ActionUrl}}">Verify</a>
<a class="fallback-link" href="{{.ActionUrl}}">{{.ActionUrl}}</a>
</p>
<p>
Thanks,<br/>
{{.AppName}} team
</p>
{{end}}
`
+46 -71
View File
@@ -1,8 +1,8 @@
package mails package mails
import ( import (
"html/template"
"net/mail" "net/mail"
"strings"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/mails/templates" "github.com/pocketbase/pocketbase/mails/templates"
@@ -10,46 +10,6 @@ import (
"github.com/pocketbase/pocketbase/tokens" "github.com/pocketbase/pocketbase/tokens"
) )
func prepareUserEmailBody(
app core.App,
user *models.User,
token string,
actionUrl string,
bodyTemplate string,
) (string, error) {
settings := app.Settings()
// replace action url placeholder params (if any)
actionUrlParams := map[string]string{
core.EmailPlaceholderAppUrl: settings.Meta.AppUrl,
core.EmailPlaceholderToken: token,
}
for k, v := range actionUrlParams {
actionUrl = strings.ReplaceAll(actionUrl, k, v)
}
var urlErr error
actionUrl, urlErr = normalizeUrl(actionUrl)
if urlErr != nil {
return "", urlErr
}
params := struct {
AppName string
AppUrl string
User *models.User
Token string
ActionUrl string
}{
AppName: settings.Meta.AppName,
AppUrl: settings.Meta.AppUrl,
User: user,
Token: token,
ActionUrl: actionUrl,
}
return resolveTemplateContent(params, templates.Layout, bodyTemplate)
}
// SendUserPasswordReset sends a password reset request email to the specified user. // SendUserPasswordReset sends a password reset request email to the specified user.
func SendUserPasswordReset(app core.App, user *models.User) error { func SendUserPasswordReset(app core.App, user *models.User) error {
token, tokenErr := tokens.NewUserResetPasswordToken(app, user) token, tokenErr := tokens.NewUserResetPasswordToken(app, user)
@@ -66,24 +26,20 @@ func SendUserPasswordReset(app core.App, user *models.User) error {
} }
sendErr := app.OnMailerBeforeUserResetPasswordSend().Trigger(event, func(e *core.MailerUserEvent) error { sendErr := app.OnMailerBeforeUserResetPasswordSend().Trigger(event, func(e *core.MailerUserEvent) error {
body, err := prepareUserEmailBody( settings := app.Settings()
app,
user, subject, body, err := resolveEmailTemplate(app, token, settings.Meta.ResetPasswordTemplate)
token,
app.Settings().Meta.UserResetPasswordUrl,
templates.UserPasswordResetBody,
)
if err != nil { if err != nil {
return err return err
} }
return e.MailClient.Send( return e.MailClient.Send(
mail.Address{ mail.Address{
Name: app.Settings().Meta.SenderName, Name: settings.Meta.SenderName,
Address: app.Settings().Meta.SenderAddress, Address: settings.Meta.SenderAddress,
}, },
mail.Address{Address: e.User.Email}, mail.Address{Address: e.User.Email},
("Reset your " + app.Settings().Meta.AppName + " password"), subject,
body, body,
nil, nil,
) )
@@ -112,24 +68,20 @@ func SendUserVerification(app core.App, user *models.User) error {
} }
sendErr := app.OnMailerBeforeUserVerificationSend().Trigger(event, func(e *core.MailerUserEvent) error { sendErr := app.OnMailerBeforeUserVerificationSend().Trigger(event, func(e *core.MailerUserEvent) error {
body, err := prepareUserEmailBody( settings := app.Settings()
app,
user, subject, body, err := resolveEmailTemplate(app, token, settings.Meta.VerificationTemplate)
token,
app.Settings().Meta.UserVerificationUrl,
templates.UserVerificationBody,
)
if err != nil { if err != nil {
return err return err
} }
return e.MailClient.Send( return e.MailClient.Send(
mail.Address{ mail.Address{
Name: app.Settings().Meta.SenderName, Name: settings.Meta.SenderName,
Address: app.Settings().Meta.SenderAddress, Address: settings.Meta.SenderAddress,
}, },
mail.Address{Address: e.User.Email}, mail.Address{Address: e.User.Email},
("Verify your " + app.Settings().Meta.AppName + " email"), subject,
body, body,
nil, nil,
) )
@@ -161,24 +113,20 @@ func SendUserChangeEmail(app core.App, user *models.User, newEmail string) error
} }
sendErr := app.OnMailerBeforeUserChangeEmailSend().Trigger(event, func(e *core.MailerUserEvent) error { sendErr := app.OnMailerBeforeUserChangeEmailSend().Trigger(event, func(e *core.MailerUserEvent) error {
body, err := prepareUserEmailBody( settings := app.Settings()
app,
user, subject, body, err := resolveEmailTemplate(app, token, settings.Meta.ConfirmEmailChangeTemplate)
token,
app.Settings().Meta.UserConfirmEmailChangeUrl,
templates.UserConfirmEmailChangeBody,
)
if err != nil { if err != nil {
return err return err
} }
return e.MailClient.Send( return e.MailClient.Send(
mail.Address{ mail.Address{
Name: app.Settings().Meta.SenderName, Name: settings.Meta.SenderName,
Address: app.Settings().Meta.SenderAddress, Address: settings.Meta.SenderAddress,
}, },
mail.Address{Address: newEmail}, mail.Address{Address: newEmail},
("Confirm your " + app.Settings().Meta.AppName + " new email address"), subject,
body, body,
nil, nil,
) )
@@ -190,3 +138,30 @@ func SendUserChangeEmail(app core.App, user *models.User, newEmail string) error
return sendErr return sendErr
} }
func resolveEmailTemplate(
app core.App,
token string,
emailTemplate core.EmailTemplate,
) (subject string, body string, err error) {
settings := app.Settings()
subject, rawBody, _ := emailTemplate.Resolve(
settings.Meta.AppName,
settings.Meta.AppUrl,
token,
)
params := struct {
HtmlContent template.HTML
}{
HtmlContent: template.HTML(rawBody),
}
body, err = resolveTemplateContent(params, templates.Layout, templates.HtmlBody)
if err != nil {
return "", "", err
}
return subject, body, nil
}
+3 -3
View File
@@ -27,7 +27,7 @@ func TestSendUserPasswordReset(t *testing.T) {
} }
expectedParts := []string{ expectedParts := []string{
"http://localhost:8090/#/users/confirm-password-reset/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.", "http://localhost:8090/_/#/users/confirm-password-reset/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.",
} }
for _, part := range expectedParts { for _, part := range expectedParts {
if !strings.Contains(testApp.TestMailer.LastHtmlBody, part) { if !strings.Contains(testApp.TestMailer.LastHtmlBody, part) {
@@ -52,7 +52,7 @@ func TestSendUserVerification(t *testing.T) {
} }
expectedParts := []string{ expectedParts := []string{
"http://localhost:8090/#/users/confirm-verification/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.", "http://localhost:8090/_/#/users/confirm-verification/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.",
} }
for _, part := range expectedParts { for _, part := range expectedParts {
if !strings.Contains(testApp.TestMailer.LastHtmlBody, part) { if !strings.Contains(testApp.TestMailer.LastHtmlBody, part) {
@@ -77,7 +77,7 @@ func TestSendUserChangeEmail(t *testing.T) {
} }
expectedParts := []string{ expectedParts := []string{
"http://localhost:8090/#/users/confirm-email-change/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.", "http://localhost:8090/_/#/users/confirm-email-change/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.",
} }
for _, part := range expectedParts { for _, part := range expectedParts {
if !strings.Contains(testApp.TestMailer.LastHtmlBody, part) { if !strings.Contains(testApp.TestMailer.LastHtmlBody, part) {
+5
View File
@@ -96,6 +96,7 @@ func init() {
UpdateRule: &profileOwnerRule, UpdateRule: &profileOwnerRule,
Schema: schema.NewSchema( Schema: schema.NewSchema(
&schema.SchemaField{ &schema.SchemaField{
Id: "pbfielduser",
Name: models.ProfileCollectionUserFieldName, Name: models.ProfileCollectionUserFieldName,
Type: schema.FieldTypeUser, Type: schema.FieldTypeUser,
Unique: true, Unique: true,
@@ -107,11 +108,13 @@ func init() {
}, },
}, },
&schema.SchemaField{ &schema.SchemaField{
Id: "pbfieldname",
Name: "name", Name: "name",
Type: schema.FieldTypeText, Type: schema.FieldTypeText,
Options: &schema.TextOptions{}, Options: &schema.TextOptions{},
}, },
&schema.SchemaField{ &schema.SchemaField{
Id: "pbfieldavatar",
Name: "avatar", Name: "avatar",
Type: schema.FieldTypeFile, Type: schema.FieldTypeFile,
Options: &schema.FileOptions{ Options: &schema.FileOptions{
@@ -128,6 +131,8 @@ func init() {
}, },
), ),
} }
collection.Id = "systemprofiles0"
collection.MarkAsNew()
return daos.New(db).SaveCollection(collection) return daos.New(db).SaveCollection(collection)
}, func(db dbx.Builder) error { }, func(db dbx.Builder) error {
@@ -0,0 +1,57 @@
package logs
import (
"github.com/pocketbase/dbx"
)
func init() {
LogsMigrations.Register(func(db dbx.Builder) error {
// delete old index (don't check for error because of backward compatibility with old installations)
db.DropIndex("_requests", "_request_ip_idx").Execute()
// rename ip -> remoteIp
if _, err := db.RenameColumn("_requests", "ip", "remoteIp").Execute(); err != nil {
return err
}
// add new userIp column
if _, err := db.AddColumn("_requests", "userIp", `TEXT DEFAULT "127.0.0.1" NOT NULL`).Execute(); err != nil {
return err
}
// add new indexes
if _, err := db.CreateIndex("_requests", "_request_remote_ip_idx", "remoteIp").Execute(); err != nil {
return err
}
if _, err := db.CreateIndex("_requests", "_request_user_ip_idx", "userIp").Execute(); err != nil {
return err
}
return nil
}, func(db dbx.Builder) error {
// delete new indexes
if _, err := db.DropIndex("_requests", "_request_remote_ip_idx").Execute(); err != nil {
return err
}
if _, err := db.DropIndex("_requests", "_request_user_ip_idx").Execute(); err != nil {
return err
}
// drop userIp column
if _, err := db.DropColumn("_requests", "userIp").Execute(); err != nil {
return err
}
// restore original remoteIp column name
if _, err := db.RenameColumn("_requests", "remoteIp", "ip").Execute(); err != nil {
return err
}
// restore original index
if _, err := db.CreateIndex("_requests", "_request_ip_idx", "ip").Execute(); err != nil {
return err
}
return nil
})
}
+49 -9
View File
@@ -9,17 +9,35 @@ import (
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
const (
// DefaultIdLength is the default length of the generated model id.
DefaultIdLength = 15
// DefaultIdAlphabet is the default characters set used for generating the model id.
DefaultIdAlphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
)
// ColumnValueMapper defines an interface for custom db model data serialization. // ColumnValueMapper defines an interface for custom db model data serialization.
type ColumnValueMapper interface { type ColumnValueMapper interface {
// ColumnValueMap returns the data to be used when persisting the model. // ColumnValueMap returns the data to be used when persisting the model.
ColumnValueMap() map[string]any ColumnValueMap() map[string]any
} }
// FilesManager defines an interface with common methods that files manager models should implement.
type FilesManager interface {
// BaseFilesPath returns the storage dir path used by the interface instance.
BaseFilesPath() string
}
// Model defines an interface with common methods that all db models should have. // Model defines an interface with common methods that all db models should have.
type Model interface { type Model interface {
TableName() string TableName() string
IsNew() bool
MarkAsNew()
UnmarkAsNew()
HasId() bool HasId() bool
GetId() string GetId() string
SetId(id string)
GetCreated() types.DateTime GetCreated() types.DateTime
GetUpdated() types.DateTime GetUpdated() types.DateTime
RefreshId() RefreshId()
@@ -33,45 +51,67 @@ type Model interface {
// BaseModel defines common fields and methods used by all other models. // BaseModel defines common fields and methods used by all other models.
type BaseModel struct { type BaseModel struct {
isNewFlag bool
Id string `db:"id" json:"id"` Id string `db:"id" json:"id"`
Created types.DateTime `db:"created" json:"created"` Created types.DateTime `db:"created" json:"created"`
Updated types.DateTime `db:"updated" json:"updated"` Updated types.DateTime `db:"updated" json:"updated"`
} }
// HasId returns whether the model has a nonzero primary key (aka. id). // HasId returns whether the model has a nonzero id.
func (m *BaseModel) HasId() bool { func (m *BaseModel) HasId() bool {
return m.GetId() != "" return m.GetId() != ""
} }
// GetId returns the model's id. // GetId returns the model id.
func (m *BaseModel) GetId() string { func (m *BaseModel) GetId() string {
return m.Id return m.Id
} }
// GetCreated returns the model's Created datetime. // SetId sets the model id to the provided string value.
func (m *BaseModel) SetId(id string) {
m.Id = id
}
// MarkAsNew sets the model isNewFlag enforcing [m.IsNew()] to be true.
func (m *BaseModel) MarkAsNew() {
m.isNewFlag = true
}
// UnmarkAsNew resets the model isNewFlag.
func (m *BaseModel) UnmarkAsNew() {
m.isNewFlag = false
}
// IsNew indicates what type of db query (insert or update)
// should be used with the model instance.
func (m *BaseModel) IsNew() bool {
return m.isNewFlag || !m.HasId()
}
// GetCreated returns the model Created datetime.
func (m *BaseModel) GetCreated() types.DateTime { func (m *BaseModel) GetCreated() types.DateTime {
return m.Created return m.Created
} }
// GetUpdated returns the model's Updated datetime. // GetUpdated returns the model Updated datetime.
func (m *BaseModel) GetUpdated() types.DateTime { func (m *BaseModel) GetUpdated() types.DateTime {
return m.Updated return m.Updated
} }
// RefreshId generates and sets a new model id. // RefreshId generates and sets a new model id.
// //
// The generated id is a cryptographically random 15 characters length string // The generated id is a cryptographically random 15 characters length string.
// (could change in the future).
func (m *BaseModel) RefreshId() { func (m *BaseModel) RefreshId() {
m.Id = security.RandomString(15) m.Id = security.RandomStringWithAlphabet(DefaultIdLength, DefaultIdAlphabet)
} }
// RefreshCreated updates the model's Created field with the current datetime. // RefreshCreated updates the model Created field with the current datetime.
func (m *BaseModel) RefreshCreated() { func (m *BaseModel) RefreshCreated() {
m.Created = types.NowDateTime() m.Created = types.NowDateTime()
} }
// RefreshUpdated updates the model's Created field with the current datetime. // RefreshUpdated updates the model Updated field with the current datetime.
func (m *BaseModel) RefreshUpdated() { func (m *BaseModel) RefreshUpdated() {
m.Updated = types.NowDateTime() m.Updated = types.NowDateTime()
} }
+43 -13
View File
@@ -34,25 +34,55 @@ func TestBaseModelHasId(t *testing.T) {
} }
} }
func TestBaseModelGetId(t *testing.T) { func TestBaseModelId(t *testing.T) {
m0 := models.BaseModel{} m := models.BaseModel{}
if m0.GetId() != "" {
t.Fatalf("Expected zero id value, got %v", m0.GetId()) if m.GetId() != "" {
t.Fatalf("Expected empty id value, got %v", m.GetId())
} }
id := "abc" m.SetId("test")
m1 := models.BaseModel{Id: id}
if m1.GetId() != id { if m.GetId() != "test" {
t.Fatalf("Expected id %v, got %v", id, m1.GetId()) t.Fatalf("Expected %q id, got %v", "test", m.GetId())
}
m.RefreshId()
if len(m.GetId()) != 15 {
t.Fatalf("Expected 15 chars id, got %v", m.GetId())
} }
} }
func TestBaseModelRefreshId(t *testing.T) { func TestBaseModelIsNew(t *testing.T) {
m := models.BaseModel{} m0 := models.BaseModel{}
m.RefreshId() m1 := models.BaseModel{Id: ""}
m2 := models.BaseModel{Id: "test"}
m3 := models.BaseModel{}
m3.MarkAsNew()
m4 := models.BaseModel{Id: "test"}
m4.MarkAsNew()
m5 := models.BaseModel{Id: "test"}
m5.MarkAsNew()
m5.UnmarkAsNew()
if m.GetId() == "" { scenarios := []struct {
t.Fatalf("Expected nonempty id value, got %v", m.GetId()) model models.BaseModel
expected bool
}{
{m0, true},
{m1, true},
{m2, false},
{m3, true},
{m4, true},
{m5, false},
}
for i, s := range scenarios {
result := s.model.IsNew()
if result != s.expected {
t.Errorf("(%d) Expected IsNew %v, got %v", i, s.expected, result)
}
} }
} }
+1
View File
@@ -3,6 +3,7 @@ package models
import "github.com/pocketbase/pocketbase/models/schema" import "github.com/pocketbase/pocketbase/models/schema"
var _ Model = (*Collection)(nil) var _ Model = (*Collection)(nil)
var _ FilesManager = (*Collection)(nil)
type Collection struct { type Collection struct {
BaseModel BaseModel
+4 -3
View File
@@ -16,6 +16,7 @@ import (
var _ Model = (*Record)(nil) var _ Model = (*Record)(nil)
var _ ColumnValueMapper = (*Record)(nil) var _ ColumnValueMapper = (*Record)(nil)
var _ FilesManager = (*Record)(nil)
type Record struct { type Record struct {
BaseModel BaseModel
@@ -68,10 +69,10 @@ func NewRecordFromNullStringMap(collection *Collection, data dbx.NullStringMap)
// NewRecordsFromNullStringMaps initializes a new Record model for // NewRecordsFromNullStringMaps initializes a new Record model for
// each row in the provided NullStringMap slice. // each row in the provided NullStringMap slice.
func NewRecordsFromNullStringMaps(collection *Collection, rows []dbx.NullStringMap) []*Record { func NewRecordsFromNullStringMaps(collection *Collection, rows []dbx.NullStringMap) []*Record {
result := []*Record{} result := make([]*Record, len(rows))
for _, row := range rows { for i, row := range rows {
result = append(result, NewRecordFromNullStringMap(collection, row)) result[i] = NewRecordFromNullStringMap(collection, row)
} }
return result return result
+3 -3
View File
@@ -118,7 +118,7 @@ func TestNewRecordFromNullStringMap(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
expected := `{"@collectionId":"","@collectionName":"test","created":"2022-01-01 10:00:00.123","field1":"test","field2":null,"field3":true,"field4":123.123,"field5":"test1","field6":["test"],"id":"c23eb053-d07e-4fbe-86b3-b8ac31982e9a","updated":"2022-01-01 10:00:00.456"}` expected := `{"@collectionId":"","@collectionName":"test","created":"2022-01-01 10:00:00.123","field1":"test","field2":"","field3":true,"field4":123.123,"field5":"test1","field6":["test"],"id":"c23eb053-d07e-4fbe-86b3-b8ac31982e9a","updated":"2022-01-01 10:00:00.456"}`
if string(encoded) != expected { if string(encoded) != expected {
t.Fatalf("Expected %v, got \n%v", expected, string(encoded)) t.Fatalf("Expected %v, got \n%v", expected, string(encoded))
@@ -185,10 +185,10 @@ func TestNewRecordsFromNullStringMaps(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
expected := `[{"@collectionId":"","@collectionName":"test","created":"2022-01-01 10:00:00.123","field1":"test1","field2":null,"id":"11111111-d07e-4fbe-86b3-b8ac31982e9a","updated":"2022-01-01 10:00:00.456"},{"@collectionId":"","@collectionName":"test","created":"","field1":"test2","field2":123,"id":"22222222-d07e-4fbe-86b3-b8ac31982e9a","updated":""}]` expected := `[{"@collectionId":"","@collectionName":"test","created":"2022-01-01 10:00:00.123","field1":"test1","field2":0,"id":"11111111-d07e-4fbe-86b3-b8ac31982e9a","updated":"2022-01-01 10:00:00.456"},{"@collectionId":"","@collectionName":"test","created":"","field1":"test2","field2":123,"id":"22222222-d07e-4fbe-86b3-b8ac31982e9a","updated":""}]`
if string(encoded) != expected { if string(encoded) != expected {
t.Fatalf("Expected %v, got \n%v", expected, string(encoded)) t.Fatalf("Expected \n%v, got \n%v", expected, string(encoded))
} }
} }
+2 -1
View File
@@ -18,7 +18,8 @@ type Request struct {
Method string `db:"method" json:"method"` Method string `db:"method" json:"method"`
Status int `db:"status" json:"status"` Status int `db:"status" json:"status"`
Auth string `db:"auth" json:"auth"` Auth string `db:"auth" json:"auth"`
Ip string `db:"ip" json:"ip"` UserIp string `db:"userIp" json:"userIp"`
RemoteIp string `db:"remoteIp" json:"remoteIp"`
Referer string `db:"referer" json:"referer"` Referer string `db:"referer" json:"referer"`
UserAgent string `db:"userAgent" json:"userAgent"` UserAgent string `db:"userAgent" json:"userAgent"`
Meta types.JsonMap `db:"meta" json:"meta"` Meta types.JsonMap `db:"meta" json:"meta"`
+18 -26
View File
@@ -7,6 +7,7 @@ import (
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is" "github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/pocketbase/pocketbase/tools/list" "github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/types" "github.com/pocketbase/pocketbase/tools/types"
"github.com/spf13/cast" "github.com/spf13/cast"
@@ -218,31 +219,19 @@ func (f *SchemaField) PrepareValue(value any) any {
f.InitOptions() f.InitOptions()
switch f.Type { switch f.Type {
case FieldTypeText, FieldTypeEmail, FieldTypeUrl: // string case FieldTypeText, FieldTypeEmail, FieldTypeUrl:
if value == nil {
return nil
}
return cast.ToString(value) return cast.ToString(value)
case FieldTypeJson: // string case FieldTypeJson:
if value == nil {
return nil
}
val, _ := types.ParseJsonRaw(value) val, _ := types.ParseJsonRaw(value)
return val return val
case FieldTypeNumber: // nil, int or float case FieldTypeNumber:
if value == nil {
return nil
}
return cast.ToFloat64(value) return cast.ToFloat64(value)
case FieldTypeBool: // bool case FieldTypeBool:
return cast.ToBool(value) return cast.ToBool(value)
case FieldTypeDate: // string, DateTime or time.Time case FieldTypeDate:
if value == nil {
return nil
}
val, _ := types.ParseDateTime(value) val, _ := types.ParseDateTime(value)
return val return val
case FieldTypeSelect: // nil, string or slice of strings case FieldTypeSelect:
val := list.ToUniqueStringSlice(value) val := list.ToUniqueStringSlice(value)
options, _ := f.Options.(*SelectOptions) options, _ := f.Options.(*SelectOptions)
@@ -250,11 +239,11 @@ func (f *SchemaField) PrepareValue(value any) any {
if len(val) > 0 { if len(val) > 0 {
return val[0] return val[0]
} }
return nil return ""
} }
return val return val
case FieldTypeFile: // nil, string or slice of strings case FieldTypeFile:
val := list.ToUniqueStringSlice(value) val := list.ToUniqueStringSlice(value)
options, _ := f.Options.(*FileOptions) options, _ := f.Options.(*FileOptions)
@@ -262,11 +251,11 @@ func (f *SchemaField) PrepareValue(value any) any {
if len(val) > 0 { if len(val) > 0 {
return val[0] return val[0]
} }
return nil return ""
} }
return val return val
case FieldTypeRelation: // nil, string or slice of strings case FieldTypeRelation:
ids := list.ToUniqueStringSlice(value) ids := list.ToUniqueStringSlice(value)
options, _ := f.Options.(*RelationOptions) options, _ := f.Options.(*RelationOptions)
@@ -274,11 +263,11 @@ func (f *SchemaField) PrepareValue(value any) any {
if len(ids) > 0 { if len(ids) > 0 {
return ids[0] return ids[0]
} }
return nil return ""
} }
return ids return ids
case FieldTypeUser: // nil, string or slice of strings case FieldTypeUser:
ids := list.ToUniqueStringSlice(value) ids := list.ToUniqueStringSlice(value)
options, _ := f.Options.(*UserOptions) options, _ := f.Options.(*UserOptions)
@@ -286,7 +275,7 @@ func (f *SchemaField) PrepareValue(value any) any {
if len(ids) > 0 { if len(ids) > 0 {
return ids[0] return ids[0]
} }
return nil return ""
} }
return ids return ids
@@ -470,7 +459,10 @@ func (o FileOptions) Validate() error {
return validation.ValidateStruct(&o, return validation.ValidateStruct(&o,
validation.Field(&o.MaxSelect, validation.Required, validation.Min(1)), validation.Field(&o.MaxSelect, validation.Required, validation.Min(1)),
validation.Field(&o.MaxSize, validation.Required, validation.Min(1)), validation.Field(&o.MaxSize, validation.Required, validation.Min(1)),
validation.Field(&o.Thumbs, validation.Each(validation.Match(regexp.MustCompile(`^[1-9]\d*x[1-9]\d*$`)))), validation.Field(&o.Thumbs, validation.Each(
validation.NotIn("0x0", "0x0t", "0x0b", "0x0f"),
validation.Match(filesystem.ThumbSizeRegex),
)),
) )
} }
+26 -34
View File
@@ -498,19 +498,22 @@ func TestSchemaFieldPrepareValue(t *testing.T) {
{schema.SchemaField{Type: "unknown"}, []int{1, 2, 1}, "[1,2,1]"}, {schema.SchemaField{Type: "unknown"}, []int{1, 2, 1}, "[1,2,1]"},
// text // text
{schema.SchemaField{Type: schema.FieldTypeText}, nil, `null`}, {schema.SchemaField{Type: schema.FieldTypeText}, nil, `""`},
{schema.SchemaField{Type: schema.FieldTypeText}, "", `""`},
{schema.SchemaField{Type: schema.FieldTypeText}, []int{1, 2}, `""`}, {schema.SchemaField{Type: schema.FieldTypeText}, []int{1, 2}, `""`},
{schema.SchemaField{Type: schema.FieldTypeText}, "test", `"test"`}, {schema.SchemaField{Type: schema.FieldTypeText}, "test", `"test"`},
{schema.SchemaField{Type: schema.FieldTypeText}, 123, `"123"`}, {schema.SchemaField{Type: schema.FieldTypeText}, 123, `"123"`},
// email // email
{schema.SchemaField{Type: schema.FieldTypeEmail}, nil, `null`}, {schema.SchemaField{Type: schema.FieldTypeEmail}, nil, `""`},
{schema.SchemaField{Type: schema.FieldTypeEmail}, "", `""`},
{schema.SchemaField{Type: schema.FieldTypeEmail}, []int{1, 2}, `""`}, {schema.SchemaField{Type: schema.FieldTypeEmail}, []int{1, 2}, `""`},
{schema.SchemaField{Type: schema.FieldTypeEmail}, "test", `"test"`}, {schema.SchemaField{Type: schema.FieldTypeEmail}, "test", `"test"`},
{schema.SchemaField{Type: schema.FieldTypeEmail}, 123, `"123"`}, {schema.SchemaField{Type: schema.FieldTypeEmail}, 123, `"123"`},
// url // url
{schema.SchemaField{Type: schema.FieldTypeUrl}, nil, `null`}, {schema.SchemaField{Type: schema.FieldTypeUrl}, nil, `""`},
{schema.SchemaField{Type: schema.FieldTypeUrl}, "", `""`},
{schema.SchemaField{Type: schema.FieldTypeUrl}, []int{1, 2}, `""`}, {schema.SchemaField{Type: schema.FieldTypeUrl}, []int{1, 2}, `""`},
{schema.SchemaField{Type: schema.FieldTypeUrl}, "test", `"test"`}, {schema.SchemaField{Type: schema.FieldTypeUrl}, "test", `"test"`},
{schema.SchemaField{Type: schema.FieldTypeUrl}, 123, `"123"`}, {schema.SchemaField{Type: schema.FieldTypeUrl}, 123, `"123"`},
@@ -523,7 +526,9 @@ func TestSchemaFieldPrepareValue(t *testing.T) {
{schema.SchemaField{Type: schema.FieldTypeJson}, []int{1, 2, 1}, `[1,2,1]`}, {schema.SchemaField{Type: schema.FieldTypeJson}, []int{1, 2, 1}, `[1,2,1]`},
// number // number
{schema.SchemaField{Type: schema.FieldTypeNumber}, nil, "null"}, {schema.SchemaField{Type: schema.FieldTypeNumber}, nil, "0"},
{schema.SchemaField{Type: schema.FieldTypeNumber}, "", "0"},
{schema.SchemaField{Type: schema.FieldTypeNumber}, "test", "0"},
{schema.SchemaField{Type: schema.FieldTypeNumber}, 1, "1"}, {schema.SchemaField{Type: schema.FieldTypeNumber}, 1, "1"},
{schema.SchemaField{Type: schema.FieldTypeNumber}, 1.5, "1.5"}, {schema.SchemaField{Type: schema.FieldTypeNumber}, 1.5, "1.5"},
{schema.SchemaField{Type: schema.FieldTypeNumber}, "1.5", "1.5"}, {schema.SchemaField{Type: schema.FieldTypeNumber}, "1.5", "1.5"},
@@ -533,22 +538,24 @@ func TestSchemaFieldPrepareValue(t *testing.T) {
{schema.SchemaField{Type: schema.FieldTypeBool}, 1, "true"}, {schema.SchemaField{Type: schema.FieldTypeBool}, 1, "true"},
{schema.SchemaField{Type: schema.FieldTypeBool}, 0, "false"}, {schema.SchemaField{Type: schema.FieldTypeBool}, 0, "false"},
{schema.SchemaField{Type: schema.FieldTypeBool}, "", "false"}, {schema.SchemaField{Type: schema.FieldTypeBool}, "", "false"},
{schema.SchemaField{Type: schema.FieldTypeBool}, "test", "false"},
{schema.SchemaField{Type: schema.FieldTypeBool}, "false", "false"}, {schema.SchemaField{Type: schema.FieldTypeBool}, "false", "false"},
{schema.SchemaField{Type: schema.FieldTypeBool}, "true", "true"}, {schema.SchemaField{Type: schema.FieldTypeBool}, "true", "true"},
{schema.SchemaField{Type: schema.FieldTypeBool}, false, "false"}, {schema.SchemaField{Type: schema.FieldTypeBool}, false, "false"},
{schema.SchemaField{Type: schema.FieldTypeBool}, true, "true"}, {schema.SchemaField{Type: schema.FieldTypeBool}, true, "true"},
// date // date
{schema.SchemaField{Type: schema.FieldTypeDate}, nil, "null"}, {schema.SchemaField{Type: schema.FieldTypeDate}, nil, `""`},
{schema.SchemaField{Type: schema.FieldTypeDate}, "", `""`}, {schema.SchemaField{Type: schema.FieldTypeDate}, "", `""`},
{schema.SchemaField{Type: schema.FieldTypeDate}, "test", `""`},
{schema.SchemaField{Type: schema.FieldTypeDate}, 1641024040, `"2022-01-01 08:00:40.000"`}, {schema.SchemaField{Type: schema.FieldTypeDate}, 1641024040, `"2022-01-01 08:00:40.000"`},
{schema.SchemaField{Type: schema.FieldTypeDate}, "2022-01-01 11:27:10.123", `"2022-01-01 11:27:10.123"`}, {schema.SchemaField{Type: schema.FieldTypeDate}, "2022-01-01 11:27:10.123", `"2022-01-01 11:27:10.123"`},
{schema.SchemaField{Type: schema.FieldTypeDate}, types.DateTime{}, `""`}, {schema.SchemaField{Type: schema.FieldTypeDate}, types.DateTime{}, `""`},
{schema.SchemaField{Type: schema.FieldTypeDate}, time.Time{}, `""`}, {schema.SchemaField{Type: schema.FieldTypeDate}, time.Time{}, `""`},
// select (single) // select (single)
{schema.SchemaField{Type: schema.FieldTypeSelect}, nil, `null`}, {schema.SchemaField{Type: schema.FieldTypeSelect}, nil, `""`},
{schema.SchemaField{Type: schema.FieldTypeSelect}, "", `null`}, {schema.SchemaField{Type: schema.FieldTypeSelect}, "", `""`},
{schema.SchemaField{Type: schema.FieldTypeSelect}, 123, `"123"`}, {schema.SchemaField{Type: schema.FieldTypeSelect}, 123, `"123"`},
{schema.SchemaField{Type: schema.FieldTypeSelect}, "test", `"test"`}, {schema.SchemaField{Type: schema.FieldTypeSelect}, "test", `"test"`},
{schema.SchemaField{Type: schema.FieldTypeSelect}, []string{"test1", "test2"}, `"test1"`}, {schema.SchemaField{Type: schema.FieldTypeSelect}, []string{"test1", "test2"}, `"test1"`},
@@ -624,8 +631,8 @@ func TestSchemaFieldPrepareValue(t *testing.T) {
}, },
// file (single) // file (single)
{schema.SchemaField{Type: schema.FieldTypeFile}, nil, `null`}, {schema.SchemaField{Type: schema.FieldTypeFile}, nil, `""`},
{schema.SchemaField{Type: schema.FieldTypeFile}, "", `null`}, {schema.SchemaField{Type: schema.FieldTypeFile}, "", `""`},
{schema.SchemaField{Type: schema.FieldTypeFile}, 123, `"123"`}, {schema.SchemaField{Type: schema.FieldTypeFile}, 123, `"123"`},
{schema.SchemaField{Type: schema.FieldTypeFile}, "test", `"test"`}, {schema.SchemaField{Type: schema.FieldTypeFile}, "test", `"test"`},
{schema.SchemaField{Type: schema.FieldTypeFile}, []string{"test1", "test2"}, `"test1"`}, {schema.SchemaField{Type: schema.FieldTypeFile}, []string{"test1", "test2"}, `"test1"`},
@@ -690,8 +697,8 @@ func TestSchemaFieldPrepareValue(t *testing.T) {
}, },
// relation (single) // relation (single)
{schema.SchemaField{Type: schema.FieldTypeRelation}, nil, `null`}, {schema.SchemaField{Type: schema.FieldTypeRelation}, nil, `""`},
{schema.SchemaField{Type: schema.FieldTypeRelation}, "", `null`}, {schema.SchemaField{Type: schema.FieldTypeRelation}, "", `""`},
{schema.SchemaField{Type: schema.FieldTypeRelation}, 123, `"123"`}, {schema.SchemaField{Type: schema.FieldTypeRelation}, 123, `"123"`},
{schema.SchemaField{Type: schema.FieldTypeRelation}, "abc", `"abc"`}, {schema.SchemaField{Type: schema.FieldTypeRelation}, "abc", `"abc"`},
{schema.SchemaField{Type: schema.FieldTypeRelation}, "1ba88b4f-e9da-42f0-9764-9a55c953e724", `"1ba88b4f-e9da-42f0-9764-9a55c953e724"`}, {schema.SchemaField{Type: schema.FieldTypeRelation}, "1ba88b4f-e9da-42f0-9764-9a55c953e724", `"1ba88b4f-e9da-42f0-9764-9a55c953e724"`},
@@ -761,8 +768,8 @@ func TestSchemaFieldPrepareValue(t *testing.T) {
}, },
// user (single) // user (single)
{schema.SchemaField{Type: schema.FieldTypeUser}, nil, `null`}, {schema.SchemaField{Type: schema.FieldTypeUser}, nil, `""`},
{schema.SchemaField{Type: schema.FieldTypeUser}, "", `null`}, {schema.SchemaField{Type: schema.FieldTypeUser}, "", `""`},
{schema.SchemaField{Type: schema.FieldTypeUser}, 123, `"123"`}, {schema.SchemaField{Type: schema.FieldTypeUser}, 123, `"123"`},
{schema.SchemaField{Type: schema.FieldTypeUser}, "1ba88b4f-e9da-42f0-9764-9a55c953e724", `"1ba88b4f-e9da-42f0-9764-9a55c953e724"`}, {schema.SchemaField{Type: schema.FieldTypeUser}, "1ba88b4f-e9da-42f0-9764-9a55c953e724", `"1ba88b4f-e9da-42f0-9764-9a55c953e724"`},
{ {
@@ -1240,29 +1247,11 @@ func TestFileOptionsValidate(t *testing.T) {
[]string{"thumbs"}, []string{"thumbs"},
}, },
{ {
"invalid thumbs format - zero width", "invalid thumbs format - zero width and height",
schema.FileOptions{ schema.FileOptions{
MaxSize: 1, MaxSize: 1,
MaxSelect: 2, MaxSelect: 2,
Thumbs: []string{"0x100"}, Thumbs: []string{"0x0", "0x0t", "0x0b", "0x0f"},
},
[]string{"thumbs"},
},
{
"invalid thumbs format - zero height",
schema.FileOptions{
MaxSize: 1,
MaxSelect: 2,
Thumbs: []string{"100x0"},
},
[]string{"thumbs"},
},
{
"invalid thumbs format - zero with and height",
schema.FileOptions{
MaxSize: 1,
MaxSelect: 2,
Thumbs: []string{"0x0"},
}, },
[]string{"thumbs"}, []string{"thumbs"},
}, },
@@ -1271,7 +1260,10 @@ func TestFileOptionsValidate(t *testing.T) {
schema.FileOptions{ schema.FileOptions{
MaxSize: 1, MaxSize: 1,
MaxSelect: 2, MaxSelect: 2,
Thumbs: []string{"100x100", "200x100", "1x1"}, Thumbs: []string{
"100x100", "200x100", "0x100", "100x0",
"10x10t", "10x10b", "10x10f",
},
}, },
[]string{}, []string{},
}, },
Loaded 100 of 269 files, more files were not shown because too many files have changed in this diff. Show more