repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/event_request_test.go | core/event_request_test.go | package core_test
import (
"encoding/json"
"net/http"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestEventRequestRealIP(t *testing.T) {
t.Parallel()
headers := map[string][]string{
"CF-Connecting-IP": {"1.2.3.4", "1.1.1.1"},
"Fly-Client-IP": {"1.2.3.4", "1.1.1.2"},
"X-Real-IP": {"1.2.3.4", "1.1.1.3,1.1.1.4"},
"X-Forwarded-For": {"1.2.3.4", "invalid,1.1.1.5,1.1.1.6,invalid"},
}
scenarios := []struct {
name string
headers map[string][]string
trustedHeaders []string
useLeftmostIP bool
expected string
}{
{
"no trusted headers",
headers,
nil,
false,
"127.0.0.1",
},
{
"non-matching trusted header",
headers,
[]string{"header1", "header2"},
false,
"127.0.0.1",
},
{
"trusted X-Real-IP (rightmost)",
headers,
[]string{"header1", "x-real-ip", "x-forwarded-for"},
false,
"1.1.1.4",
},
{
"trusted X-Real-IP (leftmost)",
headers,
[]string{"header1", "x-real-ip", "x-forwarded-for"},
true,
"1.1.1.3",
},
{
"trusted X-Forwarded-For (rightmost)",
headers,
[]string{"header1", "x-forwarded-for"},
false,
"1.1.1.6",
},
{
"trusted X-Forwarded-For (leftmost)",
headers,
[]string{"header1", "x-forwarded-for"},
true,
"1.1.1.5",
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
app, err := tests.NewTestApp()
if err != nil {
t.Fatal(err)
}
defer app.Cleanup()
app.Settings().TrustedProxy.Headers = s.trustedHeaders
app.Settings().TrustedProxy.UseLeftmostIP = s.useLeftmostIP
event := core.RequestEvent{}
event.App = app
event.Request, err = http.NewRequest(http.MethodGet, "/", nil)
if err != nil {
t.Fatal(err)
}
event.Request.RemoteAddr = "127.0.0.1:80" // fallback
for k, values := range s.headers {
for _, v := range values {
event.Request.Header.Add(k, v)
}
}
result := event.RealIP()
if result != s.expected {
t.Fatalf("Expected ip %q, got %q", s.expected, result)
}
})
}
}
func TestEventRequestHasSuperUserAuth(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
superuser, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test@example.com")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
record *core.Record
expected bool
}{
{"nil record", nil, false},
{"regular user record", user, false},
{"superuser record", superuser, true},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
e := core.RequestEvent{}
e.Auth = s.record
result := e.HasSuperuserAuth()
if result != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, result)
}
})
}
}
func TestRequestEventRequestInfo(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
userCol, err := app.FindCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
user1 := core.NewRecord(userCol)
user1.Id = "user1"
user1.SetEmail("test1@example.com")
user2 := core.NewRecord(userCol)
user2.Id = "user2"
user2.SetEmail("test2@example.com")
testBody := `{"a":123,"b":"test"}`
event := core.RequestEvent{}
event.Request, err = http.NewRequest("POST", "/test?q1=123&q2=456", strings.NewReader(testBody))
if err != nil {
t.Fatal(err)
}
event.Request.Header.Add("content-type", "application/json")
event.Request.Header.Add("x-test", "test")
event.Set(core.RequestEventKeyInfoContext, "test")
event.Auth = user1
t.Run("init", func(t *testing.T) {
info, err := event.RequestInfo()
if err != nil {
t.Fatalf("Failed to resolve request info: %v", err)
}
raw, err := json.Marshal(info)
if err != nil {
t.Fatalf("Failed to serialize request info: %v", err)
}
rawStr := string(raw)
expected := `{"query":{"q1":"123","q2":"456"},"headers":{"content_type":"application/json","x_test":"test"},"body":{"a":123,"b":"test"},"auth":{"avatar":"","collectionId":"_pb_users_auth_","collectionName":"users","created":"","emailVisibility":false,"file":[],"id":"user1","name":"","rel":"","updated":"","username":"","verified":false},"method":"POST","context":"test"}`
if expected != rawStr {
t.Fatalf("Expected\n%v\ngot\n%v", expected, rawStr)
}
})
t.Run("change user and context", func(t *testing.T) {
event.Set(core.RequestEventKeyInfoContext, "test2")
event.Auth = user2
info, err := event.RequestInfo()
if err != nil {
t.Fatalf("Failed to resolve request info: %v", err)
}
raw, err := json.Marshal(info)
if err != nil {
t.Fatalf("Failed to serialize request info: %v", err)
}
rawStr := string(raw)
expected := `{"query":{"q1":"123","q2":"456"},"headers":{"content_type":"application/json","x_test":"test"},"body":{"a":123,"b":"test"},"auth":{"avatar":"","collectionId":"_pb_users_auth_","collectionName":"users","created":"","emailVisibility":false,"file":[],"id":"user2","name":"","rel":"","updated":"","username":"","verified":false},"method":"POST","context":"test2"}`
if expected != rawStr {
t.Fatalf("Expected\n%v\ngot\n%v", expected, rawStr)
}
})
}
func TestRequestInfoHasSuperuserAuth(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
superuser, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test@example.com")
if err != nil {
t.Fatal(err)
}
event := core.RequestEvent{}
event.Request, err = http.NewRequest("POST", "/test?q1=123&q2=456", strings.NewReader(`{"a":123,"b":"test"}`))
if err != nil {
t.Fatal(err)
}
event.Request.Header.Add("content-type", "application/json")
scenarios := []struct {
name string
record *core.Record
expected bool
}{
{"nil record", nil, false},
{"regular user record", user, false},
{"superuser record", superuser, true},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
event.Auth = s.record
info, err := event.RequestInfo()
if err != nil {
t.Fatalf("Failed to resolve request info: %v", err)
}
result := info.HasSuperuserAuth()
if result != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, result)
}
})
}
}
func TestRequestInfoClone(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
userCol, err := app.FindCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
user := core.NewRecord(userCol)
user.Id = "user1"
user.SetEmail("test1@example.com")
event := core.RequestEvent{}
event.Request, err = http.NewRequest("POST", "/test?q1=123&q2=456", strings.NewReader(`{"a":123,"b":"test"}`))
if err != nil {
t.Fatal(err)
}
event.Request.Header.Add("content-type", "application/json")
event.Auth = user
info, err := event.RequestInfo()
if err != nil {
t.Fatalf("Failed to resolve request info: %v", err)
}
clone := info.Clone()
// modify the clone fields to ensure that it is a shallow copy
clone.Headers["new_header"] = "test"
clone.Query["new_query"] = "test"
clone.Body["new_body"] = "test"
clone.Auth.Id = "user2" // should be a Fresh copy of the record
// check the original data
// ---
originalRaw, err := json.Marshal(info)
if err != nil {
t.Fatalf("Failed to serialize original request info: %v", err)
}
originalRawStr := string(originalRaw)
expectedRawStr := `{"query":{"q1":"123","q2":"456"},"headers":{"content_type":"application/json"},"body":{"a":123,"b":"test"},"auth":{"avatar":"","collectionId":"_pb_users_auth_","collectionName":"users","created":"","emailVisibility":false,"file":[],"id":"user1","name":"","rel":"","updated":"","username":"","verified":false},"method":"POST","context":"default"}`
if expectedRawStr != originalRawStr {
t.Fatalf("Expected original info\n%v\ngot\n%v", expectedRawStr, originalRawStr)
}
// check the clone data
// ---
cloneRaw, err := json.Marshal(clone)
if err != nil {
t.Fatalf("Failed to serialize clone request info: %v", err)
}
cloneRawStr := string(cloneRaw)
expectedCloneStr := `{"query":{"new_query":"test","q1":"123","q2":"456"},"headers":{"content_type":"application/json","new_header":"test"},"body":{"a":123,"b":"test","new_body":"test"},"auth":{"avatar":"","collectionId":"_pb_users_auth_","collectionName":"users","created":"","emailVisibility":false,"file":[],"id":"user2","name":"","rel":"","updated":"","username":"","verified":false},"method":"POST","context":"default"}`
if expectedCloneStr != cloneRawStr {
t.Fatalf("Expected clone info\n%v\ngot\n%v", expectedCloneStr, cloneRawStr)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/log_query_test.go | core/log_query_test.go | package core_test
import (
"encoding/json"
"fmt"
"testing"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestFindLogById(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
tests.StubLogsData(app)
scenarios := []struct {
id string
expectError bool
}{
{"", true},
{"invalid", true},
{"00000000-9f38-44fb-bf82-c8f53b310d91", true},
{"873f2133-9f38-44fb-bf82-c8f53b310d91", false},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.id), func(t *testing.T) {
log, err := app.FindLogById(s.id)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
if log != nil && log.Id != s.id {
t.Fatalf("Expected log with id %q, got %q", s.id, log.Id)
}
})
}
}
func TestLogsStats(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
tests.StubLogsData(app)
expected := `[{"date":"2022-05-01 10:00:00.000Z","total":1},{"date":"2022-05-02 10:00:00.000Z","total":1}]`
now := time.Now().UTC().Format(types.DefaultDateLayout)
exp := dbx.NewExp("[[created]] <= {:date}", dbx.Params{"date": now})
result, err := app.LogsStats(exp)
if err != nil {
t.Fatal(err)
}
encoded, _ := json.Marshal(result)
if string(encoded) != expected {
t.Fatalf("Expected\n%q\ngot\n%q", expected, string(encoded))
}
}
func TestDeleteOldLogs(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
tests.StubLogsData(app)
scenarios := []struct {
date string
expectedTotal int
}{
{"2022-01-01 10:00:00.000Z", 2}, // no logs to delete before that time
{"2022-05-01 11:00:00.000Z", 1}, // only 1 log should have left
{"2022-05-03 11:00:00.000Z", 0}, // no more logs should have left
{"2022-05-04 11:00:00.000Z", 0}, // no more logs should have left
}
for _, s := range scenarios {
t.Run(s.date, func(t *testing.T) {
date, dateErr := time.Parse(types.DefaultDateLayout, s.date)
if dateErr != nil {
t.Fatalf("Date error %v", dateErr)
}
deleteErr := app.DeleteOldLogs(date)
if deleteErr != nil {
t.Fatalf("Delete error %v", deleteErr)
}
// check total remaining logs
var total int
countErr := app.AuxModelQuery(&core.Log{}).Select("count(*)").Row(&total)
if countErr != nil {
t.Errorf("Count error %v", countErr)
}
if total != s.expectedTotal {
t.Errorf("Expected %d remaining logs, got %d", s.expectedTotal, total)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/collection_model_auth_options.go | core/collection_model_auth_options.go | package core
import (
"strconv"
"strings"
"time"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/tools/auth"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/pocketbase/pocketbase/tools/types"
"github.com/spf13/cast"
)
func (m *Collection) unsetMissingOAuth2MappedFields() {
if !m.IsAuth() {
return
}
if m.OAuth2.MappedFields.Id != "" {
if m.Fields.GetByName(m.OAuth2.MappedFields.Id) == nil {
m.OAuth2.MappedFields.Id = ""
}
}
if m.OAuth2.MappedFields.Name != "" {
if m.Fields.GetByName(m.OAuth2.MappedFields.Name) == nil {
m.OAuth2.MappedFields.Name = ""
}
}
if m.OAuth2.MappedFields.Username != "" {
if m.Fields.GetByName(m.OAuth2.MappedFields.Username) == nil {
m.OAuth2.MappedFields.Username = ""
}
}
if m.OAuth2.MappedFields.AvatarURL != "" {
if m.Fields.GetByName(m.OAuth2.MappedFields.AvatarURL) == nil {
m.OAuth2.MappedFields.AvatarURL = ""
}
}
}
func (m *Collection) setDefaultAuthOptions() {
m.collectionAuthOptions = collectionAuthOptions{
VerificationTemplate: defaultVerificationTemplate,
ResetPasswordTemplate: defaultResetPasswordTemplate,
ConfirmEmailChangeTemplate: defaultConfirmEmailChangeTemplate,
AuthRule: types.Pointer(""),
AuthAlert: AuthAlertConfig{
Enabled: true,
EmailTemplate: defaultAuthAlertTemplate,
},
PasswordAuth: PasswordAuthConfig{
Enabled: true,
IdentityFields: []string{FieldNameEmail},
},
MFA: MFAConfig{
Enabled: false,
Duration: 1800, // 30min
},
OTP: OTPConfig{
Enabled: false,
Duration: 180, // 3min
Length: 8,
EmailTemplate: defaultOTPTemplate,
},
AuthToken: TokenConfig{
Secret: security.RandomString(50),
Duration: 604800, // 7 days
},
PasswordResetToken: TokenConfig{
Secret: security.RandomString(50),
Duration: 1800, // 30min
},
EmailChangeToken: TokenConfig{
Secret: security.RandomString(50),
Duration: 1800, // 30min
},
VerificationToken: TokenConfig{
Secret: security.RandomString(50),
Duration: 259200, // 3days
},
FileToken: TokenConfig{
Secret: security.RandomString(50),
Duration: 180, // 3min
},
}
}
var _ optionsValidator = (*collectionAuthOptions)(nil)
// collectionAuthOptions defines the options for the "auth" type collection.
type collectionAuthOptions struct {
// AuthRule could be used to specify additional record constraints
// applied after record authentication and right before returning the
// auth token response to the client.
//
// For example, to allow only verified users you could set it to
// "verified = true".
//
// Set it to empty string to allow any Auth collection record to authenticate.
//
// Set it to nil to disallow authentication altogether for the collection
// (that includes password, OAuth2, etc.).
AuthRule *string `form:"authRule" json:"authRule"`
// ManageRule gives admin-like permissions to allow fully managing
// the auth record(s), eg. changing the password without requiring
// to enter the old one, directly updating the verified state and email, etc.
//
// This rule is executed in addition to the Create and Update API rules.
ManageRule *string `form:"manageRule" json:"manageRule"`
// AuthAlert defines options related to the auth alerts on new device login.
AuthAlert AuthAlertConfig `form:"authAlert" json:"authAlert"`
// OAuth2 specifies whether OAuth2 auth is enabled for the collection
// and which OAuth2 providers are allowed.
OAuth2 OAuth2Config `form:"oauth2" json:"oauth2"`
// PasswordAuth defines options related to the collection password authentication.
PasswordAuth PasswordAuthConfig `form:"passwordAuth" json:"passwordAuth"`
// MFA defines options related to the Multi-factor authentication (MFA).
MFA MFAConfig `form:"mfa" json:"mfa"`
// OTP defines options related to the One-time password authentication (OTP).
OTP OTPConfig `form:"otp" json:"otp"`
// Various token configurations
// ---
AuthToken TokenConfig `form:"authToken" json:"authToken"`
PasswordResetToken TokenConfig `form:"passwordResetToken" json:"passwordResetToken"`
EmailChangeToken TokenConfig `form:"emailChangeToken" json:"emailChangeToken"`
VerificationToken TokenConfig `form:"verificationToken" json:"verificationToken"`
FileToken TokenConfig `form:"fileToken" json:"fileToken"`
// Default email templates
// ---
VerificationTemplate EmailTemplate `form:"verificationTemplate" json:"verificationTemplate"`
ResetPasswordTemplate EmailTemplate `form:"resetPasswordTemplate" json:"resetPasswordTemplate"`
ConfirmEmailChangeTemplate EmailTemplate `form:"confirmEmailChangeTemplate" json:"confirmEmailChangeTemplate"`
}
func (o *collectionAuthOptions) validate(cv *collectionValidator) error {
err := validation.ValidateStruct(o,
validation.Field(
&o.AuthRule,
validation.By(cv.checkRule),
validation.By(cv.ensureNoSystemRuleChange(cv.original.AuthRule)),
),
validation.Field(
&o.ManageRule,
validation.NilOrNotEmpty,
validation.By(cv.checkRule),
validation.By(cv.ensureNoSystemRuleChange(cv.original.ManageRule)),
),
validation.Field(&o.AuthAlert),
validation.Field(&o.PasswordAuth),
validation.Field(&o.OAuth2),
validation.Field(&o.OTP),
validation.Field(&o.MFA),
validation.Field(&o.AuthToken),
validation.Field(&o.PasswordResetToken),
validation.Field(&o.EmailChangeToken),
validation.Field(&o.VerificationToken),
validation.Field(&o.FileToken),
validation.Field(&o.VerificationTemplate, validation.Required),
validation.Field(&o.ResetPasswordTemplate, validation.Required),
validation.Field(&o.ConfirmEmailChangeTemplate, validation.Required),
)
if err != nil {
return err
}
if o.MFA.Enabled {
// if MFA is enabled require at least 2 auth methods
//
// @todo maybe consider disabling the check because if custom auth methods
// are registered it may fail since we don't have mechanism to detect them at the moment
authsEnabled := 0
if o.PasswordAuth.Enabled {
authsEnabled++
}
if o.OAuth2.Enabled {
authsEnabled++
}
if o.OTP.Enabled {
authsEnabled++
}
if authsEnabled < 2 {
return validation.Errors{
"mfa": validation.Errors{
"enabled": validation.NewError("validation_mfa_not_enough_auths", "MFA requires at least 2 auth methods to be enabled."),
},
}
}
if o.MFA.Rule != "" {
mfaRuleValidators := []validation.RuleFunc{
cv.checkRule,
cv.ensureNoSystemRuleChange(&cv.original.MFA.Rule),
}
for _, validator := range mfaRuleValidators {
err := validator(&o.MFA.Rule)
if err != nil {
return validation.Errors{
"mfa": validation.Errors{
"rule": err,
},
}
}
}
}
}
// extra check to ensure that only unique identity fields are used
if o.PasswordAuth.Enabled {
err = validation.Validate(o.PasswordAuth.IdentityFields, validation.By(cv.checkFieldsForUniqueIndex))
if err != nil {
return validation.Errors{
"passwordAuth": validation.Errors{
"identityFields": err,
},
}
}
}
return nil
}
// -------------------------------------------------------------------
type EmailTemplate struct {
Subject string `form:"subject" json:"subject"`
Body string `form:"body" json:"body"`
}
// 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(&t.Body, validation.Required),
)
}
// Resolve replaces the placeholder parameters in the current email
// template and returns its components as ready-to-use strings.
func (t EmailTemplate) Resolve(placeholders map[string]any) (subject, body string) {
body = t.Body
subject = t.Subject
for k, v := range placeholders {
vStr := cast.ToString(v)
// replace subject placeholder params (if any)
subject = strings.ReplaceAll(subject, k, vStr)
// replace body placeholder params (if any)
body = strings.ReplaceAll(body, k, vStr)
}
return subject, body
}
// -------------------------------------------------------------------
type AuthAlertConfig struct {
Enabled bool `form:"enabled" json:"enabled"`
EmailTemplate EmailTemplate `form:"emailTemplate" json:"emailTemplate"`
}
// Validate makes AuthAlertConfig validatable by implementing [validation.Validatable] interface.
func (c AuthAlertConfig) Validate() error {
return validation.ValidateStruct(&c,
// note: for now always run the email template validations even
// if not enabled since it could be used separately
validation.Field(&c.EmailTemplate),
)
}
// -------------------------------------------------------------------
type TokenConfig struct {
Secret string `form:"secret" json:"secret,omitempty"`
// Duration specifies how long an issued token to be valid (in seconds)
Duration int64 `form:"duration" json:"duration"`
}
// Validate makes TokenConfig validatable by implementing [validation.Validatable] interface.
func (c TokenConfig) Validate() error {
return validation.ValidateStruct(&c,
validation.Field(&c.Secret, validation.Required, validation.Length(30, 255)),
validation.Field(&c.Duration, validation.Required, validation.Min(10), validation.Max(94670856)), // ~3y max
)
}
// DurationTime returns the current Duration as [time.Duration].
func (c TokenConfig) DurationTime() time.Duration {
return time.Duration(c.Duration) * time.Second
}
// -------------------------------------------------------------------
type OTPConfig struct {
Enabled bool `form:"enabled" json:"enabled"`
// Duration specifies how long the OTP to be valid (in seconds)
Duration int64 `form:"duration" json:"duration"`
// Length specifies the auto generated password length.
Length int `form:"length" json:"length"`
// EmailTemplate is the default OTP email template that will be send to the auth record.
//
// In addition to the system placeholders you can also make use of
// [core.EmailPlaceholderOTPId] and [core.EmailPlaceholderOTP].
EmailTemplate EmailTemplate `form:"emailTemplate" json:"emailTemplate"`
}
// Validate makes OTPConfig validatable by implementing [validation.Validatable] interface.
func (c OTPConfig) Validate() error {
return validation.ValidateStruct(&c,
validation.Field(&c.Duration, validation.When(c.Enabled, validation.Required, validation.Min(10), validation.Max(86400))),
validation.Field(&c.Length, validation.When(c.Enabled, validation.Required, validation.Min(4))),
// note: for now always run the email template validations even
// if not enabled since it could be used separately
validation.Field(&c.EmailTemplate),
)
}
// DurationTime returns the current Duration as [time.Duration].
func (c OTPConfig) DurationTime() time.Duration {
return time.Duration(c.Duration) * time.Second
}
// -------------------------------------------------------------------
type MFAConfig struct {
Enabled bool `form:"enabled" json:"enabled"`
// Duration specifies how long an issued MFA to be valid (in seconds)
Duration int64 `form:"duration" json:"duration"`
// Rule is an optional field to restrict MFA only for the records that satisfy the rule.
//
// Leave it empty to enable MFA for everyone.
Rule string `form:"rule" json:"rule"`
}
// Validate makes MFAConfig validatable by implementing [validation.Validatable] interface.
func (c MFAConfig) Validate() error {
return validation.ValidateStruct(&c,
validation.Field(&c.Duration, validation.When(c.Enabled, validation.Required, validation.Min(10), validation.Max(86400))),
)
}
// DurationTime returns the current Duration as [time.Duration].
func (c MFAConfig) DurationTime() time.Duration {
return time.Duration(c.Duration) * time.Second
}
// -------------------------------------------------------------------
type PasswordAuthConfig struct {
Enabled bool `form:"enabled" json:"enabled"`
// IdentityFields is a list of field names that could be used as
// identity during password authentication.
//
// Usually only fields that has single column UNIQUE index are accepted as values.
IdentityFields []string `form:"identityFields" json:"identityFields"`
}
// Validate makes PasswordAuthConfig validatable by implementing [validation.Validatable] interface.
func (c PasswordAuthConfig) Validate() error {
// strip duplicated values
c.IdentityFields = list.ToUniqueStringSlice(c.IdentityFields)
if !c.Enabled {
return nil // no need to validate
}
return validation.ValidateStruct(&c,
validation.Field(&c.IdentityFields, validation.Required),
)
}
// -------------------------------------------------------------------
type OAuth2KnownFields struct {
Id string `form:"id" json:"id"`
Name string `form:"name" json:"name"`
Username string `form:"username" json:"username"`
AvatarURL string `form:"avatarURL" json:"avatarURL"`
}
type OAuth2Config struct {
Providers []OAuth2ProviderConfig `form:"providers" json:"providers"`
MappedFields OAuth2KnownFields `form:"mappedFields" json:"mappedFields"`
Enabled bool `form:"enabled" json:"enabled"`
}
// GetProviderConfig returns the first OAuth2ProviderConfig that matches the specified name.
//
// Returns false and zero config if no such provider is available in c.Providers.
func (c OAuth2Config) GetProviderConfig(name string) (config OAuth2ProviderConfig, exists bool) {
for _, p := range c.Providers {
if p.Name == name {
return p, true
}
}
return
}
// Validate makes OAuth2Config validatable by implementing [validation.Validatable] interface.
func (c OAuth2Config) Validate() error {
if !c.Enabled {
return nil // no need to validate
}
return validation.ValidateStruct(&c,
// note: don't require providers for now as they could be externally registered/removed
validation.Field(&c.Providers, validation.By(checkForDuplicatedProviders)),
)
}
func checkForDuplicatedProviders(value any) error {
configs, _ := value.([]OAuth2ProviderConfig)
existing := map[string]struct{}{}
for i, c := range configs {
if c.Name == "" {
continue // the name nonempty state is validated separately
}
if _, ok := existing[c.Name]; ok {
return validation.Errors{
strconv.Itoa(i): validation.Errors{
"name": validation.NewError("validation_duplicated_provider", "The provider {{.name}} is already registered.").
SetParams(map[string]any{"name": c.Name}),
},
}
}
existing[c.Name] = struct{}{}
}
return nil
}
type OAuth2ProviderConfig struct {
// PKCE overwrites the default provider PKCE config option.
//
// This usually shouldn't be needed but some OAuth2 vendors, like the LinkedIn OIDC,
// may require manual adjustment due to returning error if extra parameters are added to the request
// (https://github.com/pocketbase/pocketbase/discussions/3799#discussioncomment-7640312)
PKCE *bool `form:"pkce" json:"pkce"`
Name string `form:"name" json:"name"`
ClientId string `form:"clientId" json:"clientId"`
ClientSecret string `form:"clientSecret" json:"clientSecret,omitempty"`
AuthURL string `form:"authURL" json:"authURL"`
TokenURL string `form:"tokenURL" json:"tokenURL"`
UserInfoURL string `form:"userInfoURL" json:"userInfoURL"`
DisplayName string `form:"displayName" json:"displayName"`
Extra map[string]any `form:"extra" json:"extra"`
}
// Validate makes OAuth2ProviderConfig validatable by implementing [validation.Validatable] interface.
func (c OAuth2ProviderConfig) Validate() error {
return validation.ValidateStruct(&c,
validation.Field(&c.Name, validation.Required, validation.By(checkProviderName)),
validation.Field(&c.ClientId, validation.Required),
validation.Field(&c.ClientSecret, validation.Required),
validation.Field(&c.AuthURL, is.URL),
validation.Field(&c.TokenURL, is.URL),
validation.Field(&c.UserInfoURL, is.URL),
)
}
func checkProviderName(value any) error {
name, _ := value.(string)
if name == "" {
return nil // nothing to check
}
if _, err := auth.NewProviderByName(name); err != nil {
return validation.NewError("validation_missing_provider", "Invalid or missing provider with name {{.name}}.").
SetParams(map[string]any{"name": name})
}
return nil
}
// InitProvider returns a new auth.Provider instance loaded with the current OAuth2ProviderConfig options.
func (c OAuth2ProviderConfig) InitProvider() (auth.Provider, error) {
provider, err := auth.NewProviderByName(c.Name)
if err != nil {
return nil, err
}
if c.ClientId != "" {
provider.SetClientId(c.ClientId)
}
if c.ClientSecret != "" {
provider.SetClientSecret(c.ClientSecret)
}
if c.AuthURL != "" {
provider.SetAuthURL(c.AuthURL)
}
if c.UserInfoURL != "" {
provider.SetUserInfoURL(c.UserInfoURL)
}
if c.TokenURL != "" {
provider.SetTokenURL(c.TokenURL)
}
if c.DisplayName != "" {
provider.SetDisplayName(c.DisplayName)
}
if c.PKCE != nil {
provider.SetPKCE(*c.PKCE)
}
if c.Extra != nil {
provider.SetExtra(c.Extra)
}
return provider, nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/mfa_query.go | core/mfa_query.go | package core
import (
"errors"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/types"
)
// FindAllMFAsByRecord returns all MFA models linked to the provided auth record.
func (app *BaseApp) FindAllMFAsByRecord(authRecord *Record) ([]*MFA, error) {
result := []*MFA{}
err := app.RecordQuery(CollectionNameMFAs).
AndWhere(dbx.HashExp{
"collectionRef": authRecord.Collection().Id,
"recordRef": authRecord.Id,
}).
OrderBy("created DESC").
All(&result)
if err != nil {
return nil, err
}
return result, nil
}
// FindAllMFAsByCollection returns all MFA models linked to the provided collection.
func (app *BaseApp) FindAllMFAsByCollection(collection *Collection) ([]*MFA, error) {
result := []*MFA{}
err := app.RecordQuery(CollectionNameMFAs).
AndWhere(dbx.HashExp{"collectionRef": collection.Id}).
OrderBy("created DESC").
All(&result)
if err != nil {
return nil, err
}
return result, nil
}
// FindMFAById returns a single MFA model by its id.
func (app *BaseApp) FindMFAById(id string) (*MFA, error) {
result := &MFA{}
err := app.RecordQuery(CollectionNameMFAs).
AndWhere(dbx.HashExp{"id": id}).
Limit(1).
One(result)
if err != nil {
return nil, err
}
return result, nil
}
// DeleteAllMFAsByRecord deletes all MFA models associated with the provided record.
//
// Returns a combined error with the failed deletes.
func (app *BaseApp) DeleteAllMFAsByRecord(authRecord *Record) error {
models, err := app.FindAllMFAsByRecord(authRecord)
if err != nil {
return err
}
var errs []error
for _, m := range models {
if err := app.Delete(m); err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}
// DeleteExpiredMFAs deletes the expired MFAs for all auth collections.
func (app *BaseApp) DeleteExpiredMFAs() error {
authCollections, err := app.FindAllCollections(CollectionTypeAuth)
if err != nil {
return err
}
// note: perform even if MFA is disabled to ensure that there are no dangling old records
for _, collection := range authCollections {
minValidDate, err := types.ParseDateTime(time.Now().Add(-1 * collection.MFA.DurationTime()))
if err != nil {
return err
}
items := []*Record{}
err = app.RecordQuery(CollectionNameMFAs).
AndWhere(dbx.HashExp{"collectionRef": collection.Id}).
AndWhere(dbx.NewExp("[[created]] < {:date}", dbx.Params{"date": minValidDate})).
All(&items)
if err != nil {
return err
}
for _, item := range items {
err = app.Delete(item)
if err != nil {
return err
}
}
}
return nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_date.go | core/field_date.go | package core
import (
"context"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
Fields[FieldTypeDate] = func() Field {
return &DateField{}
}
}
const FieldTypeDate = "date"
var _ Field = (*DateField)(nil)
// DateField defines "date" type field to store a single [types.DateTime] value.
//
// The respective zero record field value is the zero [types.DateTime].
type DateField struct {
// Name (required) is the unique name of the field.
Name string `form:"name" json:"name"`
// Id is the unique stable field identifier.
//
// It is automatically generated from the name when adding to a collection FieldsList.
Id string `form:"id" json:"id"`
// System prevents the renaming and removal of the field.
System bool `form:"system" json:"system"`
// Hidden hides the field from the API response.
Hidden bool `form:"hidden" json:"hidden"`
// Presentable hints the Dashboard UI to use the underlying
// field record value in the relation preview label.
Presentable bool `form:"presentable" json:"presentable"`
// ---
// Min specifies the min allowed field value.
//
// Leave it empty to skip the validator.
Min types.DateTime `form:"min" json:"min"`
// Max specifies the max allowed field value.
//
// Leave it empty to skip the validator.
Max types.DateTime `form:"max" json:"max"`
// Required will require the field value to be non-zero [types.DateTime].
Required bool `form:"required" json:"required"`
}
// Type implements [Field.Type] interface method.
func (f *DateField) Type() string {
return FieldTypeDate
}
// GetId implements [Field.GetId] interface method.
func (f *DateField) GetId() string {
return f.Id
}
// SetId implements [Field.SetId] interface method.
func (f *DateField) SetId(id string) {
f.Id = id
}
// GetName implements [Field.GetName] interface method.
func (f *DateField) GetName() string {
return f.Name
}
// SetName implements [Field.SetName] interface method.
func (f *DateField) SetName(name string) {
f.Name = name
}
// GetSystem implements [Field.GetSystem] interface method.
func (f *DateField) GetSystem() bool {
return f.System
}
// SetSystem implements [Field.SetSystem] interface method.
func (f *DateField) SetSystem(system bool) {
f.System = system
}
// GetHidden implements [Field.GetHidden] interface method.
func (f *DateField) GetHidden() bool {
return f.Hidden
}
// SetHidden implements [Field.SetHidden] interface method.
func (f *DateField) SetHidden(hidden bool) {
f.Hidden = hidden
}
// ColumnType implements [Field.ColumnType] interface method.
func (f *DateField) ColumnType(app App) string {
return "TEXT DEFAULT '' NOT NULL"
}
// PrepareValue implements [Field.PrepareValue] interface method.
func (f *DateField) PrepareValue(record *Record, raw any) (any, error) {
// ignore scan errors since the format may change between versions
// and to allow running db adjusting migrations
val, _ := types.ParseDateTime(raw)
return val, nil
}
// ValidateValue implements [Field.ValidateValue] interface method.
func (f *DateField) ValidateValue(ctx context.Context, app App, record *Record) error {
val, ok := record.GetRaw(f.Name).(types.DateTime)
if !ok {
return validators.ErrUnsupportedValueType
}
if val.IsZero() {
if f.Required {
return validation.ErrRequired
}
return nil // nothing to check
}
if !f.Min.IsZero() {
if err := validation.Min(f.Min.Time()).Validate(val.Time()); err != nil {
return err
}
}
if !f.Max.IsZero() {
if err := validation.Max(f.Max.Time()).Validate(val.Time()); err != nil {
return err
}
}
return nil
}
// ValidateSettings implements [Field.ValidateSettings] interface method.
func (f *DateField) ValidateSettings(ctx context.Context, app App, collection *Collection) error {
return validation.ValidateStruct(f,
validation.Field(&f.Id, validation.By(DefaultFieldIdValidationRule)),
validation.Field(&f.Name, validation.By(DefaultFieldNameValidationRule)),
validation.Field(&f.Max, validation.By(f.checkRange(f.Min, f.Max))),
)
}
func (f *DateField) checkRange(min types.DateTime, max types.DateTime) validation.RuleFunc {
return func(value any) error {
v, _ := value.(types.DateTime)
if v.IsZero() {
return nil // nothing to check
}
dr := validation.Date(types.DefaultDateLayout)
if !min.IsZero() {
dr.Min(min.Time())
}
if !max.IsZero() {
dr.Max(max.Time())
}
return dr.Validate(v.String())
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/log_model.go | core/log_model.go | package core
import "github.com/pocketbase/pocketbase/tools/types"
var (
_ Model = (*Log)(nil)
)
const LogsTableName = "_logs"
type Log struct {
BaseModel
Created types.DateTime `db:"created" json:"created"`
Data types.JSONMap[any] `db:"data" json:"data"`
Message string `db:"message" json:"message"`
Level int `db:"level" json:"level"`
}
func (m *Log) TableName() string {
return LogsTableName
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/db_retry_test.go | core/db_retry_test.go | package core
import (
"errors"
"fmt"
"testing"
)
func TestGetDefaultRetryInterval(t *testing.T) {
t.Parallel()
if i := getDefaultRetryInterval(-1); i.Milliseconds() != 1000 {
t.Fatalf("Expected 1000ms, got %v", i)
}
if i := getDefaultRetryInterval(999); i.Milliseconds() != 1000 {
t.Fatalf("Expected 1000ms, got %v", i)
}
if i := getDefaultRetryInterval(3); i.Milliseconds() != 200 {
t.Fatalf("Expected 500ms, got %v", i)
}
}
func TestBaseLockRetry(t *testing.T) {
t.Parallel()
scenarios := []struct {
err error
failUntilAttempt int
expectedAttempts int
}{
{nil, 3, 1},
{errors.New("test"), 3, 1},
{errors.New("database is locked"), 3, 3},
{errors.New("table is locked"), 3, 3},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.err), func(t *testing.T) {
lastAttempt := 0
err := baseLockRetry(func(attempt int) error {
lastAttempt = attempt
if attempt < s.failUntilAttempt {
return s.err
}
return nil
}, s.failUntilAttempt+2)
if lastAttempt != s.expectedAttempts {
t.Errorf("Expected lastAttempt to be %d, got %d", s.expectedAttempts, lastAttempt)
}
if s.failUntilAttempt == s.expectedAttempts && err != nil {
t.Fatalf("Expected nil, got err %v", err)
}
if s.failUntilAttempt != s.expectedAttempts && s.err != nil && err == nil {
t.Fatalf("Expected error %q, got nil", s.err)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_bool_test.go | core/field_bool_test.go | package core_test
import (
"context"
"fmt"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestBoolFieldBaseMethods(t *testing.T) {
testFieldBaseMethods(t, core.FieldTypeBool)
}
func TestBoolFieldColumnType(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.BoolField{}
expected := "BOOLEAN DEFAULT FALSE NOT NULL"
if v := f.ColumnType(app); v != expected {
t.Fatalf("Expected\n%q\ngot\n%q", expected, v)
}
}
func TestBoolFieldPrepareValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.BoolField{}
record := core.NewRecord(core.NewBaseCollection("test"))
scenarios := []struct {
raw any
expected bool
}{
{"", false},
{"f", false},
{"t", true},
{1, true},
{0, false},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.raw), func(t *testing.T) {
v, err := f.PrepareValue(record, s.raw)
if err != nil {
t.Fatal(err)
}
if v != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, v)
}
})
}
}
func TestBoolFieldValidateValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field *core.BoolField
record func() *core.Record
expectError bool
}{
{
"invalid raw value",
&core.BoolField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 123)
return record
},
true,
},
{
"missing field value (non-required)",
&core.BoolField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("abc", true)
return record
},
true, // because of failed nil.(bool) cast
},
{
"missing field value (required)",
&core.BoolField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("abc", true)
return record
},
true,
},
{
"false field value (non-required)",
&core.BoolField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", false)
return record
},
false,
},
{
"false field value (required)",
&core.BoolField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", false)
return record
},
true,
},
{
"true field value (required)",
&core.BoolField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", true)
return record
},
false,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
err := s.field.ValidateValue(context.Background(), app, s.record())
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
func TestBoolFieldValidateSettings(t *testing.T) {
testDefaultFieldIdValidation(t, core.FieldTypeBool)
testDefaultFieldNameValidation(t, core.FieldTypeBool)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_json.go | core/field_json.go | package core
import (
"context"
"slices"
"strconv"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
Fields[FieldTypeJSON] = func() Field {
return &JSONField{}
}
}
const FieldTypeJSON = "json"
const DefaultJSONFieldMaxSize int64 = 1 << 20
var (
_ Field = (*JSONField)(nil)
_ MaxBodySizeCalculator = (*JSONField)(nil)
)
// JSONField defines "json" type field for storing any serialized JSON value.
//
// The respective zero record field value is the zero [types.JSONRaw].
type JSONField struct {
// Name (required) is the unique name of the field.
Name string `form:"name" json:"name"`
// Id is the unique stable field identifier.
//
// It is automatically generated from the name when adding to a collection FieldsList.
Id string `form:"id" json:"id"`
// System prevents the renaming and removal of the field.
System bool `form:"system" json:"system"`
// Hidden hides the field from the API response.
Hidden bool `form:"hidden" json:"hidden"`
// Presentable hints the Dashboard UI to use the underlying
// field record value in the relation preview label.
Presentable bool `form:"presentable" json:"presentable"`
// ---
// MaxSize specifies the maximum size of the allowed field value (in bytes and up to 2^53-1).
//
// If zero, a default limit of 1MB is applied.
MaxSize int64 `form:"maxSize" json:"maxSize"`
// Required will require the field value to be non-empty JSON value
// (aka. not "null", `""`, "[]", "{}").
Required bool `form:"required" json:"required"`
}
// Type implements [Field.Type] interface method.
func (f *JSONField) Type() string {
return FieldTypeJSON
}
// GetId implements [Field.GetId] interface method.
func (f *JSONField) GetId() string {
return f.Id
}
// SetId implements [Field.SetId] interface method.
func (f *JSONField) SetId(id string) {
f.Id = id
}
// GetName implements [Field.GetName] interface method.
func (f *JSONField) GetName() string {
return f.Name
}
// SetName implements [Field.SetName] interface method.
func (f *JSONField) SetName(name string) {
f.Name = name
}
// GetSystem implements [Field.GetSystem] interface method.
func (f *JSONField) GetSystem() bool {
return f.System
}
// SetSystem implements [Field.SetSystem] interface method.
func (f *JSONField) SetSystem(system bool) {
f.System = system
}
// GetHidden implements [Field.GetHidden] interface method.
func (f *JSONField) GetHidden() bool {
return f.Hidden
}
// SetHidden implements [Field.SetHidden] interface method.
func (f *JSONField) SetHidden(hidden bool) {
f.Hidden = hidden
}
// ColumnType implements [Field.ColumnType] interface method.
func (f *JSONField) ColumnType(app App) string {
return "JSON DEFAULT NULL"
}
// PrepareValue implements [Field.PrepareValue] interface method.
func (f *JSONField) PrepareValue(record *Record, raw any) (any, error) {
if str, ok := raw.(string); ok {
// in order to support seamlessly both json and multipart/form-data requests,
// the following normalization rules are applied for plain string values:
// - "true" is converted to the json `true`
// - "false" is converted to the json `false`
// - "null" is converted to the json `null`
// - "[1,2,3]" is converted to the json `[1,2,3]`
// - "{\"a\":1,\"b\":2}" is converted to the json `{"a":1,"b":2}`
// - numeric strings are converted to json number
// - double quoted strings are left as they are (aka. without normalizations)
// - any other string (empty string too) is double quoted
if str == "" {
raw = strconv.Quote(str)
} else if str == "null" || str == "true" || str == "false" {
raw = str
} else if ((str[0] >= '0' && str[0] <= '9') ||
str[0] == '-' ||
str[0] == '"' ||
str[0] == '[' ||
str[0] == '{') &&
is.JSON.Validate(str) == nil {
raw = str
} else {
raw = strconv.Quote(str)
}
}
return types.ParseJSONRaw(raw)
}
var emptyJSONValues = []string{
"null", `""`, "[]", "{}", "",
}
// ValidateValue implements [Field.ValidateValue] interface method.
func (f *JSONField) ValidateValue(ctx context.Context, app App, record *Record) error {
raw, ok := record.GetRaw(f.Name).(types.JSONRaw)
if !ok {
return validators.ErrUnsupportedValueType
}
maxSize := f.CalculateMaxBodySize()
if int64(len(raw)) > maxSize {
return validation.NewError(
"validation_json_size_limit",
"The maximum allowed JSON size is {{.maxSize}} bytes",
).SetParams(map[string]any{"maxSize": maxSize})
}
if is.JSON.Validate(raw) != nil {
return validation.NewError("validation_invalid_json", "Must be a valid json value")
}
rawStr := strings.TrimSpace(raw.String())
if f.Required && slices.Contains(emptyJSONValues, rawStr) {
return validation.ErrRequired
}
return nil
}
// ValidateSettings implements [Field.ValidateSettings] interface method.
func (f *JSONField) ValidateSettings(ctx context.Context, app App, collection *Collection) error {
return validation.ValidateStruct(f,
validation.Field(&f.Id, validation.By(DefaultFieldIdValidationRule)),
validation.Field(&f.Name, validation.By(DefaultFieldNameValidationRule)),
validation.Field(&f.MaxSize, validation.Min(0), validation.Max(maxSafeJSONInt)),
)
}
// CalculateMaxBodySize implements the [MaxBodySizeCalculator] interface.
func (f *JSONField) CalculateMaxBodySize() int64 {
if f.MaxSize <= 0 {
return DefaultJSONFieldMaxSize
}
return f.MaxSize
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_file.go | core/field_file.go | package core
import (
"context"
"database/sql/driver"
"errors"
"fmt"
"log"
"regexp"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/types"
"github.com/spf13/cast"
)
func init() {
Fields[FieldTypeFile] = func() Field {
return &FileField{}
}
}
const FieldTypeFile = "file"
const DefaultFileFieldMaxSize int64 = 5 << 20
var looseFilenameRegex = regexp.MustCompile(`^[^\./\\][^/\\]+$`)
const (
deletedFilesPrefix = internalCustomFieldKeyPrefix + "_deletedFilesPrefix_"
uploadedFilesPrefix = internalCustomFieldKeyPrefix + "_uploadedFilesPrefix_"
)
var (
_ Field = (*FileField)(nil)
_ MultiValuer = (*FileField)(nil)
_ DriverValuer = (*FileField)(nil)
_ GetterFinder = (*FileField)(nil)
_ SetterFinder = (*FileField)(nil)
_ RecordInterceptor = (*FileField)(nil)
_ MaxBodySizeCalculator = (*FileField)(nil)
)
// FileField defines "file" type field for managing record file(s).
//
// Only the file name is stored as part of the record value.
// New files (aka. files to upload) are expected to be of *filesytem.File.
//
// If MaxSelect is not set or <= 1, then the field value is expected to be a single record id.
//
// If MaxSelect is > 1, then the field value is expected to be a slice of record ids.
//
// The respective zero record field value is either empty string (single) or empty string slice (multiple).
//
// ---
//
// The following additional setter keys are available:
//
// - "fieldName+" - append one or more files to the existing record one. For example:
//
// // []string{"old1.txt", "old2.txt", "new1_ajkvass.txt", "new2_klhfnwd.txt"}
// record.Set("documents+", []*filesystem.File{new1, new2})
//
// - "+fieldName" - prepend one or more files to the existing record one. For example:
//
// // []string{"new1_ajkvass.txt", "new2_klhfnwd.txt", "old1.txt", "old2.txt",}
// record.Set("+documents", []*filesystem.File{new1, new2})
//
// - "fieldName-" - subtract/delete one or more files from the existing record one. For example:
//
// // []string{"old2.txt",}
// record.Set("documents-", "old1.txt")
type FileField struct {
// Name (required) is the unique name of the field.
Name string `form:"name" json:"name"`
// Id is the unique stable field identifier.
//
// It is automatically generated from the name when adding to a collection FieldsList.
Id string `form:"id" json:"id"`
// System prevents the renaming and removal of the field.
System bool `form:"system" json:"system"`
// Hidden hides the field from the API response.
Hidden bool `form:"hidden" json:"hidden"`
// Presentable hints the Dashboard UI to use the underlying
// field record value in the relation preview label.
Presentable bool `form:"presentable" json:"presentable"`
// ---
// MaxSize specifies the maximum size of a single uploaded file (in bytes and up to 2^53-1).
//
// If zero, a default limit of 5MB is applied.
MaxSize int64 `form:"maxSize" json:"maxSize"`
// MaxSelect specifies the max allowed files.
//
// For multiple files the value must be > 1, otherwise fallbacks to single (default).
MaxSelect int `form:"maxSelect" json:"maxSelect"`
// MimeTypes specifies an optional list of the allowed file mime types.
//
// Leave it empty to disable the validator.
MimeTypes []string `form:"mimeTypes" json:"mimeTypes"`
// Thumbs specifies an optional list of the supported thumbs for image based files.
//
// Each entry must be in one of the following formats:
//
// - WxH (eg. 100x300) - crop to WxH viewbox (from center)
// - WxHt (eg. 100x300t) - crop to WxH viewbox (from top)
// - WxHb (eg. 100x300b) - crop to WxH viewbox (from bottom)
// - WxHf (eg. 100x300f) - fit inside a WxH viewbox (without cropping)
// - 0xH (eg. 0x300) - resize to H height preserving the aspect ratio
// - Wx0 (eg. 100x0) - resize to W width preserving the aspect ratio
Thumbs []string `form:"thumbs" json:"thumbs"`
// Protected will require the users to provide a special file token to access the file.
//
// Note that by default all files are publicly accessible.
//
// For the majority of the cases this is fine because by default
// all file names have random part appended to their name which
// need to be known by the user before accessing the file.
Protected bool `form:"protected" json:"protected"`
// Required will require the field value to have at least one file.
Required bool `form:"required" json:"required"`
}
// Type implements [Field.Type] interface method.
func (f *FileField) Type() string {
return FieldTypeFile
}
// GetId implements [Field.GetId] interface method.
func (f *FileField) GetId() string {
return f.Id
}
// SetId implements [Field.SetId] interface method.
func (f *FileField) SetId(id string) {
f.Id = id
}
// GetName implements [Field.GetName] interface method.
func (f *FileField) GetName() string {
return f.Name
}
// SetName implements [Field.SetName] interface method.
func (f *FileField) SetName(name string) {
f.Name = name
}
// GetSystem implements [Field.GetSystem] interface method.
func (f *FileField) GetSystem() bool {
return f.System
}
// SetSystem implements [Field.SetSystem] interface method.
func (f *FileField) SetSystem(system bool) {
f.System = system
}
// GetHidden implements [Field.GetHidden] interface method.
func (f *FileField) GetHidden() bool {
return f.Hidden
}
// SetHidden implements [Field.SetHidden] interface method.
func (f *FileField) SetHidden(hidden bool) {
f.Hidden = hidden
}
// IsMultiple implements MultiValuer interface and checks whether the
// current field options support multiple values.
func (f *FileField) IsMultiple() bool {
return f.MaxSelect > 1
}
// ColumnType implements [Field.ColumnType] interface method.
func (f *FileField) ColumnType(app App) string {
if f.IsMultiple() {
return "JSON DEFAULT '[]' NOT NULL"
}
return "TEXT DEFAULT '' NOT NULL"
}
// PrepareValue implements [Field.PrepareValue] interface method.
func (f *FileField) PrepareValue(record *Record, raw any) (any, error) {
return f.normalizeValue(raw), nil
}
// DriverValue implements the [DriverValuer] interface.
func (f *FileField) DriverValue(record *Record) (driver.Value, error) {
files := f.toSliceValue(record.GetRaw(f.Name))
if f.IsMultiple() {
ja := make(types.JSONArray[string], len(files))
for i, v := range files {
ja[i] = f.getFileName(v)
}
return ja, nil
}
if len(files) == 0 {
return "", nil
}
return f.getFileName(files[len(files)-1]), nil
}
// ValidateSettings implements [Field.ValidateSettings] interface method.
func (f *FileField) ValidateSettings(ctx context.Context, app App, collection *Collection) error {
return validation.ValidateStruct(f,
validation.Field(&f.Id, validation.By(DefaultFieldIdValidationRule)),
validation.Field(&f.Name, validation.By(DefaultFieldNameValidationRule)),
validation.Field(&f.MaxSelect, validation.Min(0), validation.Max(maxSafeJSONInt)),
validation.Field(&f.MaxSize, validation.Min(0), validation.Max(maxSafeJSONInt)),
validation.Field(&f.Thumbs, validation.Each(
validation.NotIn("0x0", "0x0t", "0x0b", "0x0f"),
validation.Match(filesystem.ThumbSizeRegex),
)),
)
}
// ValidateValue implements [Field.ValidateValue] interface method.
func (f *FileField) ValidateValue(ctx context.Context, app App, record *Record) error {
files := f.toSliceValue(record.GetRaw(f.Name))
if len(files) == 0 {
if f.Required {
return validation.ErrRequired
}
return nil // nothing to check
}
// validate existing and disallow new plain string filenames submission
// (new files must be *filesystem.File)
// ---
oldExistingStrings := f.toSliceValue(f.getLatestOldValue(app, record))
existingStrings := list.ToInterfaceSlice(f.extractPlainStrings(files))
addedStrings := f.excludeFiles(existingStrings, oldExistingStrings)
if len(addedStrings) > 0 {
invalidFiles := make([]string, len(addedStrings))
for i, invalid := range addedStrings {
invalidStr := cast.ToString(invalid)
if len(invalidStr) > 250 {
invalidStr = invalidStr[:250]
}
invalidFiles[i] = invalidStr
}
return validation.NewError("validation_invalid_file", "Invalid new files: {{.invalidFiles}}.").
SetParams(map[string]any{"invalidFiles": invalidFiles})
}
maxSelect := f.maxSelect()
if len(files) > maxSelect {
return validation.NewError("validation_too_many_files", "The maximum allowed files is {{.maxSelect}}").
SetParams(map[string]any{"maxSelect": maxSelect})
}
// validate uploaded
// ---
uploads := f.extractUploadableFiles(files)
for _, upload := range uploads {
// loosely check the filename just in case it was manually changed after the normalization
err := validation.Length(1, 150).Validate(upload.Name)
if err != nil {
return err
}
err = validation.Match(looseFilenameRegex).Validate(upload.Name)
if err != nil {
return err
}
// check size
err = validators.UploadedFileSize(f.maxSize())(upload)
if err != nil {
return err
}
// check type
if len(f.MimeTypes) > 0 {
err = validators.UploadedFileMimeType(f.MimeTypes)(upload)
if err != nil {
return err
}
}
}
return nil
}
func (f *FileField) maxSize() int64 {
if f.MaxSize <= 0 {
return DefaultFileFieldMaxSize
}
return f.MaxSize
}
func (f *FileField) maxSelect() int {
if f.MaxSelect <= 1 {
return 1
}
return f.MaxSelect
}
// CalculateMaxBodySize implements the [MaxBodySizeCalculator] interface.
func (f *FileField) CalculateMaxBodySize() int64 {
return f.maxSize() * int64(f.maxSelect())
}
// Interceptors
// -------------------------------------------------------------------
// Intercept implements the [RecordInterceptor] interface.
//
// note: files delete after records deletion is handled globally by the app FileManager hook
func (f *FileField) Intercept(
ctx context.Context,
app App,
record *Record,
actionName string,
actionFunc func() error,
) error {
switch actionName {
case InterceptorActionCreateExecute, InterceptorActionUpdateExecute:
oldValue := f.getLatestOldValue(app, record)
err := f.processFilesToUpload(ctx, app, record)
if err != nil {
return err
}
err = actionFunc()
if err != nil {
return errors.Join(err, f.afterRecordExecuteFailure(newContextIfInvalid(ctx), app, record))
}
f.rememberFilesToDelete(app, record, oldValue)
f.afterRecordExecuteSuccess(newContextIfInvalid(ctx), app, record)
return nil
case InterceptorActionAfterCreateError, InterceptorActionAfterUpdateError:
// when in transaction we assume that the error was handled by afterRecordExecuteFailure
if app.IsTransactional() {
return actionFunc()
}
failedToDelete, deleteErr := f.deleteNewlyUploadedFiles(newContextIfInvalid(ctx), app, record)
if deleteErr != nil {
app.Logger().Warn(
"Failed to cleanup all new files after record commit failure",
"error", deleteErr,
"failedToDelete", failedToDelete,
)
}
record.SetRaw(deletedFilesPrefix+f.Name, nil)
if record.IsNew() {
// try to delete the record directory if there are no other files
//
// note: executed only on create failure to avoid accidentally
// deleting a concurrently updating directory due to the
// eventual consistent nature of some storage providers
err := f.deleteEmptyRecordDir(newContextIfInvalid(ctx), app, record)
if err != nil {
app.Logger().Warn("Failed to delete empty dir after new record commit failure", "error", err)
}
}
return actionFunc()
case InterceptorActionAfterCreate, InterceptorActionAfterUpdate:
record.SetRaw(uploadedFilesPrefix+f.Name, nil)
err := f.processFilesToDelete(ctx, app, record)
if err != nil {
return err
}
return actionFunc()
default:
return actionFunc()
}
}
func (f *FileField) getLatestOldValue(app App, record *Record) any {
if !record.IsNew() {
latestOriginal, err := app.FindRecordById(record.Collection(), cast.ToString(record.LastSavedPK()))
if err == nil {
return latestOriginal.GetRaw(f.Name)
}
}
return record.Original().GetRaw(f.Name)
}
func (f *FileField) afterRecordExecuteSuccess(ctx context.Context, app App, record *Record) {
uploaded, _ := record.GetRaw(uploadedFilesPrefix + f.Name).([]*filesystem.File)
// replace the uploaded file objects with their plain string names
newValue := f.toSliceValue(record.GetRaw(f.Name))
for i, v := range newValue {
if file, ok := v.(*filesystem.File); ok {
uploaded = append(uploaded, file)
newValue[i] = file.Name
}
}
f.setValue(record, newValue)
record.SetRaw(uploadedFilesPrefix+f.Name, uploaded)
}
func (f *FileField) afterRecordExecuteFailure(ctx context.Context, app App, record *Record) error {
uploaded := f.extractUploadableFiles(f.toSliceValue(record.GetRaw(f.Name)))
toDelete := make([]string, len(uploaded))
for i, file := range uploaded {
toDelete[i] = file.Name
}
// delete previously uploaded files
failedToDelete, deleteErr := f.deleteFilesByNamesList(ctx, app, record, list.ToUniqueStringSlice(toDelete))
if len(failedToDelete) > 0 {
app.Logger().Warn(
"Failed to cleanup the new uploaded file after record db write failure",
"error", deleteErr,
"failedToDelete", failedToDelete,
)
}
return deleteErr
}
func (f *FileField) deleteEmptyRecordDir(ctx context.Context, app App, record *Record) error {
fsys, err := app.NewFilesystem()
if err != nil {
return err
}
defer fsys.Close()
fsys.SetContext(newContextIfInvalid(ctx))
dir := record.BaseFilesPath()
if !fsys.IsEmptyDir(dir) {
return nil // no-op
}
err = fsys.Delete(dir)
if err != nil && !errors.Is(err, filesystem.ErrNotFound) {
return err
}
return nil
}
func (f *FileField) processFilesToDelete(ctx context.Context, app App, record *Record) error {
markedForDelete, _ := record.GetRaw(deletedFilesPrefix + f.Name).([]string)
if len(markedForDelete) == 0 {
return nil
}
old := list.ToInterfaceSlice(markedForDelete)
new := list.ToInterfaceSlice(f.extractPlainStrings(f.toSliceValue(record.GetRaw(f.Name))))
diff := f.excludeFiles(old, new)
toDelete := make([]string, len(diff))
for i, del := range diff {
toDelete[i] = f.getFileName(del)
}
failedToDelete, err := f.deleteFilesByNamesList(ctx, app, record, list.ToUniqueStringSlice(toDelete))
record.SetRaw(deletedFilesPrefix+f.Name, failedToDelete)
return err
}
func (f *FileField) rememberFilesToDelete(app App, record *Record, oldValue any) {
old := list.ToInterfaceSlice(f.extractPlainStrings(f.toSliceValue(oldValue)))
new := list.ToInterfaceSlice(f.extractPlainStrings(f.toSliceValue(record.GetRaw(f.Name))))
diff := f.excludeFiles(old, new)
toDelete, _ := record.GetRaw(deletedFilesPrefix + f.Name).([]string)
for _, del := range diff {
toDelete = append(toDelete, f.getFileName(del))
}
record.SetRaw(deletedFilesPrefix+f.Name, toDelete)
}
func (f *FileField) processFilesToUpload(ctx context.Context, app App, record *Record) error {
uploads := f.extractUploadableFiles(f.toSliceValue(record.GetRaw(f.Name)))
if len(uploads) == 0 {
return nil
}
if record.Id == "" {
return errors.New("uploading files requires the record to have a valid nonempty id")
}
fsys, err := app.NewFilesystem()
if err != nil {
return err
}
defer fsys.Close()
fsys.SetContext(ctx)
var failed []error // list of upload errors
var succeeded []string // list of uploaded file names
for _, upload := range uploads {
path := record.BaseFilesPath() + "/" + upload.Name
if err := fsys.UploadFile(upload, path); err == nil {
succeeded = append(succeeded, upload.Name)
} else {
failed = append(failed, fmt.Errorf("%q: %w", upload.Name, err))
break // for now stop on the first error since we currently don't allow partial uploads
}
}
if len(failed) > 0 {
// cleanup - try to delete the successfully uploaded files (if any)
_, cleanupErr := f.deleteFilesByNamesList(newContextIfInvalid(ctx), app, record, succeeded)
failed = append(failed, cleanupErr)
return fmt.Errorf("failed to upload all files: %w", errors.Join(failed...))
}
return nil
}
func (f *FileField) deleteNewlyUploadedFiles(ctx context.Context, app App, record *Record) ([]string, error) {
uploaded, _ := record.GetRaw(uploadedFilesPrefix + f.Name).([]*filesystem.File)
if len(uploaded) == 0 {
return nil, nil
}
names := make([]string, len(uploaded))
for i, file := range uploaded {
names[i] = file.Name
}
failed, err := f.deleteFilesByNamesList(ctx, app, record, list.ToUniqueStringSlice(names))
if err != nil {
return failed, err
}
record.SetRaw(uploadedFilesPrefix+f.Name, nil)
return nil, nil
}
// deleteFiles deletes a list of record files by their names.
// Returns the failed/remaining files.
func (f *FileField) deleteFilesByNamesList(ctx context.Context, app App, record *Record, filenames []string) ([]string, error) {
if len(filenames) == 0 {
return nil, nil // nothing to delete
}
if record.Id == "" {
return filenames, errors.New("the record doesn't have an id")
}
fsys, err := app.NewFilesystem()
if err != nil {
return filenames, err
}
defer fsys.Close()
fsys.SetContext(ctx)
var failures []error
for i := len(filenames) - 1; i >= 0; i-- {
filename := filenames[i]
if filename == "" || strings.ContainsAny(filename, "/\\") {
continue // empty or not a plain filename
}
path := record.BaseFilesPath() + "/" + filename
err := fsys.Delete(path)
if err != nil && !errors.Is(err, filesystem.ErrNotFound) {
// store the delete error
failures = append(failures, fmt.Errorf("file %d (%q): %w", i, filename, err))
} else {
// remove the deleted file from the list
filenames = append(filenames[:i], filenames[i+1:]...)
// try to delete the related file thumbs (if any)
thumbsErr := fsys.DeletePrefix(record.BaseFilesPath() + "/thumbs_" + filename + "/")
if len(thumbsErr) > 0 {
app.Logger().Warn("Failed to delete file thumbs", "error", errors.Join(thumbsErr...))
}
}
}
if len(failures) > 0 {
return filenames, fmt.Errorf("failed to delete all files: %w", errors.Join(failures...))
}
return nil, nil
}
// newContextIfInvalid returns a new Background context if the provided one was cancelled.
func newContextIfInvalid(ctx context.Context) context.Context {
if ctx.Err() == nil {
return ctx
}
return context.Background()
}
// -------------------------------------------------------------------
// FindGetter implements the [GetterFinder] interface.
func (f *FileField) FindGetter(key string) GetterFunc {
switch key {
case f.Name:
return func(record *Record) any {
return record.GetRaw(f.Name)
}
case f.Name + ":unsaved":
return func(record *Record) any {
return f.extractUploadableFiles(f.toSliceValue(record.GetRaw(f.Name)))
}
case f.Name + ":uploaded":
// deprecated
log.Println("[file field getter] please replace :uploaded with :unsaved")
return func(record *Record) any {
return f.extractUploadableFiles(f.toSliceValue(record.GetRaw(f.Name)))
}
default:
return nil
}
}
// -------------------------------------------------------------------
// FindSetter implements the [SetterFinder] interface.
func (f *FileField) FindSetter(key string) SetterFunc {
switch key {
case f.Name:
return f.setValue
case "+" + f.Name:
return f.prependValue
case f.Name + "+":
return f.appendValue
case f.Name + "-":
return f.subtractValue
default:
return nil
}
}
func (f *FileField) setValue(record *Record, raw any) {
val := f.normalizeValue(raw)
record.SetRaw(f.Name, val)
}
func (f *FileField) prependValue(record *Record, toPrepend any) {
files := f.toSliceValue(record.GetRaw(f.Name))
prepends := f.toSliceValue(toPrepend)
if len(prepends) > 0 {
files = append(prepends, files...)
}
f.setValue(record, files)
}
func (f *FileField) appendValue(record *Record, toAppend any) {
files := f.toSliceValue(record.GetRaw(f.Name))
appends := f.toSliceValue(toAppend)
if len(appends) > 0 {
files = append(files, appends...)
}
f.setValue(record, files)
}
func (f *FileField) subtractValue(record *Record, toRemove any) {
files := f.excludeFiles(
f.toSliceValue(record.GetRaw(f.Name)),
f.toSliceValue(toRemove),
)
f.setValue(record, files)
}
func (f *FileField) normalizeValue(raw any) any {
files := f.toSliceValue(raw)
if f.IsMultiple() {
return files
}
if len(files) > 0 {
return files[len(files)-1] // the last selected
}
return ""
}
func (f *FileField) toSliceValue(raw any) []any {
var result []any
switch value := raw.(type) {
case nil:
// nothing to cast
case *filesystem.File:
result = append(result, value)
case filesystem.File:
result = append(result, &value)
case []*filesystem.File:
for _, v := range value {
result = append(result, v)
}
case []filesystem.File:
for _, v := range value {
result = append(result, &v)
}
case []any:
for _, v := range value {
casted := f.toSliceValue(v)
if len(casted) == 1 {
result = append(result, casted[0])
}
}
default:
result = list.ToInterfaceSlice(list.ToUniqueStringSlice(value))
}
return f.uniqueFiles(result)
}
func (f *FileField) uniqueFiles(files []any) []any {
found := make(map[string]struct{}, len(files))
result := make([]any, 0, len(files))
for _, fv := range files {
name := f.getFileName(fv)
if _, ok := found[name]; !ok {
result = append(result, fv)
found[name] = struct{}{}
}
}
return result
}
func (f *FileField) extractPlainStrings(files []any) []string {
result := []string{}
for _, raw := range files {
if f, ok := raw.(string); ok {
result = append(result, f)
}
}
return result
}
func (f *FileField) extractUploadableFiles(files []any) []*filesystem.File {
result := []*filesystem.File{}
for _, raw := range files {
if upload, ok := raw.(*filesystem.File); ok {
result = append(result, upload)
}
}
return result
}
func (f *FileField) excludeFiles(base []any, toExclude []any) []any {
result := make([]any, 0, len(base))
SUBTRACT_LOOP:
for _, fv := range base {
for _, exclude := range toExclude {
if f.getFileName(exclude) == f.getFileName(fv) {
continue SUBTRACT_LOOP // skip
}
}
result = append(result, fv)
}
return result
}
func (f *FileField) getFileName(file any) string {
switch v := file.(type) {
case string:
return v
case *filesystem.File:
return v.Name
default:
return ""
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_select_test.go | core/field_select_test.go | package core_test
import (
"context"
"encoding/json"
"fmt"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestSelectFieldBaseMethods(t *testing.T) {
testFieldBaseMethods(t, core.FieldTypeSelect)
}
func TestSelectFieldColumnType(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
name string
field *core.SelectField
expected string
}{
{
"single (zero)",
&core.SelectField{},
"TEXT DEFAULT '' NOT NULL",
},
{
"single",
&core.SelectField{MaxSelect: 1},
"TEXT DEFAULT '' NOT NULL",
},
{
"multiple",
&core.SelectField{MaxSelect: 2},
"JSON DEFAULT '[]' NOT NULL",
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
if v := s.field.ColumnType(app); v != s.expected {
t.Fatalf("Expected\n%q\ngot\n%q", s.expected, v)
}
})
}
}
func TestSelectFieldIsMultiple(t *testing.T) {
scenarios := []struct {
name string
field *core.SelectField
expected bool
}{
{
"single (zero)",
&core.SelectField{},
false,
},
{
"single",
&core.SelectField{MaxSelect: 1},
false,
},
{
"multiple (>1)",
&core.SelectField{MaxSelect: 2},
true,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
if v := s.field.IsMultiple(); v != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, v)
}
})
}
}
func TestSelectFieldPrepareValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
record := core.NewRecord(core.NewBaseCollection("test"))
scenarios := []struct {
raw any
field *core.SelectField
expected string
}{
// single
{nil, &core.SelectField{}, `""`},
{"", &core.SelectField{}, `""`},
{123, &core.SelectField{}, `"123"`},
{"a", &core.SelectField{}, `"a"`},
{`["a"]`, &core.SelectField{}, `"a"`},
{[]string{}, &core.SelectField{}, `""`},
{[]string{"a", "b"}, &core.SelectField{}, `"b"`},
// multiple
{nil, &core.SelectField{MaxSelect: 2}, `[]`},
{"", &core.SelectField{MaxSelect: 2}, `[]`},
{123, &core.SelectField{MaxSelect: 2}, `["123"]`},
{"a", &core.SelectField{MaxSelect: 2}, `["a"]`},
{`["a"]`, &core.SelectField{MaxSelect: 2}, `["a"]`},
{[]string{}, &core.SelectField{MaxSelect: 2}, `[]`},
{[]string{"a", "b", "c"}, &core.SelectField{MaxSelect: 2}, `["a","b","c"]`},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v_%v", i, s.raw, s.field.IsMultiple()), func(t *testing.T) {
v, err := s.field.PrepareValue(record, s.raw)
if err != nil {
t.Fatal(err)
}
vRaw, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
if string(vRaw) != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, vRaw)
}
})
}
}
func TestSelectFieldDriverValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
raw any
field *core.SelectField
expected string
}{
// single
{nil, &core.SelectField{}, `""`},
{"", &core.SelectField{}, `""`},
{123, &core.SelectField{}, `"123"`},
{"a", &core.SelectField{}, `"a"`},
{`["a"]`, &core.SelectField{}, `"a"`},
{[]string{}, &core.SelectField{}, `""`},
{[]string{"a", "b"}, &core.SelectField{}, `"b"`},
// multiple
{nil, &core.SelectField{MaxSelect: 2}, `[]`},
{"", &core.SelectField{MaxSelect: 2}, `[]`},
{123, &core.SelectField{MaxSelect: 2}, `["123"]`},
{"a", &core.SelectField{MaxSelect: 2}, `["a"]`},
{`["a"]`, &core.SelectField{MaxSelect: 2}, `["a"]`},
{[]string{}, &core.SelectField{MaxSelect: 2}, `[]`},
{[]string{"a", "b", "c"}, &core.SelectField{MaxSelect: 2}, `["a","b","c"]`},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v_%v", i, s.raw, s.field.IsMultiple()), func(t *testing.T) {
record := core.NewRecord(core.NewBaseCollection("test"))
record.SetRaw(s.field.GetName(), s.raw)
v, err := s.field.DriverValue(record)
if err != nil {
t.Fatal(err)
}
if s.field.IsMultiple() {
_, ok := v.(types.JSONArray[string])
if !ok {
t.Fatalf("Expected types.JSONArray value, got %T", v)
}
} else {
_, ok := v.(string)
if !ok {
t.Fatalf("Expected string value, got %T", v)
}
}
vRaw, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
if string(vRaw) != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, vRaw)
}
})
}
}
func TestSelectFieldValidateValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
values := []string{"a", "b", "c"}
scenarios := []struct {
name string
field *core.SelectField
record func() *core.Record
expectError bool
}{
// single
{
"[single] zero field value (not required)",
&core.SelectField{Name: "test", Values: values, MaxSelect: 1},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "")
return record
},
false,
},
{
"[single] zero field value (required)",
&core.SelectField{Name: "test", Values: values, MaxSelect: 1, Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "")
return record
},
true,
},
{
"[single] unknown value",
&core.SelectField{Name: "test", Values: values, MaxSelect: 1},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "unknown")
return record
},
true,
},
{
"[single] known value",
&core.SelectField{Name: "test", Values: values, MaxSelect: 1},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "a")
return record
},
false,
},
{
"[single] > MaxSelect",
&core.SelectField{Name: "test", Values: values, MaxSelect: 1},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", []string{"a", "b"})
return record
},
true,
},
// multiple
{
"[multiple] zero field value (not required)",
&core.SelectField{Name: "test", Values: values, MaxSelect: 2},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", []string{})
return record
},
false,
},
{
"[multiple] zero field value (required)",
&core.SelectField{Name: "test", Values: values, MaxSelect: 2, Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", []string{})
return record
},
true,
},
{
"[multiple] unknown value",
&core.SelectField{Name: "test", Values: values, MaxSelect: 2},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", []string{"a", "unknown"})
return record
},
true,
},
{
"[multiple] known value",
&core.SelectField{Name: "test", Values: values, MaxSelect: 2},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", []string{"a", "b"})
return record
},
false,
},
{
"[multiple] > MaxSelect",
&core.SelectField{Name: "test", Values: values, MaxSelect: 2},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", []string{"a", "b", "c"})
return record
},
true,
},
{
"[multiple] > MaxSelect (duplicated values)",
&core.SelectField{Name: "test", Values: values, MaxSelect: 2},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", []string{"a", "b", "b", "a"})
return record
},
false,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
err := s.field.ValidateValue(context.Background(), app, s.record())
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
func TestSelectFieldValidateSettings(t *testing.T) {
testDefaultFieldIdValidation(t, core.FieldTypeSelect)
testDefaultFieldNameValidation(t, core.FieldTypeSelect)
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
name string
field func() *core.SelectField
expectErrors []string
}{
{
"zero minimal",
func() *core.SelectField {
return &core.SelectField{
Id: "test",
Name: "test",
}
},
[]string{"values"},
},
{
"MaxSelect > Values length",
func() *core.SelectField {
return &core.SelectField{
Id: "test",
Name: "test",
Values: []string{"a", "b"},
MaxSelect: 3,
}
},
[]string{"maxSelect"},
},
{
"MaxSelect <= Values length",
func() *core.SelectField {
return &core.SelectField{
Id: "test",
Name: "test",
Values: []string{"a", "b"},
MaxSelect: 2,
}
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
field := s.field()
collection := core.NewBaseCollection("test_collection")
collection.Fields.Add(field)
errs := field.ValidateSettings(context.Background(), app, collection)
tests.TestValidationErrors(t, errs, s.expectErrors)
})
}
}
func TestSelectFieldFindSetter(t *testing.T) {
values := []string{"a", "b", "c", "d"}
scenarios := []struct {
name string
key string
value any
field *core.SelectField
hasSetter bool
expected string
}{
{
"no match",
"example",
"b",
&core.SelectField{Name: "test", MaxSelect: 1, Values: values},
false,
"",
},
{
"exact match (single)",
"test",
"b",
&core.SelectField{Name: "test", MaxSelect: 1, Values: values},
true,
`"b"`,
},
{
"exact match (multiple)",
"test",
[]string{"a", "b"},
&core.SelectField{Name: "test", MaxSelect: 2, Values: values},
true,
`["a","b"]`,
},
{
"append (single)",
"test+",
"b",
&core.SelectField{Name: "test", MaxSelect: 1, Values: values},
true,
`"b"`,
},
{
"append (multiple)",
"test+",
[]string{"a"},
&core.SelectField{Name: "test", MaxSelect: 2, Values: values},
true,
`["c","d","a"]`,
},
{
"prepend (single)",
"+test",
"b",
&core.SelectField{Name: "test", MaxSelect: 1, Values: values},
true,
`"d"`, // the last of the existing values
},
{
"prepend (multiple)",
"+test",
[]string{"a"},
&core.SelectField{Name: "test", MaxSelect: 2, Values: values},
true,
`["a","c","d"]`,
},
{
"subtract (single)",
"test-",
"d",
&core.SelectField{Name: "test", MaxSelect: 1, Values: values},
true,
`"c"`,
},
{
"subtract (multiple)",
"test-",
[]string{"unknown", "c"},
&core.SelectField{Name: "test", MaxSelect: 2, Values: values},
true,
`["d"]`,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
collection := core.NewBaseCollection("test_collection")
collection.Fields.Add(s.field)
setter := s.field.FindSetter(s.key)
hasSetter := setter != nil
if hasSetter != s.hasSetter {
t.Fatalf("Expected hasSetter %v, got %v", s.hasSetter, hasSetter)
}
if !hasSetter {
return
}
record := core.NewRecord(collection)
record.SetRaw(s.field.GetName(), []string{"c", "d"})
setter(record, s.value)
raw, err := json.Marshal(record.Get(s.field.GetName()))
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
if rawStr != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, rawStr)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/db_model.go | core/db_model.go | package core
// Model defines an interface with common methods that all db models should have.
//
// Note: for simplicity composite pk are not supported.
type Model interface {
TableName() string
PK() any
LastSavedPK() any
IsNew() bool
MarkAsNew()
MarkAsNotNew()
}
// BaseModel defines a base struct that is intended to be embedded into other custom models.
type BaseModel struct {
lastSavedPK string
// Id is the primary key of the model.
// It is usually autogenerated by the parent model implementation.
Id string `db:"id" json:"id" form:"id" xml:"id"`
}
// LastSavedPK returns the last saved primary key of the model.
//
// Its value is updated to the latest PK value after MarkAsNotNew() or PostScan() calls.
func (m *BaseModel) LastSavedPK() any {
return m.lastSavedPK
}
func (m *BaseModel) PK() any {
return m.Id
}
// IsNew indicates what type of db query (insert or update)
// should be used with the model instance.
func (m *BaseModel) IsNew() bool {
return m.lastSavedPK == ""
}
// MarkAsNew clears the pk field and marks the current model as "new"
// (aka. forces m.IsNew() to be true).
func (m *BaseModel) MarkAsNew() {
m.lastSavedPK = ""
}
// MarkAsNew set the pk field to the Id value and marks the current model
// as NOT "new" (aka. forces m.IsNew() to be false).
func (m *BaseModel) MarkAsNotNew() {
m.lastSavedPK = m.Id
}
// PostScan implements the [dbx.PostScanner] interface.
//
// It is usually executed right after the model is populated with the db row values.
func (m *BaseModel) PostScan() error {
m.MarkAsNotNew()
return nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/event_request_batch.go | core/event_request_batch.go | package core
import (
"net/http"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/tools/hook"
)
type BatchRequestEvent struct {
hook.Event
*RequestEvent
Batch []*InternalRequest
}
type InternalRequest struct {
// note: for uploading files the value must be either *filesystem.File or []*filesystem.File
Body map[string]any `form:"body" json:"body"`
Headers map[string]string `form:"headers" json:"headers"`
Method string `form:"method" json:"method"`
URL string `form:"url" json:"url"`
}
func (br InternalRequest) Validate() error {
return validation.ValidateStruct(&br,
validation.Field(&br.Method, validation.Required, validation.In(http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete)),
validation.Field(&br.URL, validation.Required, validation.Length(0, 2000)),
)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field.go | core/field.go | package core
import (
"context"
"database/sql/driver"
"regexp"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tools/list"
)
var fieldNameRegex = regexp.MustCompile(`^\w+$`)
const maxSafeJSONInt int64 = 1<<53 - 1
// Commonly used field names.
const (
FieldNameId = "id"
FieldNameCollectionId = "collectionId"
FieldNameCollectionName = "collectionName"
FieldNameExpand = "expand"
FieldNameEmail = "email"
FieldNameEmailVisibility = "emailVisibility"
FieldNameVerified = "verified"
FieldNameTokenKey = "tokenKey"
FieldNamePassword = "password"
)
// SystemFields returns special internal field names that are usually readonly.
var SystemDynamicFieldNames = []string{
FieldNameCollectionId,
FieldNameCollectionName,
FieldNameExpand,
}
// Common RecordInterceptor action names.
const (
InterceptorActionValidate = "validate"
InterceptorActionDelete = "delete"
InterceptorActionDeleteExecute = "deleteExecute"
InterceptorActionAfterDelete = "afterDelete"
InterceptorActionAfterDeleteError = "afterDeleteError"
InterceptorActionCreate = "create"
InterceptorActionCreateExecute = "createExecute"
InterceptorActionAfterCreate = "afterCreate"
InterceptorActionAfterCreateError = "afterCreateFailure"
InterceptorActionUpdate = "update"
InterceptorActionUpdateExecute = "updateExecute"
InterceptorActionAfterUpdate = "afterUpdate"
InterceptorActionAfterUpdateError = "afterUpdateError"
)
// Common field errors.
var (
ErrUnknownField = validation.NewError("validation_unknown_field", "Unknown or invalid field.")
ErrInvalidFieldValue = validation.NewError("validation_invalid_field_value", "Invalid field value.")
ErrMustBeSystemAndHidden = validation.NewError("validation_must_be_system_and_hidden", `The field must be marked as "System" and "Hidden".`)
ErrMustBeSystem = validation.NewError("validation_must_be_system", `The field must be marked as "System".`)
)
// FieldFactoryFunc defines a simple function to construct a specific Field instance.
type FieldFactoryFunc func() Field
// Fields holds all available collection fields.
var Fields = map[string]FieldFactoryFunc{}
// Field defines a common interface that all Collection fields should implement.
type Field interface {
// note: the getters has an explicit "Get" prefix to avoid conflicts with their related field members
// GetId returns the field id.
GetId() string
// SetId changes the field id.
SetId(id string)
// GetName returns the field name.
GetName() string
// SetName changes the field name.
SetName(name string)
// GetSystem returns the field system flag state.
GetSystem() bool
// SetSystem changes the field system flag state.
SetSystem(system bool)
// GetHidden returns the field hidden flag state.
GetHidden() bool
// SetHidden changes the field hidden flag state.
SetHidden(hidden bool)
// Type returns the unique type of the field.
Type() string
// ColumnType returns the DB column definition of the field.
ColumnType(app App) string
// PrepareValue returns a properly formatted field value based on the provided raw one.
//
// This method is also called on record construction to initialize its default field value.
PrepareValue(record *Record, raw any) (any, error)
// ValidateSettings validates the current field value associated with the provided record.
ValidateValue(ctx context.Context, app App, record *Record) error
// ValidateSettings validates the current field settings.
ValidateSettings(ctx context.Context, app App, collection *Collection) error
}
// MaxBodySizeCalculator defines an optional field interface for
// specifying the max size of a field value.
type MaxBodySizeCalculator interface {
// CalculateMaxBodySize returns the approximate max body size of a field value.
CalculateMaxBodySize() int64
}
type (
SetterFunc func(record *Record, raw any)
// SetterFinder defines a field interface for registering custom field value setters.
SetterFinder interface {
// FindSetter returns a single field value setter function
// by performing pattern-like field matching using the specified key.
//
// The key is usually just the field name but it could also
// contains "modifier" characters based on which you can perform custom set operations
// (ex. "users+" could be mapped to a function that will append new user to the existing field value).
//
// Return nil if you want to fallback to the default field value setter.
FindSetter(key string) SetterFunc
}
)
type (
GetterFunc func(record *Record) any
// GetterFinder defines a field interface for registering custom field value getters.
GetterFinder interface {
// FindGetter returns a single field value getter function
// by performing pattern-like field matching using the specified key.
//
// The key is usually just the field name but it could also
// contains "modifier" characters based on which you can perform custom get operations
// (ex. "description:excerpt" could be mapped to a function that will return an excerpt of the current field value).
//
// Return nil if you want to fallback to the default field value setter.
FindGetter(key string) GetterFunc
}
)
// DriverValuer defines a Field interface for exporting and formatting
// a field value for the database.
type DriverValuer interface {
// DriverValue exports a single field value for persistence in the database.
DriverValue(record *Record) (driver.Value, error)
}
// MultiValuer defines a field interface that every multi-valued (eg. with MaxSelect) field has.
type MultiValuer interface {
// IsMultiple checks whether the field is configured to support multiple or single values.
IsMultiple() bool
}
// RecordInterceptor defines a field interface for reacting to various
// Record related operations (create, delete, validate, etc.).
type RecordInterceptor interface {
// Interceptor is invoked when a specific record action occurs
// allowing you to perform extra validations and normalization
// (ex. uploading or deleting files).
//
// Note that users must call actionFunc() manually if they want to
// execute the specific record action.
Intercept(
ctx context.Context,
app App,
record *Record,
actionName string,
actionFunc func() error,
) error
}
// DefaultFieldIdValidationRule performs base validation on a field id value.
func DefaultFieldIdValidationRule(value any) error {
v, ok := value.(string)
if !ok {
return validators.ErrUnsupportedValueType
}
rules := []validation.Rule{
validation.Required,
validation.Length(1, 100),
}
for _, r := range rules {
if err := r.Validate(v); err != nil {
return err
}
}
return nil
}
// exclude special filter and system literals
var excludeNames = append([]any{
"null", "true", "false", "_rowid_",
}, list.ToInterfaceSlice(SystemDynamicFieldNames)...)
// DefaultFieldIdValidationRule performs base validation on a field name value.
func DefaultFieldNameValidationRule(value any) error {
v, ok := value.(string)
if !ok {
return validators.ErrUnsupportedValueType
}
rules := []validation.Rule{
validation.Required,
validation.Length(1, 100),
validation.Match(fieldNameRegex),
validation.NotIn(excludeNames...),
validation.By(checkForVia),
}
for _, r := range rules {
if err := r.Validate(v); err != nil {
return err
}
}
return nil
}
func checkForVia(value any) error {
v, _ := value.(string)
if v == "" {
return nil
}
if strings.Contains(strings.ToLower(v), "_via_") {
return validation.NewError("validation_found_via", `The value cannot contain "_via_".`)
}
return nil
}
func noopSetter(record *Record, raw any) {
// do nothing
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/db_test.go | core/db_test.go | package core_test
import (
"context"
"errors"
"testing"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestGenerateDefaultRandomId(t *testing.T) {
t.Parallel()
id1 := core.GenerateDefaultRandomId()
id2 := core.GenerateDefaultRandomId()
if id1 == id2 {
t.Fatalf("Expected id1 and id2 to differ, got %q", id1)
}
if l := len(id1); l != 15 {
t.Fatalf("Expected id1 length %d, got %d", 15, l)
}
if l := len(id2); l != 15 {
t.Fatalf("Expected id2 length %d, got %d", 15, l)
}
}
func TestModelQuery(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
modelsQuery := app.ModelQuery(&core.Collection{})
logsModelQuery := app.AuxModelQuery(&core.Collection{})
if app.ConcurrentDB() == modelsQuery.Info().Builder {
t.Fatalf("ModelQuery() is not using app.ConcurrentDB()")
}
if app.AuxConcurrentDB() == logsModelQuery.Info().Builder {
t.Fatalf("AuxModelQuery() is not using app.AuxConcurrentDB()")
}
expectedSQL := "SELECT {{_collections}}.* FROM `_collections`"
for i, q := range []*dbx.SelectQuery{modelsQuery, logsModelQuery} {
sql := q.Build().SQL()
if sql != expectedSQL {
t.Fatalf("[%d] Expected select\n%s\ngot\n%s", i, expectedSQL, sql)
}
}
}
func TestValidate(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
u := &mockSuperusers{}
testErr := errors.New("test")
app.OnModelValidate().BindFunc(func(e *core.ModelEvent) error {
return testErr
})
err := app.Validate(u)
if err != testErr {
t.Fatalf("Expected error %v, got %v", testErr, err)
}
}
func TestValidateWithContext(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
u := &mockSuperusers{}
testErr := errors.New("test")
app.OnModelValidate().BindFunc(func(e *core.ModelEvent) error {
if v := e.Context.Value("test"); v != 123 {
t.Fatalf("Expected 'test' context value %#v, got %#v", 123, v)
}
return testErr
})
//nolint:staticcheck
ctx := context.WithValue(context.Background(), "test", 123)
err := app.ValidateWithContext(ctx, u)
if err != testErr {
t.Fatalf("Expected error %v, got %v", testErr, err)
}
}
// -------------------------------------------------------------------
type mockSuperusers struct {
core.BaseModel
Email string `db:"email"`
}
func (m *mockSuperusers) TableName() string {
return core.CollectionNameSuperusers
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/collection_query.go | core/collection_query.go | package core
import (
"bytes"
"database/sql"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/list"
)
const StoreKeyCachedCollections = "pbAppCachedCollections"
// CollectionQuery returns a new Collection select query.
func (app *BaseApp) CollectionQuery() *dbx.SelectQuery {
return app.ModelQuery(&Collection{})
}
// FindCollections finds all collections by the given type(s).
//
// If collectionTypes is not set, it returns all collections.
//
// Example:
//
// app.FindAllCollections() // all collections
// app.FindAllCollections("auth", "view") // only auth and view collections
func (app *BaseApp) FindAllCollections(collectionTypes ...string) ([]*Collection, error) {
collections := []*Collection{}
q := app.CollectionQuery()
types := list.NonzeroUniques(collectionTypes)
if len(types) > 0 {
q.AndWhere(dbx.In("type", list.ToInterfaceSlice(types)...))
}
err := q.OrderBy("rowid ASC").All(&collections)
if err != nil {
return nil, err
}
return collections, nil
}
// ReloadCachedCollections fetches all collections and caches them into the app store.
func (app *BaseApp) ReloadCachedCollections() error {
collections, err := app.FindAllCollections()
if err != nil {
return err
}
app.Store().Set(StoreKeyCachedCollections, collections)
return nil
}
// FindCollectionByNameOrId finds a single collection by its name (case insensitive) or id.
func (app *BaseApp) FindCollectionByNameOrId(nameOrId string) (*Collection, error) {
m := &Collection{}
err := app.CollectionQuery().
AndWhere(dbx.NewExp("[[id]]={:id} OR LOWER([[name]])={:name}", dbx.Params{
"id": nameOrId,
"name": strings.ToLower(nameOrId),
})).
Limit(1).
One(m)
if err != nil {
return nil, err
}
return m, nil
}
// FindCachedCollectionByNameOrId is similar to [BaseApp.FindCollectionByNameOrId]
// but retrieves the Collection from the app cache instead of making a db call.
//
// NB! This method is suitable for read-only Collection operations.
//
// Returns [sql.ErrNoRows] if no Collection is found for consistency
// with the [BaseApp.FindCollectionByNameOrId] method.
//
// If you plan making changes to the returned Collection model,
// use [BaseApp.FindCollectionByNameOrId] instead.
//
// Caveats:
//
// - The returned Collection should be used only for read-only operations.
// Avoid directly modifying the returned cached Collection as it will affect
// the global cached value even if you don't persist the changes in the database!
// - If you are updating a Collection in a transaction and then call this method before commit,
// it'll return the cached Collection state and not the one from the uncommitted transaction.
// - The cache is automatically updated on collections db change (create/update/delete).
// To manually reload the cache you can call [BaseApp.ReloadCachedCollections].
func (app *BaseApp) FindCachedCollectionByNameOrId(nameOrId string) (*Collection, error) {
collections, _ := app.Store().Get(StoreKeyCachedCollections).([]*Collection)
if collections == nil {
// cache is not initialized yet (eg. run in a system migration)
return app.FindCollectionByNameOrId(nameOrId)
}
for _, c := range collections {
if strings.EqualFold(c.Name, nameOrId) || c.Id == nameOrId {
return c, nil
}
}
return nil, sql.ErrNoRows
}
// FindCollectionReferences returns information for all relation fields
// referencing the provided collection.
//
// If the provided collection has reference to itself then it will be
// also included in the result. To exclude it, pass the collection id
// as the excludeIds argument.
func (app *BaseApp) FindCollectionReferences(collection *Collection, excludeIds ...string) (map[*Collection][]Field, error) {
collections := []*Collection{}
query := app.CollectionQuery()
if uniqueExcludeIds := list.NonzeroUniques(excludeIds); len(uniqueExcludeIds) > 0 {
query.AndWhere(dbx.NotIn("id", list.ToInterfaceSlice(uniqueExcludeIds)...))
}
if err := query.All(&collections); err != nil {
return nil, err
}
result := map[*Collection][]Field{}
for _, c := range collections {
for _, rawField := range c.Fields {
f, ok := rawField.(*RelationField)
if ok && f.CollectionId == collection.Id {
result[c] = append(result[c], f)
}
}
}
return result, nil
}
// FindCachedCollectionReferences is similar to [BaseApp.FindCollectionReferences]
// but retrieves the Collection from the app cache instead of making a db call.
//
// NB! This method is suitable for read-only Collection operations.
//
// If you plan making changes to the returned Collection model,
// use [BaseApp.FindCollectionReferences] instead.
//
// Caveats:
//
// - The returned Collection should be used only for read-only operations.
// Avoid directly modifying the returned cached Collection as it will affect
// the global cached value even if you don't persist the changes in the database!
// - If you are updating a Collection in a transaction and then call this method before commit,
// it'll return the cached Collection state and not the one from the uncommitted transaction.
// - The cache is automatically updated on collections db change (create/update/delete).
// To manually reload the cache you can call [BaseApp.ReloadCachedCollections].
func (app *BaseApp) FindCachedCollectionReferences(collection *Collection, excludeIds ...string) (map[*Collection][]Field, error) {
collections, _ := app.Store().Get(StoreKeyCachedCollections).([]*Collection)
if collections == nil {
// cache is not initialized yet (eg. run in a system migration)
return app.FindCollectionReferences(collection, excludeIds...)
}
result := map[*Collection][]Field{}
for _, c := range collections {
if slices.Contains(excludeIds, c.Id) {
continue
}
for _, rawField := range c.Fields {
f, ok := rawField.(*RelationField)
if ok && f.CollectionId == collection.Id {
result[c] = append(result[c], f)
}
}
}
return result, nil
}
// IsCollectionNameUnique checks that there is no existing collection
// with the provided name (case insensitive!).
//
// Note: case insensitive check because the name is used also as
// table name for the records.
func (app *BaseApp) IsCollectionNameUnique(name string, excludeIds ...string) bool {
if name == "" {
return false
}
query := app.CollectionQuery().
Select("count(*)").
AndWhere(dbx.NewExp("LOWER([[name]])={:name}", dbx.Params{"name": strings.ToLower(name)})).
Limit(1)
if uniqueExcludeIds := list.NonzeroUniques(excludeIds); len(uniqueExcludeIds) > 0 {
query.AndWhere(dbx.NotIn("id", list.ToInterfaceSlice(uniqueExcludeIds)...))
}
var total int
return query.Row(&total) == nil && total == 0
}
// TruncateCollection deletes all records associated with the provided collection.
//
// The truncate operation is executed in a single transaction,
// aka. either everything is deleted or none.
//
// Note that this method will also trigger the records related
// cascade and file delete actions.
func (app *BaseApp) TruncateCollection(collection *Collection) error {
if collection.IsView() {
return errors.New("view collections cannot be truncated since they don't store their own records")
}
return app.RunInTransaction(func(txApp App) error {
records := make([]*Record, 0, 500)
for {
err := txApp.RecordQuery(collection).Limit(500).All(&records)
if err != nil {
return err
}
if len(records) == 0 {
return nil
}
for _, record := range records {
err = txApp.Delete(record)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return err
}
}
records = records[:0]
}
})
}
// -------------------------------------------------------------------
// saveViewCollection persists the provided View collection changes:
// - deletes the old related SQL view (if any)
// - creates a new SQL view with the latest newCollection.Options.Query
// - generates new feilds list based on newCollection.Options.Query
// - updates newCollection.Fields based on the generated view table info and query
// - saves the newCollection
//
// This method returns an error if newCollection is not a "view".
func saveViewCollection(app App, newCollection, oldCollection *Collection) error {
if !newCollection.IsView() {
return errors.New("not a view collection")
}
return app.RunInTransaction(func(txApp App) error {
query := newCollection.ViewQuery
// generate collection fields from the query
viewFields, err := txApp.CreateViewFields(query)
if err != nil {
return err
}
// delete old renamed view
if oldCollection != nil {
if err := txApp.DeleteView(oldCollection.Name); err != nil {
return err
}
}
// wrap view query if necessary
query, err = normalizeViewQueryId(txApp, query)
if err != nil {
return fmt.Errorf("failed to normalize view query id: %w", err)
}
// (re)create the view
if err := txApp.SaveView(newCollection.Name, query); err != nil {
return err
}
newCollection.Fields = viewFields
return txApp.Save(newCollection)
})
}
// normalizeViewQueryId wraps (if necessary) the provided view query
// with a subselect to ensure that the id column is a text since
// currently we don't support non-string model ids
// (see https://github.com/pocketbase/pocketbase/issues/3110).
func normalizeViewQueryId(app App, query string) (string, error) {
query = strings.Trim(strings.TrimSpace(query), ";")
info, err := getQueryTableInfo(app, query)
if err != nil {
return "", err
}
for _, row := range info {
if strings.EqualFold(row.Name, FieldNameId) && strings.EqualFold(row.Type, "TEXT") {
return query, nil // no wrapping needed
}
}
// raw parse to preserve the columns order
rawParsed := new(identifiersParser)
if err := rawParsed.parse(query); err != nil {
return "", err
}
columns := make([]string, 0, len(rawParsed.columns))
for _, col := range rawParsed.columns {
if col.alias == FieldNameId {
columns = append(columns, fmt.Sprintf("CAST([[%s]] as TEXT) [[%s]]", col.alias, col.alias))
} else {
columns = append(columns, "[["+col.alias+"]]")
}
}
query = fmt.Sprintf("SELECT %s FROM (%s)", strings.Join(columns, ","), query)
return query, nil
}
// resaveViewsWithChangedFields updates all view collections with changed fields.
func resaveViewsWithChangedFields(app App, excludeIds ...string) error {
collections, err := app.FindAllCollections(CollectionTypeView)
if err != nil {
return err
}
return app.RunInTransaction(func(txApp App) error {
for _, collection := range collections {
if len(excludeIds) > 0 && list.ExistInSlice(collection.Id, excludeIds) {
continue
}
// clone the existing fields for temp modifications
oldFields, err := collection.Fields.Clone()
if err != nil {
return err
}
// generate new fields from the query
newFields, err := txApp.CreateViewFields(collection.ViewQuery)
if err != nil {
return err
}
// unset the fields' ids to exclude from the comparison
for _, f := range oldFields {
f.SetId("")
}
for _, f := range newFields {
f.SetId("")
}
encodedNewFields, err := json.Marshal(newFields)
if err != nil {
return err
}
encodedOldFields, err := json.Marshal(oldFields)
if err != nil {
return err
}
if bytes.EqualFold(encodedNewFields, encodedOldFields) {
continue // no changes
}
if err := saveViewCollection(txApp, collection, nil); err != nil {
return err
}
}
return nil
})
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/otp_model_test.go | core/otp_model_test.go | package core_test
import (
"fmt"
"testing"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestNewOTP(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
otp := core.NewOTP(app)
if otp.Collection().Name != core.CollectionNameOTPs {
t.Fatalf("Expected record with %q collection, got %q", core.CollectionNameOTPs, otp.Collection().Name)
}
}
func TestOTPProxyRecord(t *testing.T) {
t.Parallel()
record := core.NewRecord(core.NewBaseCollection("test"))
record.Id = "test_id"
otp := core.OTP{}
otp.SetProxyRecord(record)
if otp.ProxyRecord() == nil || otp.ProxyRecord().Id != record.Id {
t.Fatalf("Expected proxy record with id %q, got %v", record.Id, otp.ProxyRecord())
}
}
func TestOTPRecordRef(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
otp := core.NewOTP(app)
testValues := []string{"test_1", "test2", ""}
for i, testValue := range testValues {
t.Run(fmt.Sprintf("%d_%q", i, testValue), func(t *testing.T) {
otp.SetRecordRef(testValue)
if v := otp.RecordRef(); v != testValue {
t.Fatalf("Expected getter %q, got %q", testValue, v)
}
if v := otp.GetString("recordRef"); v != testValue {
t.Fatalf("Expected field value %q, got %q", testValue, v)
}
})
}
}
func TestOTPCollectionRef(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
otp := core.NewOTP(app)
testValues := []string{"test_1", "test2", ""}
for i, testValue := range testValues {
t.Run(fmt.Sprintf("%d_%q", i, testValue), func(t *testing.T) {
otp.SetCollectionRef(testValue)
if v := otp.CollectionRef(); v != testValue {
t.Fatalf("Expected getter %q, got %q", testValue, v)
}
if v := otp.GetString("collectionRef"); v != testValue {
t.Fatalf("Expected field value %q, got %q", testValue, v)
}
})
}
}
func TestOTPSentTo(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
otp := core.NewOTP(app)
testValues := []string{"test_1", "test2", ""}
for i, testValue := range testValues {
t.Run(fmt.Sprintf("%d_%q", i, testValue), func(t *testing.T) {
otp.SetSentTo(testValue)
if v := otp.SentTo(); v != testValue {
t.Fatalf("Expected getter %q, got %q", testValue, v)
}
if v := otp.GetString("sentTo"); v != testValue {
t.Fatalf("Expected field value %q, got %q", testValue, v)
}
})
}
}
func TestOTPCreated(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
otp := core.NewOTP(app)
if v := otp.Created().String(); v != "" {
t.Fatalf("Expected empty created, got %q", v)
}
now := types.NowDateTime()
otp.SetRaw("created", now)
if v := otp.Created().String(); v != now.String() {
t.Fatalf("Expected %q created, got %q", now.String(), v)
}
}
func TestOTPUpdated(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
otp := core.NewOTP(app)
if v := otp.Updated().String(); v != "" {
t.Fatalf("Expected empty updated, got %q", v)
}
now := types.NowDateTime()
otp.SetRaw("updated", now)
if v := otp.Updated().String(); v != now.String() {
t.Fatalf("Expected %q updated, got %q", now.String(), v)
}
}
func TestOTPHasExpired(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
now := types.NowDateTime()
otp := core.NewOTP(app)
otp.SetRaw("created", now.Add(-5*time.Minute))
scenarios := []struct {
maxElapsed time.Duration
expected bool
}{
{0 * time.Minute, true},
{3 * time.Minute, true},
{5 * time.Minute, true},
{6 * time.Minute, false},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.maxElapsed.String()), func(t *testing.T) {
result := otp.HasExpired(s.maxElapsed)
if result != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, result)
}
})
}
}
func TestOTPPreValidate(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
otpsCol, err := app.FindCollectionByNameOrId(core.CollectionNameOTPs)
if err != nil {
t.Fatal(err)
}
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
t.Run("no proxy record", func(t *testing.T) {
otp := &core.OTP{}
if err := app.Validate(otp); err == nil {
t.Fatal("Expected collection validation error")
}
})
t.Run("non-OTP collection", func(t *testing.T) {
otp := &core.OTP{}
otp.SetProxyRecord(core.NewRecord(core.NewBaseCollection("invalid")))
otp.SetRecordRef(user.Id)
otp.SetCollectionRef(user.Collection().Id)
otp.SetPassword("test123")
if err := app.Validate(otp); err == nil {
t.Fatal("Expected collection validation error")
}
})
t.Run("OTP collection", func(t *testing.T) {
otp := &core.OTP{}
otp.SetProxyRecord(core.NewRecord(otpsCol))
otp.SetRecordRef(user.Id)
otp.SetCollectionRef(user.Collection().Id)
otp.SetPassword("test123")
if err := app.Validate(otp); err != nil {
t.Fatalf("Expected nil validation error, got %v", err)
}
})
}
func TestOTPValidateHook(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
demo1, err := app.FindRecordById("demo1", "84nmscqy84lsi1t")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
otp func() *core.OTP
expectErrors []string
}{
{
"empty",
func() *core.OTP {
return core.NewOTP(app)
},
[]string{"collectionRef", "recordRef", "password"},
},
{
"non-auth collection",
func() *core.OTP {
otp := core.NewOTP(app)
otp.SetCollectionRef(demo1.Collection().Id)
otp.SetRecordRef(demo1.Id)
otp.SetPassword("test123")
return otp
},
[]string{"collectionRef"},
},
{
"missing record id",
func() *core.OTP {
otp := core.NewOTP(app)
otp.SetCollectionRef(user.Collection().Id)
otp.SetRecordRef("missing")
otp.SetPassword("test123")
return otp
},
[]string{"recordRef"},
},
{
"valid ref",
func() *core.OTP {
otp := core.NewOTP(app)
otp.SetCollectionRef(user.Collection().Id)
otp.SetRecordRef(user.Id)
otp.SetPassword("test123")
return otp
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
errs := app.Validate(s.otp())
tests.TestValidationErrors(t, errs, s.expectErrors)
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_query_test.go | core/record_query_test.go | package core_test
import (
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"testing"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/dbutils"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestRecordQueryWithDifferentCollectionValues(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, err := app.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
collection any
expectedTotal int
expectError bool
}{
{"with nil value", nil, 0, true},
{"with invalid or missing collection id/name", "missing", 0, true},
{"with pointer model", collection, 3, false},
{"with value model", *collection, 3, false},
{"with name", "demo1", 3, false},
{"with id", "wsmn24bux7wo113", 3, false},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
var records []*core.Record
err := app.RecordQuery(s.collection).All(&records)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasError %v, got %v", s.expectError, hasErr)
}
if total := len(records); total != s.expectedTotal {
t.Fatalf("Expected %d records, got %d", s.expectedTotal, total)
}
})
}
}
func TestRecordQueryOne(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
name string
collection string
recordId string
model any
}{
{
"record model",
"demo1",
"84nmscqy84lsi1t",
&core.Record{},
},
{
"record proxy",
"demo1",
"84nmscqy84lsi1t",
&struct {
core.BaseRecordProxy
}{},
},
{
"custom struct",
"demo1",
"84nmscqy84lsi1t",
&struct {
Id string `db:"id" json:"id"`
}{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
collection, err := app.FindCollectionByNameOrId(s.collection)
if err != nil {
t.Fatal(err)
}
q := app.RecordQuery(collection).
Where(dbx.HashExp{"id": s.recordId})
if err := q.One(s.model); err != nil {
t.Fatal(err)
}
raw, err := json.Marshal(s.model)
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
if !strings.Contains(rawStr, fmt.Sprintf(`"id":%q`, s.recordId)) {
t.Fatalf("Missing id %q in\n%s", s.recordId, rawStr)
}
})
}
}
func TestRecordQueryAll(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
type customStructs struct {
Id string `db:"id" json:"id"`
}
type mockRecordProxy struct {
core.BaseRecordProxy
}
scenarios := []struct {
name string
collection string
recordIds []any
result any
}{
{
"slice of Record models",
"demo1",
[]any{"84nmscqy84lsi1t", "al1h9ijdeojtsjy"},
&[]core.Record{},
},
{
"slice of pointer Record models",
"demo1",
[]any{"84nmscqy84lsi1t", "al1h9ijdeojtsjy"},
&[]*core.Record{},
},
{
"slice of Record proxies",
"demo1",
[]any{"84nmscqy84lsi1t", "al1h9ijdeojtsjy"},
&[]mockRecordProxy{},
},
{
"slice of pointer Record proxies",
"demo1",
[]any{"84nmscqy84lsi1t", "al1h9ijdeojtsjy"},
&[]mockRecordProxy{},
},
{
"slice of custom structs",
"demo1",
[]any{"84nmscqy84lsi1t", "al1h9ijdeojtsjy"},
&[]customStructs{},
},
{
"slice of pointer custom structs",
"demo1",
[]any{"84nmscqy84lsi1t", "al1h9ijdeojtsjy"},
&[]customStructs{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
collection, err := app.FindCollectionByNameOrId(s.collection)
if err != nil {
t.Fatal(err)
}
q := app.RecordQuery(collection).
Where(dbx.HashExp{"id": s.recordIds})
if err := q.All(s.result); err != nil {
t.Fatal(err)
}
raw, err := json.Marshal(s.result)
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
sliceOfMaps := []any{}
if err := json.Unmarshal(raw, &sliceOfMaps); err != nil {
t.Fatal(err)
}
if len(sliceOfMaps) != len(s.recordIds) {
t.Fatalf("Expected %d items, got %d", len(s.recordIds), len(sliceOfMaps))
}
for _, id := range s.recordIds {
if !strings.Contains(rawStr, fmt.Sprintf(`"id":%q`, id)) {
t.Fatalf("Missing id %q in\n%s", id, rawStr)
}
}
})
}
}
func TestFindRecordById(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
collectionIdOrName string
id string
filters []func(q *dbx.SelectQuery) error
expectError bool
}{
{"demo2", "missing", nil, true},
{"missing", "0yxhwia2amd8gec", nil, true},
{"demo2", "0yxhwia2amd8gec", nil, false},
{"demo2", "0yxhwia2amd8gec", []func(q *dbx.SelectQuery) error{}, false},
{"demo2", "0yxhwia2amd8gec", []func(q *dbx.SelectQuery) error{nil, nil}, false},
{"demo2", "0yxhwia2amd8gec", []func(q *dbx.SelectQuery) error{
nil,
func(q *dbx.SelectQuery) error { return nil },
}, false},
{"demo2", "0yxhwia2amd8gec", []func(q *dbx.SelectQuery) error{
func(q *dbx.SelectQuery) error {
q.AndWhere(dbx.HashExp{"title": "missing"})
return nil
},
}, true},
{"demo2", "0yxhwia2amd8gec", []func(q *dbx.SelectQuery) error{
func(q *dbx.SelectQuery) error {
return errors.New("test error")
},
}, true},
{"demo2", "0yxhwia2amd8gec", []func(q *dbx.SelectQuery) error{
func(q *dbx.SelectQuery) error {
q.AndWhere(dbx.HashExp{"title": "test3"})
return nil
},
}, false},
{"demo2", "0yxhwia2amd8gec", []func(q *dbx.SelectQuery) error{
func(q *dbx.SelectQuery) error {
q.AndWhere(dbx.HashExp{"title": "test3"})
return nil
},
nil,
}, false},
{"demo2", "0yxhwia2amd8gec", []func(q *dbx.SelectQuery) error{
func(q *dbx.SelectQuery) error {
q.AndWhere(dbx.HashExp{"title": "test3"})
return nil
},
func(q *dbx.SelectQuery) error {
q.AndWhere(dbx.HashExp{"active": false})
return nil
},
}, true},
{"sz5l5z67tg7gku0", "0yxhwia2amd8gec", []func(q *dbx.SelectQuery) error{
func(q *dbx.SelectQuery) error {
q.AndWhere(dbx.HashExp{"title": "test3"})
return nil
},
func(q *dbx.SelectQuery) error {
q.AndWhere(dbx.HashExp{"active": true})
return nil
},
}, false},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s_%s_%d", i, s.collectionIdOrName, s.id, len(s.filters)), func(t *testing.T) {
record, err := app.FindRecordById(
s.collectionIdOrName,
s.id,
s.filters...,
)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
if record != nil && record.Id != s.id {
t.Fatalf("Expected record with id %s, got %s", s.id, record.Id)
}
})
}
}
func TestFindRecordsByIds(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
collectionIdOrName string
ids []string
filters []func(q *dbx.SelectQuery) error
expectTotal int
expectError bool
}{
{"demo2", []string{}, nil, 0, false},
{"demo2", []string{""}, nil, 0, false},
{"demo2", []string{"missing"}, nil, 0, false},
{"missing", []string{"0yxhwia2amd8gec"}, nil, 0, true},
{"demo2", []string{"0yxhwia2amd8gec"}, nil, 1, false},
{"sz5l5z67tg7gku0", []string{"0yxhwia2amd8gec"}, nil, 1, false},
{
"demo2",
[]string{"0yxhwia2amd8gec", "llvuca81nly1qls"},
nil,
2,
false,
},
{
"demo2",
[]string{"0yxhwia2amd8gec", "llvuca81nly1qls"},
[]func(q *dbx.SelectQuery) error{},
2,
false,
},
{
"demo2",
[]string{"0yxhwia2amd8gec", "llvuca81nly1qls"},
[]func(q *dbx.SelectQuery) error{nil, nil},
2,
false,
},
{
"demo2",
[]string{"0yxhwia2amd8gec", "llvuca81nly1qls"},
[]func(q *dbx.SelectQuery) error{
func(q *dbx.SelectQuery) error {
return nil // empty filter
},
},
2,
false,
},
{
"demo2",
[]string{"0yxhwia2amd8gec", "llvuca81nly1qls"},
[]func(q *dbx.SelectQuery) error{
func(q *dbx.SelectQuery) error {
return nil // empty filter
},
func(q *dbx.SelectQuery) error {
return errors.New("test error")
},
},
0,
true,
},
{
"demo2",
[]string{"0yxhwia2amd8gec", "llvuca81nly1qls"},
[]func(q *dbx.SelectQuery) error{
func(q *dbx.SelectQuery) error {
q.AndWhere(dbx.HashExp{"active": true})
return nil
},
nil,
},
1,
false,
},
{
"sz5l5z67tg7gku0",
[]string{"0yxhwia2amd8gec", "llvuca81nly1qls"},
[]func(q *dbx.SelectQuery) error{
func(q *dbx.SelectQuery) error {
q.AndWhere(dbx.HashExp{"active": true})
return nil
},
func(q *dbx.SelectQuery) error {
q.AndWhere(dbx.Not(dbx.HashExp{"title": ""}))
return nil
},
},
1,
false,
},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s_%v_%d", i, s.collectionIdOrName, s.ids, len(s.filters)), func(t *testing.T) {
records, err := app.FindRecordsByIds(
s.collectionIdOrName,
s.ids,
s.filters...,
)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
if len(records) != s.expectTotal {
t.Fatalf("Expected %d records, got %d", s.expectTotal, len(records))
}
for _, r := range records {
if !slices.Contains(s.ids, r.Id) {
t.Fatalf("Couldn't find id %s in %v", r.Id, s.ids)
}
}
})
}
}
func TestFindAllRecords(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
collectionIdOrName string
expressions []dbx.Expression
expectIds []string
expectError bool
}{
{
"missing",
nil,
[]string{},
true,
},
{
"demo2",
nil,
[]string{
"achvryl401bhse3",
"llvuca81nly1qls",
"0yxhwia2amd8gec",
},
false,
},
{
"demo2",
[]dbx.Expression{
nil,
dbx.HashExp{"id": "123"},
},
[]string{},
false,
},
{
"sz5l5z67tg7gku0",
[]dbx.Expression{
dbx.Like("title", "test").Match(true, true),
dbx.HashExp{"active": true},
},
[]string{
"achvryl401bhse3",
"0yxhwia2amd8gec",
},
false,
},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.collectionIdOrName), func(t *testing.T) {
records, err := app.FindAllRecords(s.collectionIdOrName, s.expressions...)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
if len(records) != len(s.expectIds) {
t.Fatalf("Expected %d records, got %d", len(s.expectIds), len(records))
}
for _, r := range records {
if !slices.Contains(s.expectIds, r.Id) {
t.Fatalf("Couldn't find id %s in %v", r.Id, s.expectIds)
}
}
})
}
}
func TestFindFirstRecordByData(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
collectionIdOrName string
key string
value any
expectId string
expectError bool
}{
{
"missing",
"id",
"llvuca81nly1qls",
"llvuca81nly1qls",
true,
},
{
"demo2",
"",
"llvuca81nly1qls",
"",
true,
},
{
"demo2",
"id",
"invalid",
"",
true,
},
{
"demo2",
"id",
"llvuca81nly1qls",
"llvuca81nly1qls",
false,
},
{
"sz5l5z67tg7gku0",
"title",
"test3",
"0yxhwia2amd8gec",
false,
},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s_%s_%v", i, s.collectionIdOrName, s.key, s.value), func(t *testing.T) {
record, err := app.FindFirstRecordByData(s.collectionIdOrName, s.key, s.value)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
if !s.expectError && record.Id != s.expectId {
t.Fatalf("Expected record with id %s, got %v", s.expectId, record.Id)
}
})
}
}
func TestFindRecordsByFilter(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
name string
collectionIdOrName string
filter string
sort string
limit int
offset int
params []dbx.Params
expectError bool
expectRecordIds []string
}{
{
"missing collection",
"missing",
"id != ''",
"",
0,
0,
nil,
true,
nil,
},
{
"invalid filter",
"demo2",
"someMissingField > 1",
"",
0,
0,
nil,
true,
nil,
},
{
"empty filter",
"demo2",
"",
"",
0,
0,
nil,
false,
[]string{
"llvuca81nly1qls",
"achvryl401bhse3",
"0yxhwia2amd8gec",
},
},
{
"simple filter",
"demo2",
"id != ''",
"",
0,
0,
nil,
false,
[]string{
"llvuca81nly1qls",
"achvryl401bhse3",
"0yxhwia2amd8gec",
},
},
{
"multi-condition filter with sort",
"demo2",
"id != '' && active=true",
"-created,title",
-1, // should behave the same as 0
0,
nil,
false,
[]string{
"0yxhwia2amd8gec",
"achvryl401bhse3",
},
},
{
"with limit and offset",
"sz5l5z67tg7gku0",
"id != ''",
"title",
2,
1,
nil,
false,
[]string{
"achvryl401bhse3",
"0yxhwia2amd8gec",
},
},
{
"with placeholder params",
"demo2",
"active = {:active}",
"",
10,
0,
[]dbx.Params{{"active": false}},
false,
[]string{
"llvuca81nly1qls",
},
},
{
"with json filter and sort",
"demo4",
"json_object != null && json_object.a.b = 'test'",
"-json_object.a",
10,
0,
[]dbx.Params{{"active": false}},
false,
[]string{
"i9naidtvr6qsgb4",
},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
records, err := app.FindRecordsByFilter(
s.collectionIdOrName,
s.filter,
s.sort,
s.limit,
s.offset,
s.params...,
)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
if hasErr {
return
}
if len(records) != len(s.expectRecordIds) {
t.Fatalf("Expected %d records, got %d", len(s.expectRecordIds), len(records))
}
for i, id := range s.expectRecordIds {
if id != records[i].Id {
t.Fatalf("Expected record with id %q, got %q at index %d", id, records[i].Id, i)
}
}
})
}
}
func TestFindFirstRecordByFilter(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
name string
collectionIdOrName string
filter string
params []dbx.Params
expectError bool
expectRecordId string
}{
{
"missing collection",
"missing",
"id != ''",
nil,
true,
"",
},
{
"invalid filter",
"demo2",
"someMissingField > 1",
nil,
true,
"",
},
{
"empty filter",
"demo2",
"",
nil,
false,
"llvuca81nly1qls",
},
{
"valid filter but no matches",
"demo2",
"id = 'test'",
nil,
true,
"",
},
{
"valid filter and multiple matches",
"sz5l5z67tg7gku0",
"id != ''",
nil,
false,
"llvuca81nly1qls",
},
{
"with placeholder params",
"demo2",
"active = {:active}",
[]dbx.Params{{"active": false}},
false,
"llvuca81nly1qls",
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
record, err := app.FindFirstRecordByFilter(s.collectionIdOrName, s.filter, s.params...)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
if hasErr {
return
}
if record.Id != s.expectRecordId {
t.Fatalf("Expected record with id %q, got %q", s.expectRecordId, record.Id)
}
})
}
}
func TestCountRecords(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
name string
collectionIdOrName string
expressions []dbx.Expression
expectTotal int64
expectError bool
}{
{
"missing collection",
"missing",
nil,
0,
true,
},
{
"valid collection name",
"demo2",
nil,
3,
false,
},
{
"valid collection id",
"sz5l5z67tg7gku0",
nil,
3,
false,
},
{
"nil expression",
"demo2",
[]dbx.Expression{nil},
3,
false,
},
{
"no matches",
"demo2",
[]dbx.Expression{
nil,
dbx.Like("title", "missing"),
dbx.HashExp{"active": true},
},
0,
false,
},
{
"with matches",
"demo2",
[]dbx.Expression{
nil,
dbx.Like("title", "test"),
dbx.HashExp{"active": true},
},
2,
false,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
total, err := app.CountRecords(s.collectionIdOrName, s.expressions...)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
if total != s.expectTotal {
t.Fatalf("Expected total %d, got %d", s.expectTotal, total)
}
})
}
}
func TestFindAuthRecordByToken(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
name string
token string
types []string
expectedId string
}{
{
"empty token",
"",
nil,
"",
},
{
"invalid token",
"invalid",
nil,
"",
},
{
"expired token",
"eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoxNjQwOTkxNjYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.2D3tmqPn3vc5LoqqCz8V-iCDVXo9soYiH0d32G7FQT4",
nil,
"",
},
{
"valid auth token",
"eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
nil,
"4q1xlclmfloku33",
},
{
"valid verification token",
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImRjNDlrNmpnZWpuNDBoMyIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6InZlcmlmaWNhdGlvbiIsImNvbGxlY3Rpb25JZCI6ImtwdjcwOXNrMmxxYnFrOCIsImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSJ9.5GmuZr4vmwk3Cb_3ZZWNxwbE75KZC-j71xxIPR9AsVw",
nil,
"dc49k6jgejn40h3",
},
{
"auth token with file type only check",
"eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
[]string{core.TokenTypeFile},
"",
},
{
"auth token with file and auth type check",
"eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
[]string{core.TokenTypeFile, core.TokenTypeAuth},
"4q1xlclmfloku33",
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
record, err := app.FindAuthRecordByToken(s.token, s.types...)
hasErr := err != nil
expectErr := s.expectedId == ""
if hasErr != expectErr {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", expectErr, hasErr, err)
}
if hasErr {
return
}
if record.Id != s.expectedId {
t.Fatalf("Expected record with id %q, got %q", s.expectedId, record.Id)
}
})
}
}
func TestFindAuthRecordByEmail(t *testing.T) {
t.Parallel()
scenarios := []struct {
collectionIdOrName string
email string
nocaseIndex bool
expectError bool
}{
{"missing", "test@example.com", false, true},
{"demo2", "test@example.com", false, true},
{"users", "missing@example.com", false, true},
{"users", "test@example.com", false, false},
{"clients", "test2@example.com", false, false},
// case-insensitive tests
{"clients", "TeSt2@example.com", false, true},
{"clients", "TeSt2@example.com", true, false},
}
for _, s := range scenarios {
t.Run(fmt.Sprintf("%s_%s", s.collectionIdOrName, s.email), func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, _ := app.FindCollectionByNameOrId(s.collectionIdOrName)
if collection != nil {
emailIndex, ok := dbutils.FindSingleColumnUniqueIndex(collection.Indexes, core.FieldNameEmail)
if ok {
if s.nocaseIndex {
emailIndex.Columns[0].Collate = "nocase"
} else {
emailIndex.Columns[0].Collate = ""
}
collection.RemoveIndex(emailIndex.IndexName)
collection.Indexes = append(collection.Indexes, emailIndex.Build())
err := app.Save(collection)
if err != nil {
t.Fatalf("Failed to update email index: %v", err)
}
}
}
record, err := app.FindAuthRecordByEmail(s.collectionIdOrName, s.email)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
if hasErr {
return
}
if !strings.EqualFold(record.Email(), s.email) {
t.Fatalf("Expected record with email %s, got %s", s.email, record.Email())
}
})
}
}
func TestCanAccessRecord(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
superuser, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test@example.com")
if err != nil {
t.Fatal(err)
}
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
record, err := app.FindRecordById("demo1", "imy661ixudk5izi")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
record *core.Record
requestInfo *core.RequestInfo
rule *string
expected bool
expectError bool
}{
{
"as superuser with nil rule",
record,
&core.RequestInfo{
Auth: superuser,
},
nil,
true,
false,
},
{
"as superuser with non-empty rule",
record,
&core.RequestInfo{
Auth: superuser,
},
types.Pointer("id = ''"), // the filter rule should be ignored
true,
false,
},
{
"as superuser with invalid rule",
record,
&core.RequestInfo{
Auth: superuser,
},
types.Pointer("id ?!@ 1"), // the filter rule should be ignored
true,
false,
},
{
"as guest with nil rule",
record,
&core.RequestInfo{},
nil,
false,
false,
},
{
"as guest with empty rule",
record,
&core.RequestInfo{},
types.Pointer(""),
true,
false,
},
{
"as guest with invalid rule",
record,
&core.RequestInfo{},
types.Pointer("id ?!@ 1"),
false,
true,
},
{
"as guest with mismatched rule",
record,
&core.RequestInfo{},
types.Pointer("@request.auth.id != ''"),
false,
false,
},
{
"as guest with matched rule",
record,
&core.RequestInfo{
Body: map[string]any{"test": 1},
},
types.Pointer("@request.auth.id != '' || @request.body.test = 1"),
true,
false,
},
{
"as auth record with nil rule",
record,
&core.RequestInfo{
Auth: user,
},
nil,
false,
false,
},
{
"as auth record with empty rule",
record,
&core.RequestInfo{
Auth: user,
},
types.Pointer(""),
true,
false,
},
{
"as auth record with invalid rule",
record,
&core.RequestInfo{
Auth: user,
},
types.Pointer("id ?!@ 1"),
false,
true,
},
{
"as auth record with mismatched rule",
record,
&core.RequestInfo{
Auth: user,
Body: map[string]any{"test": 1},
},
types.Pointer("@request.auth.id != '' && @request.body.test > 1"),
false,
false,
},
{
"as auth record with matched rule",
record,
&core.RequestInfo{
Auth: user,
Body: map[string]any{"test": 2},
},
types.Pointer("@request.auth.id != '' && @request.body.test > 1"),
true,
false,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result, err := app.CanAccessRecord(s.record, s.requestInfo, s.rule)
if result != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, result)
}
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/event_request_batch_test.go | core/event_request_batch_test.go | package core_test
import (
"net/http"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestInternalRequestValidate(t *testing.T) {
scenarios := []struct {
name string
request core.InternalRequest
expectedErrors []string
}{
{
"empty struct",
core.InternalRequest{},
[]string{"method", "url"},
},
// method
{
"GET method",
core.InternalRequest{URL: "test", Method: http.MethodGet},
[]string{},
},
{
"POST method",
core.InternalRequest{URL: "test", Method: http.MethodPost},
[]string{},
},
{
"PUT method",
core.InternalRequest{URL: "test", Method: http.MethodPut},
[]string{},
},
{
"PATCH method",
core.InternalRequest{URL: "test", Method: http.MethodPatch},
[]string{},
},
{
"DELETE method",
core.InternalRequest{URL: "test", Method: http.MethodDelete},
[]string{},
},
{
"unknown method",
core.InternalRequest{URL: "test", Method: "unknown"},
[]string{"method"},
},
// url
{
"url <= 2000",
core.InternalRequest{URL: strings.Repeat("a", 2000), Method: http.MethodGet},
[]string{},
},
{
"url > 2000",
core.InternalRequest{URL: strings.Repeat("a", 2001), Method: http.MethodGet},
[]string{"url"},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
tests.TestValidationErrors(t, s.request.Validate(), s.expectedErrors)
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_model.go | core/record_model.go | package core
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log"
"maps"
"slices"
"sort"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tools/dbutils"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/inflector"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/store"
"github.com/pocketbase/pocketbase/tools/types"
"github.com/spf13/cast"
)
// used as a workaround by some fields for persisting local state between various events
// (for now is kept private and cannot be changed or cloned outside of the core package)
const internalCustomFieldKeyPrefix = "@pbInternal"
var (
_ Model = (*Record)(nil)
_ HookTagger = (*Record)(nil)
_ DBExporter = (*Record)(nil)
_ FilesManager = (*Record)(nil)
)
type Record struct {
collection *Collection
originalData map[string]any
customVisibility *store.Store[string, bool]
data *store.Store[string, any]
expand *store.Store[string, any]
BaseModel
exportCustomData bool
ignoreEmailVisibility bool
ignoreUnchangedFields bool
}
const systemHookIdRecord = "__pbRecordSystemHook__"
func (app *BaseApp) registerRecordHooks() {
app.OnModelValidate().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdRecord,
Func: func(me *ModelEvent) error {
if re, ok := newRecordEventFromModelEvent(me); ok {
err := me.App.OnRecordValidate().Trigger(re, func(re *RecordEvent) error {
syncModelEventWithRecordEvent(me, re)
defer syncRecordEventWithModelEvent(re, me)
return me.Next()
})
syncModelEventWithRecordEvent(me, re)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelCreate().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdRecord,
Func: func(me *ModelEvent) error {
if re, ok := newRecordEventFromModelEvent(me); ok {
err := me.App.OnRecordCreate().Trigger(re, func(re *RecordEvent) error {
syncModelEventWithRecordEvent(me, re)
defer syncRecordEventWithModelEvent(re, me)
return me.Next()
})
syncModelEventWithRecordEvent(me, re)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelCreateExecute().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdRecord,
Func: func(me *ModelEvent) error {
if re, ok := newRecordEventFromModelEvent(me); ok {
err := me.App.OnRecordCreateExecute().Trigger(re, func(re *RecordEvent) error {
syncModelEventWithRecordEvent(me, re)
defer syncRecordEventWithModelEvent(re, me)
return me.Next()
})
syncModelEventWithRecordEvent(me, re)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelAfterCreateSuccess().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdRecord,
Func: func(me *ModelEvent) error {
if re, ok := newRecordEventFromModelEvent(me); ok {
err := me.App.OnRecordAfterCreateSuccess().Trigger(re, func(re *RecordEvent) error {
syncModelEventWithRecordEvent(me, re)
defer syncRecordEventWithModelEvent(re, me)
return me.Next()
})
syncModelEventWithRecordEvent(me, re)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelAfterCreateError().Bind(&hook.Handler[*ModelErrorEvent]{
Id: systemHookIdRecord,
Func: func(me *ModelErrorEvent) error {
if re, ok := newRecordErrorEventFromModelErrorEvent(me); ok {
err := me.App.OnRecordAfterCreateError().Trigger(re, func(re *RecordErrorEvent) error {
syncModelErrorEventWithRecordErrorEvent(me, re)
defer syncRecordErrorEventWithModelErrorEvent(re, me)
return me.Next()
})
syncModelErrorEventWithRecordErrorEvent(me, re)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelUpdate().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdRecord,
Func: func(me *ModelEvent) error {
if re, ok := newRecordEventFromModelEvent(me); ok {
err := me.App.OnRecordUpdate().Trigger(re, func(re *RecordEvent) error {
syncModelEventWithRecordEvent(me, re)
defer syncRecordEventWithModelEvent(re, me)
return me.Next()
})
syncModelEventWithRecordEvent(me, re)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelUpdateExecute().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdRecord,
Func: func(me *ModelEvent) error {
if re, ok := newRecordEventFromModelEvent(me); ok {
err := me.App.OnRecordUpdateExecute().Trigger(re, func(re *RecordEvent) error {
syncModelEventWithRecordEvent(me, re)
defer syncRecordEventWithModelEvent(re, me)
return me.Next()
})
syncModelEventWithRecordEvent(me, re)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelAfterUpdateSuccess().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdRecord,
Func: func(me *ModelEvent) error {
if re, ok := newRecordEventFromModelEvent(me); ok {
err := me.App.OnRecordAfterUpdateSuccess().Trigger(re, func(re *RecordEvent) error {
syncModelEventWithRecordEvent(me, re)
defer syncRecordEventWithModelEvent(re, me)
return me.Next()
})
syncModelEventWithRecordEvent(me, re)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelAfterUpdateError().Bind(&hook.Handler[*ModelErrorEvent]{
Id: systemHookIdRecord,
Func: func(me *ModelErrorEvent) error {
if re, ok := newRecordErrorEventFromModelErrorEvent(me); ok {
err := me.App.OnRecordAfterUpdateError().Trigger(re, func(re *RecordErrorEvent) error {
syncModelErrorEventWithRecordErrorEvent(me, re)
defer syncRecordErrorEventWithModelErrorEvent(re, me)
return me.Next()
})
syncModelErrorEventWithRecordErrorEvent(me, re)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelDelete().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdRecord,
Func: func(me *ModelEvent) error {
if re, ok := newRecordEventFromModelEvent(me); ok {
err := me.App.OnRecordDelete().Trigger(re, func(re *RecordEvent) error {
syncModelEventWithRecordEvent(me, re)
defer syncRecordEventWithModelEvent(re, me)
return me.Next()
})
syncModelEventWithRecordEvent(me, re)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelDeleteExecute().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdRecord,
Func: func(me *ModelEvent) error {
if re, ok := newRecordEventFromModelEvent(me); ok {
err := me.App.OnRecordDeleteExecute().Trigger(re, func(re *RecordEvent) error {
syncModelEventWithRecordEvent(me, re)
defer syncRecordEventWithModelEvent(re, me)
return me.Next()
})
syncModelEventWithRecordEvent(me, re)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelAfterDeleteSuccess().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdRecord,
Func: func(me *ModelEvent) error {
if re, ok := newRecordEventFromModelEvent(me); ok {
err := me.App.OnRecordAfterDeleteSuccess().Trigger(re, func(re *RecordEvent) error {
syncModelEventWithRecordEvent(me, re)
defer syncRecordEventWithModelEvent(re, me)
return me.Next()
})
syncModelEventWithRecordEvent(me, re)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelAfterDeleteError().Bind(&hook.Handler[*ModelErrorEvent]{
Id: systemHookIdRecord,
Func: func(me *ModelErrorEvent) error {
if re, ok := newRecordErrorEventFromModelErrorEvent(me); ok {
err := me.App.OnRecordAfterDeleteError().Trigger(re, func(re *RecordErrorEvent) error {
syncModelErrorEventWithRecordErrorEvent(me, re)
defer syncRecordErrorEventWithModelErrorEvent(re, me)
return me.Next()
})
syncModelErrorEventWithRecordErrorEvent(me, re)
return err
}
return me.Next()
},
Priority: -99,
})
// ---------------------------------------------------------------
app.OnRecordValidate().Bind(&hook.Handler[*RecordEvent]{
Id: systemHookIdRecord,
Func: func(e *RecordEvent) error {
return e.Record.callFieldInterceptors(
e.Context,
e.App,
InterceptorActionValidate,
func() error {
return onRecordValidate(e)
},
)
},
Priority: 99,
})
app.OnRecordCreate().Bind(&hook.Handler[*RecordEvent]{
Id: systemHookIdRecord,
Func: func(e *RecordEvent) error {
return e.Record.callFieldInterceptors(
e.Context,
e.App,
InterceptorActionCreate,
e.Next,
)
},
Priority: -99,
})
app.OnRecordCreateExecute().Bind(&hook.Handler[*RecordEvent]{
Id: systemHookIdRecord,
Func: func(e *RecordEvent) error {
return e.Record.callFieldInterceptors(
e.Context,
e.App,
InterceptorActionCreateExecute,
func() error {
return onRecordSaveExecute(e)
},
)
},
Priority: 99,
})
app.OnRecordAfterCreateSuccess().Bind(&hook.Handler[*RecordEvent]{
Id: systemHookIdRecord,
Func: func(e *RecordEvent) error {
return e.Record.callFieldInterceptors(
e.Context,
e.App,
InterceptorActionAfterCreate,
e.Next,
)
},
Priority: -99,
})
app.OnRecordAfterCreateError().Bind(&hook.Handler[*RecordErrorEvent]{
Id: systemHookIdRecord,
Func: func(e *RecordErrorEvent) error {
return e.Record.callFieldInterceptors(
e.Context,
e.App,
InterceptorActionAfterCreateError,
e.Next,
)
},
Priority: -99,
})
app.OnRecordUpdate().Bind(&hook.Handler[*RecordEvent]{
Id: systemHookIdRecord,
Func: func(e *RecordEvent) error {
return e.Record.callFieldInterceptors(
e.Context,
e.App,
InterceptorActionUpdate,
e.Next,
)
},
Priority: -99,
})
app.OnRecordUpdateExecute().Bind(&hook.Handler[*RecordEvent]{
Id: systemHookIdRecord,
Func: func(e *RecordEvent) error {
return e.Record.callFieldInterceptors(
e.Context,
e.App,
InterceptorActionUpdateExecute,
func() error {
return onRecordSaveExecute(e)
},
)
},
Priority: 99,
})
app.OnRecordAfterUpdateSuccess().Bind(&hook.Handler[*RecordEvent]{
Id: systemHookIdRecord,
Func: func(e *RecordEvent) error {
return e.Record.callFieldInterceptors(
e.Context,
e.App,
InterceptorActionAfterUpdate,
e.Next,
)
},
Priority: -99,
})
app.OnRecordAfterUpdateError().Bind(&hook.Handler[*RecordErrorEvent]{
Id: systemHookIdRecord,
Func: func(e *RecordErrorEvent) error {
return e.Record.callFieldInterceptors(
e.Context,
e.App,
InterceptorActionAfterUpdateError,
e.Next,
)
},
Priority: -99,
})
app.OnRecordDelete().Bind(&hook.Handler[*RecordEvent]{
Id: systemHookIdRecord,
Func: func(e *RecordEvent) error {
return e.Record.callFieldInterceptors(
e.Context,
e.App,
InterceptorActionDelete,
func() error {
if e.Record.Collection().IsView() {
return errors.New("view records cannot be deleted")
}
return e.Next()
},
)
},
Priority: -99,
})
app.OnRecordDeleteExecute().Bind(&hook.Handler[*RecordEvent]{
Id: systemHookIdRecord,
Func: func(e *RecordEvent) error {
return e.Record.callFieldInterceptors(
e.Context,
e.App,
InterceptorActionDeleteExecute,
func() error {
return onRecordDeleteExecute(e)
},
)
},
Priority: 99,
})
app.OnRecordAfterDeleteSuccess().Bind(&hook.Handler[*RecordEvent]{
Id: systemHookIdRecord,
Func: func(e *RecordEvent) error {
return e.Record.callFieldInterceptors(
e.Context,
e.App,
InterceptorActionAfterDelete,
e.Next,
)
},
Priority: -99,
})
app.OnRecordAfterDeleteError().Bind(&hook.Handler[*RecordErrorEvent]{
Id: systemHookIdRecord,
Func: func(e *RecordErrorEvent) error {
return e.Record.callFieldInterceptors(
e.Context,
e.App,
InterceptorActionAfterDeleteError,
e.Next,
)
},
Priority: -99,
})
}
// -------------------------------------------------------------------
// newRecordFromNullStringMap initializes a single new Record model
// with data loaded from the provided NullStringMap.
//
// Note that this method is intended to load and Scan data from a database row result.
func newRecordFromNullStringMap(collection *Collection, data dbx.NullStringMap) (*Record, error) {
record := NewRecord(collection)
var fieldName string
for _, field := range collection.Fields {
fieldName = field.GetName()
nullString, ok := data[fieldName]
var value any
var err error
if ok && nullString.Valid {
value, err = field.PrepareValue(record, nullString.String)
} else {
value, err = field.PrepareValue(record, nil)
}
if err != nil {
return nil, err
}
// we load only the original data to avoid unnecessary copying the same data into the record.data store
// (it is also the reason why we don't invoke PostScan on the record itself)
record.originalData[fieldName] = value
if fieldName == FieldNameId {
record.Id = cast.ToString(value)
}
}
record.BaseModel.PostScan()
return record, nil
}
// newRecordsFromNullStringMaps initializes a new Record model for
// each row in the provided NullStringMap slice.
//
// Note that this method is intended to load and Scan data from a database rows result.
func newRecordsFromNullStringMaps(collection *Collection, rows []dbx.NullStringMap) ([]*Record, error) {
result := make([]*Record, len(rows))
var err error
for i, row := range rows {
result[i], err = newRecordFromNullStringMap(collection, row)
if err != nil {
return nil, err
}
}
return result, nil
}
// -------------------------------------------------------------------
// NewRecord initializes a new empty Record model.
func NewRecord(collection *Collection) *Record {
record := &Record{
collection: collection,
data: store.New[string, any](nil),
customVisibility: store.New[string, bool](nil),
originalData: make(map[string]any, len(collection.Fields)),
}
// initialize default field values
var fieldName string
for _, field := range collection.Fields {
fieldName = field.GetName()
if fieldName == FieldNameId {
continue
}
value, _ := field.PrepareValue(record, nil)
record.originalData[fieldName] = value
}
return record
}
// Collection returns the Collection model associated with the current Record model.
//
// NB! The returned collection is only for read purposes and it shouldn't be modified
// because it could have unintended side-effects on other Record models from the same collection.
func (m *Record) Collection() *Collection {
return m.collection
}
// TableName returns the table name associated with the current Record model.
func (m *Record) TableName() string {
return m.collection.Name
}
// PostScan implements the [dbx.PostScanner] interface.
//
// It essentially refreshes/updates the current Record original state
// as if the model was fetched from the databases for the first time.
//
// Or in other words, it means that m.Original().FieldsData() will have
// the same values as m.Record().FieldsData().
func (m *Record) PostScan() error {
if m.Id == "" {
return errors.New("missing record primary key")
}
if err := m.BaseModel.PostScan(); err != nil {
return err
}
m.originalData = m.FieldsData()
return nil
}
// HookTags returns the hook tags associated with the current record.
func (m *Record) HookTags() []string {
return []string{m.collection.Name, m.collection.Id}
}
// BaseFilesPath returns the storage dir path used by the record.
func (m *Record) BaseFilesPath() string {
id := cast.ToString(m.LastSavedPK())
if id == "" {
id = m.Id
}
return m.collection.BaseFilesPath() + "/" + id
}
// Original returns a shallow copy of the current record model populated
// with its ORIGINAL db data state (aka. right after PostScan())
// and everything else reset to the defaults.
//
// If record was created using NewRecord() the original will be always
// a blank record (until PostScan() is invoked).
func (m *Record) Original() *Record {
newRecord := NewRecord(m.collection)
newRecord.originalData = maps.Clone(m.originalData)
if newRecord.originalData[FieldNameId] != nil {
newRecord.lastSavedPK = cast.ToString(newRecord.originalData[FieldNameId])
newRecord.Id = newRecord.lastSavedPK
}
return newRecord
}
// Fresh returns a shallow copy of the current record model populated
// with its LATEST data state and everything else reset to the defaults
// (aka. no expand, no unknown fields and with default visibility flags).
func (m *Record) Fresh() *Record {
newRecord := m.Original()
// note: this will also load the Id field through m.GetRaw
var fieldName string
for _, field := range m.collection.Fields {
fieldName = field.GetName()
newRecord.SetRaw(fieldName, m.GetRaw(fieldName))
}
return newRecord
}
// Clone returns a shallow copy of the current record model with all of
// its collection and unknown fields data, expand and flags copied.
//
// use [Record.Fresh()] instead if you want a copy with only the latest
// collection fields data and everything else reset to the defaults.
func (m *Record) Clone() *Record {
newRecord := m.Original()
newRecord.Id = m.Id
newRecord.exportCustomData = m.exportCustomData
newRecord.ignoreEmailVisibility = m.ignoreEmailVisibility
newRecord.ignoreUnchangedFields = m.ignoreUnchangedFields
newRecord.customVisibility.Reset(m.customVisibility.GetAll())
data := m.data.GetAll()
for k, v := range data {
newRecord.SetRaw(k, v)
}
if m.expand != nil {
newRecord.SetExpand(m.expand.GetAll())
}
return newRecord
}
// Expand returns a shallow copy of the current Record model expand data (if any).
func (m *Record) Expand() map[string]any {
if m.expand == nil {
// return a dummy initialized map to avoid assignment to nil map errors
return map[string]any{}
}
return m.expand.GetAll()
}
// SetExpand replaces the current Record's expand with the provided expand arg data (shallow copied).
func (m *Record) SetExpand(expand map[string]any) {
if m.expand == nil {
m.expand = store.New[string, any](nil)
}
m.expand.Reset(expand)
}
// MergeExpand merges recursively the provided expand data into
// the current model's expand (if any).
//
// Note that if an expanded prop with the same key is a slice (old or new expand)
// then both old and new records will be merged into a new slice (aka. a :merge: [b,c] => [a,b,c]).
// Otherwise the "old" expanded record will be replace with the "new" one (aka. a :merge: aNew => aNew).
func (m *Record) MergeExpand(expand map[string]any) {
// nothing to merge
if len(expand) == 0 {
return
}
// no old expand
if m.expand == nil {
m.expand = store.New(expand)
return
}
oldExpand := m.expand.GetAll()
for key, new := range expand {
old, ok := oldExpand[key]
if !ok {
oldExpand[key] = new
continue
}
var wasOldSlice bool
var oldSlice []*Record
switch v := old.(type) {
case *Record:
oldSlice = []*Record{v}
case []*Record:
wasOldSlice = true
oldSlice = v
default:
// invalid old expand data -> assign directly the new
// (no matter whether new is valid or not)
oldExpand[key] = new
continue
}
var wasNewSlice bool
var newSlice []*Record
switch v := new.(type) {
case *Record:
newSlice = []*Record{v}
case []*Record:
wasNewSlice = true
newSlice = v
default:
// invalid new expand data -> skip
continue
}
oldIndexed := make(map[string]*Record, len(oldSlice))
for _, oldRecord := range oldSlice {
oldIndexed[oldRecord.Id] = oldRecord
}
for _, newRecord := range newSlice {
oldRecord := oldIndexed[newRecord.Id]
if oldRecord != nil {
// note: there is no need to update oldSlice since oldRecord is a reference
oldRecord.MergeExpand(newRecord.Expand())
} else {
// missing new entry
oldSlice = append(oldSlice, newRecord)
}
}
if wasOldSlice || wasNewSlice || len(oldSlice) == 0 {
oldExpand[key] = oldSlice
} else {
oldExpand[key] = oldSlice[0]
}
}
m.expand.Reset(oldExpand)
}
// FieldsData returns a shallow copy ONLY of the collection's fields record's data.
func (m *Record) FieldsData() map[string]any {
result := make(map[string]any, len(m.collection.Fields))
var fieldName string
for _, field := range m.collection.Fields {
fieldName = field.GetName()
result[fieldName] = m.Get(fieldName)
}
return result
}
// CustomData returns a shallow copy ONLY of the custom record fields data,
// aka. fields that are neither defined by the collection, nor special system ones.
//
// Note that custom fields prefixed with "@pbInternal" are always skipped.
func (m *Record) CustomData() map[string]any {
if m.data == nil {
return nil
}
fields := m.Collection().Fields
knownFields := make(map[string]struct{}, len(fields))
for _, f := range fields {
knownFields[f.GetName()] = struct{}{}
}
result := map[string]any{}
rawData := m.data.GetAll()
for k, v := range rawData {
if _, ok := knownFields[k]; !ok {
// skip internal custom fields
if strings.HasPrefix(k, internalCustomFieldKeyPrefix) {
continue
}
result[k] = v
}
}
return result
}
// WithCustomData toggles the export/serialization of custom data fields
// (false by default).
func (m *Record) WithCustomData(state bool) *Record {
m.exportCustomData = state
return m
}
// IgnoreEmailVisibility toggles the flag to ignore the auth record email visibility check.
func (m *Record) IgnoreEmailVisibility(state bool) *Record {
m.ignoreEmailVisibility = state
return m
}
// IgnoreUnchangedFields toggles the flag to ignore the unchanged fields
// from the DB export for the UPDATE SQL query.
//
// This could be used if you want to save only the record fields that you've changed
// without overwrite other untouched fields in case of concurrent update.
//
// Note that the fields change comparison is based on the current fields against m.Original()
// (aka. if you have performed save on the same Record instance multiple times you may have to refetch it,
// so that m.Original() could reflect the last saved change).
func (m *Record) IgnoreUnchangedFields(state bool) *Record {
m.ignoreUnchangedFields = state
return m
}
// Set sets the provided key-value data pair into the current Record
// model directly as it is WITHOUT NORMALIZATIONS.
//
// See also [Record.Set].
func (m *Record) SetRaw(key string, value any) {
if key == FieldNameId {
m.Id = cast.ToString(value)
}
m.data.Set(key, value)
}
// SetIfFieldExists sets the provided key-value data pair into the current Record model
// ONLY if key is existing Collection field name/modifier.
//
// This method does nothing if key is not a known Collection field name/modifier.
//
// On success returns the matched Field, otherwise - nil.
//
// To set any key-value, including custom/unknown fields, use the [Record.Set] method.
func (m *Record) SetIfFieldExists(key string, value any) Field {
for _, field := range m.Collection().Fields {
ff, ok := field.(SetterFinder)
if ok {
setter := ff.FindSetter(key)
if setter != nil {
setter(m, value)
return field
}
}
// fallback to the default field PrepareValue method for direct match
if key == field.GetName() {
value, _ = field.PrepareValue(m, value)
m.SetRaw(key, value)
return field
}
}
return nil
}
// Set sets the provided key-value data pair into the current Record model.
//
// If the record collection has field with name matching the provided "key",
// the value will be further normalized according to the field setter(s).
func (m *Record) Set(key string, value any) {
switch key {
case FieldNameExpand: // for backward-compatibility with earlier versions
m.SetExpand(cast.ToStringMap(value))
default:
field := m.SetIfFieldExists(key, value)
if field == nil {
// custom key - set it without any transformations
m.SetRaw(key, value)
}
}
}
func (m *Record) GetRaw(key string) any {
if key == FieldNameId {
return m.Id
}
if v, ok := m.data.GetOk(key); ok {
return v
}
return m.originalData[key]
}
// Get returns a normalized single record model data value for "key".
func (m *Record) Get(key string) any {
switch key {
case FieldNameExpand: // for backward-compatibility with earlier versions
return m.Expand()
default:
for _, field := range m.Collection().Fields {
gm, ok := field.(GetterFinder)
if !ok {
continue // no custom getters
}
getter := gm.FindGetter(key)
if getter != nil {
return getter(m)
}
}
return m.GetRaw(key)
}
}
// Load bulk loads the provided data into the current Record model.
func (m *Record) Load(data map[string]any) {
for k, v := range data {
m.Set(k, v)
}
}
// GetBool returns the data value for "key" as a bool.
func (m *Record) GetBool(key string) bool {
return cast.ToBool(m.Get(key))
}
// GetString returns the data value for "key" as a string.
func (m *Record) GetString(key string) string {
return cast.ToString(m.Get(key))
}
// GetInt returns the data value for "key" as an int.
func (m *Record) GetInt(key string) int {
return cast.ToInt(m.Get(key))
}
// GetFloat returns the data value for "key" as a float64.
func (m *Record) GetFloat(key string) float64 {
return cast.ToFloat64(m.Get(key))
}
// GetDateTime returns the data value for "key" as a DateTime instance.
func (m *Record) GetDateTime(key string) types.DateTime {
d, _ := types.ParseDateTime(m.Get(key))
return d
}
// GetGeoPoint returns the data value for "key" as a GeoPoint instance.
func (m *Record) GetGeoPoint(key string) types.GeoPoint {
point := types.GeoPoint{}
_ = point.Scan(m.Get(key))
return point
}
// GetStringSlice returns the data value for "key" as a slice of non-zero unique strings.
func (m *Record) GetStringSlice(key string) []string {
return list.ToUniqueStringSlice(m.Get(key))
}
// GetUnsavedFiles returns the uploaded files for the provided "file" field key,
// (aka. the current [*filesytem.File] values) so that you can apply further
// validations or modifications (including changing the file name or content before persisting).
//
// Example:
//
// files := record.GetUnsavedFiles("documents")
// for _, f := range files {
// f.Name = "doc_" + f.Name // add a prefix to each file name
// }
// app.Save(record) // the files are pointers so the applied changes will transparently reflect on the record value
func (m *Record) GetUnsavedFiles(key string) []*filesystem.File {
if !strings.HasSuffix(key, ":unsaved") {
key += ":unsaved"
}
values, _ := m.Get(key).([]*filesystem.File)
return values
}
// Deprecated: replaced with GetUnsavedFiles.
func (m *Record) GetUploadedFiles(key string) []*filesystem.File {
log.Println("Please replace GetUploadedFiles with GetUnsavedFiles")
return m.GetUnsavedFiles(key)
}
// Retrieves the "key" json field value and unmarshals it into "result".
//
// Example
//
// result := struct {
// FirstName string `json:"first_name"`
// }{}
// err := m.UnmarshalJSONField("my_field_name", &result)
func (m *Record) UnmarshalJSONField(key string, result any) error {
return json.Unmarshal([]byte(m.GetString(key)), &result)
}
// ExpandedOne retrieves a single relation Record from the already
// loaded expand data of the current model.
//
// If the requested expand relation is multiple, this method returns
// only first available Record from the expanded relation.
//
// Returns nil if there is no such expand relation loaded.
func (m *Record) ExpandedOne(relField string) *Record {
if m.expand == nil {
return nil
}
rel := m.expand.Get(relField)
switch v := rel.(type) {
case *Record:
return v
case []*Record:
if len(v) > 0 {
return v[0]
}
}
return nil
}
// ExpandedAll retrieves a slice of relation Records from the already
// loaded expand data of the current model.
//
// If the requested expand relation is single, this method normalizes
// the return result and will wrap the single model as a slice.
//
// Returns nil slice if there is no such expand relation loaded.
func (m *Record) ExpandedAll(relField string) []*Record {
if m.expand == nil {
return nil
}
rel := m.expand.Get(relField)
switch v := rel.(type) {
case *Record:
return []*Record{v}
case []*Record:
return v
}
return nil
}
// FindFileFieldByFile returns the first file type field for which
// any of the record's data contains the provided filename.
func (m *Record) FindFileFieldByFile(filename string) *FileField {
for _, field := range m.Collection().Fields {
if field.Type() != FieldTypeFile {
continue
}
f, ok := field.(*FileField)
if !ok {
continue
}
filenames := m.GetStringSlice(f.GetName())
if slices.Contains(filenames, filename) {
return f
}
}
return nil
}
// DBExport implements the [DBExporter] interface and returns a key-value
// map with the data to be persisted when saving the Record in the database.
func (m *Record) DBExport(app App) (map[string]any, error) {
result, err := m.dbExport()
if err != nil {
return nil, err
}
// remove exported fields that haven't changed
// (with exception of the id column)
if !m.IsNew() && m.ignoreUnchangedFields {
oldResult, err := m.Original().dbExport()
if err != nil {
return nil, err
}
for oldK, oldV := range oldResult {
if oldK == idColumn {
continue
}
newV, ok := result[oldK]
if ok && areValuesEqual(newV, oldV) {
delete(result, oldK)
}
}
}
return result, nil
}
func (m *Record) dbExport() (map[string]any, error) {
fields := m.Collection().Fields
result := make(map[string]any, len(fields))
var fieldName string
for _, field := range fields {
fieldName = field.GetName()
if f, ok := field.(DriverValuer); ok {
v, err := f.DriverValue(m)
if err != nil {
return nil, err
}
result[fieldName] = v
} else {
result[fieldName] = m.GetRaw(fieldName)
}
}
return result, nil
}
func areValuesEqual(a any, b any) bool {
switch av := a.(type) {
case string:
bv, ok := b.(string)
return ok && bv == av
case bool:
bv, ok := b.(bool)
return ok && bv == av
case float32:
bv, ok := b.(float32)
return ok && bv == av
case float64:
bv, ok := b.(float64)
return ok && bv == av
case uint:
bv, ok := b.(uint)
return ok && bv == av
case uint8:
bv, ok := b.(uint8)
return ok && bv == av
case uint16:
bv, ok := b.(uint16)
return ok && bv == av
case uint32:
bv, ok := b.(uint32)
return ok && bv == av
case uint64:
bv, ok := b.(uint64)
return ok && bv == av
case int:
bv, ok := b.(int)
return ok && bv == av
case int8:
bv, ok := b.(int8)
return ok && bv == av
case int16:
bv, ok := b.(int16)
return ok && bv == av
case int32:
bv, ok := b.(int32)
return ok && bv == av
case int64:
bv, ok := b.(int64)
return ok && bv == av
case []byte:
bv, ok := b.([]byte)
return ok && bytes.Equal(av, bv)
case []string:
bv, ok := b.([]string)
return ok && slices.Equal(av, bv)
case []int:
bv, ok := b.([]int)
return ok && slices.Equal(av, bv)
case []int32:
bv, ok := b.([]int32)
return ok && slices.Equal(av, bv)
case []int64:
bv, ok := b.([]int64)
return ok && slices.Equal(av, bv)
case []float32:
bv, ok := b.([]float32)
return ok && slices.Equal(av, bv)
case []float64:
bv, ok := b.([]float64)
return ok && slices.Equal(av, bv)
case types.JSONArray[string]:
bv, ok := b.(types.JSONArray[string])
return ok && slices.Equal(av, bv)
case types.JSONRaw:
bv, ok := b.(types.JSONRaw)
return ok && bytes.Equal(av, bv)
default:
aRaw, err := json.Marshal(a)
if err != nil {
return false
}
bRaw, err := json.Marshal(b)
if err != nil {
return false
}
return bytes.Equal(aRaw, bRaw)
}
}
// Hide hides the specified fields from the public safe serialization of the record.
func (record *Record) Hide(fieldNames ...string) *Record {
for _, name := range fieldNames {
record.customVisibility.Set(name, false)
}
return record
}
// Unhide forces to unhide the specified fields from the public safe serialization
// of the record (even when the collection field itself is marked as hidden).
func (record *Record) Unhide(fieldNames ...string) *Record {
for _, name := range fieldNames {
record.customVisibility.Set(name, true)
}
return record
}
// PublicExport exports only the record fields that are safe to be public.
//
// To export unknown data fields you need to set record.WithCustomData(true).
//
// For auth records, to force the export of the email field you need to set
// record.IgnoreEmailVisibility(true).
func (record *Record) PublicExport() map[string]any {
export := make(map[string]any, len(record.collection.Fields)+3)
var isVisible, hasCustomVisibility bool
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | true |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_query_expand_test.go | core/record_query_expand_test.go | package core_test
import (
"encoding/json"
"errors"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/list"
)
func TestExpandRecords(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
testName string
collectionIdOrName string
recordIds []string
expands []string
fetchFunc core.ExpandFetchFunc
expectNonemptyExpandProps int
expectExpandFailures int
}{
{
"empty records",
"",
[]string{},
[]string{"self_rel_one", "self_rel_many.self_rel_one"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
0,
0,
},
{
"empty expand",
"demo4",
[]string{"i9naidtvr6qsgb4", "qzaqccwrmva4o1n"},
[]string{},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
0,
0,
},
{
"fetchFunc with error",
"demo4",
[]string{"i9naidtvr6qsgb4", "qzaqccwrmva4o1n"},
[]string{"self_rel_one", "self_rel_many.self_rel_one"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return nil, errors.New("test error")
},
0,
2,
},
{
"missing relation field",
"demo4",
[]string{"i9naidtvr6qsgb4", "qzaqccwrmva4o1n"},
[]string{"missing"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
0,
1,
},
{
"existing, but non-relation type field",
"demo4",
[]string{"i9naidtvr6qsgb4", "qzaqccwrmva4o1n"},
[]string{"title"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
0,
1,
},
{
"invalid/missing second level expand",
"demo4",
[]string{"i9naidtvr6qsgb4", "qzaqccwrmva4o1n"},
[]string{"rel_one_no_cascade.title"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
0,
1,
},
{
"with nil fetchfunc",
"users",
[]string{
"bgs820n361vj1qd",
"4q1xlclmfloku33",
"oap640cot4yru2s", // no rels
},
[]string{"rel"},
nil,
2,
0,
},
{
"expand normalizations",
"demo4",
[]string{"i9naidtvr6qsgb4", "qzaqccwrmva4o1n"},
[]string{
"self_rel_one", "self_rel_many.self_rel_many.rel_one_no_cascade",
"self_rel_many.self_rel_one.self_rel_many.self_rel_one.rel_one_no_cascade",
"self_rel_many", "self_rel_many.",
" self_rel_many ", "",
},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
9,
0,
},
{
"single expand",
"users",
[]string{
"bgs820n361vj1qd",
"4q1xlclmfloku33",
"oap640cot4yru2s", // no rels
},
[]string{"rel"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
2,
0,
},
{
"with nil fetchfunc",
"users",
[]string{
"bgs820n361vj1qd",
"4q1xlclmfloku33",
"oap640cot4yru2s", // no rels
},
[]string{"rel"},
nil,
2,
0,
},
{
"maxExpandDepth reached",
"demo4",
[]string{"qzaqccwrmva4o1n"},
[]string{"self_rel_many.self_rel_many.self_rel_many.self_rel_many.self_rel_many.self_rel_many.self_rel_many.self_rel_many.self_rel_many.self_rel_many.self_rel_many.self_rel_many"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
6,
0,
},
{
"simple back single relation field expand (deprecated syntax)",
"demo3",
[]string{"lcl9d87w22ml6jy"},
[]string{"demo4(rel_one_no_cascade_required)"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
1,
0,
},
{
"simple back expand via single relation field",
"demo3",
[]string{"lcl9d87w22ml6jy"},
[]string{"demo4_via_rel_one_no_cascade_required"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
1,
0,
},
{
"nested back expand via single relation field",
"demo3",
[]string{"lcl9d87w22ml6jy"},
[]string{
"demo4_via_rel_one_no_cascade_required.self_rel_many.self_rel_many.self_rel_one",
},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
5,
0,
},
{
"nested back expand via multiple relation field",
"demo3",
[]string{"lcl9d87w22ml6jy"},
[]string{
"demo4_via_rel_many_no_cascade_required.self_rel_many.rel_many_no_cascade_required.demo4_via_rel_many_no_cascade_required",
},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
7,
0,
},
{
"expand multiple relations sharing a common path",
"demo4",
[]string{"qzaqccwrmva4o1n"},
[]string{
"rel_one_no_cascade",
"rel_many_no_cascade",
"self_rel_many.self_rel_one.rel_many_cascade",
"self_rel_many.self_rel_one.rel_many_no_cascade_required",
},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
5,
0,
},
}
for _, s := range scenarios {
t.Run(s.testName, func(t *testing.T) {
ids := list.ToUniqueStringSlice(s.recordIds)
records, _ := app.FindRecordsByIds(s.collectionIdOrName, ids)
failed := app.ExpandRecords(records, s.expands, s.fetchFunc)
if len(failed) != s.expectExpandFailures {
t.Errorf("Expected %d failures, got %d\n%v", s.expectExpandFailures, len(failed), failed)
}
encoded, _ := json.Marshal(records)
encodedStr := string(encoded)
totalExpandProps := strings.Count(encodedStr, `"`+core.FieldNameExpand+`":`)
totalEmptyExpands := strings.Count(encodedStr, `"`+core.FieldNameExpand+`":{}`)
totalNonemptyExpands := totalExpandProps - totalEmptyExpands
if s.expectNonemptyExpandProps != totalNonemptyExpands {
t.Errorf("Expected %d expand props, got %d\n%v", s.expectNonemptyExpandProps, totalNonemptyExpands, encodedStr)
}
})
}
}
func TestExpandRecord(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
testName string
collectionIdOrName string
recordId string
expands []string
fetchFunc core.ExpandFetchFunc
expectNonemptyExpandProps int
expectExpandFailures int
}{
{
"empty expand",
"demo4",
"i9naidtvr6qsgb4",
[]string{},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
0,
0,
},
{
"fetchFunc with error",
"demo4",
"i9naidtvr6qsgb4",
[]string{"self_rel_one", "self_rel_many.self_rel_one"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return nil, errors.New("test error")
},
0,
2,
},
{
"missing relation field",
"demo4",
"i9naidtvr6qsgb4",
[]string{"missing"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
0,
1,
},
{
"existing, but non-relation type field",
"demo4",
"i9naidtvr6qsgb4",
[]string{"title"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
0,
1,
},
{
"invalid/missing second level expand",
"demo4",
"qzaqccwrmva4o1n",
[]string{"rel_one_no_cascade.title"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
0,
1,
},
{
"expand normalizations",
"demo4",
"qzaqccwrmva4o1n",
[]string{
"self_rel_one", "self_rel_many.self_rel_many.rel_one_no_cascade",
"self_rel_many.self_rel_one.self_rel_many.self_rel_one.rel_one_no_cascade",
"self_rel_many", "self_rel_many.",
" self_rel_many ", "",
},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
8,
0,
},
{
"no rels to expand",
"users",
"oap640cot4yru2s",
[]string{"rel"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
0,
0,
},
{
"maxExpandDepth reached",
"demo4",
"qzaqccwrmva4o1n",
[]string{"self_rel_many.self_rel_many.self_rel_many.self_rel_many.self_rel_many.self_rel_many.self_rel_many.self_rel_many.self_rel_many.self_rel_many.self_rel_many.self_rel_many"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
6,
0,
},
{
"simple indirect expand via single relation field (deprecated syntax)",
"demo3",
"lcl9d87w22ml6jy",
[]string{"demo4(rel_one_no_cascade_required)"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
1,
0,
},
{
"simple indirect expand via single relation field",
"demo3",
"lcl9d87w22ml6jy",
[]string{"demo4_via_rel_one_no_cascade_required"},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
1,
0,
},
{
"nested indirect expand via single relation field",
"demo3",
"lcl9d87w22ml6jy",
[]string{
"demo4(rel_one_no_cascade_required).self_rel_many.self_rel_many.self_rel_one",
},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
5,
0,
},
{
"nested indirect expand via single relation field",
"demo3",
"lcl9d87w22ml6jy",
[]string{
"demo4_via_rel_many_no_cascade_required.self_rel_many.rel_many_no_cascade_required.demo4_via_rel_many_no_cascade_required",
},
func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
},
7,
0,
},
}
for _, s := range scenarios {
t.Run(s.testName, func(t *testing.T) {
record, _ := app.FindRecordById(s.collectionIdOrName, s.recordId)
failed := app.ExpandRecord(record, s.expands, s.fetchFunc)
if len(failed) != s.expectExpandFailures {
t.Errorf("Expected %d failures, got %d\n%v", s.expectExpandFailures, len(failed), failed)
}
encoded, _ := json.Marshal(record)
encodedStr := string(encoded)
totalExpandProps := strings.Count(encodedStr, `"`+core.FieldNameExpand+`":`)
totalEmptyExpands := strings.Count(encodedStr, `"`+core.FieldNameExpand+`":{}`)
totalNonemptyExpands := totalExpandProps - totalEmptyExpands
if s.expectNonemptyExpandProps != totalNonemptyExpands {
t.Errorf("Expected %d expand props, got %d\n%v", s.expectNonemptyExpandProps, totalNonemptyExpands, encodedStr)
}
})
}
}
func TestBackRelationExpandSingeVsArrayResult(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
record, err := app.FindRecordById("demo3", "7nwo8tuiatetxdm")
if err != nil {
t.Fatal(err)
}
// non-unique indirect expand
{
errs := app.ExpandRecord(record, []string{"demo4_via_rel_one_cascade"}, func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
})
if len(errs) > 0 {
t.Fatal(errs)
}
result, ok := record.Expand()["demo4_via_rel_one_cascade"].([]*core.Record)
if !ok {
t.Fatalf("Expected the expanded result to be a slice, got %v", result)
}
}
// unique indirect expand
{
// mock a unique constraint for the rel_one_cascade field
// ---
demo4, err := app.FindCollectionByNameOrId("demo4")
if err != nil {
t.Fatal(err)
}
demo4.Indexes = append(demo4.Indexes, "create unique index idx_unique_expand on demo4 (rel_one_cascade)")
if err := app.Save(demo4); err != nil {
t.Fatalf("Failed to mock unique constraint: %v", err)
}
// ---
errs := app.ExpandRecord(record, []string{"demo4_via_rel_one_cascade"}, func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
})
if len(errs) > 0 {
t.Fatal(errs)
}
result, ok := record.Expand()["demo4_via_rel_one_cascade"].(*core.Record)
if !ok {
t.Fatalf("Expected the expanded result to be a single model, got %v", result)
}
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_query.go | core/record_query.go | package core
import (
"context"
"database/sql"
"errors"
"fmt"
"reflect"
"strings"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/dbutils"
"github.com/pocketbase/pocketbase/tools/inflector"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/search"
"github.com/pocketbase/pocketbase/tools/security"
)
var recordProxyType = reflect.TypeOf((*RecordProxy)(nil)).Elem()
// RecordQuery returns a new Record select query from a collection model, id or name.
//
// In case a collection id or name is provided and that collection doesn't
// actually exists, the generated query will be created with a cancelled context
// and will fail once an executor (Row(), One(), All(), etc.) is called.
func (app *BaseApp) RecordQuery(collectionModelOrIdentifier any) *dbx.SelectQuery {
var tableName string
collection, collectionErr := getCollectionByModelOrIdentifier(app, collectionModelOrIdentifier)
if collection != nil {
tableName = collection.Name
}
if tableName == "" {
// update with some fake table name for easier debugging
tableName = "@@__invalidCollectionModelOrIdentifier"
}
query := app.ConcurrentDB().Select(app.ConcurrentDB().QuoteSimpleColumnName(tableName) + ".*").From(tableName)
// in case of an error attach a new context and cancel it immediately with the error
if collectionErr != nil {
ctx, cancelFunc := context.WithCancelCause(context.Background())
query.WithContext(ctx)
cancelFunc(collectionErr)
}
return query.WithBuildHook(func(q *dbx.Query) {
q.WithExecHook(execLockRetry(app.config.QueryTimeout, defaultMaxLockRetries)).
WithOneHook(func(q *dbx.Query, a any, op func(b any) error) error {
if a == nil {
return op(a)
}
switch v := a.(type) {
case *Record:
record, err := resolveRecordOneHook(collection, op)
if err != nil {
return err
}
*v = *record
return nil
case RecordProxy:
record, err := resolveRecordOneHook(collection, op)
if err != nil {
return err
}
v.SetProxyRecord(record)
return nil
default:
return op(a)
}
}).
WithAllHook(func(q *dbx.Query, sliceA any, op func(sliceB any) error) error {
if sliceA == nil {
return op(sliceA)
}
switch v := sliceA.(type) {
case *[]*Record:
records, err := resolveRecordAllHook(collection, op)
if err != nil {
return err
}
*v = records
return nil
case *[]Record:
records, err := resolveRecordAllHook(collection, op)
if err != nil {
return err
}
nonPointers := make([]Record, len(records))
for i, r := range records {
nonPointers[i] = *r
}
*v = nonPointers
return nil
default: // expects []RecordProxy slice
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return errors.New("must be a pointer")
}
rv = dereference(rv)
if rv.Kind() != reflect.Slice {
return errors.New("must be a slice of RecordSetters")
}
et := rv.Type().Elem()
var isSliceOfPointers bool
if et.Kind() == reflect.Ptr {
isSliceOfPointers = true
et = et.Elem()
}
if !reflect.PointerTo(et).Implements(recordProxyType) {
return op(sliceA)
}
records, err := resolveRecordAllHook(collection, op)
if err != nil {
return err
}
// create an empty slice
if rv.IsNil() {
rv.Set(reflect.MakeSlice(rv.Type(), 0, len(records)))
}
for _, record := range records {
ev := reflect.New(et)
if !ev.CanInterface() {
continue
}
ps, ok := ev.Interface().(RecordProxy)
if !ok {
continue
}
ps.SetProxyRecord(record)
ev = ev.Elem()
if isSliceOfPointers {
ev = ev.Addr()
}
rv.Set(reflect.Append(rv, ev))
}
return nil
}
})
})
}
func resolveRecordOneHook(collection *Collection, op func(dst any) error) (*Record, error) {
data := dbx.NullStringMap{}
if err := op(&data); err != nil {
return nil, err
}
return newRecordFromNullStringMap(collection, data)
}
func resolveRecordAllHook(collection *Collection, op func(dst any) error) ([]*Record, error) {
data := []dbx.NullStringMap{}
if err := op(&data); err != nil {
return nil, err
}
return newRecordsFromNullStringMaps(collection, data)
}
// dereference returns the underlying value v points to.
func dereference(v reflect.Value) reflect.Value {
for v.Kind() == reflect.Ptr {
if v.IsNil() {
// initialize with a new value and continue searching
v.Set(reflect.New(v.Type().Elem()))
}
v = v.Elem()
}
return v
}
func getCollectionByModelOrIdentifier(app App, collectionModelOrIdentifier any) (*Collection, error) {
switch c := collectionModelOrIdentifier.(type) {
case *Collection:
return c, nil
case Collection:
return &c, nil
case string:
return app.FindCachedCollectionByNameOrId(c)
default:
return nil, errors.New("unknown collection identifier - must be collection model, id or name")
}
}
// -------------------------------------------------------------------
// FindRecordById finds the Record model by its id.
func (app *BaseApp) FindRecordById(
collectionModelOrIdentifier any,
recordId string,
optFilters ...func(q *dbx.SelectQuery) error,
) (*Record, error) {
collection, err := getCollectionByModelOrIdentifier(app, collectionModelOrIdentifier)
if err != nil {
return nil, err
}
record := &Record{}
query := app.RecordQuery(collection).
AndWhere(dbx.HashExp{collection.Name + ".id": recordId})
// apply filter funcs (if any)
for _, filter := range optFilters {
if filter == nil {
continue
}
if err = filter(query); err != nil {
return nil, err
}
}
err = query.Limit(1).One(record)
if err != nil {
return nil, err
}
return record, nil
}
// FindRecordsByIds finds all records by the specified ids.
// If no records are found, returns an empty slice.
func (app *BaseApp) FindRecordsByIds(
collectionModelOrIdentifier any,
recordIds []string,
optFilters ...func(q *dbx.SelectQuery) error,
) ([]*Record, error) {
collection, err := getCollectionByModelOrIdentifier(app, collectionModelOrIdentifier)
if err != nil {
return nil, err
}
query := app.RecordQuery(collection).
AndWhere(dbx.In(
collection.Name+".id",
list.ToInterfaceSlice(recordIds)...,
))
for _, filter := range optFilters {
if filter == nil {
continue
}
if err = filter(query); err != nil {
return nil, err
}
}
records := make([]*Record, 0, len(recordIds))
err = query.All(&records)
if err != nil {
return nil, err
}
return records, nil
}
// FindAllRecords finds all records matching specified db expressions.
//
// Returns all collection records if no expression is provided.
//
// Returns an empty slice if no records are found.
//
// Example:
//
// // no extra expressions
// app.FindAllRecords("example")
//
// // with extra expressions
// expr1 := dbx.HashExp{"email": "test@example.com"}
// expr2 := dbx.NewExp("LOWER(username) = {:username}", dbx.Params{"username": "test"})
// app.FindAllRecords("example", expr1, expr2)
func (app *BaseApp) FindAllRecords(collectionModelOrIdentifier any, exprs ...dbx.Expression) ([]*Record, error) {
query := app.RecordQuery(collectionModelOrIdentifier)
for _, expr := range exprs {
if expr != nil { // add only the non-nil expressions
query.AndWhere(expr)
}
}
var records []*Record
if err := query.All(&records); err != nil {
return nil, err
}
return records, nil
}
// FindFirstRecordByData returns the first found record matching
// the provided key-value pair.
func (app *BaseApp) FindFirstRecordByData(collectionModelOrIdentifier any, key string, value any) (*Record, error) {
record := &Record{}
err := app.RecordQuery(collectionModelOrIdentifier).
AndWhere(dbx.HashExp{inflector.Columnify(key): value}).
Limit(1).
One(record)
if err != nil {
return nil, err
}
return record, nil
}
// FindRecordsByFilter returns limit number of records matching the
// provided string filter.
//
// NB! Use the last "params" argument to bind untrusted user variables!
//
// The filter argument is optional and can be empty string to target
// all available records.
//
// The sort argument is optional and can be empty string OR the same format
// used in the web APIs, ex. "-created,title".
//
// If the limit argument is <= 0, no limit is applied to the query and
// all matching records are returned.
//
// Returns an empty slice if no records are found.
//
// Example:
//
// app.FindRecordsByFilter(
// "posts",
// "title ~ {:title} && visible = {:visible}",
// "-created",
// 10,
// 0,
// dbx.Params{"title": "lorem ipsum", "visible": true}
// )
func (app *BaseApp) FindRecordsByFilter(
collectionModelOrIdentifier any,
filter string,
sort string,
limit int,
offset int,
params ...dbx.Params,
) ([]*Record, error) {
collection, err := getCollectionByModelOrIdentifier(app, collectionModelOrIdentifier)
if err != nil {
return nil, err
}
q := app.RecordQuery(collection)
// build a fields resolver and attach the generated conditions to the query
// ---
resolver := NewRecordFieldResolver(
app,
collection, // the base collection
nil, // no request data
true, // allow searching hidden/protected fields like "email"
)
if filter != "" {
expr, err := search.FilterData(filter).BuildExpr(resolver, params...)
if err != nil {
return nil, fmt.Errorf("invalid filter expression: %w", err)
}
q.AndWhere(expr)
}
if sort != "" {
for _, sortField := range search.ParseSortFromString(sort) {
expr, err := sortField.BuildExpr(resolver)
if err != nil {
return nil, err
}
if expr != "" {
q.AndOrderBy(expr)
}
}
}
err = resolver.UpdateQuery(q) // attaches any adhoc joins and aliases
if err != nil {
return nil, err
}
// ---
if offset > 0 {
q.Offset(int64(offset))
}
if limit > 0 {
q.Limit(int64(limit))
}
records := []*Record{}
if err := q.All(&records); err != nil {
return nil, err
}
return records, nil
}
// FindFirstRecordByFilter returns the first available record matching the provided filter (if any).
//
// NB! Use the last params argument to bind untrusted user variables!
//
// Returns sql.ErrNoRows if no record is found.
//
// Example:
//
// app.FindFirstRecordByFilter("posts", "")
// app.FindFirstRecordByFilter("posts", "slug={:slug} && status='public'", dbx.Params{"slug": "test"})
func (app *BaseApp) FindFirstRecordByFilter(
collectionModelOrIdentifier any,
filter string,
params ...dbx.Params,
) (*Record, error) {
result, err := app.FindRecordsByFilter(collectionModelOrIdentifier, filter, "", 1, 0, params...)
if err != nil {
return nil, err
}
if len(result) == 0 {
return nil, sql.ErrNoRows
}
return result[0], nil
}
// CountRecords returns the total number of records in a collection.
func (app *BaseApp) CountRecords(collectionModelOrIdentifier any, exprs ...dbx.Expression) (int64, error) {
var total int64
q := app.RecordQuery(collectionModelOrIdentifier).Select("count(*)")
for _, expr := range exprs {
if expr != nil { // add only the non-nil expressions
q.AndWhere(expr)
}
}
err := q.Row(&total)
return total, err
}
// FindAuthRecordByToken finds the auth record associated with the provided JWT
// (auth, file, verifyEmail, changeEmail, passwordReset types).
//
// Optionally specify a list of validTypes to check tokens only from those types.
//
// Returns an error if the JWT is invalid, expired or not associated to an auth collection record.
func (app *BaseApp) FindAuthRecordByToken(token string, validTypes ...string) (*Record, error) {
if token == "" {
return nil, errors.New("missing token")
}
unverifiedClaims, err := security.ParseUnverifiedJWT(token)
if err != nil {
return nil, err
}
// check required claims
id, _ := unverifiedClaims[TokenClaimId].(string)
collectionId, _ := unverifiedClaims[TokenClaimCollectionId].(string)
tokenType, _ := unverifiedClaims[TokenClaimType].(string)
if id == "" || collectionId == "" || tokenType == "" {
return nil, errors.New("missing or invalid token claims")
}
// check types (if explicitly set)
if len(validTypes) > 0 && !list.ExistInSlice(tokenType, validTypes) {
return nil, fmt.Errorf("invalid token type %q, expects %q", tokenType, strings.Join(validTypes, ","))
}
record, err := app.FindRecordById(collectionId, id)
if err != nil {
return nil, err
}
if !record.Collection().IsAuth() {
return nil, errors.New("the token is not associated to an auth collection record")
}
var baseTokenKey string
switch tokenType {
case TokenTypeAuth:
baseTokenKey = record.Collection().AuthToken.Secret
case TokenTypeFile:
baseTokenKey = record.Collection().FileToken.Secret
case TokenTypeVerification:
baseTokenKey = record.Collection().VerificationToken.Secret
case TokenTypePasswordReset:
baseTokenKey = record.Collection().PasswordResetToken.Secret
case TokenTypeEmailChange:
baseTokenKey = record.Collection().EmailChangeToken.Secret
default:
return nil, errors.New("unknown token type " + tokenType)
}
secret := record.TokenKey() + baseTokenKey
// verify token signature
_, err = security.ParseJWT(token, secret)
if err != nil {
return nil, err
}
return record, nil
}
// FindAuthRecordByEmail finds the auth record associated with the provided email.
//
// The email check would be case-insensitive if the related collection
// email unique index has COLLATE NOCASE specified for the email column.
//
// Returns an error if it is not an auth collection or the record is not found.
func (app *BaseApp) FindAuthRecordByEmail(collectionModelOrIdentifier any, email string) (*Record, error) {
collection, err := getCollectionByModelOrIdentifier(app, collectionModelOrIdentifier)
if err != nil {
return nil, fmt.Errorf("failed to fetch auth collection: %w", err)
}
if !collection.IsAuth() {
return nil, fmt.Errorf("%q is not an auth collection", collection.Name)
}
record := &Record{}
var expr dbx.Expression
index, ok := dbutils.FindSingleColumnUniqueIndex(collection.Indexes, FieldNameEmail)
if ok && strings.EqualFold(index.Columns[0].Collate, "nocase") {
// case-insensitive search
expr = dbx.NewExp("[["+FieldNameEmail+"]] = {:email} COLLATE NOCASE", dbx.Params{"email": email})
} else {
expr = dbx.HashExp{FieldNameEmail: email}
}
err = app.RecordQuery(collection).
AndWhere(expr).
Limit(1).
One(record)
if err != nil {
return nil, err
}
return record, nil
}
// CanAccessRecord checks if a record is allowed to be accessed by the
// specified requestInfo and accessRule.
//
// Rule and db checks are ignored in case requestInfo.Auth is a superuser.
//
// The returned error indicate that something unexpected happened during
// the check (eg. invalid rule or db query error).
//
// The method always return false on invalid rule or db query error.
//
// Example:
//
// requestInfo, _ := e.RequestInfo()
// record, _ := app.FindRecordById("example", "RECORD_ID")
// rule := types.Pointer("@request.auth.id != '' || status = 'public'")
// // ... or use one of the record collection's rule, eg. record.Collection().ViewRule
//
// if ok, _ := app.CanAccessRecord(record, requestInfo, rule); ok { ... }
func (app *BaseApp) CanAccessRecord(record *Record, requestInfo *RequestInfo, accessRule *string) (bool, error) {
// superusers can access everything
if requestInfo.HasSuperuserAuth() {
return true, nil
}
// only superusers can access this record
if accessRule == nil {
return false, nil
}
// empty public rule, aka. everyone can access
if *accessRule == "" {
return true, nil
}
var exists int
query := app.RecordQuery(record.Collection()).
Select("(1)").
AndWhere(dbx.HashExp{record.Collection().Name + ".id": record.Id})
// parse and apply the access rule filter
resolver := NewRecordFieldResolver(app, record.Collection(), requestInfo, true)
expr, err := search.FilterData(*accessRule).BuildExpr(resolver)
if err != nil {
return false, err
}
err = resolver.UpdateQuery(query)
if err != nil {
return false, err
}
err = query.AndWhere(expr).Limit(1).Row(&exists)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return false, err
}
return exists > 0, nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/base_backup.go | core/base_backup.go | package core
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"os"
"path/filepath"
"runtime"
"sort"
"time"
"github.com/pocketbase/pocketbase/tools/archive"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/pocketbase/pocketbase/tools/inflector"
"github.com/pocketbase/pocketbase/tools/osutils"
"github.com/pocketbase/pocketbase/tools/security"
)
const (
StoreKeyActiveBackup = "@activeBackup"
)
// CreateBackup creates a new backup of the current app pb_data directory.
//
// If name is empty, it will be autogenerated.
// If backup with the same name exists, the new backup file will replace it.
//
// The backup is executed within a transaction, meaning that new writes
// will be temporary "blocked" until the backup file is generated.
//
// To safely perform the backup, it is recommended to have free disk space
// for at least 2x the size of the pb_data directory.
//
// By default backups are stored in pb_data/backups
// (the backups directory itself is excluded from the generated backup).
//
// When using S3 storage for the uploaded collection files, you have to
// take care manually to backup those since they are not part of the pb_data.
//
// Backups can be stored on S3 if it is configured in app.Settings().Backups.
func (app *BaseApp) CreateBackup(ctx context.Context, name string) error {
if app.Store().Has(StoreKeyActiveBackup) {
return errors.New("try again later - another backup/restore operation has already been started")
}
app.Store().Set(StoreKeyActiveBackup, name)
defer app.Store().Remove(StoreKeyActiveBackup)
event := new(BackupEvent)
event.App = app
event.Context = ctx
event.Name = name
// default root dir entries to exclude from the backup generation
event.Exclude = []string{LocalBackupsDirName, LocalTempDirName, LocalAutocertCacheDirName, lostFoundDirName}
return app.OnBackupCreate().Trigger(event, func(e *BackupEvent) error {
// generate a default name if missing
if e.Name == "" {
e.Name = generateBackupName(e.App, "pb_backup_")
}
// make sure that the special temp directory exists
// note: it needs to be inside the current pb_data to avoid "cross-device link" errors
localTempDir := filepath.Join(e.App.DataDir(), LocalTempDirName)
if err := os.MkdirAll(localTempDir, os.ModePerm); err != nil {
return fmt.Errorf("failed to create a temp dir: %w", err)
}
// archive pb_data in a temp directory, exluding the "backups" and the temp dirs
//
// run in transaction to temporary block other writes (transactions uses the NonconcurrentDB connection)
// ---
tempPath := filepath.Join(localTempDir, "pb_backup_"+security.PseudorandomString(6))
createErr := e.App.RunInTransaction(func(txApp App) error {
return txApp.AuxRunInTransaction(func(txApp App) error {
// run manual checkpoint and truncate the WAL files
// (errors are ignored because it is not that important and the PRAGMA may not be supported by the used driver)
txApp.DB().NewQuery("PRAGMA wal_checkpoint(TRUNCATE)").Execute()
txApp.AuxDB().NewQuery("PRAGMA wal_checkpoint(TRUNCATE)").Execute()
return archive.Create(txApp.DataDir(), tempPath, e.Exclude...)
})
})
if createErr != nil {
return createErr
}
defer os.Remove(tempPath)
// persist the backup in the backups filesystem
// ---
fsys, err := e.App.NewBackupsFilesystem()
if err != nil {
return err
}
defer fsys.Close()
fsys.SetContext(e.Context)
file, err := filesystem.NewFileFromPath(tempPath)
if err != nil {
return err
}
file.OriginalName = e.Name
file.Name = file.OriginalName
if err := fsys.UploadFile(file, file.Name); err != nil {
return err
}
return nil
})
}
// RestoreBackup restores the backup with the specified name and restarts
// the current running application process.
//
// NB! This feature is experimental and currently is expected to work only on UNIX based systems.
//
// To safely perform the restore it is recommended to have free disk space
// for at least 2x the size of the restored pb_data backup.
//
// The performed steps are:
//
// 1. Download the backup with the specified name in a temp location
// (this is in case of S3; otherwise it creates a temp copy of the zip)
//
// 2. Extract the backup in a temp directory inside the app "pb_data"
// (eg. "pb_data/.pb_temp_to_delete/pb_restore").
//
// 3. Move the current app "pb_data" content (excluding the local backups and the special temp dir)
// under another temp sub dir that will be deleted on the next app start up
// (eg. "pb_data/.pb_temp_to_delete/old_pb_data").
// This is because on some environments it may not be allowed
// to delete the currently open "pb_data" files.
//
// 4. Move the extracted dir content to the app "pb_data".
//
// 5. Restart the app (on successful app bootstap it will also remove the old pb_data).
//
// If a failure occure during the restore process the dir changes are reverted.
// If for whatever reason the revert is not possible, it panics.
//
// Note that if your pb_data has custom network mounts as subdirectories, then
// it is possible the restore to fail during the `os.Rename` operations
// (see https://github.com/pocketbase/pocketbase/issues/4647).
func (app *BaseApp) RestoreBackup(ctx context.Context, name string) error {
if app.Store().Has(StoreKeyActiveBackup) {
return errors.New("try again later - another backup/restore operation has already been started")
}
app.Store().Set(StoreKeyActiveBackup, name)
defer app.Store().Remove(StoreKeyActiveBackup)
event := new(BackupEvent)
event.App = app
event.Context = ctx
event.Name = name
// default root dir entries to exclude from the backup restore
event.Exclude = []string{LocalBackupsDirName, LocalTempDirName, LocalAutocertCacheDirName, lostFoundDirName}
return app.OnBackupRestore().Trigger(event, func(e *BackupEvent) error {
if runtime.GOOS == "windows" {
return errors.New("restore is not supported on Windows")
}
// make sure that the special temp directory exists
// note: it needs to be inside the current pb_data to avoid "cross-device link" errors
localTempDir := filepath.Join(e.App.DataDir(), LocalTempDirName)
if err := os.MkdirAll(localTempDir, os.ModePerm); err != nil {
return fmt.Errorf("failed to create a temp dir: %w", err)
}
fsys, err := e.App.NewBackupsFilesystem()
if err != nil {
return err
}
defer fsys.Close()
fsys.SetContext(e.Context)
if ok, _ := fsys.Exists(name); !ok {
return fmt.Errorf("missing or invalid backup file %q to restore", name)
}
extractedDataDir := filepath.Join(localTempDir, "pb_restore_"+security.PseudorandomString(8))
defer os.RemoveAll(extractedDataDir)
// extract the zip
if e.App.Settings().Backups.S3.Enabled {
br, err := fsys.GetReader(name)
if err != nil {
return err
}
defer br.Close()
// create a temp zip file from the blob.Reader and try to extract it
tempZip, err := os.CreateTemp(localTempDir, "pb_restore_zip")
if err != nil {
return err
}
defer os.Remove(tempZip.Name())
defer tempZip.Close() // note: this technically shouldn't be necessary but it is here to workaround platforms discrepancies
_, err = io.Copy(tempZip, br)
if err != nil {
return err
}
err = archive.Extract(tempZip.Name(), extractedDataDir)
if err != nil {
return err
}
// remove the temp zip file since we no longer need it
// (this is in case the app restarts and the defer calls are not called)
_ = tempZip.Close()
err = os.Remove(tempZip.Name())
if err != nil {
e.App.Logger().Warn(
"[RestoreBackup] Failed to remove the temp zip backup file",
slog.String("file", tempZip.Name()),
slog.String("error", err.Error()),
)
}
} else {
// manually construct the local path to avoid creating a copy of the zip file
// since the blob reader currently doesn't implement ReaderAt
zipPath := filepath.Join(e.App.DataDir(), LocalBackupsDirName, filepath.Base(name))
err = archive.Extract(zipPath, extractedDataDir)
if err != nil {
return err
}
}
// ensure that at least a database file exists
extractedDB := filepath.Join(extractedDataDir, "data.db")
if _, err := os.Stat(extractedDB); err != nil {
return fmt.Errorf("data.db file is missing or invalid: %w", err)
}
oldTempDataDir := filepath.Join(localTempDir, "old_pb_data_"+security.PseudorandomString(8))
replaceErr := e.App.RunInTransaction(func(txApp App) error {
return txApp.AuxRunInTransaction(func(txApp App) error {
// move the current pb_data content to a special temp location
// that will hold the old data between dirs replace
// (the temp dir will be automatically removed on the next app start)
if err := osutils.MoveDirContent(txApp.DataDir(), oldTempDataDir, e.Exclude...); err != nil {
return fmt.Errorf("failed to move the current pb_data content to a temp location: %w", err)
}
// move the extracted archive content to the app's pb_data
if err := osutils.MoveDirContent(extractedDataDir, txApp.DataDir(), e.Exclude...); err != nil {
return fmt.Errorf("failed to move the extracted archive content to pb_data: %w", err)
}
return nil
})
})
if replaceErr != nil {
return replaceErr
}
revertDataDirChanges := func() error {
return e.App.RunInTransaction(func(txApp App) error {
return txApp.AuxRunInTransaction(func(txApp App) error {
if err := osutils.MoveDirContent(txApp.DataDir(), extractedDataDir, e.Exclude...); err != nil {
return fmt.Errorf("failed to revert the extracted dir change: %w", err)
}
if err := osutils.MoveDirContent(oldTempDataDir, txApp.DataDir(), e.Exclude...); err != nil {
return fmt.Errorf("failed to revert old pb_data dir change: %w", err)
}
return nil
})
})
}
// restart the app
if err := e.App.Restart(); err != nil {
if revertErr := revertDataDirChanges(); revertErr != nil {
panic(revertErr)
}
return fmt.Errorf("failed to restart the app process: %w", err)
}
return nil
})
}
// registerAutobackupHooks registers the autobackup app serve hooks.
func (app *BaseApp) registerAutobackupHooks() {
const jobId = "__pbAutoBackup__"
loadJob := func() {
rawSchedule := app.Settings().Backups.Cron
if rawSchedule == "" {
app.Cron().Remove(jobId)
return
}
app.Cron().Add(jobId, rawSchedule, func() {
const autoPrefix = "@auto_pb_backup_"
name := generateBackupName(app, autoPrefix)
if err := app.CreateBackup(context.Background(), name); err != nil {
app.Logger().Error(
"[Backup cron] Failed to create backup",
slog.String("name", name),
slog.String("error", err.Error()),
)
}
maxKeep := app.Settings().Backups.CronMaxKeep
if maxKeep == 0 {
return // no explicit limit
}
fsys, err := app.NewBackupsFilesystem()
if err != nil {
app.Logger().Error(
"[Backup cron] Failed to initialize the backup filesystem",
slog.String("error", err.Error()),
)
return
}
defer fsys.Close()
files, err := fsys.List(autoPrefix)
if err != nil {
app.Logger().Error(
"[Backup cron] Failed to list autogenerated backups",
slog.String("error", err.Error()),
)
return
}
if maxKeep >= len(files) {
return // nothing to remove
}
// sort desc
sort.Slice(files, func(i, j int) bool {
return files[i].ModTime.After(files[j].ModTime)
})
// keep only the most recent n auto backup files
toRemove := files[maxKeep:]
for _, f := range toRemove {
if err := fsys.Delete(f.Key); err != nil {
app.Logger().Error(
"[Backup cron] Failed to remove old autogenerated backup",
slog.String("key", f.Key),
slog.String("error", err.Error()),
)
}
}
})
}
app.OnBootstrap().BindFunc(func(e *BootstrapEvent) error {
if err := e.Next(); err != nil {
return err
}
loadJob()
return nil
})
app.OnSettingsReload().BindFunc(func(e *SettingsReloadEvent) error {
if err := e.Next(); err != nil {
return err
}
loadJob()
return nil
})
}
func generateBackupName(app App, prefix string) string {
appName := inflector.Snakecase(app.Settings().Meta.AppName)
if len(appName) > 50 {
appName = appName[:50]
}
return fmt.Sprintf(
"%s%s_%s.zip",
prefix,
appName,
time.Now().UTC().Format("20060102150405"),
)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/fields_list_test.go | core/fields_list_test.go | package core_test
import (
"bytes"
"encoding/json"
"slices"
"strconv"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
)
func TestNewFieldsList(t *testing.T) {
fields := core.NewFieldsList(
&core.TextField{Id: "id1", Name: "test1"},
&core.TextField{Name: "test2"},
&core.TextField{Id: "id1", Name: "test1_new"}, // should replace the original id1 field
)
if len(fields) != 2 {
t.Fatalf("Expected 2 fields, got %d (%v)", len(fields), fields)
}
for _, f := range fields {
if f.GetId() == "" {
t.Fatalf("Expected field id to be set, found empty id for field %v", f)
}
}
if fields[0].GetName() != "test1_new" {
t.Fatalf("Expected field with name test1_new, got %s", fields[0].GetName())
}
if fields[1].GetName() != "test2" {
t.Fatalf("Expected field with name test2, got %s", fields[1].GetName())
}
}
func TestFieldsListClone(t *testing.T) {
f1 := &core.TextField{Name: "test1"}
f2 := &core.EmailField{Name: "test2"}
s1 := core.NewFieldsList(f1, f2)
s2, err := s1.Clone()
if err != nil {
t.Fatal(err)
}
s1Str := s1.String()
s2Str := s2.String()
if s1Str != s2Str {
t.Fatalf("Expected the cloned list to be equal, got \n%v\nVS\n%v", s1, s2)
}
// change in one list shouldn't result to change in the other
// (aka. check if it is a deep clone)
s1[0].SetName("test1_update")
if s2[0].GetName() != "test1" {
t.Fatalf("Expected s2 field name to not change, got %q", s2[0].GetName())
}
}
func TestFieldsListFieldNames(t *testing.T) {
f1 := &core.TextField{Name: "test1"}
f2 := &core.EmailField{Name: "test2"}
testFieldsList := core.NewFieldsList(f1, f2)
result := testFieldsList.FieldNames()
expected := []string{f1.Name, f2.Name}
if len(result) != len(expected) {
t.Fatalf("Expected %d slice elements, got %d\n%v", len(expected), len(result), result)
}
for _, name := range expected {
if !slices.Contains(result, name) {
t.Fatalf("Missing name %q in %v", name, result)
}
}
}
func TestFieldsListAsMap(t *testing.T) {
f1 := &core.TextField{Name: "test1"}
f2 := &core.EmailField{Name: "test2"}
testFieldsList := core.NewFieldsList(f1, f2)
result := testFieldsList.AsMap()
expectedIndexes := []string{f1.Name, f2.Name}
if len(result) != len(expectedIndexes) {
t.Fatalf("Expected %d map elements, got %d\n%v", len(expectedIndexes), len(result), result)
}
for _, index := range expectedIndexes {
if _, ok := result[index]; !ok {
t.Fatalf("Missing index %q", index)
}
}
}
func TestFieldsListGetById(t *testing.T) {
f1 := &core.TextField{Id: "id1", Name: "test1"}
f2 := &core.EmailField{Id: "id2", Name: "test2"}
testFieldsList := core.NewFieldsList(f1, f2)
// missing field id
result1 := testFieldsList.GetById("test1")
if result1 != nil {
t.Fatalf("Found unexpected field %v", result1)
}
// existing field id
result2 := testFieldsList.GetById("id2")
if result2 == nil || result2.GetId() != "id2" {
t.Fatalf("Cannot find field with id %q, got %v ", "id2", result2)
}
}
func TestFieldsListGetByName(t *testing.T) {
f1 := &core.TextField{Id: "id1", Name: "test1"}
f2 := &core.EmailField{Id: "id2", Name: "test2"}
testFieldsList := core.NewFieldsList(f1, f2)
// missing field name
result1 := testFieldsList.GetByName("id1")
if result1 != nil {
t.Fatalf("Found unexpected field %v", result1)
}
// existing field name
result2 := testFieldsList.GetByName("test2")
if result2 == nil || result2.GetName() != "test2" {
t.Fatalf("Cannot find field with name %q, got %v ", "test2", result2)
}
}
func TestFieldsListRemove(t *testing.T) {
testFieldsList := core.NewFieldsList(
&core.TextField{Id: "id1", Name: "test1"},
&core.TextField{Id: "id2", Name: "test2"},
&core.TextField{Id: "id3", Name: "test3"},
&core.TextField{Id: "id4", Name: "test4"},
&core.TextField{Id: "id5", Name: "test5"},
&core.TextField{Id: "id6", Name: "test6"},
)
// remove by id
testFieldsList.RemoveById("id2")
testFieldsList.RemoveById("test3") // should do nothing
// remove by name
testFieldsList.RemoveByName("test5")
testFieldsList.RemoveByName("id6") // should do nothing
expected := []string{"test1", "test3", "test4", "test6"}
if len(testFieldsList) != len(expected) {
t.Fatalf("Expected %d, got %d\n%v", len(expected), len(testFieldsList), testFieldsList)
}
for _, name := range expected {
if f := testFieldsList.GetByName(name); f == nil {
t.Fatalf("Missing field %q", name)
}
}
}
func TestFieldsListAdd(t *testing.T) {
f0 := &core.TextField{}
f1 := &core.TextField{Name: "test1"}
f2 := &core.TextField{Id: "f2Id", Name: "test2"}
f3 := &core.TextField{Id: "f3Id", Name: "test3"}
testFieldsList := core.NewFieldsList(f0, f1, f2, f3)
f2New := &core.EmailField{Id: "f2Id", Name: "test2_new"}
f4 := &core.URLField{Name: "test4"}
testFieldsList.Add(f2New)
testFieldsList.Add(f4)
if len(testFieldsList) != 5 {
t.Fatalf("Expected %d, got %d\n%v", 5, len(testFieldsList), testFieldsList)
}
// check if each field has id
for _, f := range testFieldsList {
if f.GetId() == "" {
t.Fatalf("Expected field id to be set, found empty id for field %v", f)
}
}
// check if f2 field was replaced
if f := testFieldsList.GetById("f2Id"); f == nil || f.Type() != core.FieldTypeEmail {
t.Fatalf("Expected f2 field to be replaced, found %v", f)
}
// check if f4 was added
if f := testFieldsList.GetByName("test4"); f == nil || f.GetName() != "test4" {
t.Fatalf("Expected f4 field to be added, found %v", f)
}
}
func TestFieldsListAddMarshaledJSON(t *testing.T) {
t.Parallel()
scenarios := []struct {
name string
raw []byte
expectError bool
expectedFields map[string]string
}{
{
"nil",
nil,
false,
map[string]string{"abc": core.FieldTypeNumber},
},
{
"empty array",
[]byte(`[]`),
false,
map[string]string{"abc": core.FieldTypeNumber},
},
{
"empty object",
[]byte(`{}`),
true,
map[string]string{"abc": core.FieldTypeNumber},
},
{
"array with empty object",
[]byte(`[{}]`),
true,
map[string]string{"abc": core.FieldTypeNumber},
},
{
"single object with invalid type",
[]byte(`{"type":"missing","name":"test"}`),
true,
map[string]string{"abc": core.FieldTypeNumber},
},
{
"single object with valid type",
[]byte(`{"type":"text","name":"test"}`),
false,
map[string]string{
"abc": core.FieldTypeNumber,
"test": core.FieldTypeText,
},
},
{
"array of object with valid types",
[]byte(`[{"type":"text","name":"test1"},{"type":"url","name":"test2"}]`),
false,
map[string]string{
"abc": core.FieldTypeNumber,
"test1": core.FieldTypeText,
"test2": core.FieldTypeURL,
},
},
{
"fields with duplicated ids should replace existing fields",
[]byte(`[{"type":"text","name":"test1"},{"type":"url","name":"test2"},{"type":"text","name":"abc2", "id":"abc_id"}]`),
false,
map[string]string{
"abc2": core.FieldTypeText,
"test1": core.FieldTypeText,
"test2": core.FieldTypeURL,
},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
testList := core.NewFieldsList(&core.NumberField{Name: "abc", Id: "abc_id"})
err := testList.AddMarshaledJSON(s.raw)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v", s.expectError, hasErr)
}
if len(s.expectedFields) != len(testList) {
t.Fatalf("Expected %d fields, got %d", len(s.expectedFields), len(testList))
}
for fieldName, typ := range s.expectedFields {
f := testList.GetByName(fieldName)
if f == nil {
t.Errorf("Missing expected field %q", fieldName)
continue
}
if f.Type() != typ {
t.Errorf("Expect field %q to has type %q, got %q", fieldName, typ, f.Type())
}
}
})
}
}
func TestFieldsListAddAt(t *testing.T) {
scenarios := []struct {
position int
expected []string
}{
{-2, []string{"test1", "test2_new", "test3", "test4"}},
{-1, []string{"test1", "test2_new", "test3", "test4"}},
{0, []string{"test2_new", "test4", "test1", "test3"}},
{1, []string{"test1", "test2_new", "test4", "test3"}},
{2, []string{"test1", "test3", "test2_new", "test4"}},
{3, []string{"test1", "test3", "test2_new", "test4"}},
{4, []string{"test1", "test3", "test2_new", "test4"}},
{5, []string{"test1", "test3", "test2_new", "test4"}},
}
for _, s := range scenarios {
t.Run(strconv.Itoa(s.position), func(t *testing.T) {
f1 := &core.TextField{Id: "f1Id", Name: "test1"}
f2 := &core.TextField{Id: "f2Id", Name: "test2"}
f3 := &core.TextField{Id: "f3Id", Name: "test3"}
testFieldsList := core.NewFieldsList(f1, f2, f3)
f2New := &core.EmailField{Id: "f2Id", Name: "test2_new"}
f4 := &core.URLField{Name: "test4"}
testFieldsList.AddAt(s.position, f2New, f4)
rawNames, err := json.Marshal(testFieldsList.FieldNames())
if err != nil {
t.Fatal(err)
}
rawExpected, err := json.Marshal(s.expected)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(rawNames, rawExpected) {
t.Fatalf("Expected fields\n%s\ngot\n%s", rawExpected, rawNames)
}
})
}
}
func TestFieldsListAddMarshaledJSONAt(t *testing.T) {
scenarios := []struct {
position int
expected []string
}{
{-2, []string{"test1", "test2_new", "test3", "test4"}},
{-1, []string{"test1", "test2_new", "test3", "test4"}},
{0, []string{"test2_new", "test4", "test1", "test3"}},
{1, []string{"test1", "test2_new", "test4", "test3"}},
{2, []string{"test1", "test3", "test2_new", "test4"}},
{3, []string{"test1", "test3", "test2_new", "test4"}},
{4, []string{"test1", "test3", "test2_new", "test4"}},
{5, []string{"test1", "test3", "test2_new", "test4"}},
}
for _, s := range scenarios {
t.Run(strconv.Itoa(s.position), func(t *testing.T) {
f1 := &core.TextField{Id: "f1Id", Name: "test1"}
f2 := &core.TextField{Id: "f2Id", Name: "test2"}
f3 := &core.TextField{Id: "f3Id", Name: "test3"}
testFieldsList := core.NewFieldsList(f1, f2, f3)
err := testFieldsList.AddMarshaledJSONAt(s.position, []byte(`[
{"id":"f2Id", "name":"test2_new", "type": "text"},
{"name": "test4", "type": "text"}
]`))
if err != nil {
t.Fatal(err)
}
rawNames, err := json.Marshal(testFieldsList.FieldNames())
if err != nil {
t.Fatal(err)
}
rawExpected, err := json.Marshal(s.expected)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(rawNames, rawExpected) {
t.Fatalf("Expected fields\n%s\ngot\n%s", rawExpected, rawNames)
}
})
}
}
func TestFieldsListStringAndValue(t *testing.T) {
t.Run("empty list", func(t *testing.T) {
testFieldsList := core.NewFieldsList()
str := testFieldsList.String()
if str != "[]" {
t.Fatalf("Expected empty slice, got\n%q", str)
}
v, err := testFieldsList.Value()
if err != nil {
t.Fatal(err)
}
if v != str {
t.Fatalf("Expected String and Value to match")
}
})
t.Run("list with fields", func(t *testing.T) {
testFieldsList := core.NewFieldsList(
&core.TextField{Id: "f1id", Name: "test1"},
&core.BoolField{Id: "f2id", Name: "test2"},
&core.URLField{Id: "f3id", Name: "test3"},
)
str := testFieldsList.String()
v, err := testFieldsList.Value()
if err != nil {
t.Fatal(err)
}
if v != str {
t.Fatalf("Expected String and Value to match")
}
expectedParts := []string{
`"type":"bool"`,
`"type":"url"`,
`"type":"text"`,
`"id":"f1id"`,
`"id":"f2id"`,
`"id":"f3id"`,
`"name":"test1"`,
`"name":"test2"`,
`"name":"test3"`,
}
for _, part := range expectedParts {
if !strings.Contains(str, part) {
t.Fatalf("Missing %q in\nn%v", part, str)
}
}
})
}
func TestFieldsListScan(t *testing.T) {
scenarios := []struct {
name string
data any
expectError bool
expectJSON string
}{
{"nil", nil, false, "[]"},
{"empty string", "", false, "[]"},
{"empty byte", []byte{}, false, "[]"},
{"empty string array", "[]", false, "[]"},
{"invalid string", "invalid", true, "[]"},
{"non-string", 123, true, "[]"},
{"item with no field type", `[{}]`, true, "[]"},
{
"unknown field type",
`[{"id":"123","name":"test1","type":"unknown"},{"id":"456","name":"test2","type":"bool"}]`,
true,
`[]`,
},
{
"only the minimum field options",
`[{"id":"123","name":"test1","type":"text","required":true},{"id":"456","name":"test2","type":"bool"}]`,
false,
`[{"autogeneratePattern":"","hidden":false,"id":"123","max":0,"min":0,"name":"test1","pattern":"","presentable":false,"primaryKey":false,"required":true,"system":false,"type":"text"},{"hidden":false,"id":"456","name":"test2","presentable":false,"required":false,"system":false,"type":"bool"}]`,
},
{
"all field options",
`[{"autogeneratePattern":"","hidden":true,"id":"123","max":12,"min":0,"name":"test1","pattern":"","presentable":true,"primaryKey":false,"required":true,"system":false,"type":"text"},{"hidden":false,"id":"456","name":"test2","presentable":false,"required":false,"system":true,"type":"bool"}]`,
false,
`[{"autogeneratePattern":"","hidden":true,"id":"123","max":12,"min":0,"name":"test1","pattern":"","presentable":true,"primaryKey":false,"required":true,"system":false,"type":"text"},{"hidden":false,"id":"456","name":"test2","presentable":false,"required":false,"system":true,"type":"bool"}]`,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
testFieldsList := core.FieldsList{}
err := testFieldsList.Scan(s.data)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
str := testFieldsList.String()
if str != s.expectJSON {
t.Fatalf("Expected\n%v\ngot\n%v", s.expectJSON, str)
}
})
}
}
func TestFieldsListJSON(t *testing.T) {
scenarios := []struct {
name string
data string
expectError bool
expectJSON string
}{
{"empty string", "", true, "[]"},
{"invalid string", "invalid", true, "[]"},
{"empty string array", "[]", false, "[]"},
{"item with no field type", `[{}]`, true, "[]"},
{
"unknown field type",
`[{"id":"123","name":"test1","type":"unknown"},{"id":"456","name":"test2","type":"bool"}]`,
true,
`[]`,
},
{
"only the minimum field options",
`[{"id":"123","name":"test1","type":"text","required":true},{"id":"456","name":"test2","type":"bool"}]`,
false,
`[{"autogeneratePattern":"","hidden":false,"id":"123","max":0,"min":0,"name":"test1","pattern":"","presentable":false,"primaryKey":false,"required":true,"system":false,"type":"text"},{"hidden":false,"id":"456","name":"test2","presentable":false,"required":false,"system":false,"type":"bool"}]`,
},
{
"all field options",
`[{"autogeneratePattern":"","hidden":true,"id":"123","max":12,"min":0,"name":"test1","pattern":"","presentable":true,"primaryKey":false,"required":true,"system":false,"type":"text"},{"hidden":false,"id":"456","name":"test2","presentable":false,"required":false,"system":true,"type":"bool"}]`,
false,
`[{"autogeneratePattern":"","hidden":true,"id":"123","max":12,"min":0,"name":"test1","pattern":"","presentable":true,"primaryKey":false,"required":true,"system":false,"type":"text"},{"hidden":false,"id":"456","name":"test2","presentable":false,"required":false,"system":true,"type":"bool"}]`,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
testFieldsList := core.FieldsList{}
err := testFieldsList.UnmarshalJSON([]byte(s.data))
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
raw, err := testFieldsList.MarshalJSON()
if err != nil {
t.Fatal(err)
}
str := string(raw)
if str != s.expectJSON {
t.Fatalf("Expected\n%v\ngot\n%v", s.expectJSON, str)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/auth_origin_query.go | core/auth_origin_query.go | package core
import (
"errors"
"github.com/pocketbase/dbx"
)
// FindAllAuthOriginsByRecord returns all AuthOrigin models linked to the provided auth record (in DESC order).
func (app *BaseApp) FindAllAuthOriginsByRecord(authRecord *Record) ([]*AuthOrigin, error) {
result := []*AuthOrigin{}
err := app.RecordQuery(CollectionNameAuthOrigins).
AndWhere(dbx.HashExp{
"collectionRef": authRecord.Collection().Id,
"recordRef": authRecord.Id,
}).
OrderBy("created DESC").
All(&result)
if err != nil {
return nil, err
}
return result, nil
}
// FindAllAuthOriginsByCollection returns all AuthOrigin models linked to the provided collection (in DESC order).
func (app *BaseApp) FindAllAuthOriginsByCollection(collection *Collection) ([]*AuthOrigin, error) {
result := []*AuthOrigin{}
err := app.RecordQuery(CollectionNameAuthOrigins).
AndWhere(dbx.HashExp{"collectionRef": collection.Id}).
OrderBy("created DESC").
All(&result)
if err != nil {
return nil, err
}
return result, nil
}
// FindAuthOriginById returns a single AuthOrigin model by its id.
func (app *BaseApp) FindAuthOriginById(id string) (*AuthOrigin, error) {
result := &AuthOrigin{}
err := app.RecordQuery(CollectionNameAuthOrigins).
AndWhere(dbx.HashExp{"id": id}).
Limit(1).
One(result)
if err != nil {
return nil, err
}
return result, nil
}
// FindAuthOriginByRecordAndFingerprint returns a single AuthOrigin model
// by its authRecord relation and fingerprint.
func (app *BaseApp) FindAuthOriginByRecordAndFingerprint(authRecord *Record, fingerprint string) (*AuthOrigin, error) {
result := &AuthOrigin{}
err := app.RecordQuery(CollectionNameAuthOrigins).
AndWhere(dbx.HashExp{
"collectionRef": authRecord.Collection().Id,
"recordRef": authRecord.Id,
"fingerprint": fingerprint,
}).
Limit(1).
One(result)
if err != nil {
return nil, err
}
return result, nil
}
// DeleteAllAuthOriginsByRecord deletes all AuthOrigin models associated with the provided record.
//
// Returns a combined error with the failed deletes.
func (app *BaseApp) DeleteAllAuthOriginsByRecord(authRecord *Record) error {
models, err := app.FindAllAuthOriginsByRecord(authRecord)
if err != nil {
return err
}
var errs []error
for _, m := range models {
if err := app.Delete(m); err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_model_auth.go | core/record_model_auth.go | package core
import "github.com/pocketbase/pocketbase/tools/security"
// Email returns the "email" record field value (usually available with Auth collections).
func (m *Record) Email() string {
return m.GetString(FieldNameEmail)
}
// SetEmail sets the "email" record field value (usually available with Auth collections).
func (m *Record) SetEmail(email string) {
m.Set(FieldNameEmail, email)
}
// Verified returns the "emailVisibility" record field value (usually available with Auth collections).
func (m *Record) EmailVisibility() bool {
return m.GetBool(FieldNameEmailVisibility)
}
// SetEmailVisibility sets the "emailVisibility" record field value (usually available with Auth collections).
func (m *Record) SetEmailVisibility(visible bool) {
m.Set(FieldNameEmailVisibility, visible)
}
// Verified returns the "verified" record field value (usually available with Auth collections).
func (m *Record) Verified() bool {
return m.GetBool(FieldNameVerified)
}
// SetVerified sets the "verified" record field value (usually available with Auth collections).
func (m *Record) SetVerified(verified bool) {
m.Set(FieldNameVerified, verified)
}
// TokenKey returns the "tokenKey" record field value (usually available with Auth collections).
func (m *Record) TokenKey() string {
return m.GetString(FieldNameTokenKey)
}
// SetTokenKey sets the "tokenKey" record field value (usually available with Auth collections).
func (m *Record) SetTokenKey(key string) {
m.Set(FieldNameTokenKey, key)
}
// RefreshTokenKey generates and sets a new random auth record "tokenKey".
func (m *Record) RefreshTokenKey() {
m.Set(FieldNameTokenKey+autogenerateModifier, "")
}
// SetPassword sets the "password" record field value (usually available with Auth collections).
func (m *Record) SetPassword(password string) {
// note: the tokenKey will be auto changed if necessary before db write
m.Set(FieldNamePassword, password)
}
// SetRandomPassword sets the "password" auth record field to a random autogenerated value.
//
// The autogenerated password is ~30 characters and it is set directly as hash,
// aka. the field plain password value validators (length, pattern, etc.) are ignored
// (this is usually used as part of the auto created OTP or OAuth2 user flows).
func (m *Record) SetRandomPassword() string {
pass := security.RandomString(30)
m.Set(FieldNamePassword, pass)
m.RefreshTokenKey() // manually refresh the token key because the plain password is resetted
// unset the plain value to skip the field validators
if raw, ok := m.GetRaw(FieldNamePassword).(*PasswordFieldValue); ok {
raw.Plain = ""
}
return pass
}
// ValidatePassword validates a plain password against the "password" record field.
//
// Returns false if the password is incorrect.
func (m *Record) ValidatePassword(password string) bool {
pv, ok := m.GetRaw(FieldNamePassword).(*PasswordFieldValue)
if !ok {
return false
}
return pv.Validate(password)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/base_backup_test.go | core/base_backup_test.go | package core_test
import (
"context"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/archive"
"github.com/pocketbase/pocketbase/tools/list"
)
func TestCreateBackup(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
// set some long app name with spaces and special characters
app.Settings().Meta.AppName = "test @! " + strings.Repeat("a", 100)
expectedAppNamePrefix := "test_" + strings.Repeat("a", 45)
// test pending error
app.Store().Set(core.StoreKeyActiveBackup, "")
if err := app.CreateBackup(context.Background(), "test.zip"); err == nil {
t.Fatal("Expected pending error, got nil")
}
app.Store().Remove(core.StoreKeyActiveBackup)
// create with auto generated name
if err := app.CreateBackup(context.Background(), ""); err != nil {
t.Fatal("Failed to create a backup with autogenerated name")
}
// create with custom name
if err := app.CreateBackup(context.Background(), "custom"); err != nil {
t.Fatal("Failed to create a backup with custom name")
}
// create new with the same name (aka. replace)
if err := app.CreateBackup(context.Background(), "custom"); err != nil {
t.Fatal("Failed to create and replace a backup with the same name")
}
backupsDir := filepath.Join(app.DataDir(), core.LocalBackupsDirName)
entries, err := os.ReadDir(backupsDir)
if err != nil {
t.Fatal(err)
}
expectedFiles := []string{
`^pb_backup_` + expectedAppNamePrefix + `_\w+\.zip$`,
`^pb_backup_` + expectedAppNamePrefix + `_\w+\.zip.attrs$`,
"custom",
"custom.attrs",
}
if len(entries) != len(expectedFiles) {
names := getEntryNames(entries)
t.Fatalf("Expected %d backup files, got %d: \n%v", len(expectedFiles), len(entries), names)
}
for i, entry := range entries {
if !list.ExistInSliceWithRegex(entry.Name(), expectedFiles) {
t.Fatalf("[%d] Missing backup file %q", i, entry.Name())
}
if strings.HasSuffix(entry.Name(), ".attrs") {
continue
}
path := filepath.Join(backupsDir, entry.Name())
if err := verifyBackupContent(app, path); err != nil {
t.Fatalf("[%d] Failed to verify backup content: %v", i, err)
}
}
}
func TestRestoreBackup(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
// create a initial test backup to ensure that there are at least 1
// backup file and that the generated zip doesn't contain the backups dir
if err := app.CreateBackup(context.Background(), "initial"); err != nil {
t.Fatal("Failed to create test initial backup")
}
// create test backup
if err := app.CreateBackup(context.Background(), "test"); err != nil {
t.Fatal("Failed to create test backup")
}
// test pending error
app.Store().Set(core.StoreKeyActiveBackup, "")
if err := app.RestoreBackup(context.Background(), "test"); err == nil {
t.Fatal("Expected pending error, got nil")
}
app.Store().Remove(core.StoreKeyActiveBackup)
// missing backup
if err := app.RestoreBackup(context.Background(), "missing"); err == nil {
t.Fatal("Expected missing error, got nil")
}
}
// -------------------------------------------------------------------
func verifyBackupContent(app core.App, path string) error {
dir, err := os.MkdirTemp("", "backup_test")
if err != nil {
return err
}
defer os.RemoveAll(dir)
if err := archive.Extract(path, dir); err != nil {
return err
}
expectedRootEntries := []string{
"storage",
"data.db",
"data.db-shm",
"data.db-wal",
"auxiliary.db",
"auxiliary.db-shm",
"auxiliary.db-wal",
".gitignore",
}
entries, err := os.ReadDir(dir)
if err != nil {
return err
}
if len(entries) != len(expectedRootEntries) {
names := getEntryNames(entries)
return fmt.Errorf("Expected %d backup files, got %d: \n%v", len(expectedRootEntries), len(entries), names)
}
for _, entry := range entries {
if !list.ExistInSliceWithRegex(entry.Name(), expectedRootEntries) {
return fmt.Errorf("Didn't expect %q entry", entry.Name())
}
}
return nil
}
func getEntryNames(entries []fs.DirEntry) []string {
names := make([]string, len(entries))
for i, entry := range entries {
names[i] = entry.Name()
}
return names
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/collection_model_auth_templates.go | core/collection_model_auth_templates.go | package core
// Common settings placeholder tokens
const (
EmailPlaceholderAppName string = "{APP_NAME}"
EmailPlaceholderAppURL string = "{APP_URL}"
EmailPlaceholderToken string = "{TOKEN}"
EmailPlaceholderOTP string = "{OTP}"
EmailPlaceholderOTPId string = "{OTP_ID}"
EmailPlaceholderAlertInfo string = "{ALERT_INFO}"
)
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="` + EmailPlaceholderAppURL + "/_/#/auth/confirm-verification/" + EmailPlaceholderToken + `" target="_blank" rel="noopener">Verify</a>
</p>
<p>
Thanks,<br/>
` + EmailPlaceholderAppName + ` team
</p>`,
}
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="` + EmailPlaceholderAppURL + "/_/#/auth/confirm-password-reset/" + EmailPlaceholderToken + `" 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>`,
}
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="` + EmailPlaceholderAppURL + "/_/#/auth/confirm-email-change/" + EmailPlaceholderToken + `" 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>`,
}
var defaultOTPTemplate = EmailTemplate{
Subject: "OTP for " + EmailPlaceholderAppName,
Body: `<p>Hello,</p>
<p>Your one-time password is: <strong>` + EmailPlaceholderOTP + `</strong></p>
<p><i>If you didn't ask for the one-time password, you can ignore this email.</i></p>
<p>
Thanks,<br/>
` + EmailPlaceholderAppName + ` team
</p>`,
}
var defaultAuthAlertTemplate = EmailTemplate{
Subject: "Login from a new location",
Body: `<p>Hello,</p>
<p>We noticed a login to your ` + EmailPlaceholderAppName + ` account from a new location:</p>
<p><em>` + EmailPlaceholderAlertInfo + `</em></p>
<p><strong>If this wasn't you, you should immediately change your ` + EmailPlaceholderAppName + ` account password to revoke access from all other locations.</strong></p>
<p>If this was you, you may disregard this email.</p>
<p>
Thanks,<br/>
` + EmailPlaceholderAppName + ` team
</p>`,
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/collection_validate_test.go | core/collection_validate_test.go | package core_test
import (
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestCollectionValidate(t *testing.T) {
t.Parallel()
scenarios := []struct {
name string
collection func(app core.App) (*core.Collection, error)
expectedErrors []string
}{
{
name: "empty collection",
collection: func(app core.App) (*core.Collection, error) {
return &core.Collection{}, nil
},
expectedErrors: []string{
"id", "name", "type", "fields", // no default fields because the type is unknown
},
},
{
name: "unknown type with all invalid fields",
collection: func(app core.App) (*core.Collection, error) {
c := &core.Collection{}
c.Id = "invalid_id ?!@#$"
c.Name = "invalid_name ?!@#$"
c.Type = "invalid_type"
c.ListRule = types.Pointer("missing = '123'")
c.ViewRule = types.Pointer("missing = '123'")
c.CreateRule = types.Pointer("missing = '123'")
c.UpdateRule = types.Pointer("missing = '123'")
c.DeleteRule = types.Pointer("missing = '123'")
c.Indexes = []string{"create index '' on '' ()"}
// type specific fields
c.ViewQuery = "invalid" // should be ignored
c.AuthRule = types.Pointer("missing = '123'") // should be ignored
return c, nil
},
expectedErrors: []string{
"id", "name", "type", "indexes",
"listRule", "viewRule", "createRule", "updateRule", "deleteRule",
"fields", // no default fields because the type is unknown
},
},
{
name: "base with invalid fields",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("invalid_name ?!@#$")
c.Indexes = []string{"create index '' on '' ()"}
// type specific fields
c.ViewQuery = "invalid" // should be ignored
c.AuthRule = types.Pointer("missing = '123'") // should be ignored
return c, nil
},
expectedErrors: []string{"name", "indexes"},
},
{
name: "view with invalid fields",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewViewCollection("invalid_name ?!@#$")
c.Indexes = []string{"create index '' on '' ()"}
// type specific fields
c.ViewQuery = "invalid"
c.AuthRule = types.Pointer("missing = '123'") // should be ignored
return c, nil
},
expectedErrors: []string{"indexes", "name", "fields", "viewQuery"},
},
{
name: "auth with invalid fields",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("invalid_name ?!@#$")
c.Indexes = []string{"create index '' on '' ()"}
// type specific fields
c.ViewQuery = "invalid" // should be ignored
c.AuthRule = types.Pointer("missing = '123'")
return c, nil
},
expectedErrors: []string{"indexes", "name", "authRule"},
},
// type checks
{
name: "empty type",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("test")
c.Type = ""
return c, nil
},
expectedErrors: []string{"type"},
},
{
name: "unknown type",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("test")
c.Type = "unknown"
return c, nil
},
expectedErrors: []string{"type"},
},
{
name: "base type",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("test")
return c, nil
},
expectedErrors: []string{},
},
{
name: "view type",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewViewCollection("test")
c.ViewQuery = "select 1 as id"
return c, nil
},
expectedErrors: []string{},
},
{
name: "auth type",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("test")
return c, nil
},
expectedErrors: []string{},
},
{
name: "changing type",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("users")
c.Type = core.CollectionTypeBase
return c, nil
},
expectedErrors: []string{"type"},
},
// system checks
{
name: "change from system to regular",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId(core.CollectionNameSuperusers)
c.System = false
return c, nil
},
expectedErrors: []string{"system"},
},
{
name: "change from regular to system",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("demo1")
c.System = true
return c, nil
},
expectedErrors: []string{"system"},
},
{
name: "create system",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("new_system")
c.System = true
return c, nil
},
expectedErrors: []string{},
},
// id checks
{
name: "empty id",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("test")
c.Id = ""
return c, nil
},
expectedErrors: []string{"id"},
},
{
name: "invalid id",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("test")
c.Id = "!invalid"
return c, nil
},
expectedErrors: []string{"id"},
},
{
name: "existing id",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("test")
c.Id = "_pb_users_auth_"
return c, nil
},
expectedErrors: []string{"id"},
},
{
name: "changing id",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("demo3")
c.Id = "anything"
return c, nil
},
expectedErrors: []string{"id"},
},
{
name: "valid id",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("test")
c.Id = "anything"
return c, nil
},
expectedErrors: []string{},
},
// name checks
{
name: "empty name",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("")
c.Id = "test"
return c, nil
},
expectedErrors: []string{"name"},
},
{
name: "invalid name",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("!invalid")
return c, nil
},
expectedErrors: []string{"name"},
},
{
name: "name with _via_",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("a_via_b")
return c, nil
},
expectedErrors: []string{"name"},
},
{
name: "create with existing collection name",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("demo1")
return c, nil
},
expectedErrors: []string{"name"},
},
{
name: "create with existing internal table name",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("_collections")
return c, nil
},
expectedErrors: []string{"name"},
},
{
name: "update with existing collection name",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("users")
c.Name = "demo1"
return c, nil
},
expectedErrors: []string{"name"},
},
{
name: "update with existing internal table name",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("users")
c.Name = "_collections"
return c, nil
},
expectedErrors: []string{"name"},
},
{
name: "system collection name change",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId(core.CollectionNameSuperusers)
c.Name = "superusers_new"
return c, nil
},
expectedErrors: []string{"name"},
},
{
name: "create with valid name",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("new_col")
return c, nil
},
expectedErrors: []string{},
},
{
name: "update with valid name",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("demo1")
c.Name = "demo1_new"
return c, nil
},
expectedErrors: []string{},
},
// rule checks
{
name: "invalid base rules",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("new")
c.ListRule = types.Pointer("!invalid")
c.ViewRule = types.Pointer("missing = 123")
c.CreateRule = types.Pointer("id = 123 && missing = 456")
c.UpdateRule = types.Pointer("@request.body.missing:changed = false")
c.DeleteRule = types.Pointer("(id=123")
return c, nil
},
expectedErrors: []string{"listRule", "viewRule", "createRule", "updateRule", "deleteRule"},
},
{
name: "valid base rules",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("new")
c.Fields.Add(&core.TextField{Name: "f1"}) // dummy field to ensure that new fields can be referenced
c.ListRule = types.Pointer("")
c.ViewRule = types.Pointer("f1 = 123")
c.CreateRule = types.Pointer("id = 123 && f1 = 456")
c.UpdateRule = types.Pointer("(id = 123 && @request.body.f1:changed = false)")
c.DeleteRule = types.Pointer("f1 = 123")
return c, nil
},
expectedErrors: []string{},
},
{
name: "view with non-nil create/update/delete rules",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewViewCollection("new")
c.ViewQuery = "select 1 as id, 'text' as f1"
c.ListRule = types.Pointer("id = 123")
c.ViewRule = types.Pointer("f1 = 456")
c.CreateRule = types.Pointer("")
c.UpdateRule = types.Pointer("")
c.DeleteRule = types.Pointer("")
return c, nil
},
expectedErrors: []string{"createRule", "updateRule", "deleteRule"},
},
{
name: "view with nil create/update/delete rules",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewViewCollection("new")
c.ViewQuery = "select 1 as id, 'text' as f1"
c.ListRule = types.Pointer("id = 1")
c.ViewRule = types.Pointer("f1 = 456")
return c, nil
},
expectedErrors: []string{},
},
{
name: "changing api rules",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("users")
c.Fields.Add(&core.TextField{Name: "f1"}) // dummy field to ensure that new fields can be referenced
c.ListRule = types.Pointer("id = 1")
c.ViewRule = types.Pointer("f1 = 456")
c.CreateRule = types.Pointer("id = 123 && f1 = 456")
c.UpdateRule = types.Pointer("(id = 123)")
c.DeleteRule = types.Pointer("f1 = 123")
return c, nil
},
expectedErrors: []string{},
},
{
name: "changing system collection api rules",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId(core.CollectionNameSuperusers)
c.ListRule = types.Pointer("1 = 1")
c.ViewRule = types.Pointer("1 = 1")
c.CreateRule = types.Pointer("1 = 1")
c.UpdateRule = types.Pointer("1 = 1")
c.DeleteRule = types.Pointer("1 = 1")
c.ManageRule = types.Pointer("1 = 1")
c.AuthRule = types.Pointer("1 = 1")
return c, nil
},
expectedErrors: []string{
"listRule", "viewRule", "createRule", "updateRule",
"deleteRule", "manageRule", "authRule",
},
},
// indexes checks
{
name: "invalid index expression",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("demo1")
c.Indexes = []string{
"create index invalid",
"create index idx_test_demo2 on anything (text)", // the name of table shouldn't matter
}
return c, nil
},
expectedErrors: []string{"indexes"},
},
{
name: "index name used in other table",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("demo1")
c.Indexes = []string{
"create index `idx_test_demo1` on demo1 (id)",
"create index `__pb_USERS_auth__username_idx` on anything (text)", // should be case-insensitive
}
return c, nil
},
expectedErrors: []string{"indexes"},
},
{
name: "duplicated index names",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("demo1")
c.Indexes = []string{
"create index idx_test_demo1 on demo1 (id)",
"create index idx_test_demo1 on anything (text)",
}
return c, nil
},
expectedErrors: []string{"indexes"},
},
{
name: "duplicated index definitions",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("demo1")
c.Indexes = []string{
"create index idx_test_demo1 on demo1 (id)",
"create index idx_test_demo2 on demo1 (id)",
}
return c, nil
},
expectedErrors: []string{"indexes"},
},
{
name: "try to add index to a view collection",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("view1")
c.Indexes = []string{"create index idx_test_view1 on view1 (id)"}
return c, nil
},
expectedErrors: []string{"indexes"},
},
{
name: "replace old with new indexes",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("demo1")
c.Indexes = []string{
"create index idx_test_demo1 on demo1 (id)",
"create index idx_test_demo2 on anything (text)", // the name of table shouldn't matter
}
return c, nil
},
expectedErrors: []string{},
},
{
name: "old + new indexes",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("demo1")
c.Indexes = []string{
"CREATE INDEX `_wsmn24bux7wo113_created_idx` ON `demo1` (`created`)",
"create index idx_test_demo1 on anything (id)",
}
return c, nil
},
expectedErrors: []string{},
},
{
name: "index for missing field",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("demo1")
c.Indexes = []string{
"create index idx_test_demo1 on anything (missing)", // still valid because it is checked on db persist
}
return c, nil
},
expectedErrors: []string{},
},
{
name: "auth collection with missing required unique indexes",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.Indexes = []string{}
return c, nil
},
expectedErrors: []string{"indexes", "passwordAuth"},
},
{
name: "auth collection with non-unique required indexes",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.Indexes = []string{
"create index test_idx1 on new_auth (tokenKey)",
"create index test_idx2 on new_auth (email)",
}
return c, nil
},
expectedErrors: []string{"indexes", "passwordAuth"},
},
{
name: "auth collection with unique required indexes",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.Indexes = []string{
"create unique index test_idx1 on new_auth (tokenKey)",
"create unique index test_idx2 on new_auth (email)",
}
return c, nil
},
expectedErrors: []string{},
},
{
name: "removing index on system field",
collection: func(app core.App) (*core.Collection, error) {
demo2, err := app.FindCollectionByNameOrId("demo2")
if err != nil {
return nil, err
}
// mark the title field as system
demo2.Fields.GetByName("title").SetSystem(true)
if err = app.Save(demo2); err != nil {
return nil, err
}
// refresh
demo2, err = app.FindCollectionByNameOrId("demo2")
if err != nil {
return nil, err
}
demo2.RemoveIndex("idx_unique_demo2_title")
return demo2, nil
},
expectedErrors: []string{"indexes"},
},
{
name: "changing partial constraint of existing index on system field",
collection: func(app core.App) (*core.Collection, error) {
demo2, err := app.FindCollectionByNameOrId("demo2")
if err != nil {
return nil, err
}
// mark the title field as system
demo2.Fields.GetByName("title").SetSystem(true)
if err = app.Save(demo2); err != nil {
return nil, err
}
// refresh
demo2, err = app.FindCollectionByNameOrId("demo2")
if err != nil {
return nil, err
}
// replace the index with a partial one
demo2.RemoveIndex("idx_unique_demo2_title")
demo2.AddIndex("idx_new_demo2_title", true, "title", "1 = 1")
return demo2, nil
},
expectedErrors: []string{},
},
{
name: "changing column sort and collate of existing index on system field",
collection: func(app core.App) (*core.Collection, error) {
demo2, err := app.FindCollectionByNameOrId("demo2")
if err != nil {
return nil, err
}
// mark the title field as system
demo2.Fields.GetByName("title").SetSystem(true)
if err = app.Save(demo2); err != nil {
return nil, err
}
// refresh
demo2, err = app.FindCollectionByNameOrId("demo2")
if err != nil {
return nil, err
}
// replace the index with a new one for the same column but with collate and sort
demo2.RemoveIndex("idx_unique_demo2_title")
demo2.AddIndex("idx_new_demo2_title", true, "title COLLATE test ASC", "")
return demo2, nil
},
expectedErrors: []string{},
},
{
name: "adding new column to index on system field",
collection: func(app core.App) (*core.Collection, error) {
demo2, err := app.FindCollectionByNameOrId("demo2")
if err != nil {
return nil, err
}
// mark the title field as system
demo2.Fields.GetByName("title").SetSystem(true)
if err = app.Save(demo2); err != nil {
return nil, err
}
// refresh
demo2, err = app.FindCollectionByNameOrId("demo2")
if err != nil {
return nil, err
}
// replace the index with a non-unique one
demo2.RemoveIndex("idx_unique_demo2_title")
demo2.AddIndex("idx_new_title", false, "title, id", "")
return demo2, nil
},
expectedErrors: []string{"indexes"},
},
{
name: "changing index type on system field",
collection: func(app core.App) (*core.Collection, error) {
demo2, err := app.FindCollectionByNameOrId("demo2")
if err != nil {
return nil, err
}
// mark the title field as system
demo2.Fields.GetByName("title").SetSystem(true)
if err = app.Save(demo2); err != nil {
return nil, err
}
// refresh
demo2, err = app.FindCollectionByNameOrId("demo2")
if err != nil {
return nil, err
}
// replace the index with a non-unique one (partial constraints are ignored)
demo2.RemoveIndex("idx_unique_demo2_title")
demo2.AddIndex("idx_new_title", false, "title", "1=1")
return demo2, nil
},
expectedErrors: []string{"indexes"},
},
{
name: "changing index on non-system field",
collection: func(app core.App) (*core.Collection, error) {
demo2, err := app.FindCollectionByNameOrId("demo2")
if err != nil {
return nil, err
}
// replace the index with a partial one
demo2.RemoveIndex("idx_demo2_active")
demo2.AddIndex("idx_demo2_active", true, "active", "1 = 1")
return demo2, nil
},
expectedErrors: []string{},
},
// fields list checks
{
name: "empty fields",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("new_auth")
c.Fields = nil // the minimum fields should auto added
return c, nil
},
expectedErrors: []string{"fields"},
},
{
name: "no id primay key field",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("new_auth")
c.Fields = core.NewFieldsList(
&core.TextField{Name: "id"},
)
return c, nil
},
expectedErrors: []string{"fields"},
},
{
name: "with id primay key field",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("new_auth")
c.Fields = core.NewFieldsList(
&core.TextField{Name: "id", PrimaryKey: true, Required: true, Pattern: `\w+`},
)
return c, nil
},
expectedErrors: []string{},
},
{
name: "duplicated field names",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("new_auth")
c.Fields = core.NewFieldsList(
&core.TextField{Name: "id", PrimaryKey: true, Required: true, Pattern: `\w+`},
&core.TextField{Id: "f1", Name: "Test"}, // case-insensitive
&core.BoolField{Id: "f2", Name: "test"},
)
return c, nil
},
expectedErrors: []string{"fields"},
},
{
name: "changing field type",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("demo1")
f := c.Fields.GetByName("text")
c.Fields.Add(&core.BoolField{Id: f.GetId(), Name: f.GetName()})
return c, nil
},
expectedErrors: []string{"fields"},
},
{
name: "renaming system field",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId(core.CollectionNameAuthOrigins)
f := c.Fields.GetByName("fingerprint")
f.SetName("fingerprint_new")
return c, nil
},
expectedErrors: []string{"fields"},
},
{
name: "deleting system field",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId(core.CollectionNameAuthOrigins)
c.Fields.RemoveByName("fingerprint")
return c, nil
},
expectedErrors: []string{"fields"},
},
{
name: "invalid field setting",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("test_new")
c.Fields.Add(&core.TextField{Name: "f1", Min: -10})
return c, nil
},
expectedErrors: []string{"fields"},
},
{
name: "valid field setting",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("test_new")
c.Fields.Add(&core.TextField{Name: "f1", Min: 10})
return c, nil
},
expectedErrors: []string{},
},
{
name: "fields view changes should be ignored",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("view1")
c.Fields = nil
return c, nil
},
expectedErrors: []string{},
},
{
name: "with reserved auth only field name (passwordConfirm)",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.Fields.Add(
&core.TextField{Name: "passwordConfirm"},
)
return c, nil
},
expectedErrors: []string{"fields"},
},
{
name: "with reserved auth only field name (oldPassword)",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.Fields.Add(
&core.TextField{Name: "oldPassword"},
)
return c, nil
},
expectedErrors: []string{"fields"},
},
{
name: "with invalid password auth field options (1)",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.Fields.Add(
&core.TextField{Name: "password", System: true, Hidden: true}, // should be PasswordField
)
return c, nil
},
expectedErrors: []string{"fields"},
},
{
name: "with valid password auth field options (2)",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.Fields.Add(
&core.PasswordField{Name: "password", System: true, Hidden: true},
)
return c, nil
},
expectedErrors: []string{},
},
{
name: "with invalid tokenKey auth field options (1)",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.Fields.Add(
&core.TextField{Name: "tokenKey", System: true}, // should be also hidden
)
return c, nil
},
expectedErrors: []string{"fields"},
},
{
name: "with valid tokenKey auth field options (2)",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.Fields.Add(
&core.TextField{Name: "tokenKey", System: true, Hidden: true},
)
return c, nil
},
expectedErrors: []string{},
},
{
name: "with invalid email auth field options (1)",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.Fields.Add(
&core.TextField{Name: "email", System: true}, // should be EmailField
)
return c, nil
},
expectedErrors: []string{"fields"},
},
{
name: "with valid email auth field options (2)",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.Fields.Add(
&core.EmailField{Name: "email", System: true},
)
return c, nil
},
expectedErrors: []string{},
},
{
name: "with invalid verified auth field options (1)",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.Fields.Add(
&core.TextField{Name: "verified", System: true}, // should be BoolField
)
return c, nil
},
expectedErrors: []string{"fields"},
},
{
name: "with valid verified auth field options (2)",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.Fields.Add(
&core.BoolField{Name: "verified", System: true},
)
return c, nil
},
expectedErrors: []string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, err := s.collection(app)
if err != nil {
t.Fatalf("Failed to retrieve test collection: %v", err)
}
result := app.Validate(collection)
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/syscall.go | core/syscall.go | //go:build !(js && wasm)
package core
import "syscall"
// execve invokes the execve(2) system call.
func execve(argv0 string, argv []string, envv []string) error {
return syscall.Exec(argv0, argv, envv)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_url.go | core/field_url.go | package core
import (
"context"
"net/url"
"slices"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/spf13/cast"
)
func init() {
Fields[FieldTypeURL] = func() Field {
return &URLField{}
}
}
const FieldTypeURL = "url"
var _ Field = (*URLField)(nil)
// URLField defines "url" type field for storing a single URL string value.
//
// The respective zero record field value is empty string.
type URLField struct {
// Name (required) is the unique name of the field.
Name string `form:"name" json:"name"`
// Id is the unique stable field identifier.
//
// It is automatically generated from the name when adding to a collection FieldsList.
Id string `form:"id" json:"id"`
// System prevents the renaming and removal of the field.
System bool `form:"system" json:"system"`
// Hidden hides the field from the API response.
Hidden bool `form:"hidden" json:"hidden"`
// Presentable hints the Dashboard UI to use the underlying
// field record value in the relation preview label.
Presentable bool `form:"presentable" json:"presentable"`
// ---
// ExceptDomains will require the URL domain to NOT be included in the listed ones.
//
// This validator can be set only if OnlyDomains is empty.
ExceptDomains []string `form:"exceptDomains" json:"exceptDomains"`
// OnlyDomains will require the URL domain to be included in the listed ones.
//
// This validator can be set only if ExceptDomains is empty.
OnlyDomains []string `form:"onlyDomains" json:"onlyDomains"`
// Required will require the field value to be non-empty URL string.
Required bool `form:"required" json:"required"`
}
// Type implements [Field.Type] interface method.
func (f *URLField) Type() string {
return FieldTypeURL
}
// GetId implements [Field.GetId] interface method.
func (f *URLField) GetId() string {
return f.Id
}
// SetId implements [Field.SetId] interface method.
func (f *URLField) SetId(id string) {
f.Id = id
}
// GetName implements [Field.GetName] interface method.
func (f *URLField) GetName() string {
return f.Name
}
// SetName implements [Field.SetName] interface method.
func (f *URLField) SetName(name string) {
f.Name = name
}
// GetSystem implements [Field.GetSystem] interface method.
func (f *URLField) GetSystem() bool {
return f.System
}
// SetSystem implements [Field.SetSystem] interface method.
func (f *URLField) SetSystem(system bool) {
f.System = system
}
// GetHidden implements [Field.GetHidden] interface method.
func (f *URLField) GetHidden() bool {
return f.Hidden
}
// SetHidden implements [Field.SetHidden] interface method.
func (f *URLField) SetHidden(hidden bool) {
f.Hidden = hidden
}
// ColumnType implements [Field.ColumnType] interface method.
func (f *URLField) ColumnType(app App) string {
return "TEXT DEFAULT '' NOT NULL"
}
// PrepareValue implements [Field.PrepareValue] interface method.
func (f *URLField) PrepareValue(record *Record, raw any) (any, error) {
return cast.ToString(raw), nil
}
// ValidateValue implements [Field.ValidateValue] interface method.
func (f *URLField) ValidateValue(ctx context.Context, app App, record *Record) error {
val, ok := record.GetRaw(f.Name).(string)
if !ok {
return validators.ErrUnsupportedValueType
}
if f.Required {
if err := validation.Required.Validate(val); err != nil {
return err
}
}
if val == "" {
return nil // nothing to check
}
if is.URL.Validate(val) != nil {
return validation.NewError("validation_invalid_url", "Must be a valid url")
}
// extract host/domain
u, _ := url.Parse(val)
// only domains check
if len(f.OnlyDomains) > 0 && !slices.Contains(f.OnlyDomains, u.Host) {
return validation.NewError("validation_url_domain_not_allowed", "Url domain is not allowed")
}
// except domains check
if len(f.ExceptDomains) > 0 && slices.Contains(f.ExceptDomains, u.Host) {
return validation.NewError("validation_url_domain_not_allowed", "Url domain is not allowed")
}
return nil
}
// ValidateSettings implements [Field.ValidateSettings] interface method.
func (f *URLField) ValidateSettings(ctx context.Context, app App, collection *Collection) error {
return validation.ValidateStruct(f,
validation.Field(&f.Id, validation.By(DefaultFieldIdValidationRule)),
validation.Field(&f.Name, validation.By(DefaultFieldNameValidationRule)),
validation.Field(
&f.ExceptDomains,
validation.When(len(f.OnlyDomains) > 0, validation.Empty).Else(validation.Each(is.Domain)),
),
validation.Field(
&f.OnlyDomains,
validation.When(len(f.ExceptDomains) > 0, validation.Empty).Else(validation.Each(is.Domain)),
),
)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/collection_validate.go | core/collection_validate.go | package core
import (
"context"
"fmt"
"regexp"
"strconv"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tools/dbutils"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/search"
"github.com/pocketbase/pocketbase/tools/types"
)
var collectionNameRegex = regexp.MustCompile(`^\w+$`)
func onCollectionValidate(e *CollectionEvent) error {
var original *Collection
if !e.Collection.IsNew() {
original = &Collection{}
if err := e.App.ModelQuery(original).Model(e.Collection.LastSavedPK(), original); err != nil {
return fmt.Errorf("failed to fetch old collection state: %w", err)
}
}
validator := newCollectionValidator(
e.Context,
e.App,
e.Collection,
original,
)
if err := validator.run(); err != nil {
return err
}
return e.Next()
}
func newCollectionValidator(ctx context.Context, app App, new, original *Collection) *collectionValidator {
validator := &collectionValidator{
ctx: ctx,
app: app,
new: new,
original: original,
}
// load old/original collection
if validator.original == nil {
validator.original = NewCollection(validator.new.Type, "")
}
return validator
}
type collectionValidator struct {
original *Collection
new *Collection
app App
ctx context.Context
}
type optionsValidator interface {
validate(cv *collectionValidator) error
}
func (validator *collectionValidator) run() error {
if validator.original.IsNew() {
validator.new.updateGeneratedIdIfExists(validator.app)
}
// generate fields from the query (overwriting any explicit user defined fields)
if validator.new.IsView() {
validator.new.Fields, _ = validator.app.CreateViewFields(validator.new.ViewQuery)
}
// validate base fields
baseErr := validation.ValidateStruct(validator.new,
validation.Field(
&validator.new.Id,
validation.Required,
validation.When(
validator.original.IsNew(),
validation.Length(1, 100),
validation.Match(DefaultIdRegex),
validation.By(validators.UniqueId(validator.app.ConcurrentDB(), validator.new.TableName())),
).Else(
validation.By(validators.Equal(validator.original.Id)),
),
),
validation.Field(
&validator.new.System,
validation.By(validator.ensureNoSystemFlagChange),
),
validation.Field(
&validator.new.Type,
validation.Required,
validation.In(
CollectionTypeBase,
CollectionTypeAuth,
CollectionTypeView,
),
validation.By(validator.ensureNoTypeChange),
),
validation.Field(
&validator.new.Name,
validation.Required,
validation.Length(1, 255),
validation.By(checkForVia),
validation.Match(collectionNameRegex),
validation.By(validator.ensureNoSystemNameChange),
validation.By(validator.checkUniqueName),
),
validation.Field(
&validator.new.Fields,
validation.By(validator.checkFieldDuplicates),
validation.By(validator.checkMinFields),
validation.When(
!validator.new.IsView(),
validation.By(validator.ensureNoSystemFieldsChange),
validation.By(validator.ensureNoFieldsTypeChange),
),
validation.When(validator.new.IsAuth(), validation.By(validator.checkReservedAuthKeys)),
validation.By(validator.checkFieldValidators),
),
validation.Field(
&validator.new.ListRule,
validation.By(validator.checkRule),
validation.By(validator.ensureNoSystemRuleChange(validator.original.ListRule)),
),
validation.Field(
&validator.new.ViewRule,
validation.By(validator.checkRule),
validation.By(validator.ensureNoSystemRuleChange(validator.original.ViewRule)),
),
validation.Field(
&validator.new.CreateRule,
validation.When(validator.new.IsView(), validation.Nil),
validation.By(validator.checkRule),
validation.By(validator.ensureNoSystemRuleChange(validator.original.CreateRule)),
),
validation.Field(
&validator.new.UpdateRule,
validation.When(validator.new.IsView(), validation.Nil),
validation.By(validator.checkRule),
validation.By(validator.ensureNoSystemRuleChange(validator.original.UpdateRule)),
),
validation.Field(
&validator.new.DeleteRule,
validation.When(validator.new.IsView(), validation.Nil),
validation.By(validator.checkRule),
validation.By(validator.ensureNoSystemRuleChange(validator.original.DeleteRule)),
),
validation.Field(&validator.new.Indexes, validation.By(validator.checkIndexes)),
)
optionsErr := validator.validateOptions()
return validators.JoinValidationErrors(baseErr, optionsErr)
}
func (validator *collectionValidator) checkUniqueName(value any) error {
v, _ := value.(string)
// ensure unique collection name
if !validator.app.IsCollectionNameUnique(v, validator.original.Id) {
return validation.NewError("validation_collection_name_exists", "Collection name must be unique (case insensitive).")
}
// ensure that the collection name doesn't collide with the id of any collection
dummyCollection := &Collection{}
if validator.app.ModelQuery(dummyCollection).Model(v, dummyCollection) == nil {
return validation.NewError("validation_collection_name_id_duplicate", "The name must not match an existing collection id.")
}
// ensure that there is no existing internal table with the provided name
if validator.original.Name != v && // has changed
validator.app.IsCollectionNameUnique(v) && // is not a collection (in case it was presaved)
validator.app.HasTable(v) {
return validation.NewError("validation_collection_name_invalid", "The name shouldn't match with an existing internal table.")
}
return nil
}
func (validator *collectionValidator) ensureNoSystemNameChange(value any) error {
v, _ := value.(string)
if !validator.original.IsNew() && validator.original.System && v != validator.original.Name {
return validation.NewError("validation_collection_system_name_change", "System collection name cannot be changed.")
}
return nil
}
func (validator *collectionValidator) ensureNoSystemFlagChange(value any) error {
v, _ := value.(bool)
if !validator.original.IsNew() && v != validator.original.System {
return validation.NewError("validation_collection_system_flag_change", "System collection state cannot be changed.")
}
return nil
}
func (validator *collectionValidator) ensureNoTypeChange(value any) error {
v, _ := value.(string)
if !validator.original.IsNew() && v != validator.original.Type {
return validation.NewError("validation_collection_type_change", "Collection type cannot be changed.")
}
return nil
}
func (validator *collectionValidator) ensureNoFieldsTypeChange(value any) error {
v, ok := value.(FieldsList)
if !ok {
return validators.ErrUnsupportedValueType
}
errs := validation.Errors{}
for i, field := range v {
oldField := validator.original.Fields.GetById(field.GetId())
if oldField != nil && oldField.Type() != field.Type() {
errs[strconv.Itoa(i)] = validation.NewError(
"validation_field_type_change",
"Field type cannot be changed.",
)
}
}
if len(errs) > 0 {
return errs
}
return nil
}
func (validator *collectionValidator) checkFieldDuplicates(value any) error {
fields, ok := value.(FieldsList)
if !ok {
return validators.ErrUnsupportedValueType
}
totalFields := len(fields)
ids := make([]string, 0, totalFields)
names := make([]string, 0, totalFields)
for i, field := range fields {
if list.ExistInSlice(field.GetId(), ids) {
return validation.Errors{
strconv.Itoa(i): validation.Errors{
"id": validation.NewError(
"validation_duplicated_field_id",
fmt.Sprintf("Duplicated or invalid field id %q", field.GetId()),
),
},
}
}
// field names are used as db columns and should be case insensitive
nameLower := strings.ToLower(field.GetName())
if list.ExistInSlice(nameLower, names) {
return validation.Errors{
strconv.Itoa(i): validation.Errors{
"name": validation.NewError(
"validation_duplicated_field_name",
"Duplicated or invalid field name {{.fieldName}}",
).SetParams(map[string]any{
"fieldName": field.GetName(),
}),
},
}
}
ids = append(ids, field.GetId())
names = append(names, nameLower)
}
return nil
}
func (validator *collectionValidator) checkFieldValidators(value any) error {
fields, ok := value.(FieldsList)
if !ok {
return validators.ErrUnsupportedValueType
}
errs := validation.Errors{}
for i, field := range fields {
if err := field.ValidateSettings(validator.ctx, validator.app, validator.new); err != nil {
errs[strconv.Itoa(i)] = err
}
}
if len(errs) > 0 {
return errs
}
return nil
}
func (cv *collectionValidator) checkViewQuery(value any) error {
v, _ := value.(string)
if v == "" {
return nil // nothing to check
}
if _, err := cv.app.CreateViewFields(v); err != nil {
return validation.NewError(
"validation_invalid_view_query",
fmt.Sprintf("Invalid query - %s", err.Error()),
)
}
return nil
}
var reservedAuthKeys = []string{"passwordConfirm", "oldPassword"}
func (cv *collectionValidator) checkReservedAuthKeys(value any) error {
fields, ok := value.(FieldsList)
if !ok {
return validators.ErrUnsupportedValueType
}
if !cv.new.IsAuth() {
return nil // not an auth collection
}
errs := validation.Errors{}
for i, field := range fields {
if list.ExistInSlice(field.GetName(), reservedAuthKeys) {
errs[strconv.Itoa(i)] = validation.Errors{
"name": validation.NewError(
"validation_reserved_field_name",
"The field name is reserved and cannot be used.",
),
}
}
}
if len(errs) > 0 {
return errs
}
return nil
}
func (cv *collectionValidator) checkMinFields(value any) error {
fields, ok := value.(FieldsList)
if !ok {
return validators.ErrUnsupportedValueType
}
if len(fields) == 0 {
return validation.ErrRequired
}
// all collections must have an "id" PK field
idField, _ := fields.GetByName(FieldNameId).(*TextField)
if idField == nil || !idField.PrimaryKey {
return validation.NewError("validation_missing_primary_key", `Missing or invalid "id" PK field.`)
}
switch cv.new.Type {
case CollectionTypeAuth:
passwordField, _ := fields.GetByName(FieldNamePassword).(*PasswordField)
if passwordField == nil {
return validation.NewError("validation_missing_password_field", `System "password" field is required.`)
}
if !passwordField.Hidden || !passwordField.System {
return validation.Errors{FieldNamePassword: ErrMustBeSystemAndHidden}
}
tokenKeyField, _ := fields.GetByName(FieldNameTokenKey).(*TextField)
if tokenKeyField == nil {
return validation.NewError("validation_missing_tokenKey_field", `System "tokenKey" field is required.`)
}
if !tokenKeyField.Hidden || !tokenKeyField.System {
return validation.Errors{FieldNameTokenKey: ErrMustBeSystemAndHidden}
}
emailField, _ := fields.GetByName(FieldNameEmail).(*EmailField)
if emailField == nil {
return validation.NewError("validation_missing_email_field", `System "email" field is required.`)
}
if !emailField.System {
return validation.Errors{FieldNameEmail: ErrMustBeSystem}
}
emailVisibilityField, _ := fields.GetByName(FieldNameEmailVisibility).(*BoolField)
if emailVisibilityField == nil {
return validation.NewError("validation_missing_emailVisibility_field", `System "emailVisibility" field is required.`)
}
if !emailVisibilityField.System {
return validation.Errors{FieldNameEmailVisibility: ErrMustBeSystem}
}
verifiedField, _ := fields.GetByName(FieldNameVerified).(*BoolField)
if verifiedField == nil {
return validation.NewError("validation_missing_verified_field", `System "verified" field is required.`)
}
if !verifiedField.System {
return validation.Errors{FieldNameVerified: ErrMustBeSystem}
}
return nil
}
return nil
}
func (validator *collectionValidator) ensureNoSystemFieldsChange(value any) error {
fields, ok := value.(FieldsList)
if !ok {
return validators.ErrUnsupportedValueType
}
if validator.original.IsNew() {
return nil // not an update
}
for _, oldField := range validator.original.Fields {
if !oldField.GetSystem() {
continue
}
newField := fields.GetById(oldField.GetId())
if newField == nil || oldField.GetName() != newField.GetName() {
return validation.NewError("validation_system_field_change", "System fields cannot be deleted or renamed.")
}
}
return nil
}
func (cv *collectionValidator) checkFieldsForUniqueIndex(value any) error {
names, ok := value.([]string)
if !ok {
return validators.ErrUnsupportedValueType
}
if len(names) == 0 {
return nil // nothing to check
}
for _, name := range names {
field := cv.new.Fields.GetByName(name)
if field == nil {
return validation.NewError("validation_missing_field", "Invalid or missing field {{.fieldName}}").
SetParams(map[string]any{"fieldName": name})
}
if _, ok := dbutils.FindSingleColumnUniqueIndex(cv.new.Indexes, name); !ok {
return validation.NewError("validation_missing_unique_constraint", "The field {{.fieldName}} doesn't have a UNIQUE constraint.").
SetParams(map[string]any{"fieldName": name})
}
}
return nil
}
// note: value could be either *string or string
func (validator *collectionValidator) checkRule(value any) error {
var vStr string
v, ok := value.(*string)
if ok {
if v != nil {
vStr = *v
}
} else {
vStr, ok = value.(string)
}
if !ok {
return validators.ErrUnsupportedValueType
}
if vStr == "" {
return nil // nothing to check
}
r := NewRecordFieldResolver(validator.app, validator.new, &RequestInfo{}, true)
_, err := search.FilterData(vStr).BuildExpr(r)
if err != nil {
return validation.NewError("validation_invalid_rule", "Invalid rule. Raw error: "+err.Error())
}
return nil
}
func (validator *collectionValidator) ensureNoSystemRuleChange(oldRule *string) validation.RuleFunc {
return func(value any) error {
if validator.original.IsNew() || !validator.original.System {
return nil // not an update of a system collection
}
rule, ok := value.(*string)
if !ok {
return validators.ErrUnsupportedValueType
}
if (rule == nil && oldRule == nil) ||
(rule != nil && oldRule != nil && *rule == *oldRule) {
return nil
}
return validation.NewError("validation_collection_system_rule_change", "System collection API rule cannot be changed.")
}
}
func (cv *collectionValidator) checkIndexes(value any) error {
indexes, _ := value.(types.JSONArray[string])
if cv.new.IsView() && len(indexes) > 0 {
return validation.NewError(
"validation_indexes_not_supported",
"View collections don't support indexes.",
)
}
duplicatedNames := make(map[string]struct{}, len(indexes))
duplicatedDefinitions := make(map[string]struct{}, len(indexes))
for i, rawIndex := range indexes {
parsed := dbutils.ParseIndex(rawIndex)
// always set a table name because it is ignored anyway in order to keep it in sync with the collection name
parsed.TableName = "validator"
if !parsed.IsValid() {
return validation.Errors{
strconv.Itoa(i): validation.NewError(
"validation_invalid_index_expression",
"Invalid CREATE INDEX expression.",
),
}
}
if _, isDuplicated := duplicatedNames[strings.ToLower(parsed.IndexName)]; isDuplicated {
return validation.Errors{
strconv.Itoa(i): validation.NewError(
"validation_duplicated_index_name",
"The index name already exists.",
),
}
}
duplicatedNames[strings.ToLower(parsed.IndexName)] = struct{}{}
// ensure that the index name is not used in another collection
var usedTblName string
_ = cv.app.ConcurrentDB().Select("tbl_name").
From("sqlite_master").
AndWhere(dbx.HashExp{"type": "index"}).
AndWhere(dbx.NewExp("LOWER([[tbl_name]])!=LOWER({:oldName})", dbx.Params{"oldName": cv.original.Name})).
AndWhere(dbx.NewExp("LOWER([[tbl_name]])!=LOWER({:newName})", dbx.Params{"newName": cv.new.Name})).
AndWhere(dbx.NewExp("LOWER([[name]])=LOWER({:indexName})", dbx.Params{"indexName": parsed.IndexName})).
Limit(1).
Row(&usedTblName)
if usedTblName != "" {
return validation.Errors{
strconv.Itoa(i): validation.NewError(
"validation_existing_index_name",
"The index name is already used in {{.usedTableName}} collection.",
).SetParams(map[string]any{"usedTableName": usedTblName}),
}
}
// reset non-important identifiers
parsed.SchemaName = "validator"
parsed.IndexName = "validator"
parsedDef := parsed.Build()
if _, isDuplicated := duplicatedDefinitions[parsedDef]; isDuplicated {
return validation.Errors{
strconv.Itoa(i): validation.NewError(
"validation_duplicated_index_definition",
"The index definition already exists.",
),
}
}
duplicatedDefinitions[parsedDef] = struct{}{}
// note: we don't check the index table name because it is always
// overwritten by the SyncRecordTableSchema to allow
// easier partial modifications (eg. changing only the collection name).
// if !strings.EqualFold(parsed.TableName, form.Name) {
// return validation.Errors{
// strconv.Itoa(i): validation.NewError(
// "validation_invalid_index_table",
// fmt.Sprintf("The index table must be the same as the collection name."),
// ),
// }
// }
}
// ensure that unique indexes on system fields are not changed or removed
if !cv.original.IsNew() {
OLD_INDEXES_LOOP:
for _, oldIndex := range cv.original.Indexes {
oldParsed := dbutils.ParseIndex(oldIndex)
if !oldParsed.Unique {
continue
}
// reset collate and sort since they are not important for the unique constraint
for i := range oldParsed.Columns {
oldParsed.Columns[i].Collate = ""
oldParsed.Columns[i].Sort = ""
}
oldParsedStr := oldParsed.Build()
for _, column := range oldParsed.Columns {
for _, f := range cv.original.Fields {
if !f.GetSystem() || !strings.EqualFold(column.Name, f.GetName()) {
continue
}
var hasMatch bool
for _, newIndex := range cv.new.Indexes {
newParsed := dbutils.ParseIndex(newIndex)
// exclude the non-important identifiers from the check
newParsed.SchemaName = oldParsed.SchemaName
newParsed.IndexName = oldParsed.IndexName
newParsed.TableName = oldParsed.TableName
// exclude partial constraints
newParsed.Where = oldParsed.Where
// reset collate and sort
for i := range newParsed.Columns {
newParsed.Columns[i].Collate = ""
newParsed.Columns[i].Sort = ""
}
if oldParsedStr == newParsed.Build() {
hasMatch = true
break
}
}
if !hasMatch {
return validation.NewError(
"validation_invalid_unique_system_field_index",
"Unique index definition on system fields ({{.fieldName}}) is invalid or missing.",
).SetParams(map[string]any{"fieldName": f.GetName()})
}
continue OLD_INDEXES_LOOP
}
}
}
}
// check for required indexes
//
// note: this is in case the indexes were removed manually when creating/importing new auth collections
// and technically it is not necessary because on app.Save() the missing indexes will be reinserted by the system collection hook
if cv.new.IsAuth() {
requiredNames := []string{FieldNameTokenKey, FieldNameEmail}
for _, name := range requiredNames {
if _, ok := dbutils.FindSingleColumnUniqueIndex(indexes, name); !ok {
return validation.NewError(
"validation_missing_required_unique_index",
`Missing required unique index for field "{{.fieldName}}".`,
).SetParams(map[string]any{"fieldName": name})
}
}
}
return nil
}
func (validator *collectionValidator) validateOptions() error {
switch validator.new.Type {
case CollectionTypeAuth:
return validator.new.collectionAuthOptions.validate(validator)
case CollectionTypeView:
return validator.new.collectionViewOptions.validate(validator)
}
return nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_relation_test.go | core/field_relation_test.go | package core_test
import (
"context"
"encoding/json"
"fmt"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestRelationFieldBaseMethods(t *testing.T) {
testFieldBaseMethods(t, core.FieldTypeRelation)
}
func TestRelationFieldColumnType(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
name string
field *core.RelationField
expected string
}{
{
"single (zero)",
&core.RelationField{},
"TEXT DEFAULT '' NOT NULL",
},
{
"single",
&core.RelationField{MaxSelect: 1},
"TEXT DEFAULT '' NOT NULL",
},
{
"multiple",
&core.RelationField{MaxSelect: 2},
"JSON DEFAULT '[]' NOT NULL",
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
if v := s.field.ColumnType(app); v != s.expected {
t.Fatalf("Expected\n%q\ngot\n%q", s.expected, v)
}
})
}
}
func TestRelationFieldIsMultiple(t *testing.T) {
scenarios := []struct {
name string
field *core.RelationField
expected bool
}{
{
"zero",
&core.RelationField{},
false,
},
{
"single",
&core.RelationField{MaxSelect: 1},
false,
},
{
"multiple",
&core.RelationField{MaxSelect: 2},
true,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
if v := s.field.IsMultiple(); v != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, v)
}
})
}
}
func TestRelationFieldPrepareValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
record := core.NewRecord(core.NewBaseCollection("test"))
scenarios := []struct {
raw any
field *core.RelationField
expected string
}{
// single
{nil, &core.RelationField{MaxSelect: 1}, `""`},
{"", &core.RelationField{MaxSelect: 1}, `""`},
{123, &core.RelationField{MaxSelect: 1}, `"123"`},
{"a", &core.RelationField{MaxSelect: 1}, `"a"`},
{`["a"]`, &core.RelationField{MaxSelect: 1}, `"a"`},
{[]string{}, &core.RelationField{MaxSelect: 1}, `""`},
{[]string{"a", "b"}, &core.RelationField{MaxSelect: 1}, `"b"`},
// multiple
{nil, &core.RelationField{MaxSelect: 2}, `[]`},
{"", &core.RelationField{MaxSelect: 2}, `[]`},
{123, &core.RelationField{MaxSelect: 2}, `["123"]`},
{"a", &core.RelationField{MaxSelect: 2}, `["a"]`},
{`["a"]`, &core.RelationField{MaxSelect: 2}, `["a"]`},
{[]string{}, &core.RelationField{MaxSelect: 2}, `[]`},
{[]string{"a", "b", "c"}, &core.RelationField{MaxSelect: 2}, `["a","b","c"]`},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v_%v", i, s.raw, s.field.IsMultiple()), func(t *testing.T) {
v, err := s.field.PrepareValue(record, s.raw)
if err != nil {
t.Fatal(err)
}
vRaw, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
if string(vRaw) != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, vRaw)
}
})
}
}
func TestRelationFieldDriverValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
raw any
field *core.RelationField
expected string
}{
// single
{nil, &core.RelationField{MaxSelect: 1}, `""`},
{"", &core.RelationField{MaxSelect: 1}, `""`},
{123, &core.RelationField{MaxSelect: 1}, `"123"`},
{"a", &core.RelationField{MaxSelect: 1}, `"a"`},
{`["a"]`, &core.RelationField{MaxSelect: 1}, `"a"`},
{[]string{}, &core.RelationField{MaxSelect: 1}, `""`},
{[]string{"a", "b"}, &core.RelationField{MaxSelect: 1}, `"b"`},
// multiple
{nil, &core.RelationField{MaxSelect: 2}, `[]`},
{"", &core.RelationField{MaxSelect: 2}, `[]`},
{123, &core.RelationField{MaxSelect: 2}, `["123"]`},
{"a", &core.RelationField{MaxSelect: 2}, `["a"]`},
{`["a"]`, &core.RelationField{MaxSelect: 2}, `["a"]`},
{[]string{}, &core.RelationField{MaxSelect: 2}, `[]`},
{[]string{"a", "b", "c"}, &core.RelationField{MaxSelect: 2}, `["a","b","c"]`},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v_%v", i, s.raw, s.field.IsMultiple()), func(t *testing.T) {
record := core.NewRecord(core.NewBaseCollection("test"))
record.SetRaw(s.field.GetName(), s.raw)
v, err := s.field.DriverValue(record)
if err != nil {
t.Fatal(err)
}
if s.field.IsMultiple() {
_, ok := v.(types.JSONArray[string])
if !ok {
t.Fatalf("Expected types.JSONArray value, got %T", v)
}
} else {
_, ok := v.(string)
if !ok {
t.Fatalf("Expected string value, got %T", v)
}
}
vRaw, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
if string(vRaw) != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, vRaw)
}
})
}
}
func TestRelationFieldValidateValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
demo1, err := app.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
field *core.RelationField
record func() *core.Record
expectError bool
}{
// single
{
"[single] zero field value (not required)",
&core.RelationField{Name: "test", MaxSelect: 1, CollectionId: demo1.Id},
func() *core.Record {
record := core.NewRecord(core.NewBaseCollection("test_collection"))
record.SetRaw("test", "")
return record
},
false,
},
{
"[single] zero field value (required)",
&core.RelationField{Name: "test", MaxSelect: 1, CollectionId: demo1.Id, Required: true},
func() *core.Record {
record := core.NewRecord(core.NewBaseCollection("test_collection"))
record.SetRaw("test", "")
return record
},
true,
},
{
"[single] id from other collection",
&core.RelationField{Name: "test", MaxSelect: 1, CollectionId: demo1.Id},
func() *core.Record {
record := core.NewRecord(core.NewBaseCollection("test_collection"))
record.SetRaw("test", "achvryl401bhse3")
return record
},
true,
},
{
"[single] valid id",
&core.RelationField{Name: "test", MaxSelect: 1, CollectionId: demo1.Id},
func() *core.Record {
record := core.NewRecord(core.NewBaseCollection("test_collection"))
record.SetRaw("test", "84nmscqy84lsi1t")
return record
},
false,
},
{
"[single] > MaxSelect",
&core.RelationField{Name: "test", MaxSelect: 1, CollectionId: demo1.Id},
func() *core.Record {
record := core.NewRecord(core.NewBaseCollection("test_collection"))
record.SetRaw("test", []string{"84nmscqy84lsi1t", "al1h9ijdeojtsjy"})
return record
},
true,
},
// multiple
{
"[multiple] zero field value (not required)",
&core.RelationField{Name: "test", MaxSelect: 2, CollectionId: demo1.Id},
func() *core.Record {
record := core.NewRecord(core.NewBaseCollection("test_collection"))
record.SetRaw("test", []string{})
return record
},
false,
},
{
"[multiple] zero field value (required)",
&core.RelationField{Name: "test", MaxSelect: 2, CollectionId: demo1.Id, Required: true},
func() *core.Record {
record := core.NewRecord(core.NewBaseCollection("test_collection"))
record.SetRaw("test", []string{})
return record
},
true,
},
{
"[multiple] id from other collection",
&core.RelationField{Name: "test", MaxSelect: 2, CollectionId: demo1.Id},
func() *core.Record {
record := core.NewRecord(core.NewBaseCollection("test_collection"))
record.SetRaw("test", []string{"84nmscqy84lsi1t", "achvryl401bhse3"})
return record
},
true,
},
{
"[multiple] valid id",
&core.RelationField{Name: "test", MaxSelect: 2, CollectionId: demo1.Id},
func() *core.Record {
record := core.NewRecord(core.NewBaseCollection("test_collection"))
record.SetRaw("test", []string{"84nmscqy84lsi1t", "al1h9ijdeojtsjy"})
return record
},
false,
},
{
"[multiple] > MaxSelect",
&core.RelationField{Name: "test", MaxSelect: 2, CollectionId: demo1.Id},
func() *core.Record {
record := core.NewRecord(core.NewBaseCollection("test_collection"))
record.SetRaw("test", []string{"84nmscqy84lsi1t", "al1h9ijdeojtsjy", "imy661ixudk5izi"})
return record
},
true,
},
{
"[multiple] < MinSelect",
&core.RelationField{Name: "test", MinSelect: 2, MaxSelect: 99, CollectionId: demo1.Id},
func() *core.Record {
record := core.NewRecord(core.NewBaseCollection("test_collection"))
record.SetRaw("test", []string{"84nmscqy84lsi1t"})
return record
},
true,
},
{
"[multiple] >= MinSelect",
&core.RelationField{Name: "test", MinSelect: 2, MaxSelect: 99, CollectionId: demo1.Id},
func() *core.Record {
record := core.NewRecord(core.NewBaseCollection("test_collection"))
record.SetRaw("test", []string{"84nmscqy84lsi1t", "al1h9ijdeojtsjy", "imy661ixudk5izi"})
return record
},
false,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
err := s.field.ValidateValue(context.Background(), app, s.record())
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
func TestRelationFieldValidateSettings(t *testing.T) {
testDefaultFieldIdValidation(t, core.FieldTypeRelation)
testDefaultFieldNameValidation(t, core.FieldTypeRelation)
app, _ := tests.NewTestApp()
defer app.Cleanup()
demo1, err := app.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
field func(col *core.Collection) *core.RelationField
expectErrors []string
}{
{
"zero minimal",
func(col *core.Collection) *core.RelationField {
return &core.RelationField{
Id: "test",
Name: "test",
}
},
[]string{"collectionId"},
},
{
"invalid collectionId",
func(col *core.Collection) *core.RelationField {
return &core.RelationField{
Id: "test",
Name: "test",
CollectionId: demo1.Name,
}
},
[]string{"collectionId"},
},
{
"valid collectionId",
func(col *core.Collection) *core.RelationField {
return &core.RelationField{
Id: "test",
Name: "test",
CollectionId: demo1.Id,
}
},
[]string{},
},
{
"base->view",
func(col *core.Collection) *core.RelationField {
return &core.RelationField{
Id: "test",
Name: "test",
CollectionId: "v9gwnfh02gjq1q0",
}
},
[]string{"collectionId"},
},
{
"view->view",
func(col *core.Collection) *core.RelationField {
col.Type = core.CollectionTypeView
return &core.RelationField{
Id: "test",
Name: "test",
CollectionId: "v9gwnfh02gjq1q0",
}
},
[]string{},
},
{
"MinSelect < 0",
func(col *core.Collection) *core.RelationField {
return &core.RelationField{
Id: "test",
Name: "test",
CollectionId: demo1.Id,
MinSelect: -1,
}
},
[]string{"minSelect"},
},
{
"MinSelect > 0",
func(col *core.Collection) *core.RelationField {
return &core.RelationField{
Id: "test",
Name: "test",
CollectionId: demo1.Id,
MinSelect: 1,
}
},
[]string{"maxSelect"},
},
{
"MaxSelect < MinSelect",
func(col *core.Collection) *core.RelationField {
return &core.RelationField{
Id: "test",
Name: "test",
CollectionId: demo1.Id,
MinSelect: 2,
MaxSelect: 1,
}
},
[]string{"maxSelect"},
},
{
"MaxSelect >= MinSelect",
func(col *core.Collection) *core.RelationField {
return &core.RelationField{
Id: "test",
Name: "test",
CollectionId: demo1.Id,
MinSelect: 2,
MaxSelect: 2,
}
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
collection := core.NewBaseCollection("test_collection")
collection.Fields.GetByName("id").SetId("test") // set a dummy known id so that it can be replaced
field := s.field(collection)
collection.Fields.Add(field)
errs := field.ValidateSettings(context.Background(), app, collection)
tests.TestValidationErrors(t, errs, s.expectErrors)
})
}
}
func TestRelationFieldFindSetter(t *testing.T) {
scenarios := []struct {
name string
key string
value any
field *core.RelationField
hasSetter bool
expected string
}{
{
"no match",
"example",
"b",
&core.RelationField{Name: "test", MaxSelect: 1},
false,
"",
},
{
"exact match (single)",
"test",
"b",
&core.RelationField{Name: "test", MaxSelect: 1},
true,
`"b"`,
},
{
"exact match (multiple)",
"test",
[]string{"a", "b"},
&core.RelationField{Name: "test", MaxSelect: 2},
true,
`["a","b"]`,
},
{
"append (single)",
"test+",
"b",
&core.RelationField{Name: "test", MaxSelect: 1},
true,
`"b"`,
},
{
"append (multiple)",
"test+",
[]string{"a"},
&core.RelationField{Name: "test", MaxSelect: 2},
true,
`["c","d","a"]`,
},
{
"prepend (single)",
"+test",
"b",
&core.RelationField{Name: "test", MaxSelect: 1},
true,
`"d"`, // the last of the existing values
},
{
"prepend (multiple)",
"+test",
[]string{"a"},
&core.RelationField{Name: "test", MaxSelect: 2},
true,
`["a","c","d"]`,
},
{
"subtract (single)",
"test-",
"d",
&core.RelationField{Name: "test", MaxSelect: 1},
true,
`"c"`,
},
{
"subtract (multiple)",
"test-",
[]string{"unknown", "c"},
&core.RelationField{Name: "test", MaxSelect: 2},
true,
`["d"]`,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
collection := core.NewBaseCollection("test_collection")
collection.Fields.Add(s.field)
setter := s.field.FindSetter(s.key)
hasSetter := setter != nil
if hasSetter != s.hasSetter {
t.Fatalf("Expected hasSetter %v, got %v", s.hasSetter, hasSetter)
}
if !hasSetter {
return
}
record := core.NewRecord(collection)
record.SetRaw(s.field.GetName(), []string{"c", "d"})
setter(record, s.value)
raw, err := json.Marshal(record.Get(s.field.GetName()))
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
if rawStr != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, rawStr)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/collection_query_test.go | core/collection_query_test.go | package core_test
import (
"context"
"database/sql"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/list"
)
func TestCollectionQuery(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
expected := "SELECT {{_collections}}.* FROM `_collections`"
sql := app.CollectionQuery().Build().SQL()
if sql != expected {
t.Errorf("Expected sql %s, got %s", expected, sql)
}
}
func TestReloadCachedCollections(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
err := app.ReloadCachedCollections()
if err != nil {
t.Fatal(err)
}
cached := app.Store().Get(core.StoreKeyCachedCollections)
cachedCollections, ok := cached.([]*core.Collection)
if !ok {
t.Fatalf("Expected []*core.Collection, got %T", cached)
}
collections, err := app.FindAllCollections()
if err != nil {
t.Fatalf("Failed to retrieve all collections: %v", err)
}
if len(cachedCollections) != len(collections) {
t.Fatalf("Expected %d collections, got %d", len(collections), len(cachedCollections))
}
for _, c := range collections {
var exists bool
for _, cc := range cachedCollections {
if cc.Id == c.Id {
exists = true
break
}
}
if !exists {
t.Fatalf("The collections cache is missing collection %q", c.Name)
}
}
}
func TestFindAllCollections(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
collectionTypes []string
expectTotal int
}{
{nil, 16},
{[]string{}, 16},
{[]string{""}, 16},
{[]string{"unknown"}, 0},
{[]string{"unknown", core.CollectionTypeAuth}, 4},
{[]string{core.CollectionTypeAuth, core.CollectionTypeView}, 7},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, strings.Join(s.collectionTypes, "_")), func(t *testing.T) {
collections, err := app.FindAllCollections(s.collectionTypes...)
if err != nil {
t.Fatal(err)
}
if len(collections) != s.expectTotal {
t.Fatalf("Expected %d collections, got %d", s.expectTotal, len(collections))
}
expectedTypes := list.NonzeroUniques(s.collectionTypes)
if len(expectedTypes) > 0 {
for _, c := range collections {
if !slices.Contains(expectedTypes, c.Type) {
t.Fatalf("Unexpected collection type %s\n%v", c.Type, c)
}
}
}
})
}
}
func TestFindCollectionByNameOrId(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
nameOrId string
expectError bool
}{
{"", true},
{"missing", true},
{"wsmn24bux7wo113", false},
{"demo1", false},
{"DEMO1", false}, // case insensitive
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.nameOrId), func(t *testing.T) {
model, err := app.FindCollectionByNameOrId(s.nameOrId)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
if model != nil && model.Id != s.nameOrId && !strings.EqualFold(model.Name, s.nameOrId) {
t.Fatalf("Expected model with identifier %s, got %v", s.nameOrId, model)
}
})
}
}
func TestFindCachedCollectionByNameOrId(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
totalQueries := 0
app.ConcurrentDB().(*dbx.DB).QueryLogFunc = func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error) {
totalQueries++
}
run := func(withCache bool) {
scenarios := []struct {
nameOrId string
expectError bool
}{
{"", true},
{"missing", true},
{"wsmn24bux7wo113", false},
{"demo1", false},
{"DEMO1", false}, // case insensitive
}
var expectedTotalQueries int
if withCache {
err := app.ReloadCachedCollections()
if err != nil {
t.Fatal(err)
}
} else {
app.Store().Reset(nil)
expectedTotalQueries = len(scenarios)
}
totalQueries = 0
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.nameOrId), func(t *testing.T) {
model, err := app.FindCachedCollectionByNameOrId(s.nameOrId)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
if model != nil && model.Id != s.nameOrId && !strings.EqualFold(model.Name, s.nameOrId) {
t.Fatalf("Expected model with identifier %s, got %v", s.nameOrId, model)
}
})
}
if totalQueries != expectedTotalQueries {
t.Fatalf("Expected %d totalQueries, got %d", expectedTotalQueries, totalQueries)
}
}
run(true)
run(false)
}
func TestFindCollectionReferences(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, err := app.FindCollectionByNameOrId("demo3")
if err != nil {
t.Fatal(err)
}
result, err := app.FindCollectionReferences(
collection,
collection.Id,
// test whether "nonempty" exclude ids condition will be skipped
"",
"",
)
if err != nil {
t.Fatal(err)
}
if len(result) != 1 {
t.Fatalf("Expected 1 collection, got %d: %v", len(result), result)
}
expectedFields := []string{
"rel_one_no_cascade",
"rel_one_no_cascade_required",
"rel_one_cascade",
"rel_one_unique",
"rel_many_no_cascade",
"rel_many_no_cascade_required",
"rel_many_cascade",
"rel_many_unique",
}
for col, fields := range result {
if col.Name != "demo4" {
t.Fatalf("Expected collection demo4, got %s", col.Name)
}
if len(fields) != len(expectedFields) {
t.Fatalf("Expected fields %v, got %v", expectedFields, fields)
}
for i, f := range fields {
if !slices.Contains(expectedFields, f.GetName()) {
t.Fatalf("[%d] Didn't expect field %v", i, f)
}
}
}
}
func TestFindCachedCollectionReferences(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, err := app.FindCollectionByNameOrId("demo3")
if err != nil {
t.Fatal(err)
}
totalQueries := 0
app.ConcurrentDB().(*dbx.DB).QueryLogFunc = func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error) {
totalQueries++
}
run := func(withCache bool) {
var expectedTotalQueries int
if withCache {
err := app.ReloadCachedCollections()
if err != nil {
t.Fatal(err)
}
} else {
app.Store().Reset(nil)
expectedTotalQueries = 1
}
totalQueries = 0
result, err := app.FindCachedCollectionReferences(
collection,
collection.Id,
// test whether "nonempty" exclude ids condition will be skipped
"",
"",
)
if err != nil {
t.Fatal(err)
}
if len(result) != 1 {
t.Fatalf("Expected 1 collection, got %d: %v", len(result), result)
}
expectedFields := []string{
"rel_one_no_cascade",
"rel_one_no_cascade_required",
"rel_one_cascade",
"rel_one_unique",
"rel_many_no_cascade",
"rel_many_no_cascade_required",
"rel_many_cascade",
"rel_many_unique",
}
for col, fields := range result {
if col.Name != "demo4" {
t.Fatalf("Expected collection demo4, got %s", col.Name)
}
if len(fields) != len(expectedFields) {
t.Fatalf("Expected fields %v, got %v", expectedFields, fields)
}
for i, f := range fields {
if !slices.Contains(expectedFields, f.GetName()) {
t.Fatalf("[%d] Didn't expect field %v", i, f)
}
}
}
if totalQueries != expectedTotalQueries {
t.Fatalf("Expected %d totalQueries, got %d", expectedTotalQueries, totalQueries)
}
}
run(true)
run(false)
}
func TestIsCollectionNameUnique(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
name string
excludeId string
expected bool
}{
{"", "", false},
{"demo1", "", false},
{"Demo1", "", false},
{"new", "", true},
{"demo1", "wsmn24bux7wo113", true},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.name), func(t *testing.T) {
result := app.IsCollectionNameUnique(s.name, s.excludeId)
if result != s.expected {
t.Errorf("Expected %v, got %v", s.expected, result)
}
})
}
}
func TestFindCollectionTruncate(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
countFiles := func(collectionId string) (int, error) {
entries, err := os.ReadDir(filepath.Join(app.DataDir(), "storage", collectionId))
return len(entries), err
}
t.Run("truncate view", func(t *testing.T) {
view2, err := app.FindCollectionByNameOrId("view2")
if err != nil {
t.Fatal(err)
}
err = app.TruncateCollection(view2)
if err == nil {
t.Fatalf("Expected truncate to fail because view collections can't be truncated")
}
})
t.Run("truncate failure", func(t *testing.T) {
demo3, err := app.FindCollectionByNameOrId("demo3")
if err != nil {
t.Fatal(err)
}
originalTotalRecords, err := app.CountRecords(demo3)
if err != nil {
t.Fatal(err)
}
originalTotalFiles, err := countFiles(demo3.Id)
if err != nil {
t.Fatal(err)
}
err = app.TruncateCollection(demo3)
if err == nil {
t.Fatalf("Expected truncate to fail due to cascade delete failed required constraint")
}
// short delay to ensure that the file delete goroutine has been executed
time.Sleep(100 * time.Millisecond)
totalRecords, err := app.CountRecords(demo3)
if err != nil {
t.Fatal(err)
}
if totalRecords != originalTotalRecords {
t.Fatalf("Expected %d records, got %d", originalTotalRecords, totalRecords)
}
totalFiles, err := countFiles(demo3.Id)
if err != nil {
t.Fatal(err)
}
if totalFiles != originalTotalFiles {
t.Fatalf("Expected %d files, got %d", originalTotalFiles, totalFiles)
}
})
t.Run("truncate success", func(t *testing.T) {
demo5, err := app.FindCollectionByNameOrId("demo5")
if err != nil {
t.Fatal(err)
}
err = app.TruncateCollection(demo5)
if err != nil {
t.Fatal(err)
}
// short delay to ensure that the file delete goroutine has been executed
time.Sleep(100 * time.Millisecond)
total, err := app.CountRecords(demo5)
if err != nil {
t.Fatal(err)
}
if total != 0 {
t.Fatalf("Expected all records to be deleted, got %v", total)
}
totalFiles, err := countFiles(demo5.Id)
if err != nil {
t.Fatal(err)
}
if totalFiles != 0 {
t.Fatalf("Expected truncated record files to be deleted, got %d", totalFiles)
}
// try to truncate again (shouldn't return an error)
err = app.TruncateCollection(demo5)
if err != nil {
t.Fatal(err)
}
})
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/db.go | core/db.go | package core
import (
"context"
"errors"
"fmt"
"hash/crc32"
"regexp"
"slices"
"strconv"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/spf13/cast"
)
const (
idColumn string = "id"
// DefaultIdLength is the default length of the generated model id.
DefaultIdLength int = 15
// DefaultIdAlphabet is the default characters set used for generating the model id.
DefaultIdAlphabet string = "abcdefghijklmnopqrstuvwxyz0123456789"
)
// DefaultIdRegex specifies the default regex pattern for an id value.
var DefaultIdRegex = regexp.MustCompile(`^\w+$`)
// DBExporter defines an interface for custom DB data export.
// Usually used as part of [App.Save].
type DBExporter interface {
// DBExport returns a key-value map with the data to be used when saving the struct in the database.
DBExport(app App) (map[string]any, error)
}
// PreValidator defines an optional model interface for registering a
// function that will run BEFORE firing the validation hooks (see [App.ValidateWithContext]).
type PreValidator interface {
// PreValidate defines a function that runs BEFORE the validation hooks.
PreValidate(ctx context.Context, app App) error
}
// PostValidator defines an optional model interface for registering a
// function that will run AFTER executing the validation hooks (see [App.ValidateWithContext]).
type PostValidator interface {
// PostValidate defines a function that runs AFTER the successful
// execution of the validation hooks.
PostValidate(ctx context.Context, app App) error
}
// GenerateDefaultRandomId generates a default random id string
// (note: the generated random string is not intended for security purposes).
func GenerateDefaultRandomId() string {
return security.PseudorandomStringWithAlphabet(DefaultIdLength, DefaultIdAlphabet)
}
// crc32Checksum generates a stringified crc32 checksum from the provided plain string.
func crc32Checksum(str string) string {
return strconv.FormatInt(int64(crc32.ChecksumIEEE([]byte(str))), 10)
}
// ModelQuery creates a new preconfigured select data.db query with preset
// SELECT, FROM and other common fields based on the provided model.
func (app *BaseApp) ModelQuery(m Model) *dbx.SelectQuery {
return app.modelQuery(app.ConcurrentDB(), m)
}
// AuxModelQuery creates a new preconfigured select auxiliary.db query with preset
// SELECT, FROM and other common fields based on the provided model.
func (app *BaseApp) AuxModelQuery(m Model) *dbx.SelectQuery {
return app.modelQuery(app.AuxConcurrentDB(), m)
}
func (app *BaseApp) modelQuery(db dbx.Builder, m Model) *dbx.SelectQuery {
tableName := m.TableName()
return db.
Select("{{" + tableName + "}}.*").
From(tableName).
WithBuildHook(func(query *dbx.Query) {
query.WithExecHook(execLockRetry(app.config.QueryTimeout, defaultMaxLockRetries))
})
}
// Delete deletes the specified model from the regular app database.
func (app *BaseApp) Delete(model Model) error {
return app.DeleteWithContext(context.Background(), model)
}
// Delete deletes the specified model from the regular app database
// (the context could be used to limit the query execution).
func (app *BaseApp) DeleteWithContext(ctx context.Context, model Model) error {
return app.delete(ctx, model, false)
}
// AuxDelete deletes the specified model from the auxiliary database.
func (app *BaseApp) AuxDelete(model Model) error {
return app.AuxDeleteWithContext(context.Background(), model)
}
// AuxDeleteWithContext deletes the specified model from the auxiliary database
// (the context could be used to limit the query execution).
func (app *BaseApp) AuxDeleteWithContext(ctx context.Context, model Model) error {
return app.delete(ctx, model, true)
}
func (app *BaseApp) delete(ctx context.Context, model Model, isForAuxDB bool) error {
event := new(ModelEvent)
event.App = app
event.Type = ModelEventTypeDelete
event.Context = ctx
event.Model = model
deleteErr := app.OnModelDelete().Trigger(event, func(e *ModelEvent) error {
pk := cast.ToString(e.Model.LastSavedPK())
if pk == "" {
return errors.New("the model can be deleted only if it is existing and has a non-empty primary key")
}
// db write
return e.App.OnModelDeleteExecute().Trigger(event, func(e *ModelEvent) error {
var db dbx.Builder
if isForAuxDB {
db = e.App.AuxNonconcurrentDB()
} else {
db = e.App.NonconcurrentDB()
}
return baseLockRetry(func(attempt int) error {
_, err := db.Delete(e.Model.TableName(), dbx.HashExp{
idColumn: pk,
}).WithContext(e.Context).Execute()
return err
}, defaultMaxLockRetries)
})
})
if deleteErr != nil {
errEvent := &ModelErrorEvent{ModelEvent: *event, Error: deleteErr}
errEvent.App = app // replace with the initial app in case it was changed by the hook
hookErr := app.OnModelAfterDeleteError().Trigger(errEvent)
if hookErr != nil {
return errors.Join(deleteErr, hookErr)
}
return deleteErr
}
if app.txInfo != nil {
// execute later after the transaction has completed
app.txInfo.OnComplete(func(txErr error) error {
if app.txInfo != nil && app.txInfo.parent != nil {
event.App = app.txInfo.parent
}
if txErr != nil {
return app.OnModelAfterDeleteError().Trigger(&ModelErrorEvent{
ModelEvent: *event,
Error: txErr,
})
}
return app.OnModelAfterDeleteSuccess().Trigger(event)
})
} else if err := event.App.OnModelAfterDeleteSuccess().Trigger(event); err != nil {
return err
}
return nil
}
// Save validates and saves the specified model into the regular app database.
//
// If you don't want to run validations, use [App.SaveNoValidate()].
func (app *BaseApp) Save(model Model) error {
return app.SaveWithContext(context.Background(), model)
}
// SaveWithContext is the same as [App.Save()] but allows specifying a context to limit the db execution.
//
// If you don't want to run validations, use [App.SaveNoValidateWithContext()].
func (app *BaseApp) SaveWithContext(ctx context.Context, model Model) error {
return app.save(ctx, model, true, false)
}
// SaveNoValidate saves the specified model into the regular app database without performing validations.
//
// If you want to also run validations before persisting, use [App.Save()].
func (app *BaseApp) SaveNoValidate(model Model) error {
return app.SaveNoValidateWithContext(context.Background(), model)
}
// SaveNoValidateWithContext is the same as [App.SaveNoValidate()]
// but allows specifying a context to limit the db execution.
//
// If you want to also run validations before persisting, use [App.SaveWithContext()].
func (app *BaseApp) SaveNoValidateWithContext(ctx context.Context, model Model) error {
return app.save(ctx, model, false, false)
}
// AuxSave validates and saves the specified model into the auxiliary app database.
//
// If you don't want to run validations, use [App.AuxSaveNoValidate()].
func (app *BaseApp) AuxSave(model Model) error {
return app.AuxSaveWithContext(context.Background(), model)
}
// AuxSaveWithContext is the same as [App.AuxSave()] but allows specifying a context to limit the db execution.
//
// If you don't want to run validations, use [App.AuxSaveNoValidateWithContext()].
func (app *BaseApp) AuxSaveWithContext(ctx context.Context, model Model) error {
return app.save(ctx, model, true, true)
}
// AuxSaveNoValidate saves the specified model into the auxiliary app database without performing validations.
//
// If you want to also run validations before persisting, use [App.AuxSave()].
func (app *BaseApp) AuxSaveNoValidate(model Model) error {
return app.AuxSaveNoValidateWithContext(context.Background(), model)
}
// AuxSaveNoValidateWithContext is the same as [App.AuxSaveNoValidate()]
// but allows specifying a context to limit the db execution.
//
// If you want to also run validations before persisting, use [App.AuxSaveWithContext()].
func (app *BaseApp) AuxSaveNoValidateWithContext(ctx context.Context, model Model) error {
return app.save(ctx, model, false, true)
}
// Validate triggers the OnModelValidate hook for the specified model.
func (app *BaseApp) Validate(model Model) error {
return app.ValidateWithContext(context.Background(), model)
}
// ValidateWithContext is the same as Validate but allows specifying the ModelEvent context.
func (app *BaseApp) ValidateWithContext(ctx context.Context, model Model) error {
if m, ok := model.(PreValidator); ok {
if err := m.PreValidate(ctx, app); err != nil {
return err
}
}
event := new(ModelEvent)
event.App = app
event.Context = ctx
event.Type = ModelEventTypeValidate
event.Model = model
return event.App.OnModelValidate().Trigger(event, func(e *ModelEvent) error {
if m, ok := e.Model.(PostValidator); ok {
if err := m.PostValidate(ctx, e.App); err != nil {
return err
}
}
return e.Next()
})
}
// -------------------------------------------------------------------
func (app *BaseApp) save(ctx context.Context, model Model, withValidations bool, isForAuxDB bool) error {
if model.IsNew() {
return app.create(ctx, model, withValidations, isForAuxDB)
}
return app.update(ctx, model, withValidations, isForAuxDB)
}
func (app *BaseApp) create(ctx context.Context, model Model, withValidations bool, isForAuxDB bool) error {
event := new(ModelEvent)
event.App = app
event.Context = ctx
event.Type = ModelEventTypeCreate
event.Model = model
saveErr := app.OnModelCreate().Trigger(event, func(e *ModelEvent) error {
// run validations (if any)
if withValidations {
validateErr := e.App.ValidateWithContext(e.Context, e.Model)
if validateErr != nil {
return validateErr
}
}
// db write
return e.App.OnModelCreateExecute().Trigger(event, func(e *ModelEvent) error {
var db dbx.Builder
if isForAuxDB {
db = e.App.AuxNonconcurrentDB()
} else {
db = e.App.NonconcurrentDB()
}
dbErr := baseLockRetry(func(attempt int) error {
if m, ok := e.Model.(DBExporter); ok {
data, err := m.DBExport(e.App)
if err != nil {
return err
}
// manually add the id to the data if missing
if _, ok := data[idColumn]; !ok {
data[idColumn] = e.Model.PK()
}
if cast.ToString(data[idColumn]) == "" {
return errors.New("empty primary key is not allowed when using the DBExporter interface")
}
_, err = db.Insert(e.Model.TableName(), data).WithContext(e.Context).Execute()
return err
}
return db.Model(e.Model).WithContext(e.Context).Insert()
}, defaultMaxLockRetries)
if dbErr != nil {
return dbErr
}
e.Model.MarkAsNotNew()
return nil
})
})
if saveErr != nil {
event.Model.MarkAsNew() // reset "new" state
errEvent := &ModelErrorEvent{ModelEvent: *event, Error: saveErr}
errEvent.App = app // replace with the initial app in case it was changed by the hook
hookErr := app.OnModelAfterCreateError().Trigger(errEvent)
if hookErr != nil {
return errors.Join(saveErr, hookErr)
}
return saveErr
}
if app.txInfo != nil {
// execute later after the transaction has completed
app.txInfo.OnComplete(func(txErr error) error {
if app.txInfo != nil && app.txInfo.parent != nil {
event.App = app.txInfo.parent
}
if txErr != nil {
event.Model.MarkAsNew() // reset "new" state
return app.OnModelAfterCreateError().Trigger(&ModelErrorEvent{
ModelEvent: *event,
Error: txErr,
})
}
return app.OnModelAfterCreateSuccess().Trigger(event)
})
} else if err := event.App.OnModelAfterCreateSuccess().Trigger(event); err != nil {
return err
}
return nil
}
func (app *BaseApp) update(ctx context.Context, model Model, withValidations bool, isForAuxDB bool) error {
event := new(ModelEvent)
event.App = app
event.Context = ctx
event.Type = ModelEventTypeUpdate
event.Model = model
saveErr := app.OnModelUpdate().Trigger(event, func(e *ModelEvent) error {
// run validations (if any)
if withValidations {
validateErr := e.App.ValidateWithContext(e.Context, e.Model)
if validateErr != nil {
return validateErr
}
}
// db write
return e.App.OnModelUpdateExecute().Trigger(event, func(e *ModelEvent) error {
var db dbx.Builder
if isForAuxDB {
db = e.App.AuxNonconcurrentDB()
} else {
db = e.App.NonconcurrentDB()
}
return baseLockRetry(func(attempt int) error {
if m, ok := e.Model.(DBExporter); ok {
data, err := m.DBExport(e.App)
if err != nil {
return err
}
// note: for now disallow primary key change for consistency with dbx.ModelQuery.Update()
if data[idColumn] != e.Model.LastSavedPK() {
return errors.New("primary key change is not allowed")
}
_, err = db.Update(e.Model.TableName(), data, dbx.HashExp{
idColumn: e.Model.LastSavedPK(),
}).WithContext(e.Context).Execute()
return err
}
return db.Model(e.Model).WithContext(e.Context).Update()
}, defaultMaxLockRetries)
})
})
if saveErr != nil {
errEvent := &ModelErrorEvent{ModelEvent: *event, Error: saveErr}
errEvent.App = app // replace with the initial app in case it was changed by the hook
hookErr := app.OnModelAfterUpdateError().Trigger(errEvent)
if hookErr != nil {
return errors.Join(saveErr, hookErr)
}
return saveErr
}
if app.txInfo != nil {
// execute later after the transaction has completed
app.txInfo.OnComplete(func(txErr error) error {
if app.txInfo != nil && app.txInfo.parent != nil {
event.App = app.txInfo.parent
}
if txErr != nil {
return app.OnModelAfterUpdateError().Trigger(&ModelErrorEvent{
ModelEvent: *event,
Error: txErr,
})
}
return app.OnModelAfterUpdateSuccess().Trigger(event)
})
} else if err := event.App.OnModelAfterUpdateSuccess().Trigger(event); err != nil {
return err
}
return nil
}
func validateCollectionId(app App, optTypes ...string) validation.RuleFunc {
return func(value any) error {
id, _ := value.(string)
if id == "" {
return nil
}
collection := &Collection{}
if err := app.ModelQuery(collection).Model(id, collection); err != nil {
return validation.NewError("validation_invalid_collection_id", "Missing or invalid collection.")
}
if len(optTypes) > 0 && !slices.Contains(optTypes, collection.Type) {
return validation.NewError(
"validation_invalid_collection_type",
fmt.Sprintf("Invalid collection type - must be %s.", strings.Join(optTypes, ", ")),
)
}
return nil
}
}
func validateRecordId(app App, collectionNameOrId string) validation.RuleFunc {
return func(value any) error {
id, _ := value.(string)
if id == "" {
return nil
}
collection, err := app.FindCachedCollectionByNameOrId(collectionNameOrId)
if err != nil {
return validation.NewError("validation_invalid_collection", "Missing or invalid collection.")
}
var exists int
rowErr := app.ConcurrentDB().Select("(1)").
From(collection.Name).
AndWhere(dbx.HashExp{"id": id}).
Limit(1).
Row(&exists)
if rowErr != nil || exists == 0 {
return validation.NewError("validation_invalid_record", "Missing or invalid record.")
}
return nil
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_tokens_test.go | core/record_tokens_test.go | package core_test
import (
"fmt"
"testing"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/spf13/cast"
)
func TestNewStaticAuthToken(t *testing.T) {
t.Parallel()
testRecordToken(t, core.TokenTypeAuth, func(record *core.Record) (string, error) {
return record.NewStaticAuthToken(0)
}, map[string]any{
core.TokenClaimRefreshable: false,
})
}
func TestNewStaticAuthTokenWithCustomDuration(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
var tolerance int64 = 1 // in sec
durations := []int64{-100, 0, 100}
for i, d := range durations {
t.Run(fmt.Sprintf("%d_%d", i, d), func(t *testing.T) {
now := time.Now()
duration := time.Duration(d) * time.Second
token, err := user.NewStaticAuthToken(duration)
if err != nil {
t.Fatal(err)
}
claims, err := security.ParseUnverifiedJWT(token)
if err != nil {
t.Fatal(err)
}
exp := cast.ToInt64(claims["exp"])
expectedDuration := duration
// should fallback to the collection setting
if expectedDuration <= 0 {
expectedDuration = user.Collection().AuthToken.DurationTime()
}
expectedMinExp := now.Add(expectedDuration).Unix() - tolerance
expectedMaxExp := now.Add(expectedDuration).Unix() + tolerance
if exp < expectedMinExp {
t.Fatalf("Expected token exp to be greater than %d, got %d", expectedMinExp, exp)
}
if exp > expectedMaxExp {
t.Fatalf("Expected token exp to be less than %d, got %d", expectedMaxExp, exp)
}
})
}
}
func TestNewAuthToken(t *testing.T) {
t.Parallel()
testRecordToken(t, core.TokenTypeAuth, func(record *core.Record) (string, error) {
return record.NewAuthToken()
}, map[string]any{
core.TokenClaimRefreshable: true,
})
}
func TestNewVerificationToken(t *testing.T) {
t.Parallel()
testRecordToken(t, core.TokenTypeVerification, func(record *core.Record) (string, error) {
return record.NewVerificationToken()
}, nil)
}
func TestNewPasswordResetToken(t *testing.T) {
t.Parallel()
testRecordToken(t, core.TokenTypePasswordReset, func(record *core.Record) (string, error) {
return record.NewPasswordResetToken()
}, nil)
}
func TestNewEmailChangeToken(t *testing.T) {
t.Parallel()
testRecordToken(t, core.TokenTypeEmailChange, func(record *core.Record) (string, error) {
return record.NewEmailChangeToken("new@example.com")
}, nil)
}
func TestNewFileToken(t *testing.T) {
t.Parallel()
testRecordToken(t, core.TokenTypeFile, func(record *core.Record) (string, error) {
return record.NewFileToken()
}, nil)
}
func testRecordToken(
t *testing.T,
tokenType string,
tokenFunc func(record *core.Record) (string, error),
expectedClaims map[string]any,
) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
demo1, err := app.FindRecordById("demo1", "84nmscqy84lsi1t")
if err != nil {
t.Fatal(err)
}
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
t.Run("non-auth record", func(t *testing.T) {
_, err = tokenFunc(demo1)
if err == nil {
t.Fatal("Expected error for non-auth records")
}
})
t.Run("auth record", func(t *testing.T) {
token, err := tokenFunc(user)
if err != nil {
t.Fatal(err)
}
tokenRecord, _ := app.FindAuthRecordByToken(token, tokenType)
if tokenRecord == nil || tokenRecord.Id != user.Id {
t.Fatalf("Expected auth record\n%v\ngot\n%v", user, tokenRecord)
}
if len(expectedClaims) > 0 {
claims, _ := security.ParseUnverifiedJWT(token)
for k, v := range expectedClaims {
if claims[k] != v {
t.Errorf("Expected claim %q with value %#v, got %#v", k, v, claims[k])
}
}
}
})
t.Run("empty signing key", func(t *testing.T) {
user.SetTokenKey("")
collection := user.Collection()
*collection = core.Collection{}
collection.Type = core.CollectionTypeAuth
_, err := tokenFunc(user)
if err == nil {
t.Fatal("Expected empty signing key error")
}
})
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/db_table_test.go | core/db_table_test.go | package core_test
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"slices"
"testing"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestHasTable(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
tableName string
expected bool
}{
{"", false},
{"test", false},
{core.CollectionNameSuperusers, true},
{"demo3", true},
{"DEMO3", true}, // table names are case insensitives by default
{"view1", true}, // view
}
for _, s := range scenarios {
t.Run(s.tableName, func(t *testing.T) {
result := app.HasTable(s.tableName)
if result != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, result)
}
})
}
}
func TestAuxHasTable(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
tableName string
expected bool
}{
{"", false},
{"test", false},
{"_lOGS", true}, // table names are case insensitives by default
}
for _, s := range scenarios {
t.Run(s.tableName, func(t *testing.T) {
result := app.AuxHasTable(s.tableName)
if result != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, result)
}
})
}
}
func TestTableColumns(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
tableName string
expected []string
}{
{"", nil},
{"_params", []string{"id", "value", "created", "updated"}},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.tableName), func(t *testing.T) {
columns, _ := app.TableColumns(s.tableName)
if len(columns) != len(s.expected) {
t.Fatalf("Expected columns %v, got %v", s.expected, columns)
}
for _, c := range columns {
if !slices.Contains(s.expected, c) {
t.Errorf("Didn't expect column %s", c)
}
}
})
}
}
func TestTableInfo(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
tableName string
expected string
}{
{"", "null"},
{"missing", "null"},
{
"_params",
`[{"PK":0,"Index":0,"Name":"created","Type":"TEXT","NotNull":true,"DefaultValue":{"String":"''","Valid":true}},{"PK":1,"Index":1,"Name":"id","Type":"TEXT","NotNull":true,"DefaultValue":{"String":"'r'||lower(hex(randomblob(7)))","Valid":true}},{"PK":0,"Index":2,"Name":"updated","Type":"TEXT","NotNull":true,"DefaultValue":{"String":"''","Valid":true}},{"PK":0,"Index":3,"Name":"value","Type":"JSON","NotNull":false,"DefaultValue":{"String":"NULL","Valid":true}}]`,
},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.tableName), func(t *testing.T) {
rows, _ := app.TableInfo(s.tableName)
raw, err := json.Marshal(rows)
if err != nil {
t.Fatal(err)
}
if str := string(raw); str != s.expected {
t.Fatalf("Expected\n%s\ngot\n%s", s.expected, str)
}
})
}
}
func TestTableIndexes(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
tableName string
expected []string
}{
{"", nil},
{"missing", nil},
{
core.CollectionNameSuperusers,
[]string{"idx_email__pbc_3323866339", "idx_tokenKey__pbc_3323866339"},
},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.tableName), func(t *testing.T) {
indexes, _ := app.TableIndexes(s.tableName)
if len(indexes) != len(s.expected) {
t.Fatalf("Expected %d indexes, got %d\n%v", len(s.expected), len(indexes), indexes)
}
for _, name := range s.expected {
if v, ok := indexes[name]; !ok || v == "" {
t.Fatalf("Expected non-empty index %q in \n%v", name, indexes)
}
}
})
}
}
func TestDeleteTable(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
tableName string
expectError bool
}{
{"", true},
{"test", false}, // missing tables are ignored
{"_admins", false},
{"demo3", false},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.tableName), func(t *testing.T) {
err := app.DeleteTable(s.tableName)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v", s.expectError, hasErr)
}
})
}
}
func TestVacuum(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
calledQueries := []string{}
app.NonconcurrentDB().(*dbx.DB).QueryLogFunc = func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error) {
calledQueries = append(calledQueries, sql)
}
app.NonconcurrentDB().(*dbx.DB).ExecLogFunc = func(ctx context.Context, t time.Duration, sql string, result sql.Result, err error) {
calledQueries = append(calledQueries, sql)
}
if err := app.Vacuum(); err != nil {
t.Fatal(err)
}
if total := len(calledQueries); total != 1 {
t.Fatalf("Expected 1 query, got %d", total)
}
if calledQueries[0] != "VACUUM" {
t.Fatalf("Expected VACUUM query, got %s", calledQueries[0])
}
}
func TestAuxVacuum(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
calledQueries := []string{}
app.AuxNonconcurrentDB().(*dbx.DB).QueryLogFunc = func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error) {
calledQueries = append(calledQueries, sql)
}
app.AuxNonconcurrentDB().(*dbx.DB).ExecLogFunc = func(ctx context.Context, t time.Duration, sql string, result sql.Result, err error) {
calledQueries = append(calledQueries, sql)
}
if err := app.AuxVacuum(); err != nil {
t.Fatal(err)
}
if total := len(calledQueries); total != 1 {
t.Fatalf("Expected 1 query, got %d", total)
}
if calledQueries[0] != "VACUUM" {
t.Fatalf("Expected VACUUM query, got %s", calledQueries[0])
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_text_test.go | core/field_text_test.go | package core_test
import (
"context"
"fmt"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestTextFieldBaseMethods(t *testing.T) {
testFieldBaseMethods(t, core.FieldTypeText)
}
func TestTextFieldColumnType(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.TextField{}
expected := "TEXT DEFAULT '' NOT NULL"
if v := f.ColumnType(app); v != expected {
t.Fatalf("Expected\n%q\ngot\n%q", expected, v)
}
}
func TestTextFieldPrepareValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.TextField{}
record := core.NewRecord(core.NewBaseCollection("test"))
scenarios := []struct {
raw any
expected string
}{
{"", ""},
{"test", "test"},
{false, "false"},
{true, "true"},
{123.456, "123.456"},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.raw), func(t *testing.T) {
v, err := f.PrepareValue(record, s.raw)
if err != nil {
t.Fatal(err)
}
vStr, ok := v.(string)
if !ok {
t.Fatalf("Expected string instance, got %T", v)
}
if vStr != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, v)
}
})
}
}
func TestTextFieldValidateValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, err := app.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
existingRecord, err := app.FindFirstRecordByFilter(collection, "id != ''")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
field *core.TextField
record func() *core.Record
expectError bool
}{
{
"invalid raw value",
&core.TextField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 123)
return record
},
true,
},
{
"zero field value (not required)",
&core.TextField{Name: "test", Pattern: `\d+`, Min: 10, Max: 100}, // other fields validators should be ignored
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "")
return record
},
false,
},
{
"zero field value (required)",
&core.TextField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "")
return record
},
true,
},
{
"non-zero field value (required)",
&core.TextField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abc")
return record
},
false,
},
{
"special forbidden character / (non-primaryKey)",
&core.TextField{Name: "test", PrimaryKey: false},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abc/")
return record
},
false,
},
{
"special forbidden character \\ (non-primaryKey)",
&core.TextField{Name: "test", PrimaryKey: false},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abc\\")
return record
},
false,
},
{
"special forbidden character . (non-primaryKey)",
&core.TextField{Name: "test", PrimaryKey: false},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abc.")
return record
},
false,
},
{
"special forbidden character ' ' (non-primaryKey)",
&core.TextField{Name: "test", PrimaryKey: false},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "ab c")
return record
},
false,
},
{
"special forbidden character * (non-primaryKey)",
&core.TextField{Name: "test", PrimaryKey: false},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abc*")
return record
},
false,
},
{
"special forbidden character / (primaryKey)",
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abc/")
return record
},
true,
},
{
"special forbidden character \\ (primaryKey)",
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abc\\")
return record
},
true,
},
{
"special forbidden character . (primaryKey)",
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abc.")
return record
},
true,
},
{
"special forbidden character ' ' (primaryKey)",
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "ab c")
return record
},
true,
},
{
"special forbidden character * (primaryKey; used in the realtime events too)",
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abc*")
return record
},
true,
},
{
"reserved pk literal (non-primaryKey)",
&core.TextField{Name: "test", PrimaryKey: false},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "aUx")
return record
},
false,
},
{
"reserved pk literal (primaryKey)",
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "aUx")
return record
},
true,
},
{
"reserved pk literal (non-exact match, primaryKey)",
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "aUx-")
return record
},
false,
},
{
"zero field value (primaryKey)",
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "")
return record
},
true,
},
{
"non-zero field value (primaryKey)",
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abcd")
return record
},
false,
},
{
"case-insensitive duplicated primary key check",
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", strings.ToUpper(existingRecord.Id))
return record
},
true,
},
{
"< min",
&core.TextField{Name: "test", Min: 4},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "абв") // multi-byte
return record
},
true,
},
{
">= min",
&core.TextField{Name: "test", Min: 3},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "абв") // multi-byte
return record
},
false,
},
{
"> default max",
&core.TextField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", strings.Repeat("a", 5001))
return record
},
true,
},
{
"<= default max",
&core.TextField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", strings.Repeat("a", 500))
return record
},
false,
},
{
"> max",
&core.TextField{Name: "test", Max: 2},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "абв") // multi-byte
return record
},
true,
},
{
"<= max",
&core.TextField{Name: "test", Min: 3},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "абв") // multi-byte
return record
},
false,
},
{
"mismatched pattern",
&core.TextField{Name: "test", Pattern: `\d+`},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abc")
return record
},
true,
},
{
"matched pattern",
&core.TextField{Name: "test", Pattern: `\d+`},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "123")
return record
},
false,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
err := s.field.ValidateValue(context.Background(), app, s.record())
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
func TestTextFieldValidateSettings(t *testing.T) {
testDefaultFieldIdValidation(t, core.FieldTypeText)
testDefaultFieldNameValidation(t, core.FieldTypeText)
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
name string
field func() *core.TextField
expectErrors []string
}{
{
"zero minimal",
func() *core.TextField {
return &core.TextField{
Id: "test",
Name: "test",
}
},
[]string{},
},
{
"primaryKey without required",
func() *core.TextField {
return &core.TextField{
Id: "test",
Name: "id",
PrimaryKey: true,
Pattern: `\d+`,
}
},
[]string{"required"},
},
{
"primaryKey without pattern",
func() *core.TextField {
return &core.TextField{
Id: "test",
Name: "id",
PrimaryKey: true,
Required: true,
}
},
[]string{"pattern"},
},
{
"primaryKey with hidden",
func() *core.TextField {
return &core.TextField{
Id: "test",
Name: "id",
Required: true,
PrimaryKey: true,
Hidden: true,
Pattern: `\d+`,
}
},
[]string{"hidden"},
},
{
"primaryKey with name != id",
func() *core.TextField {
return &core.TextField{
Id: "test",
Name: "test",
PrimaryKey: true,
Required: true,
Pattern: `\d+`,
}
},
[]string{"name"},
},
{
"multiple primaryKey fields",
func() *core.TextField {
return &core.TextField{
Id: "test2",
Name: "id",
PrimaryKey: true,
Pattern: `\d+`,
Required: true,
}
},
[]string{"primaryKey"},
},
{
"invalid pattern",
func() *core.TextField {
return &core.TextField{
Id: "test2",
Name: "id",
Pattern: `(invalid`,
}
},
[]string{"pattern"},
},
{
"valid pattern",
func() *core.TextField {
return &core.TextField{
Id: "test2",
Name: "id",
Pattern: `\d+`,
}
},
[]string{},
},
{
"invalid autogeneratePattern",
func() *core.TextField {
return &core.TextField{
Id: "test2",
Name: "id",
AutogeneratePattern: `(invalid`,
}
},
[]string{"autogeneratePattern"},
},
{
"valid autogeneratePattern",
func() *core.TextField {
return &core.TextField{
Id: "test2",
Name: "id",
AutogeneratePattern: `[a-z]+`,
}
},
[]string{},
},
{
"conflicting pattern and autogeneratePattern",
func() *core.TextField {
return &core.TextField{
Id: "test2",
Name: "id",
Pattern: `\d+`,
AutogeneratePattern: `[a-z]+`,
}
},
[]string{"autogeneratePattern"},
},
{
"Max > safe json int",
func() *core.TextField {
return &core.TextField{
Id: "test",
Name: "test",
Max: 1 << 53,
}
},
[]string{"max"},
},
{
"Max < 0",
func() *core.TextField {
return &core.TextField{
Id: "test",
Name: "test",
Max: -1,
}
},
[]string{"max"},
},
{
"Min > safe json int",
func() *core.TextField {
return &core.TextField{
Id: "test",
Name: "test",
Min: 1 << 53,
}
},
[]string{"min"},
},
{
"Min < 0",
func() *core.TextField {
return &core.TextField{
Id: "test",
Name: "test",
Min: -1,
}
},
[]string{"min"},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
field := s.field()
collection := core.NewBaseCollection("test_collection")
collection.Fields.GetByName("id").SetId("test") // set a dummy known id so that it can be replaced
collection.Fields.Add(field)
errs := field.ValidateSettings(context.Background(), app, collection)
tests.TestValidationErrors(t, errs, s.expectErrors)
})
}
}
func TestTextFieldAutogenerate(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
actionName string
field *core.TextField
record func() *core.Record
expected string
}{
{
"non-matching action",
core.InterceptorActionUpdate,
&core.TextField{Name: "test", AutogeneratePattern: "abc"},
func() *core.Record {
return core.NewRecord(collection)
},
"",
},
{
"matching action (create)",
core.InterceptorActionCreate,
&core.TextField{Name: "test", AutogeneratePattern: "abc"},
func() *core.Record {
return core.NewRecord(collection)
},
"abc",
},
{
"matching action (validate)",
core.InterceptorActionValidate,
&core.TextField{Name: "test", AutogeneratePattern: "abc"},
func() *core.Record {
return core.NewRecord(collection)
},
"abc",
},
{
"existing non-zero value",
core.InterceptorActionCreate,
&core.TextField{Name: "test", AutogeneratePattern: "abc"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "123")
return record
},
"123",
},
{
"non-new record",
core.InterceptorActionValidate,
&core.TextField{Name: "test", AutogeneratePattern: "abc"},
func() *core.Record {
record := core.NewRecord(collection)
record.Id = "test"
record.PostScan()
return record
},
"",
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
actionCalls := 0
record := s.record()
err := s.field.Intercept(context.Background(), app, record, s.actionName, func() error {
actionCalls++
return nil
})
if err != nil {
t.Fatal(err)
}
if actionCalls != 1 {
t.Fatalf("Expected actionCalls %d, got %d", 1, actionCalls)
}
v := record.GetString(s.field.GetName())
if v != s.expected {
t.Fatalf("Expected value %q, got %q", s.expected, v)
}
})
}
}
func TestTextFieldFindSetter(t *testing.T) {
scenarios := []struct {
name string
key string
value any
field *core.TextField
hasSetter bool
expected string
}{
{
"no match",
"example",
"abc",
&core.TextField{Name: "test", AutogeneratePattern: "test"},
false,
"",
},
{
"exact match",
"test",
"abc",
&core.TextField{Name: "test", AutogeneratePattern: "test"},
true,
"abc",
},
{
"autogenerate modifier",
"test:autogenerate",
"abc",
&core.TextField{Name: "test", AutogeneratePattern: "test"},
true,
"abctest",
},
{
"autogenerate modifier without AutogeneratePattern option",
"test:autogenerate",
"abc",
&core.TextField{Name: "test"},
true,
"abc",
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
collection := core.NewBaseCollection("test_collection")
collection.Fields.Add(s.field)
setter := s.field.FindSetter(s.key)
hasSetter := setter != nil
if hasSetter != s.hasSetter {
t.Fatalf("Expected hasSetter %v, got %v", s.hasSetter, hasSetter)
}
if !hasSetter {
return
}
record := core.NewRecord(collection)
setter(record, s.value)
result := record.GetString(s.field.Name)
if result != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, result)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/collection_import.go | core/collection_import.go | package core
import (
"cmp"
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"slices"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/spf13/cast"
)
// ImportCollectionsByMarshaledJSON is the same as [ImportCollections]
// but accept marshaled json array as import data (usually used for the autogenerated snapshots).
func (app *BaseApp) ImportCollectionsByMarshaledJSON(rawSliceOfMaps []byte, deleteMissing bool) error {
data := []map[string]any{}
err := json.Unmarshal(rawSliceOfMaps, &data)
if err != nil {
return err
}
return app.ImportCollections(data, deleteMissing)
}
// ImportCollections imports the provided collections data in a single transaction.
//
// For existing matching collections, the imported data is unmarshaled on top of the existing model.
//
// NB! If deleteMissing is true, ALL NON-SYSTEM COLLECTIONS AND SCHEMA FIELDS,
// that are not present in the imported configuration, WILL BE DELETED
// (this includes their related records data).
func (app *BaseApp) ImportCollections(toImport []map[string]any, deleteMissing bool) error {
if len(toImport) == 0 {
// prevent accidentally deleting all collections
return errors.New("no collections to import")
}
importedCollections := make([]*Collection, len(toImport))
mappedImported := make(map[string]*Collection, len(toImport))
// normalize imported collections data to ensure that all
// collection fields are present and properly initialized
for i, data := range toImport {
var imported *Collection
identifier := cast.ToString(data["id"])
if identifier == "" {
identifier = cast.ToString(data["name"])
}
existing, err := app.FindCollectionByNameOrId(identifier)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return err
}
if existing != nil {
// refetch for deep copy
imported, err = app.FindCollectionByNameOrId(existing.Id)
if err != nil {
return err
}
// ensure that the fields will be cleared
if data["fields"] == nil && deleteMissing {
data["fields"] = []map[string]any{}
}
rawData, err := json.Marshal(data)
if err != nil {
return err
}
// load the imported data
err = json.Unmarshal(rawData, imported)
if err != nil {
return err
}
// extend with the existing fields if necessary
for _, f := range existing.Fields {
if !f.GetSystem() && deleteMissing {
continue
}
if imported.Fields.GetById(f.GetId()) == nil {
// replace with the existing id to prevent accidental column deletion
// since otherwise the imported field will be treated as a new one
found := imported.Fields.GetByName(f.GetName())
if found != nil && found.Type() == f.Type() {
found.SetId(f.GetId())
}
imported.Fields.Add(f)
}
}
} else {
imported = &Collection{}
rawData, err := json.Marshal(data)
if err != nil {
return err
}
// load the imported data
err = json.Unmarshal(rawData, imported)
if err != nil {
return err
}
}
imported.IntegrityChecks(false)
importedCollections[i] = imported
mappedImported[imported.Id] = imported
}
// reorder views last since the view query could depend on some of the other collections
slices.SortStableFunc(importedCollections, func(a, b *Collection) int {
cmpA := -1
if a.IsView() {
cmpA = 1
}
cmpB := -1
if b.IsView() {
cmpB = 1
}
res := cmp.Compare(cmpA, cmpB)
if res == 0 {
res = a.Created.Compare(b.Created)
if res == 0 {
res = a.Updated.Compare(b.Updated)
}
}
return res
})
return app.RunInTransaction(func(txApp App) error {
existingCollections := []*Collection{}
if err := txApp.CollectionQuery().OrderBy("updated ASC").All(&existingCollections); err != nil {
return err
}
mappedExisting := make(map[string]*Collection, len(existingCollections))
for _, existing := range existingCollections {
existing.IntegrityChecks(false)
mappedExisting[existing.Id] = existing
}
// 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.Id] != nil || existing.System {
continue // exist or system
}
// delete collection
if err := txApp.Delete(existing); err != nil {
return err
}
}
}
// upsert imported collections
for _, imported := range importedCollections {
if err := txApp.SaveNoValidate(imported); err != nil {
return fmt.Errorf("failed to save collection %q: %w", imported.Name, err)
}
}
// run validations
for _, imported := range importedCollections {
original := mappedExisting[imported.Id]
if original == nil {
original = imported
}
validator := newCollectionValidator(
context.Background(),
txApp,
imported,
original,
)
if err := validator.run(); err != nil {
// serialize the validation error(s)
serializedErr, _ := json.MarshalIndent(err, "", " ")
return validation.Errors{"collections": validation.NewError(
"validation_collections_import_failure",
fmt.Sprintf("Data validations failed for collection %q (%s):\n%s", imported.Name, imported.Id, serializedErr),
)}
}
}
return nil
})
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_text.go | core/field_text.go | package core
import (
"context"
"database/sql"
"errors"
"fmt"
"regexp"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/spf13/cast"
)
func init() {
Fields[FieldTypeText] = func() Field {
return &TextField{}
}
}
const FieldTypeText = "text"
const autogenerateModifier = ":autogenerate"
var (
_ Field = (*TextField)(nil)
_ SetterFinder = (*TextField)(nil)
_ RecordInterceptor = (*TextField)(nil)
)
var forbiddenPKCharacters = []string{
".", "/", `\`, "|", `"`, "'", "`",
"<", ">", ":", "?", "*", "%", "$",
"\000", "\t", "\n", "\r", " ",
}
// (see largestReservedPKLength)
var caseInsensitiveReservedPKs = []string{
// reserved Windows files names
"CON", "PRN", "AUX", "NUL",
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
}
const largestReservedPKLength = 4
// TextField defines "text" type field for storing any string value.
//
// The respective zero record field value is empty string.
//
// The following additional setter keys are available:
//
// - "fieldName:autogenerate" - autogenerate field value if AutogeneratePattern is set. For example:
//
// record.Set("slug:autogenerate", "") // [random value]
// record.Set("slug:autogenerate", "abc-") // abc-[random value]
type TextField struct {
// Name (required) is the unique name of the field.
Name string `form:"name" json:"name"`
// Id is the unique stable field identifier.
//
// It is automatically generated from the name when adding to a collection FieldsList.
Id string `form:"id" json:"id"`
// System prevents the renaming and removal of the field.
System bool `form:"system" json:"system"`
// Hidden hides the field from the API response.
Hidden bool `form:"hidden" json:"hidden"`
// Presentable hints the Dashboard UI to use the underlying
// field record value in the relation preview label.
Presentable bool `form:"presentable" json:"presentable"`
// ---
// Min specifies the minimum required string characters.
//
// if zero value, no min limit is applied.
Min int `form:"min" json:"min"`
// Max specifies the maximum allowed string characters.
//
// If zero, a default limit of 5000 is applied.
Max int `form:"max" json:"max"`
// Pattern specifies an optional regex pattern to match against the field value.
//
// Leave it empty to skip the pattern check.
Pattern string `form:"pattern" json:"pattern"`
// AutogeneratePattern specifies an optional regex pattern that could
// be used to generate random string from it and set it automatically
// on record create if no explicit value is set or when the `:autogenerate` modifier is used.
//
// Note: the generated value still needs to satisfy min, max, pattern (if set)
AutogeneratePattern string `form:"autogeneratePattern" json:"autogeneratePattern"`
// Required will require the field value to be non-empty string.
Required bool `form:"required" json:"required"`
// PrimaryKey will mark the field as primary key.
//
// A single collection can have only 1 field marked as primary key.
PrimaryKey bool `form:"primaryKey" json:"primaryKey"`
}
// Type implements [Field.Type] interface method.
func (f *TextField) Type() string {
return FieldTypeText
}
// GetId implements [Field.GetId] interface method.
func (f *TextField) GetId() string {
return f.Id
}
// SetId implements [Field.SetId] interface method.
func (f *TextField) SetId(id string) {
f.Id = id
}
// GetName implements [Field.GetName] interface method.
func (f *TextField) GetName() string {
return f.Name
}
// SetName implements [Field.SetName] interface method.
func (f *TextField) SetName(name string) {
f.Name = name
}
// GetSystem implements [Field.GetSystem] interface method.
func (f *TextField) GetSystem() bool {
return f.System
}
// SetSystem implements [Field.SetSystem] interface method.
func (f *TextField) SetSystem(system bool) {
f.System = system
}
// GetHidden implements [Field.GetHidden] interface method.
func (f *TextField) GetHidden() bool {
return f.Hidden
}
// SetHidden implements [Field.SetHidden] interface method.
func (f *TextField) SetHidden(hidden bool) {
f.Hidden = hidden
}
// ColumnType implements [Field.ColumnType] interface method.
func (f *TextField) ColumnType(app App) string {
if f.PrimaryKey {
// note: the default is just a last resort fallback to avoid empty
// string values in case the record was inserted with raw sql and
// it is not actually used when operating with the db abstraction
return "TEXT PRIMARY KEY DEFAULT ('r'||lower(hex(randomblob(7)))) NOT NULL"
}
return "TEXT DEFAULT '' NOT NULL"
}
// PrepareValue implements [Field.PrepareValue] interface method.
func (f *TextField) PrepareValue(record *Record, raw any) (any, error) {
return cast.ToString(raw), nil
}
// ValidateValue implements [Field.ValidateValue] interface method.
func (f *TextField) ValidateValue(ctx context.Context, app App, record *Record) error {
newVal, ok := record.GetRaw(f.Name).(string)
if !ok {
return validators.ErrUnsupportedValueType
}
if f.PrimaryKey {
// disallow PK change
if !record.IsNew() {
oldVal := record.LastSavedPK()
if oldVal != newVal {
return validation.NewError("validation_pk_change", "The record primary key cannot be changed.")
}
if oldVal != "" {
// no need to further validate because the id can't be updated
// and because the id could have been inserted manually by migration from another system
// that may not comply with the user defined PocketBase validations
return nil
}
} else {
// this technically shouldn't be necessarily but again to
// minimize misuse of the Pattern validator that could cause
// side-effects on some platforms check for duplicates in a case-insensitive manner
//
// (@todo eventually may get replaced in the future with a system unique constraint to avoid races or wrapping the request in a transaction)
if f.Pattern != defaultLowercaseRecordIdPattern {
var exists int
err := app.ConcurrentDB().
Select("(1)").
From(record.TableName()).
Where(dbx.NewExp("id = {:id} COLLATE NOCASE", dbx.Params{"id": newVal})).
Limit(1).
Row(&exists)
if exists > 0 || (err != nil && !errors.Is(err, sql.ErrNoRows)) {
return validation.NewError("validation_pk_invalid", "The record primary key is invalid or already exists.")
}
}
}
}
return f.ValidatePlainValue(newVal)
}
// ValidatePlainValue validates the provided string against the field options.
func (f *TextField) ValidatePlainValue(value string) error {
if f.Required || f.PrimaryKey {
if err := validation.Required.Validate(value); err != nil {
return err
}
}
if value == "" {
return nil // nothing to check
}
// note: casted to []rune to count multi-byte chars as one
length := len([]rune(value))
if f.Min > 0 && length < f.Min {
return validation.NewError("validation_min_text_constraint", "Must be at least {{.min}} character(s).").
SetParams(map[string]any{"min": f.Min})
}
max := f.Max
if max == 0 {
max = 5000
}
if max > 0 && length > max {
return validation.NewError("validation_max_text_constraint", "Must be no more than {{.max}} character(s).").
SetParams(map[string]any{"max": max})
}
if f.Pattern != "" {
match, _ := regexp.MatchString(f.Pattern, value)
if !match {
return validation.NewError("validation_invalid_format", "Invalid value format.")
}
}
// additional primary key checks to minimize eventual filesystem compatibility issues
// because the primary key is often used as a file/directory name
if f.PrimaryKey && f.Pattern != defaultLowercaseRecordIdPattern {
for _, ch := range forbiddenPKCharacters {
if strings.Contains(value, ch) {
return validation.NewError("validation_forbidden_pk_character", "'{{.ch}}' is not a valid primary key character.").
SetParams(map[string]any{"ch": ch})
}
}
if largestReservedPKLength >= length {
for _, reserved := range caseInsensitiveReservedPKs {
if strings.EqualFold(value, reserved) {
return validation.NewError("validation_reserved_pk", "The primary key '{{.reserved}}' is reserved and cannot be used.").
SetParams(map[string]any{"reserved": reserved})
}
}
}
}
return nil
}
// ValidateSettings implements [Field.ValidateSettings] interface method.
func (f *TextField) ValidateSettings(ctx context.Context, app App, collection *Collection) error {
return validation.ValidateStruct(f,
validation.Field(&f.Id, validation.By(DefaultFieldIdValidationRule)),
validation.Field(&f.Name,
validation.By(DefaultFieldNameValidationRule),
validation.When(f.PrimaryKey, validation.In(idColumn).Error(`The primary key must be named "id".`)),
),
validation.Field(&f.PrimaryKey, validation.By(f.checkOtherFieldsForPK(collection))),
validation.Field(&f.Min, validation.Min(0), validation.Max(maxSafeJSONInt)),
validation.Field(&f.Max, validation.Min(f.Min), validation.Max(maxSafeJSONInt)),
validation.Field(&f.Pattern, validation.When(f.PrimaryKey, validation.Required), validation.By(validators.IsRegex)),
validation.Field(&f.Hidden, validation.When(f.PrimaryKey, validation.Empty)),
validation.Field(&f.Required, validation.When(f.PrimaryKey, validation.Required)),
validation.Field(&f.AutogeneratePattern, validation.By(validators.IsRegex), validation.By(f.checkAutogeneratePattern)),
)
}
func (f *TextField) checkOtherFieldsForPK(collection *Collection) validation.RuleFunc {
return func(value any) error {
v, _ := value.(bool)
if !v {
return nil // not a pk
}
totalPrimaryKeys := 0
for _, field := range collection.Fields {
if text, ok := field.(*TextField); ok && text.PrimaryKey {
totalPrimaryKeys++
}
if totalPrimaryKeys > 1 {
return validation.NewError("validation_unsupported_composite_pk", "Composite PKs are not supported and the collection must have only 1 PK.")
}
}
return nil
}
}
func (f *TextField) checkAutogeneratePattern(value any) error {
v, _ := value.(string)
if v == "" {
return nil // nothing to check
}
// run 10 tests to check for conflicts with the other field validators
for i := 0; i < 10; i++ {
generated, err := security.RandomStringByRegex(v)
if err != nil {
return validation.NewError("validation_invalid_autogenerate_pattern", err.Error())
}
// (loosely) check whether the generated pattern satisfies the current field settings
if err := f.ValidatePlainValue(generated); err != nil {
return validation.NewError(
"validation_invalid_autogenerate_pattern_value",
fmt.Sprintf("The provided autogenerate pattern could produce invalid field values, ex.: %q", generated),
)
}
}
return nil
}
// Intercept implements the [RecordInterceptor] interface.
func (f *TextField) Intercept(
ctx context.Context,
app App,
record *Record,
actionName string,
actionFunc func() error,
) error {
// set autogenerated value if missing for new records
switch actionName {
case InterceptorActionValidate, InterceptorActionCreate:
if f.AutogeneratePattern != "" && f.hasZeroValue(record) && record.IsNew() {
v, err := security.RandomStringByRegex(f.AutogeneratePattern)
if err != nil {
return fmt.Errorf("failed to autogenerate %q value: %w", f.Name, err)
}
record.SetRaw(f.Name, v)
}
}
return actionFunc()
}
func (f *TextField) hasZeroValue(record *Record) bool {
v, _ := record.GetRaw(f.Name).(string)
return v == ""
}
// FindSetter implements the [SetterFinder] interface.
func (f *TextField) FindSetter(key string) SetterFunc {
switch key {
case f.Name:
return func(record *Record, raw any) {
record.SetRaw(f.Name, cast.ToString(raw))
}
case f.Name + autogenerateModifier:
return func(record *Record, raw any) {
v := cast.ToString(raw)
if f.AutogeneratePattern != "" {
generated, _ := security.RandomStringByRegex(f.AutogeneratePattern)
v += generated
}
record.SetRaw(f.Name, v)
}
default:
return nil
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/events.go | core/events.go | package core
import (
"context"
"net"
"net/http"
"time"
"github.com/pocketbase/pocketbase/tools/auth"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/mailer"
"github.com/pocketbase/pocketbase/tools/router"
"github.com/pocketbase/pocketbase/tools/search"
"github.com/pocketbase/pocketbase/tools/subscriptions"
"golang.org/x/crypto/acme/autocert"
)
type HookTagger interface {
HookTags() []string
}
// -------------------------------------------------------------------
type baseModelEventData struct {
Model Model
}
func (e *baseModelEventData) Tags() []string {
if e.Model == nil {
return nil
}
if ht, ok := e.Model.(HookTagger); ok {
return ht.HookTags()
}
return []string{e.Model.TableName()}
}
// -------------------------------------------------------------------
type baseRecordEventData struct {
Record *Record
}
func (e *baseRecordEventData) Tags() []string {
if e.Record == nil {
return nil
}
return e.Record.HookTags()
}
// -------------------------------------------------------------------
type baseCollectionEventData struct {
Collection *Collection
}
func (e *baseCollectionEventData) Tags() []string {
if e.Collection == nil {
return nil
}
tags := make([]string, 0, 2)
if e.Collection.Id != "" {
tags = append(tags, e.Collection.Id)
}
if e.Collection.Name != "" {
tags = append(tags, e.Collection.Name)
}
return tags
}
// -------------------------------------------------------------------
// App events data
// -------------------------------------------------------------------
type BootstrapEvent struct {
hook.Event
App App
}
type TerminateEvent struct {
hook.Event
App App
IsRestart bool
}
type BackupEvent struct {
hook.Event
App App
Context context.Context
Name string // the name of the backup to create/restore.
Exclude []string // list of dir entries to exclude from the backup create/restore.
}
type ServeEvent struct {
hook.Event
App App
Router *router.Router[*RequestEvent]
Server *http.Server
CertManager *autocert.Manager
// Listener allow specifying a custom network listener.
//
// Leave it nil to use the default net.Listen("tcp", e.Server.Addr).
Listener net.Listener
// InstallerFunc is the "installer" function that is called after
// successful server tcp bind but only if there is no explicit
// superuser record created yet.
//
// It runs in a separate goroutine and its default value is [apis.DefaultInstallerFunc].
//
// It receives a system superuser record as argument that you can use to generate
// a short-lived auth token (e.g. systemSuperuser.NewStaticAuthToken(30 * time.Minute))
// and concatenate it as query param for your installer page
// (if you are using the client-side SDKs, you can then load the
// token with pb.authStore.save(token) and perform any Web API request
// e.g. creating a new superuser).
//
// Set it to nil if you want to skip the installer.
InstallerFunc func(app App, systemSuperuser *Record, baseURL string) error
}
// -------------------------------------------------------------------
// Settings events data
// -------------------------------------------------------------------
type SettingsListRequestEvent struct {
hook.Event
*RequestEvent
Settings *Settings
}
type SettingsUpdateRequestEvent struct {
hook.Event
*RequestEvent
OldSettings *Settings
NewSettings *Settings
}
type SettingsReloadEvent struct {
hook.Event
App App
}
// -------------------------------------------------------------------
// Mailer events data
// -------------------------------------------------------------------
type MailerEvent struct {
hook.Event
App App
Mailer mailer.Mailer
Message *mailer.Message
}
type MailerRecordEvent struct {
MailerEvent
baseRecordEventData
Meta map[string]any
}
// -------------------------------------------------------------------
// Model events data
// -------------------------------------------------------------------
const (
ModelEventTypeCreate = "create"
ModelEventTypeUpdate = "update"
ModelEventTypeDelete = "delete"
ModelEventTypeValidate = "validate"
)
type ModelEvent struct {
hook.Event
App App
baseModelEventData
Context context.Context
// Could be any of the ModelEventType* constants, like:
// - create
// - update
// - delete
// - validate
Type string
}
type ModelErrorEvent struct {
Error error
ModelEvent
}
// -------------------------------------------------------------------
// Record events data
// -------------------------------------------------------------------
type RecordEvent struct {
hook.Event
App App
baseRecordEventData
Context context.Context
// Could be any of the ModelEventType* constants, like:
// - create
// - update
// - delete
// - validate
Type string
}
type RecordErrorEvent struct {
Error error
RecordEvent
}
func syncModelEventWithRecordEvent(me *ModelEvent, re *RecordEvent) {
me.App = re.App
me.Context = re.Context
me.Type = re.Type
// @todo enable if after profiling doesn't have significant impact
// skip for now to avoid excessive checks and assume that the
// Model and the Record fields still points to the same instance
//
// if _, ok := me.Model.(*Record); ok {
// me.Model = re.Record
// } else if proxy, ok := me.Model.(RecordProxy); ok {
// proxy.SetProxyRecord(re.Record)
// }
}
func syncRecordEventWithModelEvent(re *RecordEvent, me *ModelEvent) {
re.App = me.App
re.Context = me.Context
re.Type = me.Type
}
func newRecordEventFromModelEvent(me *ModelEvent) (*RecordEvent, bool) {
record, ok := me.Model.(*Record)
if !ok {
proxy, ok := me.Model.(RecordProxy)
if !ok {
return nil, false
}
record = proxy.ProxyRecord()
}
re := new(RecordEvent)
re.App = me.App
re.Context = me.Context
re.Type = me.Type
re.Record = record
return re, true
}
func newRecordErrorEventFromModelErrorEvent(me *ModelErrorEvent) (*RecordErrorEvent, bool) {
recordEvent, ok := newRecordEventFromModelEvent(&me.ModelEvent)
if !ok {
return nil, false
}
re := new(RecordErrorEvent)
re.RecordEvent = *recordEvent
re.Error = me.Error
return re, true
}
func syncModelErrorEventWithRecordErrorEvent(me *ModelErrorEvent, re *RecordErrorEvent) {
syncModelEventWithRecordEvent(&me.ModelEvent, &re.RecordEvent)
me.Error = re.Error
}
func syncRecordErrorEventWithModelErrorEvent(re *RecordErrorEvent, me *ModelErrorEvent) {
syncRecordEventWithModelEvent(&re.RecordEvent, &me.ModelEvent)
re.Error = me.Error
}
// -------------------------------------------------------------------
// Collection events data
// -------------------------------------------------------------------
type CollectionEvent struct {
hook.Event
App App
baseCollectionEventData
Context context.Context
// Could be any of the ModelEventType* constants, like:
// - create
// - update
// - delete
// - validate
Type string
}
type CollectionErrorEvent struct {
Error error
CollectionEvent
}
func syncModelEventWithCollectionEvent(me *ModelEvent, ce *CollectionEvent) {
me.App = ce.App
me.Context = ce.Context
me.Type = ce.Type
me.Model = ce.Collection
}
func syncCollectionEventWithModelEvent(ce *CollectionEvent, me *ModelEvent) {
ce.App = me.App
ce.Context = me.Context
ce.Type = me.Type
if c, ok := me.Model.(*Collection); ok {
ce.Collection = c
}
}
func newCollectionEventFromModelEvent(me *ModelEvent) (*CollectionEvent, bool) {
record, ok := me.Model.(*Collection)
if !ok {
return nil, false
}
ce := new(CollectionEvent)
ce.App = me.App
ce.Context = me.Context
ce.Type = me.Type
ce.Collection = record
return ce, true
}
func newCollectionErrorEventFromModelErrorEvent(me *ModelErrorEvent) (*CollectionErrorEvent, bool) {
collectionevent, ok := newCollectionEventFromModelEvent(&me.ModelEvent)
if !ok {
return nil, false
}
ce := new(CollectionErrorEvent)
ce.CollectionEvent = *collectionevent
ce.Error = me.Error
return ce, true
}
func syncModelErrorEventWithCollectionErrorEvent(me *ModelErrorEvent, ce *CollectionErrorEvent) {
syncModelEventWithCollectionEvent(&me.ModelEvent, &ce.CollectionEvent)
me.Error = ce.Error
}
func syncCollectionErrorEventWithModelErrorEvent(ce *CollectionErrorEvent, me *ModelErrorEvent) {
syncCollectionEventWithModelEvent(&ce.CollectionEvent, &me.ModelEvent)
ce.Error = me.Error
}
// -------------------------------------------------------------------
// File API events data
// -------------------------------------------------------------------
type FileTokenRequestEvent struct {
hook.Event
*RequestEvent
baseRecordEventData
Token string
}
type FileDownloadRequestEvent struct {
hook.Event
*RequestEvent
baseCollectionEventData
Record *Record
FileField *FileField
ServedPath string
ServedName string
// ThumbError indicates the a thumb wasn't able to be generated
// (e.g. because it didn't satisfy the support image formats or it timed out).
//
// Note that PocketBase fallbacks to the original file in case of a thumb error,
// but developers can check the field and provide their own custom thumb generation if necessary.
ThumbError error
}
// -------------------------------------------------------------------
// Collection API events data
// -------------------------------------------------------------------
type CollectionsListRequestEvent struct {
hook.Event
*RequestEvent
Collections []*Collection
Result *search.Result
}
type CollectionsImportRequestEvent struct {
hook.Event
*RequestEvent
CollectionsData []map[string]any
DeleteMissing bool
}
type CollectionRequestEvent struct {
hook.Event
*RequestEvent
baseCollectionEventData
}
// -------------------------------------------------------------------
// Realtime API events data
// -------------------------------------------------------------------
type RealtimeConnectRequestEvent struct {
hook.Event
*RequestEvent
Client subscriptions.Client
// note: modifying it after the connect has no effect
IdleTimeout time.Duration
}
type RealtimeMessageEvent struct {
hook.Event
*RequestEvent
Client subscriptions.Client
Message *subscriptions.Message
}
type RealtimeSubscribeRequestEvent struct {
hook.Event
*RequestEvent
Client subscriptions.Client
Subscriptions []string
}
// -------------------------------------------------------------------
// Record CRUD API events data
// -------------------------------------------------------------------
type RecordsListRequestEvent struct {
hook.Event
*RequestEvent
baseCollectionEventData
// @todo consider removing and maybe add as generic to the search.Result?
Records []*Record
Result *search.Result
}
type RecordRequestEvent struct {
hook.Event
*RequestEvent
baseCollectionEventData
Record *Record
}
type RecordEnrichEvent struct {
hook.Event
App App
baseRecordEventData
RequestInfo *RequestInfo
}
// -------------------------------------------------------------------
// Auth Record API events data
// -------------------------------------------------------------------
type RecordCreateOTPRequestEvent struct {
hook.Event
*RequestEvent
baseCollectionEventData
Record *Record
Password string
}
type RecordAuthWithOTPRequestEvent struct {
hook.Event
*RequestEvent
baseCollectionEventData
Record *Record
OTP *OTP
}
type RecordAuthRequestEvent struct {
hook.Event
*RequestEvent
baseCollectionEventData
Record *Record
Token string
Meta any
AuthMethod string
}
type RecordAuthWithPasswordRequestEvent struct {
hook.Event
*RequestEvent
baseCollectionEventData
Record *Record
Identity string
IdentityField string
Password string
}
type RecordAuthWithOAuth2RequestEvent struct {
hook.Event
*RequestEvent
baseCollectionEventData
ProviderName string
ProviderClient auth.Provider
Record *Record
OAuth2User *auth.AuthUser
CreateData map[string]any
IsNewRecord bool
}
type RecordAuthRefreshRequestEvent struct {
hook.Event
*RequestEvent
baseCollectionEventData
Record *Record
}
type RecordRequestPasswordResetRequestEvent struct {
hook.Event
*RequestEvent
baseCollectionEventData
Record *Record
}
type RecordConfirmPasswordResetRequestEvent struct {
hook.Event
*RequestEvent
baseCollectionEventData
Record *Record
}
type RecordRequestVerificationRequestEvent struct {
hook.Event
*RequestEvent
baseCollectionEventData
Record *Record
}
type RecordConfirmVerificationRequestEvent struct {
hook.Event
*RequestEvent
baseCollectionEventData
Record *Record
}
type RecordRequestEmailChangeRequestEvent struct {
hook.Event
*RequestEvent
baseCollectionEventData
Record *Record
NewEmail string
}
type RecordConfirmEmailChangeRequestEvent struct {
hook.Event
*RequestEvent
baseCollectionEventData
Record *Record
NewEmail string
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_relation.go | core/field_relation.go | package core
import (
"context"
"database/sql/driver"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
Fields[FieldTypeRelation] = func() Field {
return &RelationField{}
}
}
const FieldTypeRelation = "relation"
var (
_ Field = (*RelationField)(nil)
_ MultiValuer = (*RelationField)(nil)
_ DriverValuer = (*RelationField)(nil)
_ SetterFinder = (*RelationField)(nil)
)
// RelationField defines "relation" type field for storing single or
// multiple collection record references.
//
// Requires the CollectionId option to be set.
//
// If MaxSelect is not set or <= 1, then the field value is expected to be a single record id.
//
// If MaxSelect is > 1, then the field value is expected to be a slice of record ids.
//
// The respective zero record field value is either empty string (single) or empty string slice (multiple).
//
// ---
//
// The following additional setter keys are available:
//
// - "fieldName+" - append one or more values to the existing record one. For example:
//
// record.Set("categories+", []string{"new1", "new2"}) // []string{"old1", "old2", "new1", "new2"}
//
// - "+fieldName" - prepend one or more values to the existing record one. For example:
//
// record.Set("+categories", []string{"new1", "new2"}) // []string{"new1", "new2", "old1", "old2"}
//
// - "fieldName-" - subtract one or more values from the existing record one. For example:
//
// record.Set("categories-", "old1") // []string{"old2"}
type RelationField struct {
// Name (required) is the unique name of the field.
Name string `form:"name" json:"name"`
// Id is the unique stable field identifier.
//
// It is automatically generated from the name when adding to a collection FieldsList.
Id string `form:"id" json:"id"`
// System prevents the renaming and removal of the field.
System bool `form:"system" json:"system"`
// Hidden hides the field from the API response.
Hidden bool `form:"hidden" json:"hidden"`
// Presentable hints the Dashboard UI to use the underlying
// field record value in the relation preview label.
Presentable bool `form:"presentable" json:"presentable"`
// ---
// CollectionId is the id of the related collection.
CollectionId string `form:"collectionId" json:"collectionId"`
// CascadeDelete indicates whether the root model should be deleted
// in case of delete of all linked relations.
CascadeDelete bool `form:"cascadeDelete" json:"cascadeDelete"`
// MinSelect indicates the min number of allowed relation records
// that could be linked to the main model.
//
// No min limit is applied if it is zero or negative value.
MinSelect int `form:"minSelect" json:"minSelect"`
// MaxSelect indicates the max number of allowed relation records
// that could be linked to the main model.
//
// For multiple select the value must be > 1, otherwise fallbacks to single (default).
//
// If MinSelect is set, MaxSelect must be at least >= MinSelect.
MaxSelect int `form:"maxSelect" json:"maxSelect"`
// Required will require the field value to be non-empty.
Required bool `form:"required" json:"required"`
}
// Type implements [Field.Type] interface method.
func (f *RelationField) Type() string {
return FieldTypeRelation
}
// GetId implements [Field.GetId] interface method.
func (f *RelationField) GetId() string {
return f.Id
}
// SetId implements [Field.SetId] interface method.
func (f *RelationField) SetId(id string) {
f.Id = id
}
// GetName implements [Field.GetName] interface method.
func (f *RelationField) GetName() string {
return f.Name
}
// SetName implements [Field.SetName] interface method.
func (f *RelationField) SetName(name string) {
f.Name = name
}
// GetSystem implements [Field.GetSystem] interface method.
func (f *RelationField) GetSystem() bool {
return f.System
}
// SetSystem implements [Field.SetSystem] interface method.
func (f *RelationField) SetSystem(system bool) {
f.System = system
}
// GetHidden implements [Field.GetHidden] interface method.
func (f *RelationField) GetHidden() bool {
return f.Hidden
}
// SetHidden implements [Field.SetHidden] interface method.
func (f *RelationField) SetHidden(hidden bool) {
f.Hidden = hidden
}
// IsMultiple implements [MultiValuer] interface and checks whether the
// current field options support multiple values.
func (f *RelationField) IsMultiple() bool {
return f.MaxSelect > 1
}
// ColumnType implements [Field.ColumnType] interface method.
func (f *RelationField) ColumnType(app App) string {
if f.IsMultiple() {
return "JSON DEFAULT '[]' NOT NULL"
}
return "TEXT DEFAULT '' NOT NULL"
}
// PrepareValue implements [Field.PrepareValue] interface method.
func (f *RelationField) PrepareValue(record *Record, raw any) (any, error) {
return f.normalizeValue(raw), nil
}
func (f *RelationField) normalizeValue(raw any) any {
val := list.ToUniqueStringSlice(raw)
if !f.IsMultiple() {
if len(val) > 0 {
return val[len(val)-1] // the last selected
}
return ""
}
return val
}
// DriverValue implements the [DriverValuer] interface.
func (f *RelationField) DriverValue(record *Record) (driver.Value, error) {
val := list.ToUniqueStringSlice(record.GetRaw(f.Name))
if !f.IsMultiple() {
if len(val) > 0 {
return val[len(val)-1], nil // the last selected
}
return "", nil
}
// serialize as json string array
return append(types.JSONArray[string]{}, val...), nil
}
// ValidateValue implements [Field.ValidateValue] interface method.
func (f *RelationField) ValidateValue(ctx context.Context, app App, record *Record) error {
ids := list.ToUniqueStringSlice(record.GetRaw(f.Name))
if len(ids) == 0 {
if f.Required {
return validation.ErrRequired
}
return nil // nothing to check
}
if f.MinSelect > 0 && len(ids) < f.MinSelect {
return validation.NewError("validation_not_enough_values", "Select at least {{.minSelect}}").
SetParams(map[string]any{"minSelect": f.MinSelect})
}
maxSelect := max(f.MaxSelect, 1)
if len(ids) > maxSelect {
return validation.NewError("validation_too_many_values", "Select no more than {{.maxSelect}}").
SetParams(map[string]any{"maxSelect": maxSelect})
}
// check if the related records exist
// ---
relCollection, err := app.FindCachedCollectionByNameOrId(f.CollectionId)
if err != nil {
return validation.NewError("validation_missing_rel_collection", "Relation connection is missing or cannot be accessed")
}
var total int
_ = app.ConcurrentDB().
Select("count(*)").
From(relCollection.Name).
AndWhere(dbx.In("id", list.ToInterfaceSlice(ids)...)).
Row(&total)
if total != len(ids) {
return validation.NewError("validation_missing_rel_records", "Failed to find all relation records with the provided ids")
}
// ---
return nil
}
// ValidateSettings implements [Field.ValidateSettings] interface method.
func (f *RelationField) ValidateSettings(ctx context.Context, app App, collection *Collection) error {
return validation.ValidateStruct(f,
validation.Field(&f.Id, validation.By(DefaultFieldIdValidationRule)),
validation.Field(&f.Name, validation.By(DefaultFieldNameValidationRule)),
validation.Field(&f.CollectionId, validation.Required, validation.By(f.checkCollectionId(app, collection))),
validation.Field(&f.MinSelect, validation.Min(0)),
validation.Field(&f.MaxSelect, validation.When(f.MinSelect > 0, validation.Required), validation.Min(f.MinSelect)),
)
}
func (f *RelationField) checkCollectionId(app App, collection *Collection) validation.RuleFunc {
return func(value any) error {
v, _ := value.(string)
if v == "" {
return nil // nothing to check
}
var oldCollection *Collection
if !collection.IsNew() {
var err error
oldCollection, err = app.FindCachedCollectionByNameOrId(collection.Id)
if err != nil {
return err
}
}
// prevent collectionId change
if oldCollection != nil {
oldField, _ := oldCollection.Fields.GetById(f.Id).(*RelationField)
if oldField != nil && oldField.CollectionId != v {
return validation.NewError(
"validation_field_relation_change",
"The relation collection cannot be changed.",
)
}
}
relCollection, _ := app.FindCachedCollectionByNameOrId(v)
// validate collectionId
if relCollection == nil || relCollection.Id != v {
return validation.NewError(
"validation_field_relation_missing_collection",
"The relation collection doesn't exist.",
)
}
// allow only views to have relations to other views
// (see https://github.com/pocketbase/pocketbase/issues/3000)
if !collection.IsView() && relCollection.IsView() {
return validation.NewError(
"validation_relation_field_non_view_base_collection",
"Only view collections are allowed to have relations to other views.",
)
}
return nil
}
}
// ---
// FindSetter implements [SetterFinder] interface method.
func (f *RelationField) FindSetter(key string) SetterFunc {
switch key {
case f.Name:
return f.setValue
case "+" + f.Name:
return f.prependValue
case f.Name + "+":
return f.appendValue
case f.Name + "-":
return f.subtractValue
default:
return nil
}
}
func (f *RelationField) setValue(record *Record, raw any) {
record.SetRaw(f.Name, f.normalizeValue(raw))
}
func (f *RelationField) appendValue(record *Record, modifierValue any) {
val := record.GetRaw(f.Name)
val = append(
list.ToUniqueStringSlice(val),
list.ToUniqueStringSlice(modifierValue)...,
)
f.setValue(record, val)
}
func (f *RelationField) prependValue(record *Record, modifierValue any) {
val := record.GetRaw(f.Name)
val = append(
list.ToUniqueStringSlice(modifierValue),
list.ToUniqueStringSlice(val)...,
)
f.setValue(record, val)
}
func (f *RelationField) subtractValue(record *Record, modifierValue any) {
val := record.GetRaw(f.Name)
val = list.SubtractSlice(
list.ToUniqueStringSlice(val),
list.ToUniqueStringSlice(modifierValue),
)
f.setValue(record, val)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/mfa_model.go | core/mfa_model.go | package core
import (
"context"
"errors"
"time"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/types"
)
const (
MFAMethodPassword = "password"
MFAMethodOAuth2 = "oauth2"
MFAMethodOTP = "otp"
)
const CollectionNameMFAs = "_mfas"
var (
_ Model = (*MFA)(nil)
_ PreValidator = (*MFA)(nil)
_ RecordProxy = (*MFA)(nil)
)
// MFA defines a Record proxy for working with the mfas collection.
type MFA struct {
*Record
}
// NewMFA instantiates and returns a new blank *MFA model.
//
// Example usage:
//
// mfa := core.NewMFA(app)
// mfa.SetRecordRef(user.Id)
// mfa.SetCollectionRef(user.Collection().Id)
// mfa.SetMethod(core.MFAMethodPassword)
// app.Save(mfa)
func NewMFA(app App) *MFA {
m := &MFA{}
c, err := app.FindCachedCollectionByNameOrId(CollectionNameMFAs)
if err != nil {
// this is just to make tests easier since mfa is a system collection and it is expected to be always accessible
// (note: the loaded record is further checked on MFA.PreValidate())
c = NewBaseCollection("@__invalid__")
}
m.Record = NewRecord(c)
return m
}
// PreValidate implements the [PreValidator] interface and checks
// whether the proxy is properly loaded.
func (m *MFA) PreValidate(ctx context.Context, app App) error {
if m.Record == nil || m.Record.Collection().Name != CollectionNameMFAs {
return errors.New("missing or invalid mfa ProxyRecord")
}
return nil
}
// ProxyRecord returns the proxied Record model.
func (m *MFA) ProxyRecord() *Record {
return m.Record
}
// SetProxyRecord loads the specified record model into the current proxy.
func (m *MFA) SetProxyRecord(record *Record) {
m.Record = record
}
// CollectionRef returns the "collectionRef" field value.
func (m *MFA) CollectionRef() string {
return m.GetString("collectionRef")
}
// SetCollectionRef updates the "collectionRef" record field value.
func (m *MFA) SetCollectionRef(collectionId string) {
m.Set("collectionRef", collectionId)
}
// RecordRef returns the "recordRef" record field value.
func (m *MFA) RecordRef() string {
return m.GetString("recordRef")
}
// SetRecordRef updates the "recordRef" record field value.
func (m *MFA) SetRecordRef(recordId string) {
m.Set("recordRef", recordId)
}
// Method returns the "method" record field value.
func (m *MFA) Method() string {
return m.GetString("method")
}
// SetMethod updates the "method" record field value.
func (m *MFA) SetMethod(method string) {
m.Set("method", method)
}
// Created returns the "created" record field value.
func (m *MFA) Created() types.DateTime {
return m.GetDateTime("created")
}
// Updated returns the "updated" record field value.
func (m *MFA) Updated() types.DateTime {
return m.GetDateTime("updated")
}
// HasExpired checks if the mfa is expired, aka. whether it has been
// more than maxElapsed time since its creation.
func (m *MFA) HasExpired(maxElapsed time.Duration) bool {
return time.Since(m.Created().Time()) > maxElapsed
}
func (app *BaseApp) registerMFAHooks() {
recordRefHooks[*MFA](app, CollectionNameMFAs, CollectionTypeAuth)
// run on every hour to cleanup expired mfa sessions
app.Cron().Add("__pbMFACleanup__", "0 * * * *", func() {
if err := app.DeleteExpiredMFAs(); err != nil {
app.Logger().Warn("Failed to delete expired MFA sessions", "error", err)
}
})
// delete existing mfas on password change
app.OnRecordUpdate().Bind(&hook.Handler[*RecordEvent]{
Func: func(e *RecordEvent) error {
err := e.Next()
if err != nil || !e.Record.Collection().IsAuth() {
return err
}
old := e.Record.Original().GetString(FieldNamePassword + ":hash")
new := e.Record.GetString(FieldNamePassword + ":hash")
if old != new {
err = e.App.DeleteAllMFAsByRecord(e.Record)
if err != nil {
e.App.Logger().Warn(
"Failed to delete all previous mfas",
"error", err,
"recordId", e.Record.Id,
"collectionId", e.Record.Collection().Id,
)
}
}
return nil
},
Priority: 99,
})
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/db_tx_test.go | core/db_tx_test.go | package core_test
import (
"errors"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestRunInTransaction(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
t.Run("failed nested transaction", func(t *testing.T) {
app.RunInTransaction(func(txApp core.App) error {
superuser, _ := txApp.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test@example.com")
return txApp.RunInTransaction(func(tx2Dao core.App) error {
if err := tx2Dao.Delete(superuser); err != nil {
t.Fatal(err)
}
return errors.New("test error")
})
})
// superuser should still exist
superuser, _ := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test@example.com")
if superuser == nil {
t.Fatal("Expected superuser test@example.com to not be deleted")
}
})
t.Run("successful nested transaction", func(t *testing.T) {
app.RunInTransaction(func(txApp core.App) error {
superuser, _ := txApp.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test@example.com")
return txApp.RunInTransaction(func(tx2Dao core.App) error {
return tx2Dao.Delete(superuser)
})
})
// superuser should have been deleted
superuser, _ := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test@example.com")
if superuser != nil {
t.Fatalf("Expected superuser test@example.com to be deleted, found %v", superuser)
}
})
}
func TestTransactionHooksCallsOnFailure(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
createHookCalls := 0
updateHookCalls := 0
deleteHookCalls := 0
afterCreateHookCalls := 0
afterUpdateHookCalls := 0
afterDeleteHookCalls := 0
app.OnModelCreate().BindFunc(func(e *core.ModelEvent) error {
createHookCalls++
return e.Next()
})
app.OnModelUpdate().BindFunc(func(e *core.ModelEvent) error {
updateHookCalls++
return e.Next()
})
app.OnModelDelete().BindFunc(func(e *core.ModelEvent) error {
deleteHookCalls++
return e.Next()
})
app.OnModelAfterCreateSuccess().BindFunc(func(e *core.ModelEvent) error {
afterCreateHookCalls++
return e.Next()
})
app.OnModelAfterUpdateSuccess().BindFunc(func(e *core.ModelEvent) error {
afterUpdateHookCalls++
return e.Next()
})
app.OnModelAfterDeleteSuccess().BindFunc(func(e *core.ModelEvent) error {
afterDeleteHookCalls++
return e.Next()
})
existingModel, _ := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test@example.com")
app.RunInTransaction(func(txApp1 core.App) error {
return txApp1.RunInTransaction(func(txApp2 core.App) error {
// test create
// ---
newModel := core.NewRecord(existingModel.Collection())
newModel.SetEmail("test_new1@example.com")
newModel.SetPassword("1234567890")
if err := txApp2.Save(newModel); err != nil {
t.Fatal(err)
}
// test update (twice)
// ---
if err := txApp2.Save(existingModel); err != nil {
t.Fatal(err)
}
if err := txApp2.Save(existingModel); err != nil {
t.Fatal(err)
}
// test delete
// ---
if err := txApp2.Delete(newModel); err != nil {
t.Fatal(err)
}
return errors.New("test_tx_error")
})
})
if createHookCalls != 1 {
t.Errorf("Expected createHookCalls to be called 1 time, got %d", createHookCalls)
}
if updateHookCalls != 2 {
t.Errorf("Expected updateHookCalls to be called 2 times, got %d", updateHookCalls)
}
if deleteHookCalls != 1 {
t.Errorf("Expected deleteHookCalls to be called 1 time, got %d", deleteHookCalls)
}
if afterCreateHookCalls != 0 {
t.Errorf("Expected afterCreateHookCalls to be called 0 times, got %d", afterCreateHookCalls)
}
if afterUpdateHookCalls != 0 {
t.Errorf("Expected afterUpdateHookCalls to be called 0 times, got %d", afterUpdateHookCalls)
}
if afterDeleteHookCalls != 0 {
t.Errorf("Expected afterDeleteHookCalls to be called 0 times, got %d", afterDeleteHookCalls)
}
}
func TestTransactionHooksCallsOnSuccess(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
createHookCalls := 0
updateHookCalls := 0
deleteHookCalls := 0
afterCreateHookCalls := 0
afterUpdateHookCalls := 0
afterDeleteHookCalls := 0
app.OnModelCreate().BindFunc(func(e *core.ModelEvent) error {
createHookCalls++
return e.Next()
})
app.OnModelUpdate().BindFunc(func(e *core.ModelEvent) error {
updateHookCalls++
return e.Next()
})
app.OnModelDelete().BindFunc(func(e *core.ModelEvent) error {
deleteHookCalls++
return e.Next()
})
app.OnModelAfterCreateSuccess().BindFunc(func(e *core.ModelEvent) error {
if e.App.IsTransactional() {
t.Fatal("Expected e.App to be non-transactional")
}
afterCreateHookCalls++
return e.Next()
})
app.OnModelAfterUpdateSuccess().BindFunc(func(e *core.ModelEvent) error {
if e.App.IsTransactional() {
t.Fatal("Expected e.App to be non-transactional")
}
afterUpdateHookCalls++
return e.Next()
})
app.OnModelAfterDeleteSuccess().BindFunc(func(e *core.ModelEvent) error {
if e.App.IsTransactional() {
t.Fatal("Expected e.App to be non-transactional")
}
afterDeleteHookCalls++
return e.Next()
})
existingModel, _ := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test@example.com")
app.RunInTransaction(func(txApp1 core.App) error {
return txApp1.RunInTransaction(func(txApp2 core.App) error {
// test create
// ---
newModel := core.NewRecord(existingModel.Collection())
newModel.SetEmail("test_new1@example.com")
newModel.SetPassword("1234567890")
if err := txApp2.Save(newModel); err != nil {
t.Fatal(err)
}
// test update (twice)
// ---
if err := txApp2.Save(existingModel); err != nil {
t.Fatal(err)
}
if err := txApp2.Save(existingModel); err != nil {
t.Fatal(err)
}
// test delete
// ---
if err := txApp2.Delete(newModel); err != nil {
t.Fatal(err)
}
return nil
})
})
if createHookCalls != 1 {
t.Errorf("Expected createHookCalls to be called 1 time, got %d", createHookCalls)
}
if updateHookCalls != 2 {
t.Errorf("Expected updateHookCalls to be called 2 times, got %d", updateHookCalls)
}
if deleteHookCalls != 1 {
t.Errorf("Expected deleteHookCalls to be called 1 time, got %d", deleteHookCalls)
}
if afterCreateHookCalls != 1 {
t.Errorf("Expected afterCreateHookCalls to be called 1 time, got %d", afterCreateHookCalls)
}
if afterUpdateHookCalls != 2 {
t.Errorf("Expected afterUpdateHookCalls to be called 2 times, got %d", afterUpdateHookCalls)
}
if afterDeleteHookCalls != 1 {
t.Errorf("Expected afterDeleteHookCalls to be called 1 time, got %d", afterDeleteHookCalls)
}
}
func TestTransactionFromInnerCreateHook(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
app.OnRecordCreateExecute("demo2").BindFunc(func(e *core.RecordEvent) error {
originalApp := e.App
return e.App.RunInTransaction(func(txApp core.App) error {
e.App = txApp
defer func() {
e.App = originalApp
}()
nextErr := e.Next()
return nextErr
})
})
app.OnRecordAfterCreateSuccess("demo2").BindFunc(func(e *core.RecordEvent) error {
if e.App.IsTransactional() {
t.Fatal("Expected e.App to be non-transactional")
}
// perform a db query with the app instance to ensure that it is still valid
_, err := e.App.FindFirstRecordByFilter("demo2", "1=1")
if err != nil {
t.Fatalf("Failed to perform a db query after tx success: %v", err)
}
return e.Next()
})
collection, err := app.FindCollectionByNameOrId("demo2")
if err != nil {
t.Fatal(err)
}
record := core.NewRecord(collection)
record.Set("title", "test_inner_tx")
if err = app.Save(record); err != nil {
t.Fatalf("Create failed: %v", err)
}
expectedHookCalls := map[string]int{
"OnRecordCreateExecute": 1,
"OnRecordAfterCreateSuccess": 1,
}
for k, total := range expectedHookCalls {
if found, ok := app.EventCalls[k]; !ok || total != found {
t.Fatalf("Expected %q %d calls, got %d", k, total, found)
}
}
}
func TestTransactionFromInnerUpdateHook(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
app.OnRecordUpdateExecute("demo2").BindFunc(func(e *core.RecordEvent) error {
originalApp := e.App
return e.App.RunInTransaction(func(txApp core.App) error {
e.App = txApp
defer func() {
e.App = originalApp
}()
nextErr := e.Next()
return nextErr
})
})
app.OnRecordAfterUpdateSuccess("demo2").BindFunc(func(e *core.RecordEvent) error {
if e.App.IsTransactional() {
t.Fatal("Expected e.App to be non-transactional")
}
// perform a db query with the app instance to ensure that it is still valid
_, err := e.App.FindFirstRecordByFilter("demo2", "1=1")
if err != nil {
t.Fatalf("Failed to perform a db query after tx success: %v", err)
}
return e.Next()
})
existingModel, err := app.FindFirstRecordByFilter("demo2", "1=1")
if err != nil {
t.Fatal(err)
}
if err = app.Save(existingModel); err != nil {
t.Fatalf("Update failed: %v", err)
}
expectedHookCalls := map[string]int{
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
}
for k, total := range expectedHookCalls {
if found, ok := app.EventCalls[k]; !ok || total != found {
t.Fatalf("Expected %q %d calls, got %d", k, total, found)
}
}
}
func TestTransactionFromInnerDeleteHook(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
app.OnRecordDeleteExecute("demo2").BindFunc(func(e *core.RecordEvent) error {
originalApp := e.App
return e.App.RunInTransaction(func(txApp core.App) error {
e.App = txApp
defer func() {
e.App = originalApp
}()
nextErr := e.Next()
return nextErr
})
})
app.OnRecordAfterDeleteSuccess("demo2").BindFunc(func(e *core.RecordEvent) error {
if e.App.IsTransactional() {
t.Fatal("Expected e.App to be non-transactional")
}
// perform a db query with the app instance to ensure that it is still valid
_, err := e.App.FindFirstRecordByFilter("demo2", "1=1")
if err != nil {
t.Fatalf("Failed to perform a db query after tx success: %v", err)
}
return e.Next()
})
existingModel, err := app.FindFirstRecordByFilter("demo2", "1=1")
if err != nil {
t.Fatal(err)
}
if err = app.Delete(existingModel); err != nil {
t.Fatalf("Delete failed: %v", err)
}
expectedHookCalls := map[string]int{
"OnRecordDeleteExecute": 1,
"OnRecordAfterDeleteSuccess": 1,
}
for k, total := range expectedHookCalls {
if found, ok := app.EventCalls[k]; !ok || total != found {
t.Fatalf("Expected %q %d calls, got %d", k, total, found)
}
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_query_expand.go | core/record_query_expand.go | package core
import (
"errors"
"fmt"
"log"
"regexp"
"strings"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/dbutils"
"github.com/pocketbase/pocketbase/tools/list"
)
// ExpandFetchFunc defines the function that is used to fetch the expanded relation records.
type ExpandFetchFunc func(relCollection *Collection, relIds []string) ([]*Record, error)
// ExpandRecord expands the relations of a single Record model.
//
// If optFetchFunc is not set, then a default function will be used
// that returns all relation records.
//
// Returns a map with the failed expand parameters and their errors.
func (app *BaseApp) ExpandRecord(record *Record, expands []string, optFetchFunc ExpandFetchFunc) map[string]error {
return app.ExpandRecords([]*Record{record}, expands, optFetchFunc)
}
// ExpandRecords expands the relations of the provided Record models list.
//
// If optFetchFunc is not set, then a default function will be used
// that returns all relation records.
//
// Returns a map with the failed expand parameters and their errors.
func (app *BaseApp) ExpandRecords(records []*Record, expands []string, optFetchFunc ExpandFetchFunc) map[string]error {
normalized := normalizeExpands(expands)
failed := map[string]error{}
for _, expand := range normalized {
if err := app.expandRecords(records, expand, optFetchFunc, 1); err != nil {
failed[expand] = err
}
}
return failed
}
// Deprecated
var indirectExpandRegexOld = regexp.MustCompile(`^(\w+)\((\w+)\)$`)
var indirectExpandRegex = regexp.MustCompile(`^(\w+)_via_(\w+)$`)
// notes:
// - if fetchFunc is nil, dao.FindRecordsByIds will be used
// - all records are expected to be from the same collection
// - if maxNestedRels(6) is reached, the function returns nil ignoring the remaining expand path
func (app *BaseApp) expandRecords(records []*Record, expandPath string, fetchFunc ExpandFetchFunc, recursionLevel int) error {
if fetchFunc == nil {
// load a default fetchFunc
fetchFunc = func(relCollection *Collection, relIds []string) ([]*Record, error) {
return app.FindRecordsByIds(relCollection.Id, relIds)
}
}
if expandPath == "" || recursionLevel > maxNestedRels || len(records) == 0 {
return nil
}
mainCollection := records[0].Collection()
var relField *RelationField
var relCollection *Collection
parts := strings.SplitN(expandPath, ".", 2)
var matches []string
// @todo remove the old syntax support
if strings.Contains(parts[0], "(") {
matches = indirectExpandRegexOld.FindStringSubmatch(parts[0])
if len(matches) == 3 {
log.Printf(
"%s expand format is deprecated and will be removed in the future. Consider replacing it with %s_via_%s.\n",
matches[0],
matches[1],
matches[2],
)
}
} else {
matches = indirectExpandRegex.FindStringSubmatch(parts[0])
}
if len(matches) == 3 {
indirectRel, _ := getCollectionByModelOrIdentifier(app, matches[1])
if indirectRel == nil {
return fmt.Errorf("couldn't find back-related collection %q", matches[1])
}
indirectRelField, _ := indirectRel.Fields.GetByName(matches[2]).(*RelationField)
if indirectRelField == nil || indirectRelField.CollectionId != mainCollection.Id {
return fmt.Errorf("couldn't find back-relation field %q in collection %q", matches[2], indirectRel.Name)
}
// add the related id(s) as a dynamic relation field value to
// allow further expand checks at later stage in a more unified manner
prepErr := func() error {
q := app.ConcurrentDB().Select("id").
From(indirectRel.Name).
Limit(1000) // the limit is arbitrary chosen and may change in the future
if indirectRelField.IsMultiple() {
q.AndWhere(dbx.Exists(dbx.NewExp(fmt.Sprintf(
"SELECT 1 FROM %s je WHERE je.value = {:id}",
dbutils.JSONEach(indirectRelField.Name),
))))
} else {
q.AndWhere(dbx.NewExp("[[" + indirectRelField.Name + "]] = {:id}"))
}
pq := q.Build().Prepare()
for _, record := range records {
var relIds []string
err := pq.Bind(dbx.Params{"id": record.Id}).Column(&relIds)
if err != nil {
return errors.Join(err, pq.Close())
}
if len(relIds) > 0 {
record.Set(parts[0], relIds)
}
}
return pq.Close()
}()
if prepErr != nil {
return prepErr
}
// indirect/back relation
relField = &RelationField{
Name: parts[0],
MaxSelect: 2147483647,
CollectionId: indirectRel.Id,
}
if _, ok := dbutils.FindSingleColumnUniqueIndex(indirectRel.Indexes, indirectRelField.GetName()); ok {
relField.MaxSelect = 1
}
relCollection = indirectRel
} else {
// direct relation
relField, _ = mainCollection.Fields.GetByName(parts[0]).(*RelationField)
if relField == nil {
return fmt.Errorf("couldn't find relation field %q in collection %q", parts[0], mainCollection.Name)
}
relCollection, _ = getCollectionByModelOrIdentifier(app, relField.CollectionId)
if relCollection == nil {
return fmt.Errorf("couldn't find related collection %q", relField.CollectionId)
}
}
// ---------------------------------------------------------------
// extract the id of the relations to expand
relIds := make([]string, 0, len(records))
for _, record := range records {
relIds = append(relIds, record.GetStringSlice(relField.Name)...)
}
// fetch rels
rels, relsErr := fetchFunc(relCollection, relIds)
if relsErr != nil {
return relsErr
}
// expand nested fields
if len(parts) > 1 {
err := app.expandRecords(rels, parts[1], fetchFunc, recursionLevel+1)
if err != nil {
return err
}
}
// reindex with the rel id
indexedRels := make(map[string]*Record, len(rels))
for _, rel := range rels {
indexedRels[rel.Id] = rel
}
for _, model := range records {
// init expand if not already
// (this is done to ensure that the "expand" key will be returned in the response even if empty)
if model.expand == nil {
model.SetExpand(nil)
}
relIds := model.GetStringSlice(relField.Name)
validRels := make([]*Record, 0, len(relIds))
for _, id := range relIds {
if rel, ok := indexedRels[id]; ok {
validRels = append(validRels, rel)
}
}
if len(validRels) == 0 {
continue // no valid relations
}
expandData := model.Expand()
// normalize access to the previously expanded rel records (if any)
var oldExpandedRels []*Record
switch v := expandData[relField.Name].(type) {
case nil:
// no old expands
case *Record:
oldExpandedRels = []*Record{v}
case []*Record:
oldExpandedRels = v
}
// merge expands
for _, oldExpandedRel := range oldExpandedRels {
// find a matching rel record
for _, rel := range validRels {
if rel.Id != oldExpandedRel.Id {
continue
}
rel.MergeExpand(oldExpandedRel.Expand())
}
}
// update the expanded data
if relField.IsMultiple() {
expandData[relField.Name] = validRels
} else {
expandData[relField.Name] = validRels[0]
}
model.SetExpand(expandData)
}
return nil
}
// normalizeExpands normalizes expand strings and merges self containing paths
// (eg. ["a.b.c", "a.b", " test ", " ", "test"] -> ["a.b.c", "test"]).
func normalizeExpands(paths []string) []string {
// normalize paths
normalized := make([]string, 0, len(paths))
for _, p := range paths {
p = strings.ReplaceAll(p, " ", "") // replace spaces
p = strings.Trim(p, ".") // trim incomplete paths
if p != "" {
normalized = append(normalized, p)
}
}
// merge containing paths
result := make([]string, 0, len(normalized))
for i, p1 := range normalized {
var skip bool
for j, p2 := range normalized {
if i == j {
continue
}
if strings.HasPrefix(p2, p1+".") {
// skip because there is more detailed expand path
skip = true
break
}
}
if !skip {
result = append(result, p1)
}
}
return list.ToUniqueStringSlice(result)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/view_test.go | core/view_test.go | package core_test
import (
"encoding/json"
"fmt"
"slices"
"testing"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func ensureNoTempViews(app core.App, t *testing.T) {
var total int
err := app.DB().Select("count(*)").
From("sqlite_schema").
AndWhere(dbx.HashExp{"type": "view"}).
AndWhere(dbx.NewExp(`[[name]] LIKE '%\_temp\_%' ESCAPE '\'`)).
Limit(1).
Row(&total)
if err != nil {
t.Fatalf("Failed to check for temp views: %v", err)
}
if total > 0 {
t.Fatalf("Expected all temp views to be deleted, got %d", total)
}
}
func TestDeleteView(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
viewName string
expectError bool
}{
{"", true},
{"demo1", true}, // not a view table
{"missing", false}, // missing or already deleted
{"view1", false}, // existing
{"VieW1", false}, // view names are case insensitives
}
for i, s := range scenarios {
err := app.DeleteView(s.viewName)
hasErr := err != nil
if hasErr != s.expectError {
t.Errorf("[%d - %q] Expected hasErr %v, got %v (%v)", i, s.viewName, s.expectError, hasErr, err)
}
}
ensureNoTempViews(app, t)
}
func TestSaveView(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
scenarioName string
viewName string
query string
expectError bool
expectColumns []string
}{
{
"empty name and query",
"",
"",
true,
nil,
},
{
"empty name",
"",
"select * from " + core.CollectionNameSuperusers,
true,
nil,
},
{
"empty query",
"123Test",
"",
true,
nil,
},
{
"invalid query",
"123Test",
"123 456",
true,
nil,
},
{
"missing table",
"123Test",
"select id from missing",
true,
nil,
},
{
"non select query",
"123Test",
"drop table " + core.CollectionNameSuperusers,
true,
nil,
},
{
"multiple select queries",
"123Test",
"select *, count(id) as c from " + core.CollectionNameSuperusers + "; select * from demo1;",
true,
nil,
},
{
"try to break the parent parenthesis",
"123Test",
"select *, count(id) as c from `" + core.CollectionNameSuperusers + "`)",
true,
nil,
},
{
"simple select query (+ trimmed semicolon)",
"123Test",
";select *, count(id) as c from " + core.CollectionNameSuperusers + ";",
false,
[]string{
"id", "created", "updated",
"password", "tokenKey", "email",
"emailVisibility", "verified",
"c",
},
},
{
"update old view with new query",
"123Test",
"select 1 as test from " + core.CollectionNameSuperusers,
false,
[]string{"test"},
},
}
for _, s := range scenarios {
t.Run(s.scenarioName, func(t *testing.T) {
err := app.SaveView(s.viewName, s.query)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
if hasErr {
return
}
infoRows, err := app.TableInfo(s.viewName)
if err != nil {
t.Fatalf("Failed to fetch table info for %s: %v", s.viewName, err)
}
if len(s.expectColumns) != len(infoRows) {
t.Fatalf("Expected %d columns, got %d", len(s.expectColumns), len(infoRows))
}
for _, row := range infoRows {
if !slices.Contains(s.expectColumns, row.Name) {
t.Fatalf("Missing %q column in %v", row.Name, s.expectColumns)
}
}
})
}
ensureNoTempViews(app, t)
}
func TestCreateViewFieldsWithDiscardedNestedTransaction(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
app.RunInTransaction(func(txApp core.App) error {
_, err := txApp.CreateViewFields("select id from missing")
if err == nil {
t.Fatal("Expected error, got nil")
}
return nil
})
ensureNoTempViews(app, t)
}
func TestCreateViewFields(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
name string
query string
expectError bool
expectFields map[string]string // name-type pairs
}{
{
"empty query",
"",
true,
nil,
},
{
"invalid query",
"test 123456",
true,
nil,
},
{
"missing table",
"select id from missing",
true,
nil,
},
{
"query with wildcard column",
"select a.id, a.* from demo1 a",
true,
nil,
},
{
"query without id",
"select text, url, created, updated from demo1",
true,
nil,
},
{
"query with comments",
`
select
-- test single line
demo1.id,
demo1.text,
/* multi
* line comment block */
demo1.url, demo1.created, demo1.updated from/* inline comment block with no spaces between the identifiers */demo1
-- comment before join
join demo2 ON (
-- comment inside join
demo2.id = demo1.id
)
-- comment before where
where (
-- comment inside where
demo2.id = demo1.id
)
`,
false,
map[string]string{
"id": core.FieldTypeText,
"text": core.FieldTypeText,
"url": core.FieldTypeURL,
"created": core.FieldTypeAutodate,
"updated": core.FieldTypeAutodate,
},
},
{
"query with all fields and quoted identifiers",
`
select
"id",
"created",
"updated",
[text],
` + "`bool`" + `,
"url",
"select_one",
"select_many",
"file_one",
"demo1"."file_many",
` + "`demo1`." + "`number`" + ` number_alias,
"email",
"datetime",
"json",
"rel_one",
"rel_many",
'single_quoted_custom_literal' as 'single_quoted_column'
from demo1
`,
false,
map[string]string{
"id": core.FieldTypeText,
"created": core.FieldTypeAutodate,
"updated": core.FieldTypeAutodate,
"text": core.FieldTypeText,
"bool": core.FieldTypeBool,
"url": core.FieldTypeURL,
"select_one": core.FieldTypeSelect,
"select_many": core.FieldTypeSelect,
"file_one": core.FieldTypeFile,
"file_many": core.FieldTypeFile,
"number_alias": core.FieldTypeNumber,
"email": core.FieldTypeEmail,
"datetime": core.FieldTypeDate,
"json": core.FieldTypeJSON,
"rel_one": core.FieldTypeRelation,
"rel_many": core.FieldTypeRelation,
"single_quoted_column": core.FieldTypeJSON,
},
},
{
"query with indirect relations fields",
"select a.id, b.id as bid, b.created from demo1 as a left join demo2 b",
false,
map[string]string{
"id": core.FieldTypeText,
"bid": core.FieldTypeRelation,
"created": core.FieldTypeAutodate,
},
},
{
"query with multiple froms, joins and style of aliasses",
`
select
a.id as id,
b.id as bid,
lj.id cid,
ij.id as did,
a.bool,
` + core.CollectionNameSuperusers + `.id as eid,
` + core.CollectionNameSuperusers + `.email
from demo1 a, demo2 as b
left join demo3 lj on lj.id = 123
inner join demo4 as ij on ij.id = 123
join ` + core.CollectionNameSuperusers + `
where 1=1
group by a.id
limit 10
`,
false,
map[string]string{
"id": core.FieldTypeText,
"bid": core.FieldTypeRelation,
"cid": core.FieldTypeRelation,
"did": core.FieldTypeRelation,
"bool": core.FieldTypeBool,
"eid": core.FieldTypeRelation,
"email": core.FieldTypeEmail,
},
},
{
"query with casts",
`select
a.id,
count(a.id) count,
cast(a.id as int) cast_int,
cast(a.id as integer) cast_integer,
cast(a.id as real) cast_real,
cast(a.id as decimal) cast_decimal,
cast(a.id as numeric) cast_numeric,
cast(a.id as text) cast_text,
cast(a.id as bool) cast_bool,
cast(a.id as boolean) cast_boolean,
avg(a.id) avg,
sum(a.id) sum,
total(a.id) total,
min(a.id) min,
max(a.id) max
from demo1 a`,
false,
map[string]string{
"id": core.FieldTypeText,
"count": core.FieldTypeNumber,
"total": core.FieldTypeNumber,
"cast_int": core.FieldTypeNumber,
"cast_integer": core.FieldTypeNumber,
"cast_real": core.FieldTypeNumber,
"cast_decimal": core.FieldTypeNumber,
"cast_numeric": core.FieldTypeNumber,
"cast_text": core.FieldTypeText,
"cast_bool": core.FieldTypeBool,
"cast_boolean": core.FieldTypeBool,
// json because they are nullable
"sum": core.FieldTypeJSON,
"avg": core.FieldTypeJSON,
"min": core.FieldTypeJSON,
"max": core.FieldTypeJSON,
},
},
{
"query with multiline cast",
`select
id,
cast(
(
case
when count(a.id) = 1 then 21
when count(a.id) = 2 then 18
else 0
end
) as int
) as cast_int
from demo1 a`,
false,
map[string]string{
"id": core.FieldTypeText,
"cast_int": core.FieldTypeNumber,
},
},
{
"query with case-insensitive and extra-spaced cast",
`select
id,
CaSt( a.id aS iNt ) as cast_int
from demo1 a`,
false,
map[string]string{
"id": core.FieldTypeText,
"cast_int": core.FieldTypeNumber,
},
},
{
"query with reserved auth collection fields",
`
select
a.id,
a.username,
a.email,
a.emailVisibility,
a.verified,
demo1.id relid
from users a
left join demo1
`,
false,
map[string]string{
"id": core.FieldTypeText,
"username": core.FieldTypeText,
"email": core.FieldTypeEmail,
"emailVisibility": core.FieldTypeBool,
"verified": core.FieldTypeBool,
"relid": core.FieldTypeRelation,
},
},
{
"query with unknown fields and aliases",
`select
id,
id as id2,
text as text_alias,
url as url_alias,
"demo1"."bool" as bool_alias,
number as number_alias,
created created_alias,
updated updated_alias,
123 as custom
from demo1`,
false,
map[string]string{
"id": core.FieldTypeText,
"id2": core.FieldTypeRelation,
"text_alias": core.FieldTypeText,
"url_alias": core.FieldTypeURL,
"bool_alias": core.FieldTypeBool,
"number_alias": core.FieldTypeNumber,
"created_alias": core.FieldTypeAutodate,
"updated_alias": core.FieldTypeAutodate,
"custom": core.FieldTypeJSON,
},
},
{
"query with distinct and reordered id column",
`select distinct
id as id2,
id,
123 as custom
from demo1`,
false,
map[string]string{
"id2": core.FieldTypeRelation,
"id": core.FieldTypeText,
"custom": core.FieldTypeJSON,
},
},
{
"query with aliasing the same field multiple times",
`select
a.id as id,
a.text as alias1,
a.text as alias2,
b.text as alias3,
b.text as alias4
from demo1 a
left join demo1 as b`,
false,
map[string]string{
"id": core.FieldTypeText,
"alias1": core.FieldTypeText,
"alias2": core.FieldTypeText,
"alias3": core.FieldTypeText,
"alias4": core.FieldTypeText,
},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result, err := app.CreateViewFields(s.query)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
if hasErr {
return
}
if len(s.expectFields) != len(result) {
serialized, _ := json.Marshal(result)
t.Fatalf("Expected %d fields, got %d: \n%s", len(s.expectFields), len(result), serialized)
}
for name, typ := range s.expectFields {
field := result.GetByName(name)
if field == nil {
t.Fatalf("Expected to find field %s, got nil", name)
}
if field.Type() != typ {
t.Fatalf("Expected field %s to be %q, got %q", name, typ, field.Type())
}
}
})
}
ensureNoTempViews(app, t)
}
func TestFindRecordByViewFile(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
prevCollection, err := app.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
totalLevels := 6
// create collection view mocks
fileOneAlias := "file_one one0"
fileManyAlias := "file_many many0"
mockCollections := make([]*core.Collection, 0, totalLevels)
for i := 0; i <= totalLevels; i++ {
view := new(core.Collection)
view.Type = core.CollectionTypeView
view.Name = fmt.Sprintf("_test_view%d", i)
view.ViewQuery = fmt.Sprintf(
"select id, %s, %s from %s",
fileOneAlias,
fileManyAlias,
prevCollection.Name,
)
// save view
if err := app.Save(view); err != nil {
t.Fatalf("Failed to save view%d: %v", i, err)
}
mockCollections = append(mockCollections, view)
prevCollection = view
fileOneAlias = fmt.Sprintf("one%d one%d", i, i+1)
fileManyAlias = fmt.Sprintf("many%d many%d", i, i+1)
}
fileOneName := "test_d61b33QdDU.txt"
fileManyName := "test_QZFjKjXchk.txt"
expectedRecordId := "84nmscqy84lsi1t"
scenarios := []struct {
name string
collectionNameOrId string
fileFieldName string
filename string
expectError bool
expectRecordId string
}{
{
"missing collection",
"missing",
"a",
fileOneName,
true,
"",
},
{
"non-view collection",
"demo1",
"file_one",
fileOneName,
true,
"",
},
{
"view collection after the max recursion limit",
mockCollections[totalLevels-1].Name,
fmt.Sprintf("one%d", totalLevels-1),
fileOneName,
true,
"",
},
{
"first view collection (single file)",
mockCollections[0].Name,
"one0",
fileOneName,
false,
expectedRecordId,
},
{
"first view collection (many files)",
mockCollections[0].Name,
"many0",
fileManyName,
false,
expectedRecordId,
},
{
"last view collection before the recursion limit (single file)",
mockCollections[totalLevels-2].Name,
fmt.Sprintf("one%d", totalLevels-2),
fileOneName,
false,
expectedRecordId,
},
{
"last view collection before the recursion limit (many files)",
mockCollections[totalLevels-2].Name,
fmt.Sprintf("many%d", totalLevels-2),
fileManyName,
false,
expectedRecordId,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
record, err := app.FindRecordByViewFile(
s.collectionNameOrId,
s.fileFieldName,
s.filename,
)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
if hasErr {
return
}
if record.Id != s.expectRecordId {
t.Fatalf("Expected recordId %q, got %q", s.expectRecordId, record.Id)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/collection_model_auth_options_test.go | core/collection_model_auth_options_test.go | package core_test
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"testing"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/auth"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestCollectionAuthOptionsValidate(t *testing.T) {
t.Parallel()
scenarios := []struct {
name string
collection func(app core.App) (*core.Collection, error)
expectedErrors []string
}{
// authRule
{
name: "nil authRule",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.AuthRule = nil
return c, nil
},
expectedErrors: []string{},
},
{
name: "empty authRule",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.AuthRule = types.Pointer("")
return c, nil
},
expectedErrors: []string{},
},
{
name: "invalid authRule",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.AuthRule = types.Pointer("missing != ''")
return c, nil
},
expectedErrors: []string{"authRule"},
},
{
name: "valid authRule",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.AuthRule = types.Pointer("id != ''")
return c, nil
},
expectedErrors: []string{},
},
// manageRule
{
name: "nil manageRule",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.ManageRule = nil
return c, nil
},
expectedErrors: []string{},
},
{
name: "empty manageRule",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.ManageRule = types.Pointer("")
return c, nil
},
expectedErrors: []string{"manageRule"},
},
{
name: "invalid manageRule",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.ManageRule = types.Pointer("missing != ''")
return c, nil
},
expectedErrors: []string{"manageRule"},
},
{
name: "valid manageRule",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.ManageRule = types.Pointer("id != ''")
return c, nil
},
expectedErrors: []string{},
},
// passwordAuth
{
name: "trigger passwordAuth validations",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.PasswordAuth = core.PasswordAuthConfig{
Enabled: true,
}
return c, nil
},
expectedErrors: []string{"passwordAuth"},
},
{
name: "passwordAuth with non-unique identity fields",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.Fields.Add(&core.TextField{Name: "test"})
c.PasswordAuth = core.PasswordAuthConfig{
Enabled: true,
IdentityFields: []string{"email", "test"},
}
return c, nil
},
expectedErrors: []string{"passwordAuth"},
},
{
name: "passwordAuth with non-unique identity fields",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.Fields.Add(&core.TextField{Name: "test"})
c.AddIndex("auth_test_idx", true, "test", "")
c.PasswordAuth = core.PasswordAuthConfig{
Enabled: true,
IdentityFields: []string{"email", "test"},
}
return c, nil
},
expectedErrors: []string{},
},
// oauth2
{
name: "trigger oauth2 validations",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.OAuth2 = core.OAuth2Config{
Enabled: true,
Providers: []core.OAuth2ProviderConfig{
{Name: "missing"},
},
}
return c, nil
},
expectedErrors: []string{"oauth2"},
},
// otp
{
name: "trigger otp validations",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.OTP = core.OTPConfig{
Enabled: true,
Duration: -10,
}
return c, nil
},
expectedErrors: []string{"otp"},
},
// mfa
{
name: "trigger mfa validations",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.MFA = core.MFAConfig{
Enabled: true,
Duration: -10,
}
return c, nil
},
expectedErrors: []string{"mfa"},
},
{
name: "mfa enabled with < 2 auth methods",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.MFA.Enabled = true
c.PasswordAuth.Enabled = true
c.OTP.Enabled = false
c.OAuth2.Enabled = false
return c, nil
},
expectedErrors: []string{"mfa"},
},
{
name: "mfa enabled with >= 2 auth methods",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.MFA.Enabled = true
c.PasswordAuth.Enabled = true
c.OTP.Enabled = true
c.OAuth2.Enabled = false
return c, nil
},
expectedErrors: []string{},
},
{
name: "mfa disabled with invalid rule",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.PasswordAuth.Enabled = true
c.OTP.Enabled = true
c.MFA.Enabled = false
c.MFA.Rule = "invalid"
return c, nil
},
expectedErrors: []string{},
},
{
name: "mfa enabled with invalid rule",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.PasswordAuth.Enabled = true
c.OTP.Enabled = true
c.MFA.Enabled = true
c.MFA.Rule = "invalid"
return c, nil
},
expectedErrors: []string{"mfa"},
},
{
name: "mfa enabled with valid rule",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.PasswordAuth.Enabled = true
c.OTP.Enabled = true
c.MFA.Enabled = true
c.MFA.Rule = "1=1"
return c, nil
},
expectedErrors: []string{},
},
// tokens
{
name: "trigger authToken validations",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.AuthToken.Secret = ""
return c, nil
},
expectedErrors: []string{"authToken"},
},
{
name: "trigger passwordResetToken validations",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.PasswordResetToken.Secret = ""
return c, nil
},
expectedErrors: []string{"passwordResetToken"},
},
{
name: "trigger emailChangeToken validations",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.EmailChangeToken.Secret = ""
return c, nil
},
expectedErrors: []string{"emailChangeToken"},
},
{
name: "trigger verificationToken validations",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.VerificationToken.Secret = ""
return c, nil
},
expectedErrors: []string{"verificationToken"},
},
{
name: "trigger fileToken validations",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.FileToken.Secret = ""
return c, nil
},
expectedErrors: []string{"fileToken"},
},
// templates
{
name: "trigger verificationTemplate validations",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.VerificationTemplate.Body = ""
return c, nil
},
expectedErrors: []string{"verificationTemplate"},
},
{
name: "trigger resetPasswordTemplate validations",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.ResetPasswordTemplate.Body = ""
return c, nil
},
expectedErrors: []string{"resetPasswordTemplate"},
},
{
name: "trigger confirmEmailChangeTemplate validations",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewAuthCollection("new_auth")
c.ConfirmEmailChangeTemplate.Body = ""
return c, nil
},
expectedErrors: []string{"confirmEmailChangeTemplate"},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, err := s.collection(app)
if err != nil {
t.Fatalf("Failed to retrieve test collection: %v", err)
}
result := app.Validate(collection)
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestEmailTemplateValidate(t *testing.T) {
scenarios := []struct {
name string
template core.EmailTemplate
expectedErrors []string
}{
{
"zero value",
core.EmailTemplate{},
[]string{"subject", "body"},
},
{
"non-empty data",
core.EmailTemplate{
Subject: "a",
Body: "b",
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.template.Validate()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestEmailTemplateResolve(t *testing.T) {
template := core.EmailTemplate{
Subject: "test_subject {PARAM3} {PARAM1}-{PARAM2} repeat-{PARAM1}",
Body: "test_body {PARAM3} {PARAM2}-{PARAM1} repeat-{PARAM2}",
}
scenarios := []struct {
name string
placeholders map[string]any
template core.EmailTemplate
expectedSubject string
expectedBody string
}{
{
"no placeholders",
nil,
template,
template.Subject,
template.Body,
},
{
"no matching placeholders",
map[string]any{"{A}": "abc", "{B}": 456},
template,
template.Subject,
template.Body,
},
{
"at least one matching placeholder",
map[string]any{"{PARAM1}": "abc", "{PARAM2}": 456},
template,
"test_subject {PARAM3} abc-456 repeat-abc",
"test_body {PARAM3} 456-abc repeat-456",
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
subject, body := s.template.Resolve(s.placeholders)
if subject != s.expectedSubject {
t.Fatalf("Expected subject\n%v\ngot\n%v", s.expectedSubject, subject)
}
if body != s.expectedBody {
t.Fatalf("Expected body\n%v\ngot\n%v", s.expectedBody, body)
}
})
}
}
func TestTokenConfigValidate(t *testing.T) {
scenarios := []struct {
name string
config core.TokenConfig
expectedErrors []string
}{
{
"zero value",
core.TokenConfig{},
[]string{"secret", "duration"},
},
{
"invalid data",
core.TokenConfig{
Secret: strings.Repeat("a", 29),
Duration: 9,
},
[]string{"secret", "duration"},
},
{
"valid data",
core.TokenConfig{
Secret: strings.Repeat("a", 30),
Duration: 10,
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.config.Validate()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestTokenConfigDurationTime(t *testing.T) {
scenarios := []struct {
config core.TokenConfig
expected time.Duration
}{
{core.TokenConfig{}, 0 * time.Second},
{core.TokenConfig{Duration: 1234}, 1234 * time.Second},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%d", i, s.config.Duration), func(t *testing.T) {
result := s.config.DurationTime()
if result != s.expected {
t.Fatalf("Expected duration %d, got %d", s.expected, result)
}
})
}
}
func TestAuthAlertConfigValidate(t *testing.T) {
scenarios := []struct {
name string
config core.AuthAlertConfig
expectedErrors []string
}{
{
"zero value (disabled)",
core.AuthAlertConfig{},
[]string{"emailTemplate"},
},
{
"zero value (enabled)",
core.AuthAlertConfig{Enabled: true},
[]string{"emailTemplate"},
},
{
"invalid template",
core.AuthAlertConfig{
EmailTemplate: core.EmailTemplate{Body: "", Subject: "b"},
},
[]string{"emailTemplate"},
},
{
"valid data",
core.AuthAlertConfig{
EmailTemplate: core.EmailTemplate{Body: "a", Subject: "b"},
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.config.Validate()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestOTPConfigValidate(t *testing.T) {
scenarios := []struct {
name string
config core.OTPConfig
expectedErrors []string
}{
{
"zero value (disabled)",
core.OTPConfig{},
[]string{"emailTemplate"},
},
{
"zero value (enabled)",
core.OTPConfig{Enabled: true},
[]string{"duration", "length", "emailTemplate"},
},
{
"invalid length (< 3)",
core.OTPConfig{
Enabled: true,
EmailTemplate: core.EmailTemplate{Body: "a", Subject: "b"},
Duration: 100,
Length: 3,
},
[]string{"length"},
},
{
"invalid duration (< 10)",
core.OTPConfig{
Enabled: true,
EmailTemplate: core.EmailTemplate{Body: "a", Subject: "b"},
Duration: 9,
Length: 100,
},
[]string{"duration"},
},
{
"invalid duration (> 86400)",
core.OTPConfig{
Enabled: true,
EmailTemplate: core.EmailTemplate{Body: "a", Subject: "b"},
Duration: 86401,
Length: 100,
},
[]string{"duration"},
},
{
"invalid template (triggering EmailTemplate validations)",
core.OTPConfig{
Enabled: true,
EmailTemplate: core.EmailTemplate{Body: "", Subject: "b"},
Duration: 86400,
Length: 4,
},
[]string{"emailTemplate"},
},
{
"valid data",
core.OTPConfig{
Enabled: true,
EmailTemplate: core.EmailTemplate{Body: "a", Subject: "b"},
Duration: 86400,
Length: 4,
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.config.Validate()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestOTPConfigDurationTime(t *testing.T) {
scenarios := []struct {
config core.OTPConfig
expected time.Duration
}{
{core.OTPConfig{}, 0 * time.Second},
{core.OTPConfig{Duration: 1234}, 1234 * time.Second},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%d", i, s.config.Duration), func(t *testing.T) {
result := s.config.DurationTime()
if result != s.expected {
t.Fatalf("Expected duration %d, got %d", s.expected, result)
}
})
}
}
func TestMFAConfigValidate(t *testing.T) {
scenarios := []struct {
name string
config core.MFAConfig
expectedErrors []string
}{
{
"zero value (disabled)",
core.MFAConfig{},
[]string{},
},
{
"zero value (enabled)",
core.MFAConfig{Enabled: true},
[]string{"duration"},
},
{
"invalid duration (< 10)",
core.MFAConfig{Enabled: true, Duration: 9},
[]string{"duration"},
},
{
"invalid duration (> 86400)",
core.MFAConfig{Enabled: true, Duration: 86401},
[]string{"duration"},
},
{
"valid data",
core.MFAConfig{Enabled: true, Duration: 86400},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.config.Validate()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestMFAConfigDurationTime(t *testing.T) {
scenarios := []struct {
config core.MFAConfig
expected time.Duration
}{
{core.MFAConfig{}, 0 * time.Second},
{core.MFAConfig{Duration: 1234}, 1234 * time.Second},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%d", i, s.config.Duration), func(t *testing.T) {
result := s.config.DurationTime()
if result != s.expected {
t.Fatalf("Expected duration %d, got %d", s.expected, result)
}
})
}
}
func TestPasswordAuthConfigValidate(t *testing.T) {
scenarios := []struct {
name string
config core.PasswordAuthConfig
expectedErrors []string
}{
{
"zero value (disabled)",
core.PasswordAuthConfig{},
[]string{},
},
{
"zero value (enabled)",
core.PasswordAuthConfig{Enabled: true},
[]string{"identityFields"},
},
{
"empty values",
core.PasswordAuthConfig{Enabled: true, IdentityFields: []string{"", ""}},
[]string{"identityFields"},
},
{
"valid data",
core.PasswordAuthConfig{Enabled: true, IdentityFields: []string{"abc"}},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.config.Validate()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestOAuth2ConfigGetProviderConfig(t *testing.T) {
scenarios := []struct {
name string
providerName string
config core.OAuth2Config
expectedExists bool
}{
{
"zero value",
"gitlab",
core.OAuth2Config{},
false,
},
{
"empty config with valid provider",
"gitlab",
core.OAuth2Config{},
false,
},
{
"non-empty config with missing provider",
"gitlab",
core.OAuth2Config{Providers: []core.OAuth2ProviderConfig{{Name: "google"}, {Name: "github"}}},
false,
},
{
"config with existing provider",
"github",
core.OAuth2Config{Providers: []core.OAuth2ProviderConfig{{Name: "google"}, {Name: "github"}}},
true,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
config, exists := s.config.GetProviderConfig(s.providerName)
if exists != s.expectedExists {
t.Fatalf("Expected exists %v, got %v", s.expectedExists, exists)
}
if exists {
if config.Name != s.providerName {
t.Fatalf("Expected config with name %q, got %q", s.providerName, config.Name)
}
} else {
if config.Name != "" {
t.Fatalf("Expected empty config, got %v", config)
}
}
})
}
}
func TestOAuth2ConfigValidate(t *testing.T) {
scenarios := []struct {
name string
config core.OAuth2Config
expectedErrors []string
}{
{
"zero value (disabled)",
core.OAuth2Config{},
[]string{},
},
{
"zero value (enabled)",
core.OAuth2Config{Enabled: true},
[]string{},
},
{
"unknown provider",
core.OAuth2Config{Enabled: true, Providers: []core.OAuth2ProviderConfig{
{Name: "missing", ClientId: "abc", ClientSecret: "456"},
}},
[]string{"providers"},
},
{
"known provider with invalid data",
core.OAuth2Config{Enabled: true, Providers: []core.OAuth2ProviderConfig{
{Name: "gitlab", ClientId: "abc", TokenURL: "!invalid!"},
}},
[]string{"providers"},
},
{
"known provider with valid data",
core.OAuth2Config{Enabled: true, Providers: []core.OAuth2ProviderConfig{
{Name: "gitlab", ClientId: "abc", ClientSecret: "456", TokenURL: "https://example.com"},
}},
[]string{},
},
{
"known provider with valid data (duplicated)",
core.OAuth2Config{Enabled: true, Providers: []core.OAuth2ProviderConfig{
{Name: "gitlab", ClientId: "abc1", ClientSecret: "1", TokenURL: "https://example1.com"},
{Name: "google", ClientId: "abc2", ClientSecret: "2", TokenURL: "https://example2.com"},
{Name: "gitlab", ClientId: "abc3", ClientSecret: "3", TokenURL: "https://example3.com"},
}},
[]string{"providers"},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.config.Validate()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestOAuth2ProviderConfigValidate(t *testing.T) {
scenarios := []struct {
name string
config core.OAuth2ProviderConfig
expectedErrors []string
}{
{
"zero value",
core.OAuth2ProviderConfig{},
[]string{"name", "clientId", "clientSecret"},
},
{
"minimum valid data",
core.OAuth2ProviderConfig{Name: "gitlab", ClientId: "abc", ClientSecret: "456"},
[]string{},
},
{
"non-existing provider",
core.OAuth2ProviderConfig{Name: "missing", ClientId: "abc", ClientSecret: "456"},
[]string{"name"},
},
{
"invalid urls",
core.OAuth2ProviderConfig{
Name: "gitlab",
ClientId: "abc",
ClientSecret: "456",
AuthURL: "!invalid!",
TokenURL: "!invalid!",
UserInfoURL: "!invalid!",
},
[]string{"authURL", "tokenURL", "userInfoURL"},
},
{
"valid urls",
core.OAuth2ProviderConfig{
Name: "gitlab",
ClientId: "abc",
ClientSecret: "456",
AuthURL: "https://example.com/a",
TokenURL: "https://example.com/b",
UserInfoURL: "https://example.com/c",
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.config.Validate()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestOAuth2ProviderConfigInitProvider(t *testing.T) {
scenarios := []struct {
name string
config core.OAuth2ProviderConfig
expectedConfig core.OAuth2ProviderConfig
expectedError bool
}{
{
"empty config",
core.OAuth2ProviderConfig{},
core.OAuth2ProviderConfig{},
true,
},
{
"missing provider",
core.OAuth2ProviderConfig{
Name: "missing",
ClientId: "test_ClientId",
ClientSecret: "test_ClientSecret",
AuthURL: "test_AuthURL",
TokenURL: "test_TokenURL",
UserInfoURL: "test_UserInfoURL",
DisplayName: "test_DisplayName",
PKCE: types.Pointer(true),
},
core.OAuth2ProviderConfig{
Name: "missing",
ClientId: "test_ClientId",
ClientSecret: "test_ClientSecret",
AuthURL: "test_AuthURL",
TokenURL: "test_TokenURL",
UserInfoURL: "test_UserInfoURL",
DisplayName: "test_DisplayName",
PKCE: types.Pointer(true),
},
true,
},
{
"existing provider minimal",
core.OAuth2ProviderConfig{
Name: "gitlab",
},
core.OAuth2ProviderConfig{
Name: "gitlab",
ClientId: "",
ClientSecret: "",
AuthURL: "https://gitlab.com/oauth/authorize",
TokenURL: "https://gitlab.com/oauth/token",
UserInfoURL: "https://gitlab.com/api/v4/user",
DisplayName: "GitLab",
PKCE: types.Pointer(true),
},
false,
},
{
"existing provider with all fields",
core.OAuth2ProviderConfig{
Name: "gitlab",
ClientId: "test_ClientId",
ClientSecret: "test_ClientSecret",
AuthURL: "test_AuthURL",
TokenURL: "test_TokenURL",
UserInfoURL: "test_UserInfoURL",
DisplayName: "test_DisplayName",
PKCE: types.Pointer(true),
Extra: map[string]any{"a": 1},
},
core.OAuth2ProviderConfig{
Name: "gitlab",
ClientId: "test_ClientId",
ClientSecret: "test_ClientSecret",
AuthURL: "test_AuthURL",
TokenURL: "test_TokenURL",
UserInfoURL: "test_UserInfoURL",
DisplayName: "test_DisplayName",
PKCE: types.Pointer(true),
Extra: map[string]any{"a": 1},
},
false,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
provider, err := s.config.InitProvider()
hasErr := err != nil
if hasErr != s.expectedError {
t.Fatalf("Expected hasErr %v, got %v", s.expectedError, hasErr)
}
if hasErr {
if provider != nil {
t.Fatalf("Expected nil provider, got %v", provider)
}
return
}
factory, ok := auth.Providers[s.expectedConfig.Name]
if !ok {
t.Fatalf("Missing factory for provider %q", s.expectedConfig.Name)
}
expectedType := fmt.Sprintf("%T", factory())
providerType := fmt.Sprintf("%T", provider)
if expectedType != providerType {
t.Fatalf("Expected provider instanceof %q, got %q", expectedType, providerType)
}
if provider.ClientId() != s.expectedConfig.ClientId {
t.Fatalf("Expected ClientId %q, got %q", s.expectedConfig.ClientId, provider.ClientId())
}
if provider.ClientSecret() != s.expectedConfig.ClientSecret {
t.Fatalf("Expected ClientSecret %q, got %q", s.expectedConfig.ClientSecret, provider.ClientSecret())
}
if provider.AuthURL() != s.expectedConfig.AuthURL {
t.Fatalf("Expected AuthURL %q, got %q", s.expectedConfig.AuthURL, provider.AuthURL())
}
if provider.UserInfoURL() != s.expectedConfig.UserInfoURL {
t.Fatalf("Expected UserInfoURL %q, got %q", s.expectedConfig.UserInfoURL, provider.UserInfoURL())
}
if provider.TokenURL() != s.expectedConfig.TokenURL {
t.Fatalf("Expected TokenURL %q, got %q", s.expectedConfig.TokenURL, provider.TokenURL())
}
if provider.DisplayName() != s.expectedConfig.DisplayName {
t.Fatalf("Expected DisplayName %q, got %q", s.expectedConfig.DisplayName, provider.DisplayName())
}
if provider.PKCE() != *s.expectedConfig.PKCE {
t.Fatalf("Expected PKCE %v, got %v", *s.expectedConfig.PKCE, provider.PKCE())
}
rawMeta, _ := json.Marshal(provider.Extra())
expectedMeta, _ := json.Marshal(s.expectedConfig.Extra)
if !bytes.Equal(rawMeta, expectedMeta) {
t.Fatalf("Expected PKCE %v, got %v", *s.expectedConfig.PKCE, provider.PKCE())
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_autodate.go | core/field_autodate.go | package core
import (
"context"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
Fields[FieldTypeAutodate] = func() Field {
return &AutodateField{}
}
}
const FieldTypeAutodate = "autodate"
// used to keep track of the last set autodate value
const autodateLastKnownPrefix = internalCustomFieldKeyPrefix + "_last_autodate_"
var (
_ Field = (*AutodateField)(nil)
_ SetterFinder = (*AutodateField)(nil)
_ RecordInterceptor = (*AutodateField)(nil)
)
// AutodateField defines an "autodate" type field, aka.
// field which datetime value could be auto set on record create/update.
//
// This field is usually used for defining timestamp fields like "created" and "updated".
//
// Requires either both or at least one of the OnCreate or OnUpdate options to be set.
type AutodateField struct {
// Name (required) is the unique name of the field.
Name string `form:"name" json:"name"`
// Id is the unique stable field identifier.
//
// It is automatically generated from the name when adding to a collection FieldsList.
Id string `form:"id" json:"id"`
// System prevents the renaming and removal of the field.
System bool `form:"system" json:"system"`
// Hidden hides the field from the API response.
Hidden bool `form:"hidden" json:"hidden"`
// Presentable hints the Dashboard UI to use the underlying
// field record value in the relation preview label.
Presentable bool `form:"presentable" json:"presentable"`
// ---
// OnCreate auto sets the current datetime as field value on record create.
OnCreate bool `form:"onCreate" json:"onCreate"`
// OnUpdate auto sets the current datetime as field value on record update.
OnUpdate bool `form:"onUpdate" json:"onUpdate"`
}
// Type implements [Field.Type] interface method.
func (f *AutodateField) Type() string {
return FieldTypeAutodate
}
// GetId implements [Field.GetId] interface method.
func (f *AutodateField) GetId() string {
return f.Id
}
// SetId implements [Field.SetId] interface method.
func (f *AutodateField) SetId(id string) {
f.Id = id
}
// GetName implements [Field.GetName] interface method.
func (f *AutodateField) GetName() string {
return f.Name
}
// SetName implements [Field.SetName] interface method.
func (f *AutodateField) SetName(name string) {
f.Name = name
}
// GetSystem implements [Field.GetSystem] interface method.
func (f *AutodateField) GetSystem() bool {
return f.System
}
// SetSystem implements [Field.SetSystem] interface method.
func (f *AutodateField) SetSystem(system bool) {
f.System = system
}
// GetHidden implements [Field.GetHidden] interface method.
func (f *AutodateField) GetHidden() bool {
return f.Hidden
}
// SetHidden implements [Field.SetHidden] interface method.
func (f *AutodateField) SetHidden(hidden bool) {
f.Hidden = hidden
}
// ColumnType implements [Field.ColumnType] interface method.
func (f *AutodateField) ColumnType(app App) string {
return "TEXT DEFAULT '' NOT NULL" // note: sqlite doesn't allow adding new columns with non-constant defaults
}
// PrepareValue implements [Field.PrepareValue] interface method.
func (f *AutodateField) PrepareValue(record *Record, raw any) (any, error) {
val, _ := types.ParseDateTime(raw)
return val, nil
}
// ValidateValue implements [Field.ValidateValue] interface method.
func (f *AutodateField) ValidateValue(ctx context.Context, app App, record *Record) error {
return nil
}
// ValidateSettings implements [Field.ValidateSettings] interface method.
func (f *AutodateField) ValidateSettings(ctx context.Context, app App, collection *Collection) error {
oldOnCreate := f.OnCreate
oldOnUpdate := f.OnUpdate
oldCollection, _ := app.FindCollectionByNameOrId(collection.Id)
if oldCollection != nil {
oldField, ok := oldCollection.Fields.GetById(f.Id).(*AutodateField)
if ok && oldField != nil {
oldOnCreate = oldField.OnCreate
oldOnUpdate = oldField.OnUpdate
}
}
return validation.ValidateStruct(f,
validation.Field(&f.Id, validation.By(DefaultFieldIdValidationRule)),
validation.Field(&f.Name, validation.By(DefaultFieldNameValidationRule)),
validation.Field(
&f.OnCreate,
validation.When(f.System, validation.By(validators.Equal(oldOnCreate))),
validation.Required.Error("either onCreate or onUpdate must be enabled").When(!f.OnUpdate),
),
validation.Field(
&f.OnUpdate,
validation.When(f.System, validation.By(validators.Equal(oldOnUpdate))),
validation.Required.Error("either onCreate or onUpdate must be enabled").When(!f.OnCreate),
),
)
}
// FindSetter implements the [SetterFinder] interface.
func (f *AutodateField) FindSetter(key string) SetterFunc {
switch key {
case f.Name:
// return noopSetter to disallow updating the value with record.Set()
return noopSetter
default:
return nil
}
}
// Intercept implements the [RecordInterceptor] interface.
func (f *AutodateField) Intercept(
ctx context.Context,
app App,
record *Record,
actionName string,
actionFunc func() error,
) error {
switch actionName {
case InterceptorActionCreateExecute:
// ignore if a date different from the old one was manually set with SetRaw
if f.OnCreate && record.GetDateTime(f.Name).Equal(f.getLastKnownValue(record)) {
now := types.NowDateTime()
record.SetRaw(f.Name, now)
record.SetRaw(autodateLastKnownPrefix+f.Name, now) // eagerly set so that it can be renewed on resave after failure
}
if err := actionFunc(); err != nil {
return err
}
record.SetRaw(autodateLastKnownPrefix+f.Name, record.GetRaw(f.Name))
return nil
case InterceptorActionUpdateExecute:
// ignore if a date different from the old one was manually set with SetRaw
if f.OnUpdate && record.GetDateTime(f.Name).Equal(f.getLastKnownValue(record)) {
now := types.NowDateTime()
record.SetRaw(f.Name, now)
record.SetRaw(autodateLastKnownPrefix+f.Name, now) // eagerly set so that it can be renewed on resave after failure
}
if err := actionFunc(); err != nil {
return err
}
record.SetRaw(autodateLastKnownPrefix+f.Name, record.GetRaw(f.Name))
return nil
default:
return actionFunc()
}
}
func (f *AutodateField) getLastKnownValue(record *Record) types.DateTime {
v := record.GetDateTime(autodateLastKnownPrefix + f.Name)
if !v.IsZero() {
return v
}
return record.Original().GetDateTime(f.Name)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/app.go | core/app.go | // Package core is the backbone of PocketBase.
//
// It defines the main PocketBase App interface and its base implementation.
package core
import (
"context"
"log/slog"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/cron"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/mailer"
"github.com/pocketbase/pocketbase/tools/store"
"github.com/pocketbase/pocketbase/tools/subscriptions"
)
// App defines the main PocketBase app interface.
//
// Note that the interface is not intended to be implemented manually by users
// and instead they should use core.BaseApp (either directly or as embedded field in a custom struct).
//
// This interface exists to make testing easier and to allow users to
// create common and pluggable helpers and methods that doesn't rely
// on a specific wrapped app struct (hence the large interface size).
type App interface {
// UnsafeWithoutHooks returns a shallow copy of the current app WITHOUT any registered hooks.
//
// NB! Note that using the returned app instance may cause data integrity errors
// since the Record validations and data normalizations (including files uploads)
// rely on the app hooks to work.
UnsafeWithoutHooks() App
// Logger returns the default app logger.
//
// If the application is not bootstrapped yet, fallbacks to slog.Default().
Logger() *slog.Logger
// IsBootstrapped checks if the application was initialized
// (aka. whether Bootstrap() was called).
IsBootstrapped() bool
// IsTransactional checks if the current app instance is part of a transaction.
IsTransactional() bool
// TxInfo returns the transaction associated with the current app instance (if any).
//
// Could be used if you want to execute indirectly a function after
// the related app transaction completes using `app.TxInfo().OnAfterFunc(callback)`.
TxInfo() *TxAppInfo
// Bootstrap initializes the application
// (aka. create data dir, open db connections, load settings, etc.).
//
// It will call ResetBootstrapState() if the application was already bootstrapped.
Bootstrap() error
// ResetBootstrapState releases the initialized core app resources
// (closing db connections, stopping cron ticker, etc.).
ResetBootstrapState() error
// DataDir returns the app data directory path.
DataDir() string
// EncryptionEnv returns the name of the app secret env key
// (currently used primarily for optional settings encryption but this may change in the future).
EncryptionEnv() string
// IsDev returns whether the app is in dev mode.
//
// When enabled logs, executed sql statements, etc. are printed to the stderr.
IsDev() bool
// Settings returns the loaded app settings.
Settings() *Settings
// Store returns the app runtime store.
Store() *store.Store[string, any]
// Cron returns the app cron instance.
Cron() *cron.Cron
// SubscriptionsBroker returns the app realtime subscriptions broker instance.
SubscriptionsBroker() *subscriptions.Broker
// NewMailClient creates and returns a new SMTP or Sendmail client
// based on the current app settings.
NewMailClient() mailer.Mailer
// NewFilesystem creates a new local or S3 filesystem instance
// for managing regular app files (ex. record uploads)
// based on the current app settings.
//
// NB! Make sure to call Close() on the returned result
// after you are done working with it.
NewFilesystem() (*filesystem.System, error)
// NewBackupsFilesystem creates a new local or S3 filesystem instance
// for managing app backups based on the current app settings.
//
// NB! Make sure to call Close() on the returned result
// after you are done working with it.
NewBackupsFilesystem() (*filesystem.System, error)
// ReloadSettings reinitializes and reloads the stored application settings.
ReloadSettings() error
// CreateBackup creates a new backup of the current app pb_data directory.
//
// Backups can be stored on S3 if it is configured in app.Settings().Backups.
//
// Please refer to the godoc of the specific core.App implementation
// for details on the backup procedures.
CreateBackup(ctx context.Context, name string) error
// RestoreBackup restores the backup with the specified name and restarts
// the current running application process.
//
// The safely perform the restore it is recommended to have free disk space
// for at least 2x the size of the restored pb_data backup.
//
// Please refer to the godoc of the specific core.App implementation
// for details on the restore procedures.
//
// NB! This feature is experimental and currently is expected to work only on UNIX based systems.
RestoreBackup(ctx context.Context, name string) error
// Restart restarts (aka. replaces) the current running application process.
//
// NB! It relies on execve which is supported only on UNIX based systems.
Restart() error
// RunSystemMigrations applies all new migrations registered in the [core.SystemMigrations] list.
RunSystemMigrations() error
// RunAppMigrations applies all new migrations registered in the [core.AppMigrations] list.
RunAppMigrations() error
// RunAllMigrations applies all system and app migrations
// (aka. from both [core.SystemMigrations] and [core.AppMigrations]).
RunAllMigrations() error
// ---------------------------------------------------------------
// DB methods
// ---------------------------------------------------------------
// DB returns the default app data.db builder instance.
//
// To minimize SQLITE_BUSY errors, it automatically routes the
// SELECT queries to the underlying concurrent db pool and everything else
// to the nonconcurrent one.
//
// For more finer control over the used connections pools you can
// call directly ConcurrentDB() or NonconcurrentDB().
DB() dbx.Builder
// ConcurrentDB returns the concurrent app data.db builder instance.
//
// This method is used mainly internally for executing db read
// operations in a concurrent/non-blocking manner.
//
// Most users should use simply DB() as it will automatically
// route the query execution to ConcurrentDB() or NonconcurrentDB().
//
// In a transaction the ConcurrentDB() and NonconcurrentDB() refer to the same *dbx.TX instance.
ConcurrentDB() dbx.Builder
// NonconcurrentDB returns the nonconcurrent app data.db builder instance.
//
// The returned db instance is limited only to a single open connection,
// meaning that it can process only 1 db operation at a time (other queries queue up).
//
// This method is used mainly internally and in the tests to execute write
// (save/delete) db operations as it helps with minimizing the SQLITE_BUSY errors.
//
// Most users should use simply DB() as it will automatically
// route the query execution to ConcurrentDB() or NonconcurrentDB().
//
// In a transaction the ConcurrentDB() and NonconcurrentDB() refer to the same *dbx.TX instance.
NonconcurrentDB() dbx.Builder
// AuxDB returns the app auxiliary.db builder instance.
//
// To minimize SQLITE_BUSY errors, it automatically routes the
// SELECT queries to the underlying concurrent db pool and everything else
// to the nonconcurrent one.
//
// For more finer control over the used connections pools you can
// call directly AuxConcurrentDB() or AuxNonconcurrentDB().
AuxDB() dbx.Builder
// AuxConcurrentDB returns the concurrent app auxiliary.db builder instance.
//
// This method is used mainly internally for executing db read
// operations in a concurrent/non-blocking manner.
//
// Most users should use simply AuxDB() as it will automatically
// route the query execution to AuxConcurrentDB() or AuxNonconcurrentDB().
//
// In a transaction the AuxConcurrentDB() and AuxNonconcurrentDB() refer to the same *dbx.TX instance.
AuxConcurrentDB() dbx.Builder
// AuxNonconcurrentDB returns the nonconcurrent app auxiliary.db builder instance.
//
// The returned db instance is limited only to a single open connection,
// meaning that it can process only 1 db operation at a time (other queries queue up).
//
// This method is used mainly internally and in the tests to execute write
// (save/delete) db operations as it helps with minimizing the SQLITE_BUSY errors.
//
// Most users should use simply AuxDB() as it will automatically
// route the query execution to AuxConcurrentDB() or AuxNonconcurrentDB().
//
// In a transaction the AuxConcurrentDB() and AuxNonconcurrentDB() refer to the same *dbx.TX instance.
AuxNonconcurrentDB() dbx.Builder
// HasTable checks if a table (or view) with the provided name exists (case insensitive).
// in the data.db.
HasTable(tableName string) bool
// AuxHasTable checks if a table (or view) with the provided name exists (case insensitive)
// in the auxiliary.db.
AuxHasTable(tableName string) bool
// TableColumns returns all column names of a single table by its name.
TableColumns(tableName string) ([]string, error)
// TableInfo returns the "table_info" pragma result for the specified table.
TableInfo(tableName string) ([]*TableInfoRow, error)
// TableIndexes returns a name grouped map with all non empty index of the specified table.
//
// Note: This method doesn't return an error on nonexisting table.
TableIndexes(tableName string) (map[string]string, error)
// DeleteTable drops the specified table.
//
// This method is a no-op if a table with the provided name doesn't exist.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "tableName" argument must come only from trusted input!
DeleteTable(tableName string) error
// DeleteView drops the specified view name.
//
// This method is a no-op if a view with the provided name doesn't exist.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "name" argument must come only from trusted input!
DeleteView(name string) error
// SaveView creates (or updates already existing) persistent SQL view.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "selectQuery" argument must come only from trusted input!
SaveView(name string, selectQuery string) error
// CreateViewFields creates a new FieldsList from the provided select query.
//
// There are some caveats:
// - The select query must have an "id" column.
// - Wildcard ("*") columns are not supported to avoid accidentally leaking sensitive data.
CreateViewFields(selectQuery string) (FieldsList, error)
// FindRecordByViewFile returns the original Record of the provided view collection file.
FindRecordByViewFile(viewCollectionModelOrIdentifier any, fileFieldName string, filename string) (*Record, error)
// Vacuum executes VACUUM on the data.db in order to reclaim unused data db disk space.
Vacuum() error
// AuxVacuum executes VACUUM on the auxiliary.db in order to reclaim unused auxiliary db disk space.
AuxVacuum() error
// ---------------------------------------------------------------
// ModelQuery creates a new preconfigured select data.db query with preset
// SELECT, FROM and other common fields based on the provided model.
ModelQuery(model Model) *dbx.SelectQuery
// AuxModelQuery creates a new preconfigured select auxiliary.db query with preset
// SELECT, FROM and other common fields based on the provided model.
AuxModelQuery(model Model) *dbx.SelectQuery
// Delete deletes the specified model from the regular app database.
Delete(model Model) error
// Delete deletes the specified model from the regular app database
// (the context could be used to limit the query execution).
DeleteWithContext(ctx context.Context, model Model) error
// AuxDelete deletes the specified model from the auxiliary database.
AuxDelete(model Model) error
// AuxDeleteWithContext deletes the specified model from the auxiliary database
// (the context could be used to limit the query execution).
AuxDeleteWithContext(ctx context.Context, model Model) error
// Save validates and saves the specified model into the regular app database.
//
// If you don't want to run validations, use [App.SaveNoValidate()].
Save(model Model) error
// SaveWithContext is the same as [App.Save()] but allows specifying a context to limit the db execution.
//
// If you don't want to run validations, use [App.SaveNoValidateWithContext()].
SaveWithContext(ctx context.Context, model Model) error
// SaveNoValidate saves the specified model into the regular app database without performing validations.
//
// If you want to also run validations before persisting, use [App.Save()].
SaveNoValidate(model Model) error
// SaveNoValidateWithContext is the same as [App.SaveNoValidate()]
// but allows specifying a context to limit the db execution.
//
// If you want to also run validations before persisting, use [App.SaveWithContext()].
SaveNoValidateWithContext(ctx context.Context, model Model) error
// AuxSave validates and saves the specified model into the auxiliary app database.
//
// If you don't want to run validations, use [App.AuxSaveNoValidate()].
AuxSave(model Model) error
// AuxSaveWithContext is the same as [App.AuxSave()] but allows specifying a context to limit the db execution.
//
// If you don't want to run validations, use [App.AuxSaveNoValidateWithContext()].
AuxSaveWithContext(ctx context.Context, model Model) error
// AuxSaveNoValidate saves the specified model into the auxiliary app database without performing validations.
//
// If you want to also run validations before persisting, use [App.AuxSave()].
AuxSaveNoValidate(model Model) error
// AuxSaveNoValidateWithContext is the same as [App.AuxSaveNoValidate()]
// but allows specifying a context to limit the db execution.
//
// If you want to also run validations before persisting, use [App.AuxSaveWithContext()].
AuxSaveNoValidateWithContext(ctx context.Context, model Model) error
// Validate triggers the OnModelValidate hook for the specified model.
Validate(model Model) error
// ValidateWithContext is the same as Validate but allows specifying the ModelEvent context.
ValidateWithContext(ctx context.Context, model Model) error
// RunInTransaction wraps fn into a transaction for the regular app database.
//
// It is safe to nest RunInTransaction calls as long as you use the callback's txApp.
RunInTransaction(fn func(txApp App) error) error
// AuxRunInTransaction wraps fn into a transaction for the auxiliary app database.
//
// It is safe to nest RunInTransaction calls as long as you use the callback's txApp.
AuxRunInTransaction(fn func(txApp App) error) error
// ---------------------------------------------------------------
// LogQuery returns a new Log select query.
LogQuery() *dbx.SelectQuery
// FindLogById finds a single Log entry by its id.
FindLogById(id string) (*Log, error)
// LogsStatsItem returns hourly grouped logs statistics.
LogsStats(expr dbx.Expression) ([]*LogsStatsItem, error)
// DeleteOldLogs delete all logs that are created before createdBefore.
DeleteOldLogs(createdBefore time.Time) error
// ---------------------------------------------------------------
// CollectionQuery returns a new Collection select query.
CollectionQuery() *dbx.SelectQuery
// FindCollections finds all collections by the given type(s).
//
// If collectionTypes is not set, it returns all collections.
//
// Example:
//
// app.FindAllCollections() // all collections
// app.FindAllCollections("auth", "view") // only auth and view collections
FindAllCollections(collectionTypes ...string) ([]*Collection, error)
// ReloadCachedCollections fetches all collections and caches them into the app store.
ReloadCachedCollections() error
// FindCollectionByNameOrId finds a single collection by its name (case insensitive) or id.s
FindCollectionByNameOrId(nameOrId string) (*Collection, error)
// FindCachedCollectionByNameOrId is similar to [App.FindCollectionByNameOrId]
// but retrieves the Collection from the app cache instead of making a db call.
//
// NB! This method is suitable for read-only Collection operations.
//
// Returns [sql.ErrNoRows] if no Collection is found for consistency
// with the [App.FindCollectionByNameOrId] method.
//
// If you plan making changes to the returned Collection model,
// use [App.FindCollectionByNameOrId] instead.
//
// Caveats:
//
// - The returned Collection should be used only for read-only operations.
// Avoid directly modifying the returned cached Collection as it will affect
// the global cached value even if you don't persist the changes in the database!
// - If you are updating a Collection in a transaction and then call this method before commit,
// it'll return the cached Collection state and not the one from the uncommitted transaction.
// - The cache is automatically updated on collections db change (create/update/delete).
// To manually reload the cache you can call [App.ReloadCachedCollections]
FindCachedCollectionByNameOrId(nameOrId string) (*Collection, error)
// FindCollectionReferences returns information for all relation
// fields referencing the provided collection.
//
// If the provided collection has reference to itself then it will be
// also included in the result. To exclude it, pass the collection id
// as the excludeIds argument.
FindCollectionReferences(collection *Collection, excludeIds ...string) (map[*Collection][]Field, error)
// FindCachedCollectionReferences is similar to [App.FindCollectionReferences]
// but retrieves the Collection from the app cache instead of making a db call.
//
// NB! This method is suitable for read-only Collection operations.
//
// If you plan making changes to the returned Collection model,
// use [App.FindCollectionReferences] instead.
//
// Caveats:
//
// - The returned Collection should be used only for read-only operations.
// Avoid directly modifying the returned cached Collection as it will affect
// the global cached value even if you don't persist the changes in the database!
// - If you are updating a Collection in a transaction and then call this method before commit,
// it'll return the cached Collection state and not the one from the uncommitted transaction.
// - The cache is automatically updated on collections db change (create/update/delete).
// To manually reload the cache you can call [App.ReloadCachedCollections].
FindCachedCollectionReferences(collection *Collection, excludeIds ...string) (map[*Collection][]Field, error)
// IsCollectionNameUnique checks that there is no existing collection
// with the provided name (case insensitive!).
//
// Note: case insensitive check because the name is used also as
// table name for the records.
IsCollectionNameUnique(name string, excludeIds ...string) bool
// TruncateCollection deletes all records associated with the provided collection.
//
// The truncate operation is executed in a single transaction,
// aka. either everything is deleted or none.
//
// Note that this method will also trigger the records related
// cascade and file delete actions.
TruncateCollection(collection *Collection) error
// ImportCollections imports the provided collections data in a single transaction.
//
// For existing matching collections, the imported data is unmarshaled on top of the existing model.
//
// NB! If deleteMissing is true, ALL NON-SYSTEM COLLECTIONS AND SCHEMA FIELDS,
// that are not present in the imported configuration, WILL BE DELETED
// (this includes their related records data).
ImportCollections(toImport []map[string]any, deleteMissing bool) error
// ImportCollectionsByMarshaledJSON is the same as [ImportCollections]
// but accept marshaled json array as import data (usually used for the autogenerated snapshots).
ImportCollectionsByMarshaledJSON(rawSliceOfMaps []byte, deleteMissing bool) error
// SyncRecordTableSchema compares the two provided collections
// and applies the necessary related record table changes.
//
// If oldCollection is null, then only newCollection is used to create the record table.
//
// This method is automatically invoked as part of a collection create/update/delete operation.
SyncRecordTableSchema(newCollection *Collection, oldCollection *Collection) error
// ---------------------------------------------------------------
// FindAllExternalAuthsByRecord returns all ExternalAuth models
// linked to the provided auth record.
FindAllExternalAuthsByRecord(authRecord *Record) ([]*ExternalAuth, error)
// FindAllExternalAuthsByCollection returns all ExternalAuth models
// linked to the provided auth collection.
FindAllExternalAuthsByCollection(collection *Collection) ([]*ExternalAuth, error)
// FindFirstExternalAuthByExpr returns the first available (the most recent created)
// ExternalAuth model that satisfies the non-nil expression.
FindFirstExternalAuthByExpr(expr dbx.Expression) (*ExternalAuth, error)
// ---------------------------------------------------------------
// FindAllMFAsByRecord returns all MFA models linked to the provided auth record.
FindAllMFAsByRecord(authRecord *Record) ([]*MFA, error)
// FindAllMFAsByCollection returns all MFA models linked to the provided collection.
FindAllMFAsByCollection(collection *Collection) ([]*MFA, error)
// FindMFAById returns a single MFA model by its id.
FindMFAById(id string) (*MFA, error)
// DeleteAllMFAsByRecord deletes all MFA models associated with the provided record.
//
// Returns a combined error with the failed deletes.
DeleteAllMFAsByRecord(authRecord *Record) error
// DeleteExpiredMFAs deletes the expired MFAs for all auth collections.
DeleteExpiredMFAs() error
// ---------------------------------------------------------------
// FindAllOTPsByRecord returns all OTP models linked to the provided auth record.
FindAllOTPsByRecord(authRecord *Record) ([]*OTP, error)
// FindAllOTPsByCollection returns all OTP models linked to the provided collection.
FindAllOTPsByCollection(collection *Collection) ([]*OTP, error)
// FindOTPById returns a single OTP model by its id.
FindOTPById(id string) (*OTP, error)
// DeleteAllOTPsByRecord deletes all OTP models associated with the provided record.
//
// Returns a combined error with the failed deletes.
DeleteAllOTPsByRecord(authRecord *Record) error
// DeleteExpiredOTPs deletes the expired OTPs for all auth collections.
DeleteExpiredOTPs() error
// ---------------------------------------------------------------
// FindAllAuthOriginsByRecord returns all AuthOrigin models linked to the provided auth record (in DESC order).
FindAllAuthOriginsByRecord(authRecord *Record) ([]*AuthOrigin, error)
// FindAllAuthOriginsByCollection returns all AuthOrigin models linked to the provided collection (in DESC order).
FindAllAuthOriginsByCollection(collection *Collection) ([]*AuthOrigin, error)
// FindAuthOriginById returns a single AuthOrigin model by its id.
FindAuthOriginById(id string) (*AuthOrigin, error)
// FindAuthOriginByRecordAndFingerprint returns a single AuthOrigin model
// by its authRecord relation and fingerprint.
FindAuthOriginByRecordAndFingerprint(authRecord *Record, fingerprint string) (*AuthOrigin, error)
// DeleteAllAuthOriginsByRecord deletes all AuthOrigin models associated with the provided record.
//
// Returns a combined error with the failed deletes.
DeleteAllAuthOriginsByRecord(authRecord *Record) error
// ---------------------------------------------------------------
// RecordQuery returns a new Record select query from a collection model, id or name.
//
// In case a collection id or name is provided and that collection doesn't
// actually exists, the generated query will be created with a cancelled context
// and will fail once an executor (Row(), One(), All(), etc.) is called.
RecordQuery(collectionModelOrIdentifier any) *dbx.SelectQuery
// FindRecordById finds the Record model by its id.
FindRecordById(collectionModelOrIdentifier any, recordId string, optFilters ...func(q *dbx.SelectQuery) error) (*Record, error)
// FindRecordsByIds finds all records by the specified ids.
// If no records are found, returns an empty slice.
FindRecordsByIds(collectionModelOrIdentifier any, recordIds []string, optFilters ...func(q *dbx.SelectQuery) error) ([]*Record, error)
// FindAllRecords finds all records matching specified db expressions.
//
// Returns all collection records if no expression is provided.
//
// Returns an empty slice if no records are found.
//
// Example:
//
// // no extra expressions
// app.FindAllRecords("example")
//
// // with extra expressions
// expr1 := dbx.HashExp{"email": "test@example.com"}
// expr2 := dbx.NewExp("LOWER(username) = {:username}", dbx.Params{"username": "test"})
// app.FindAllRecords("example", expr1, expr2)
FindAllRecords(collectionModelOrIdentifier any, exprs ...dbx.Expression) ([]*Record, error)
// FindFirstRecordByData returns the first found record matching
// the provided key-value pair.
FindFirstRecordByData(collectionModelOrIdentifier any, key string, value any) (*Record, error)
// FindRecordsByFilter returns limit number of records matching the
// provided string filter.
//
// NB! Use the last "params" argument to bind untrusted user variables!
//
// The filter argument is optional and can be empty string to target
// all available records.
//
// The sort argument is optional and can be empty string OR the same format
// used in the web APIs, ex. "-created,title".
//
// If the limit argument is <= 0, no limit is applied to the query and
// all matching records are returned.
//
// Returns an empty slice if no records are found.
//
// Example:
//
// app.FindRecordsByFilter(
// "posts",
// "title ~ {:title} && visible = {:visible}",
// "-created",
// 10,
// 0,
// dbx.Params{"title": "lorem ipsum", "visible": true}
// )
FindRecordsByFilter(
collectionModelOrIdentifier any,
filter string,
sort string,
limit int,
offset int,
params ...dbx.Params,
) ([]*Record, error)
// FindFirstRecordByFilter returns the first available record matching the provided filter (if any).
//
// NB! Use the last params argument to bind untrusted user variables!
//
// Returns sql.ErrNoRows if no record is found.
//
// Example:
//
// app.FindFirstRecordByFilter("posts", "")
// app.FindFirstRecordByFilter("posts", "slug={:slug} && status='public'", dbx.Params{"slug": "test"})
FindFirstRecordByFilter(
collectionModelOrIdentifier any,
filter string,
params ...dbx.Params,
) (*Record, error)
// CountRecords returns the total number of records in a collection.
CountRecords(collectionModelOrIdentifier any, exprs ...dbx.Expression) (int64, error)
// FindAuthRecordByToken finds the auth record associated with the provided JWT
// (auth, file, verifyEmail, changeEmail, passwordReset types).
//
// Optionally specify a list of validTypes to check tokens only from those types.
//
// Returns an error if the JWT is invalid, expired or not associated to an auth collection record.
FindAuthRecordByToken(token string, validTypes ...string) (*Record, error)
// FindAuthRecordByEmail finds the auth record associated with the provided email.
//
// Returns an error if it is not an auth collection or the record is not found.
FindAuthRecordByEmail(collectionModelOrIdentifier any, email string) (*Record, error)
// CanAccessRecord checks if a record is allowed to be accessed by the
// specified requestInfo and accessRule.
//
// Rule and db checks are ignored in case requestInfo.Auth is a superuser.
//
// The returned error indicate that something unexpected happened during
// the check (eg. invalid rule or db query error).
//
// The method always return false on invalid rule or db query error.
//
// Example:
//
// requestInfo, _ := e.RequestInfo()
// record, _ := app.FindRecordById("example", "RECORD_ID")
// rule := types.Pointer("@request.auth.id != '' || status = 'public'")
// // ... or use one of the record collection's rule, eg. record.Collection().ViewRule
//
// if ok, _ := app.CanAccessRecord(record, requestInfo, rule); ok { ... }
CanAccessRecord(record *Record, requestInfo *RequestInfo, accessRule *string) (bool, error)
// ExpandRecord expands the relations of a single Record model.
//
// If optFetchFunc is not set, then a default function will be used
// that returns all relation records.
//
// Returns a map with the failed expand parameters and their errors.
ExpandRecord(record *Record, expands []string, optFetchFunc ExpandFetchFunc) map[string]error
// ExpandRecords expands the relations of the provided Record models list.
//
// If optFetchFunc is not set, then a default function will be used
// that returns all relation records.
//
// Returns a map with the failed expand parameters and their errors.
ExpandRecords(records []*Record, expands []string, optFetchFunc ExpandFetchFunc) map[string]error
// ---------------------------------------------------------------
// App event hooks
// ---------------------------------------------------------------
// OnBootstrap hook is triggered when initializing the main application
// resources (db, app settings, etc).
OnBootstrap() *hook.Hook[*BootstrapEvent]
// OnServe hook is triggered when the app web server is started
// (after starting the TCP listener but before initializing the blocking serve task),
// allowing you to adjust its options and attach new routes or middlewares.
OnServe() *hook.Hook[*ServeEvent]
// OnTerminate hook is triggered when the app is in the process
// of being terminated (ex. on SIGTERM signal).
//
// Note that the app could be terminated abruptly without awaiting the hook completion.
OnTerminate() *hook.Hook[*TerminateEvent]
// OnBackupCreate hook is triggered on each [App.CreateBackup] call.
OnBackupCreate() *hook.Hook[*BackupEvent]
// OnBackupRestore hook is triggered before app backup restore (aka. [App.RestoreBackup] call).
//
// Note that by default on success the application is restarted and the after state of the hook is ignored.
OnBackupRestore() *hook.Hook[*BackupEvent]
// ---------------------------------------------------------------
// DB models event hooks
// ---------------------------------------------------------------
// OnModelValidate is triggered every time when a model is being validated
// (e.g. triggered by App.Validate() or App.Save()).
//
// For convenience, if you want to listen to only the Record models
// events without doing manual type assertion, you can attach to the OnRecord* proxy hooks.
//
// If the optional "tags" list (Collection id/name, Model table name, etc.) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnModelValidate(tags ...string) *hook.TaggedHook[*ModelEvent]
// ---------------------------------------------------------------
// OnModelCreate is triggered every time when a new model is being created
// (e.g. triggered by App.Save()).
//
// Operations BEFORE the e.Next() execute before the model validation
// and the INSERT DB statement.
//
// Operations AFTER the e.Next() execute after the model validation
// and the INSERT DB statement.
//
// Note that successful execution doesn't guarantee that the model
// is persisted in the database since its wrapping transaction may
// not have been committed yet.
// If you want to listen to only the actual persisted events, you can
// bind to [OnModelAfterCreateSuccess] or [OnModelAfterCreateError] hooks.
//
// For convenience, if you want to listen to only the Record models
// events without doing manual type assertion, you can attach to the OnRecord* proxy hooks.
//
// If the optional "tags" list (Collection id/name, Model table name, etc.) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnModelCreate(tags ...string) *hook.TaggedHook[*ModelEvent]
// OnModelCreateExecute is triggered after successful Model validation
// and right before the model INSERT DB statement execution.
//
// Usually it is triggered as part of the App.Save() in the following firing order:
// OnModelCreate {
// -> OnModelValidate (skipped with App.SaveNoValidate())
// -> OnModelCreateExecute
// }
//
// Note that successful execution doesn't guarantee that the model
// is persisted in the database since its wrapping transaction may have been
// committed yet.
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | true |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_number_test.go | core/field_number_test.go | package core_test
import (
"context"
"fmt"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestNumberFieldBaseMethods(t *testing.T) {
testFieldBaseMethods(t, core.FieldTypeNumber)
}
func TestNumberFieldColumnType(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.NumberField{}
expected := "NUMERIC DEFAULT 0 NOT NULL"
if v := f.ColumnType(app); v != expected {
t.Fatalf("Expected\n%q\ngot\n%q", expected, v)
}
}
func TestNumberFieldPrepareValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.NumberField{}
record := core.NewRecord(core.NewBaseCollection("test"))
scenarios := []struct {
raw any
expected float64
}{
{"", 0},
{"test", 0},
{false, 0},
{true, 1},
{-2, -2},
{123.456, 123.456},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.raw), func(t *testing.T) {
vRaw, err := f.PrepareValue(record, s.raw)
if err != nil {
t.Fatal(err)
}
v, ok := vRaw.(float64)
if !ok {
t.Fatalf("Expected float64 instance, got %T", v)
}
if v != s.expected {
t.Fatalf("Expected %f, got %f", s.expected, v)
}
})
}
}
func TestNumberFieldValidateValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field *core.NumberField
record func() *core.Record
expectError bool
}{
{
"invalid raw value",
&core.NumberField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "123")
return record
},
true,
},
{
"zero field value (not required)",
&core.NumberField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 0.0)
return record
},
false,
},
{
"zero field value (required)",
&core.NumberField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 0.0)
return record
},
true,
},
{
"non-zero field value (required)",
&core.NumberField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 123.0)
return record
},
false,
},
{
"decimal with onlyInt",
&core.NumberField{Name: "test", OnlyInt: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 123.456)
return record
},
true,
},
{
"int with onlyInt",
&core.NumberField{Name: "test", OnlyInt: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 123.0)
return record
},
false,
},
{
"< min",
&core.NumberField{Name: "test", Min: types.Pointer(2.0)},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 1.0)
return record
},
true,
},
{
">= min",
&core.NumberField{Name: "test", Min: types.Pointer(2.0)},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 2.0)
return record
},
false,
},
{
"> max",
&core.NumberField{Name: "test", Max: types.Pointer(2.0)},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 3.0)
return record
},
true,
},
{
"<= max",
&core.NumberField{Name: "test", Max: types.Pointer(2.0)},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 2.0)
return record
},
false,
},
{
"infinity",
&core.NumberField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.Set("test", "Inf")
return record
},
true,
},
{
"NaN",
&core.NumberField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.Set("test", "NaN")
return record
},
true,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
err := s.field.ValidateValue(context.Background(), app, s.record())
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
func TestNumberFieldValidateSettings(t *testing.T) {
testDefaultFieldIdValidation(t, core.FieldTypeNumber)
testDefaultFieldNameValidation(t, core.FieldTypeNumber)
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field func() *core.NumberField
expectErrors []string
}{
{
"zero",
func() *core.NumberField {
return &core.NumberField{
Id: "test",
Name: "test",
}
},
[]string{},
},
{
"decumal min",
func() *core.NumberField {
return &core.NumberField{
Id: "test",
Name: "test",
Min: types.Pointer(1.2),
}
},
[]string{},
},
{
"decumal min (onlyInt)",
func() *core.NumberField {
return &core.NumberField{
Id: "test",
Name: "test",
OnlyInt: true,
Min: types.Pointer(1.2),
}
},
[]string{"min"},
},
{
"int min (onlyInt)",
func() *core.NumberField {
return &core.NumberField{
Id: "test",
Name: "test",
OnlyInt: true,
Min: types.Pointer(1.0),
}
},
[]string{},
},
{
"decumal max",
func() *core.NumberField {
return &core.NumberField{
Id: "test",
Name: "test",
Max: types.Pointer(1.2),
}
},
[]string{},
},
{
"decumal max (onlyInt)",
func() *core.NumberField {
return &core.NumberField{
Id: "test",
Name: "test",
OnlyInt: true,
Max: types.Pointer(1.2),
}
},
[]string{"max"},
},
{
"int max (onlyInt)",
func() *core.NumberField {
return &core.NumberField{
Id: "test",
Name: "test",
OnlyInt: true,
Max: types.Pointer(1.0),
}
},
[]string{},
},
{
"min > max",
func() *core.NumberField {
return &core.NumberField{
Id: "test",
Name: "test",
Min: types.Pointer(2.0),
Max: types.Pointer(1.0),
}
},
[]string{"max"},
},
{
"min <= max",
func() *core.NumberField {
return &core.NumberField{
Id: "test",
Name: "test",
Min: types.Pointer(2.0),
Max: types.Pointer(2.0),
}
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
errs := s.field().ValidateSettings(context.Background(), app, collection)
tests.TestValidationErrors(t, errs, s.expectErrors)
})
}
}
func TestNumberFieldFindSetter(t *testing.T) {
field := &core.NumberField{Name: "test"}
collection := core.NewBaseCollection("test_collection")
collection.Fields.Add(field)
t.Run("no match", func(t *testing.T) {
f := field.FindSetter("abc")
if f != nil {
t.Fatal("Expected nil setter")
}
})
t.Run("direct name match", func(t *testing.T) {
f := field.FindSetter("test")
if f == nil {
t.Fatal("Expected non-nil setter")
}
record := core.NewRecord(collection)
record.SetRaw("test", 2.0)
f(record, "123.456") // should be casted
if v := record.Get("test"); v != 123.456 {
t.Fatalf("Expected %f, got %f", 123.456, v)
}
})
t.Run("name+ match", func(t *testing.T) {
f := field.FindSetter("test+")
if f == nil {
t.Fatal("Expected non-nil setter")
}
record := core.NewRecord(collection)
record.SetRaw("test", 2.0)
f(record, "1.5") // should be casted and appended to the existing value
if v := record.Get("test"); v != 3.5 {
t.Fatalf("Expected %f, got %f", 3.5, v)
}
})
t.Run("name- match", func(t *testing.T) {
f := field.FindSetter("test-")
if f == nil {
t.Fatal("Expected non-nil setter")
}
record := core.NewRecord(collection)
record.SetRaw("test", 2.0)
f(record, "1.5") // should be casted and subtracted from the existing value
if v := record.Get("test"); v != 0.5 {
t.Fatalf("Expected %f, got %f", 0.5, v)
}
})
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/event_request.go | core/event_request.go | package core
import (
"maps"
"net/netip"
"strings"
"sync"
"github.com/pocketbase/pocketbase/tools/inflector"
"github.com/pocketbase/pocketbase/tools/router"
)
// Common request store keys used by the middlewares and api handlers.
const (
RequestEventKeyInfoContext = "infoContext"
)
// RequestEvent defines the PocketBase router handler event.
type RequestEvent struct {
App App
cachedRequestInfo *RequestInfo
Auth *Record
router.Event
mu sync.Mutex
}
// RealIP returns the "real" IP address from the configured trusted proxy headers.
//
// If Settings.TrustedProxy is not configured or the found IP is empty,
// it fallbacks to e.RemoteIP().
//
// NB!
// Be careful when used in a security critical context as it relies on
// the trusted proxy to be properly configured and your app to be accessible only through it.
// If you are not sure, use e.RemoteIP().
func (e *RequestEvent) RealIP() string {
settings := e.App.Settings()
for _, h := range settings.TrustedProxy.Headers {
headerValues := e.Request.Header.Values(h)
if len(headerValues) == 0 {
continue
}
// extract the last header value as it is expected to be the one controlled by the proxy
ipsList := headerValues[len(headerValues)-1]
if ipsList == "" {
continue
}
ips := strings.Split(ipsList, ",")
if settings.TrustedProxy.UseLeftmostIP {
for _, ip := range ips {
parsed, err := netip.ParseAddr(strings.TrimSpace(ip))
if err == nil {
return parsed.StringExpanded()
}
}
} else {
for i := len(ips) - 1; i >= 0; i-- {
parsed, err := netip.ParseAddr(strings.TrimSpace(ips[i]))
if err == nil {
return parsed.StringExpanded()
}
}
}
}
return e.RemoteIP()
}
// HasSuperuserAuth checks whether the current RequestEvent has superuser authentication loaded.
func (e *RequestEvent) HasSuperuserAuth() bool {
return e.Auth != nil && e.Auth.IsSuperuser()
}
// RequestInfo parses the current request into RequestInfo instance.
//
// Note that the returned result is cached to avoid copying the request data multiple times
// but the auth state and other common store items are always refreshed in case they were changed by another handler.
func (e *RequestEvent) RequestInfo() (*RequestInfo, error) {
e.mu.Lock()
defer e.mu.Unlock()
if e.cachedRequestInfo != nil {
e.cachedRequestInfo.Auth = e.Auth
infoCtx, _ := e.Get(RequestEventKeyInfoContext).(string)
if infoCtx != "" {
e.cachedRequestInfo.Context = infoCtx
} else {
e.cachedRequestInfo.Context = RequestInfoContextDefault
}
} else {
// (re)init e.cachedRequestInfo based on the current request event
if err := e.initRequestInfo(); err != nil {
return nil, err
}
}
return e.cachedRequestInfo, nil
}
func (e *RequestEvent) initRequestInfo() error {
infoCtx, _ := e.Get(RequestEventKeyInfoContext).(string)
if infoCtx == "" {
infoCtx = RequestInfoContextDefault
}
info := &RequestInfo{
Context: infoCtx,
Method: e.Request.Method,
Query: map[string]string{},
Headers: map[string]string{},
Body: map[string]any{},
}
if err := e.BindBody(&info.Body); err != nil {
return err
}
// extract the first value of all query params
query := e.Request.URL.Query()
for k, v := range query {
if len(v) > 0 {
info.Query[k] = v[0]
}
}
// extract the first value of all headers and normalizes the keys
// ("X-Token" is converted to "x_token")
for k, v := range e.Request.Header {
if len(v) > 0 {
info.Headers[inflector.Snakecase(k)] = v[0]
}
}
info.Auth = e.Auth
e.cachedRequestInfo = info
return nil
}
// -------------------------------------------------------------------
const (
RequestInfoContextDefault = "default"
RequestInfoContextExpand = "expand"
RequestInfoContextRealtime = "realtime"
RequestInfoContextProtectedFile = "protectedFile"
RequestInfoContextBatch = "batch"
RequestInfoContextOAuth2 = "oauth2"
RequestInfoContextOTP = "otp"
RequestInfoContextPasswordAuth = "password"
)
// RequestInfo defines a HTTP request data struct, usually used
// as part of the `@request.*` filter resolver.
//
// The Query and Headers fields contains only the first value for each found entry.
type RequestInfo struct {
Query map[string]string `json:"query"`
Headers map[string]string `json:"headers"`
Body map[string]any `json:"body"`
Auth *Record `json:"auth"`
Method string `json:"method"`
Context string `json:"context"`
}
// HasSuperuserAuth checks whether the current RequestInfo instance
// has superuser authentication loaded.
func (info *RequestInfo) HasSuperuserAuth() bool {
return info.Auth != nil && info.Auth.IsSuperuser()
}
// Clone creates a new shallow copy of the current RequestInfo and its Auth record (if any).
func (info *RequestInfo) Clone() *RequestInfo {
clone := &RequestInfo{
Method: info.Method,
Context: info.Context,
Query: maps.Clone(info.Query),
Body: maps.Clone(info.Body),
Headers: maps.Clone(info.Headers),
}
if info.Auth != nil {
clone.Auth = info.Auth.Fresh()
}
return clone
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/auth_origin_query_test.go | core/auth_origin_query_test.go | package core_test
import (
"fmt"
"slices"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestFindAllAuthOriginsByRecord(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
demo1, err := app.FindRecordById("demo1", "84nmscqy84lsi1t")
if err != nil {
t.Fatal(err)
}
superuser2, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test2@example.com")
if err != nil {
t.Fatal(err)
}
superuser4, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test4@example.com")
if err != nil {
t.Fatal(err)
}
client1, err := app.FindAuthRecordByEmail("clients", "test@example.com")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
record *core.Record
expected []string
}{
{demo1, nil},
{superuser2, []string{"5798yh833k6w6w0", "ic55o70g4f8pcl4", "dmy260k6ksjr4ib"}},
{superuser4, nil},
{client1, []string{"9r2j0m74260ur8i"}},
}
for _, s := range scenarios {
t.Run(s.record.Collection().Name+"_"+s.record.Id, func(t *testing.T) {
result, err := app.FindAllAuthOriginsByRecord(s.record)
if err != nil {
t.Fatal(err)
}
if len(result) != len(s.expected) {
t.Fatalf("Expected total origins %d, got %d", len(s.expected), len(result))
}
for i, id := range s.expected {
if result[i].Id != id {
t.Errorf("[%d] Expected id %q, got %q", i, id, result[i].Id)
}
}
})
}
}
func TestFindAllAuthOriginsByCollection(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
demo1, err := app.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
superusers, err := app.FindCollectionByNameOrId(core.CollectionNameSuperusers)
if err != nil {
t.Fatal(err)
}
clients, err := app.FindCollectionByNameOrId("clients")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
collection *core.Collection
expected []string
}{
{demo1, nil},
{superusers, []string{"5798yh833k6w6w0", "ic55o70g4f8pcl4", "dmy260k6ksjr4ib", "5f29jy38bf5zm3f"}},
{clients, []string{"9r2j0m74260ur8i"}},
}
for _, s := range scenarios {
t.Run(s.collection.Name, func(t *testing.T) {
result, err := app.FindAllAuthOriginsByCollection(s.collection)
if err != nil {
t.Fatal(err)
}
if len(result) != len(s.expected) {
t.Fatalf("Expected total origins %d, got %d", len(s.expected), len(result))
}
for i, id := range s.expected {
if result[i].Id != id {
t.Errorf("[%d] Expected id %q, got %q", i, id, result[i].Id)
}
}
})
}
}
func TestFindAuthOriginById(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
id string
expectError bool
}{
{"", true},
{"84nmscqy84lsi1t", true}, // non-origin id
{"9r2j0m74260ur8i", false},
}
for _, s := range scenarios {
t.Run(s.id, func(t *testing.T) {
result, err := app.FindAuthOriginById(s.id)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
if hasErr {
return
}
if result.Id != s.id {
t.Fatalf("Expected record with id %q, got %q", s.id, result.Id)
}
})
}
}
func TestFindAuthOriginByRecordAndFingerprint(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
demo1, err := app.FindRecordById("demo1", "84nmscqy84lsi1t")
if err != nil {
t.Fatal(err)
}
superuser2, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test2@example.com")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
record *core.Record
fingerprint string
expectError bool
}{
{demo1, "6afbfe481c31c08c55a746cccb88ece0", true},
{superuser2, "", true},
{superuser2, "abc", true},
{superuser2, "22bbbcbed36e25321f384ccf99f60057", false}, // fingerprint from different origin
{superuser2, "6afbfe481c31c08c55a746cccb88ece0", false},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s_%s", i, s.record.Id, s.fingerprint), func(t *testing.T) {
result, err := app.FindAuthOriginByRecordAndFingerprint(s.record, s.fingerprint)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
if hasErr {
return
}
if result.Fingerprint() != s.fingerprint {
t.Fatalf("Expected origin with fingerprint %q, got %q", s.fingerprint, result.Fingerprint())
}
if result.RecordRef() != s.record.Id || result.CollectionRef() != s.record.Collection().Id {
t.Fatalf("Expected record %q (%q), got %q (%q)", s.record.Id, s.record.Collection().Id, result.RecordRef(), result.CollectionRef())
}
})
}
}
func TestDeleteAllAuthOriginsByRecord(t *testing.T) {
t.Parallel()
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
demo1, err := testApp.FindRecordById("demo1", "84nmscqy84lsi1t")
if err != nil {
t.Fatal(err)
}
superuser2, err := testApp.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test2@example.com")
if err != nil {
t.Fatal(err)
}
superuser4, err := testApp.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test4@example.com")
if err != nil {
t.Fatal(err)
}
client1, err := testApp.FindAuthRecordByEmail("clients", "test@example.com")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
record *core.Record
deletedIds []string
}{
{demo1, nil}, // non-auth record
{superuser2, []string{"5798yh833k6w6w0", "ic55o70g4f8pcl4", "dmy260k6ksjr4ib"}},
{superuser4, nil},
{client1, []string{"9r2j0m74260ur8i"}},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s_%s", i, s.record.Collection().Name, s.record.Id), func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
deletedIds := []string{}
app.OnRecordDelete().BindFunc(func(e *core.RecordEvent) error {
deletedIds = append(deletedIds, e.Record.Id)
return e.Next()
})
err := app.DeleteAllAuthOriginsByRecord(s.record)
if err != nil {
t.Fatal(err)
}
if len(deletedIds) != len(s.deletedIds) {
t.Fatalf("Expected deleted ids\n%v\ngot\n%v", s.deletedIds, deletedIds)
}
for _, id := range s.deletedIds {
if !slices.Contains(deletedIds, id) {
t.Errorf("Expected to find deleted id %q in %v", id, deletedIds)
}
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/db_connect_nodefaultdriver.go | core/db_connect_nodefaultdriver.go | //go:build no_default_driver
package core
import "github.com/pocketbase/dbx"
func DefaultDBConnect(dbPath string) (*dbx.DB, error) {
panic("DBConnect config option must be set when the no_default_driver tag is used!")
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_password_test.go | core/field_password_test.go | package core_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"golang.org/x/crypto/bcrypt"
)
func TestPasswordFieldBaseMethods(t *testing.T) {
testFieldBaseMethods(t, core.FieldTypePassword)
}
func TestPasswordFieldColumnType(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.PasswordField{}
expected := "TEXT DEFAULT '' NOT NULL"
if v := f.ColumnType(app); v != expected {
t.Fatalf("Expected\n%q\ngot\n%q", expected, v)
}
}
func TestPasswordFieldPrepareValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.PasswordField{}
record := core.NewRecord(core.NewBaseCollection("test"))
scenarios := []struct {
raw any
expected string
}{
{"", ""},
{"test", "test"},
{false, "false"},
{true, "true"},
{123.456, "123.456"},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.raw), func(t *testing.T) {
v, err := f.PrepareValue(record, s.raw)
if err != nil {
t.Fatal(err)
}
pv, ok := v.(*core.PasswordFieldValue)
if !ok {
t.Fatalf("Expected PasswordFieldValue instance, got %T", v)
}
if pv.Hash != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, v)
}
})
}
}
func TestPasswordFieldDriverValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.PasswordField{Name: "test"}
err := errors.New("example_err")
scenarios := []struct {
raw any
expected *core.PasswordFieldValue
}{
{123, &core.PasswordFieldValue{}},
{"abc", &core.PasswordFieldValue{}},
{"$2abc", &core.PasswordFieldValue{Hash: "$2abc"}},
{&core.PasswordFieldValue{Hash: "test", LastError: err}, &core.PasswordFieldValue{Hash: "test", LastError: err}},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%v", i, s.raw), func(t *testing.T) {
record := core.NewRecord(core.NewBaseCollection("test"))
record.SetRaw(f.GetName(), s.raw)
v, err := f.DriverValue(record)
vStr, ok := v.(string)
if !ok {
t.Fatalf("Expected string instance, got %T", v)
}
var errStr string
if err != nil {
errStr = err.Error()
}
var expectedErrStr string
if s.expected.LastError != nil {
expectedErrStr = s.expected.LastError.Error()
}
if errStr != expectedErrStr {
t.Fatalf("Expected error %q, got %q", expectedErrStr, errStr)
}
if vStr != s.expected.Hash {
t.Fatalf("Expected hash %q, got %q", s.expected.Hash, vStr)
}
})
}
}
func TestPasswordFieldValidateValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field *core.PasswordField
record func() *core.Record
expectError bool
}{
{
"invalid raw value",
&core.PasswordField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "123")
return record
},
true,
},
{
"zero field value (not required)",
&core.PasswordField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", &core.PasswordFieldValue{})
return record
},
false,
},
{
"zero field value (required)",
&core.PasswordField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", &core.PasswordFieldValue{})
return record
},
true,
},
{
"empty hash but non-empty plain password (required)",
&core.PasswordField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", &core.PasswordFieldValue{Plain: "test"})
return record
},
true,
},
{
"non-empty hash (required)",
&core.PasswordField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", &core.PasswordFieldValue{Hash: "test"})
return record
},
false,
},
{
"with LastError",
&core.PasswordField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", &core.PasswordFieldValue{LastError: errors.New("test")})
return record
},
true,
},
{
"< Min",
&core.PasswordField{Name: "test", Min: 3},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", &core.PasswordFieldValue{Plain: "аб"}) // multi-byte chars test
return record
},
true,
},
{
">= Min",
&core.PasswordField{Name: "test", Min: 3},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", &core.PasswordFieldValue{Plain: "абв"}) // multi-byte chars test
return record
},
false,
},
{
"> default Max",
&core.PasswordField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", &core.PasswordFieldValue{Plain: strings.Repeat("a", 72)})
return record
},
true,
},
{
"<= default Max",
&core.PasswordField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", &core.PasswordFieldValue{Plain: strings.Repeat("a", 71)})
return record
},
false,
},
{
"> Max",
&core.PasswordField{Name: "test", Max: 2},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", &core.PasswordFieldValue{Plain: "абв"}) // multi-byte chars test
return record
},
true,
},
{
"<= Max",
&core.PasswordField{Name: "test", Max: 2},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", &core.PasswordFieldValue{Plain: "аб"}) // multi-byte chars test
return record
},
false,
},
{
"non-matching pattern",
&core.PasswordField{Name: "test", Pattern: `\d+`},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", &core.PasswordFieldValue{Plain: "abc"})
return record
},
true,
},
{
"matching pattern",
&core.PasswordField{Name: "test", Pattern: `\d+`},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", &core.PasswordFieldValue{Plain: "123"})
return record
},
false,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
err := s.field.ValidateValue(context.Background(), app, s.record())
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
func TestPasswordFieldValidateSettings(t *testing.T) {
testDefaultFieldIdValidation(t, core.FieldTypePassword)
testDefaultFieldNameValidation(t, core.FieldTypePassword)
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
name string
field func(col *core.Collection) *core.PasswordField
expectErrors []string
}{
{
"zero minimal",
func(col *core.Collection) *core.PasswordField {
return &core.PasswordField{
Id: "test",
Name: "test",
}
},
[]string{},
},
{
"invalid pattern",
func(col *core.Collection) *core.PasswordField {
return &core.PasswordField{
Id: "test",
Name: "test",
Pattern: "(invalid",
}
},
[]string{"pattern"},
},
{
"valid pattern",
func(col *core.Collection) *core.PasswordField {
return &core.PasswordField{
Id: "test",
Name: "test",
Pattern: `\d+`,
}
},
[]string{},
},
{
"Min < 0",
func(col *core.Collection) *core.PasswordField {
return &core.PasswordField{
Id: "test",
Name: "test",
Min: -1,
}
},
[]string{"min"},
},
{
"Min > 71",
func(col *core.Collection) *core.PasswordField {
return &core.PasswordField{
Id: "test",
Name: "test",
Min: 72,
}
},
[]string{"min"},
},
{
"valid Min",
func(col *core.Collection) *core.PasswordField {
return &core.PasswordField{
Id: "test",
Name: "test",
Min: 5,
}
},
[]string{},
},
{
"Max < Min",
func(col *core.Collection) *core.PasswordField {
return &core.PasswordField{
Id: "test",
Name: "test",
Min: 2,
Max: 1,
}
},
[]string{"max"},
},
{
"Min > Min",
func(col *core.Collection) *core.PasswordField {
return &core.PasswordField{
Id: "test",
Name: "test",
Min: 2,
Max: 3,
}
},
[]string{},
},
{
"Max > 71",
func(col *core.Collection) *core.PasswordField {
return &core.PasswordField{
Id: "test",
Name: "test",
Max: 72,
}
},
[]string{"max"},
},
{
"cost < bcrypt.MinCost",
func(col *core.Collection) *core.PasswordField {
return &core.PasswordField{
Id: "test",
Name: "test",
Cost: bcrypt.MinCost - 1,
}
},
[]string{"cost"},
},
{
"cost > bcrypt.MaxCost",
func(col *core.Collection) *core.PasswordField {
return &core.PasswordField{
Id: "test",
Name: "test",
Cost: bcrypt.MaxCost + 1,
}
},
[]string{"cost"},
},
{
"valid cost",
func(col *core.Collection) *core.PasswordField {
return &core.PasswordField{
Id: "test",
Name: "test",
Cost: 12,
}
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
collection := core.NewBaseCollection("test_collection")
collection.Fields.GetByName("id").SetId("test") // set a dummy known id so that it can be replaced
field := s.field(collection)
collection.Fields.Add(field)
errs := field.ValidateSettings(context.Background(), app, collection)
tests.TestValidationErrors(t, errs, s.expectErrors)
})
}
}
func TestPasswordFieldFindSetter(t *testing.T) {
scenarios := []struct {
name string
key string
value any
field *core.PasswordField
hasSetter bool
expected string
}{
{
"no match",
"example",
"abc",
&core.PasswordField{Name: "test"},
false,
"",
},
{
"exact match",
"test",
"abc",
&core.PasswordField{Name: "test"},
true,
`"abc"`,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
collection := core.NewBaseCollection("test_collection")
collection.Fields.Add(s.field)
setter := s.field.FindSetter(s.key)
hasSetter := setter != nil
if hasSetter != s.hasSetter {
t.Fatalf("Expected hasSetter %v, got %v", s.hasSetter, hasSetter)
}
if !hasSetter {
return
}
record := core.NewRecord(collection)
record.SetRaw(s.field.GetName(), []string{"c", "d"})
setter(record, s.value)
raw, err := json.Marshal(record.Get(s.field.GetName()))
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
if rawStr != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, rawStr)
}
})
}
}
func TestPasswordFieldFindGetter(t *testing.T) {
scenarios := []struct {
name string
key string
field *core.PasswordField
hasGetter bool
expected string
}{
{
"no match",
"example",
&core.PasswordField{Name: "test"},
false,
"",
},
{
"field name match",
"test",
&core.PasswordField{Name: "test"},
true,
"test_plain",
},
{
"field name hash modifier",
"test:hash",
&core.PasswordField{Name: "test"},
true,
"test_hash",
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
collection := core.NewBaseCollection("test_collection")
collection.Fields.Add(s.field)
getter := s.field.FindGetter(s.key)
hasGetter := getter != nil
if hasGetter != s.hasGetter {
t.Fatalf("Expected hasGetter %v, got %v", s.hasGetter, hasGetter)
}
if !hasGetter {
return
}
record := core.NewRecord(collection)
record.SetRaw(s.field.GetName(), &core.PasswordFieldValue{Hash: "test_hash", Plain: "test_plain"})
result := getter(record)
if result != s.expected {
t.Fatalf("Expected %q, got %#v", s.expected, result)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/settings_query.go | core/settings_query.go | package core
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"os"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/pocketbase/pocketbase/tools/types"
)
type Param struct {
BaseModel
Created types.DateTime `db:"created" json:"created"`
Updated types.DateTime `db:"updated" json:"updated"`
Value types.JSONRaw `db:"value" json:"value"`
}
func (m *Param) TableName() string {
return paramsTable
}
// ReloadSettings initializes and reloads the stored application settings.
//
// If no settings were stored it will persist the current app ones.
func (app *BaseApp) ReloadSettings() error {
param := &Param{}
err := app.ModelQuery(param).Model(paramsKeySettings, param)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return err
}
// no settings were previously stored -> save
// (ReloadSettings() will be invoked again by a system hook after successful save)
if param.Id == "" {
// force insert in case the param entry was deleted manually after application start
app.Settings().MarkAsNew()
return app.Save(app.Settings())
}
event := new(SettingsReloadEvent)
event.App = app
return app.OnSettingsReload().Trigger(event, func(e *SettingsReloadEvent) error {
return e.App.Settings().loadParam(e.App, param)
})
}
// loadParam loads the settings from the stored param into the app ones.
//
// @todo note that the encryption may get removed in the future since it doesn't
// really accomplish much and it might be better to find a way to encrypt the backups
// or implement support for resolving env variables.
func (s *Settings) loadParam(app App, param *Param) error {
// try first without decryption
s.mu.Lock()
plainDecodeErr := json.Unmarshal(param.Value, s)
s.mu.Unlock()
// failed, try to decrypt
if plainDecodeErr != nil {
encryptionKey := os.Getenv(app.EncryptionEnv())
// load without decryption has failed and there is no encryption key to use for decrypt
if encryptionKey == "" {
return fmt.Errorf("invalid settings db data or missing encryption key %q", app.EncryptionEnv())
}
// decrypt
decrypted, decryptErr := security.Decrypt(string(param.Value), encryptionKey)
if decryptErr != nil {
return decryptErr
}
// decode again
s.mu.Lock()
decryptedDecodeErr := json.Unmarshal(decrypted, s)
s.mu.Unlock()
if decryptedDecodeErr != nil {
return decryptedDecodeErr
}
}
return s.PostScan()
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_bool.go | core/field_bool.go | package core
import (
"context"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/spf13/cast"
)
func init() {
Fields[FieldTypeBool] = func() Field {
return &BoolField{}
}
}
const FieldTypeBool = "bool"
var _ Field = (*BoolField)(nil)
// BoolField defines "bool" type field to store a single true/false value.
//
// The respective zero record field value is false.
type BoolField struct {
// Name (required) is the unique name of the field.
Name string `form:"name" json:"name"`
// Id is the unique stable field identifier.
//
// It is automatically generated from the name when adding to a collection FieldsList.
Id string `form:"id" json:"id"`
// System prevents the renaming and removal of the field.
System bool `form:"system" json:"system"`
// Hidden hides the field from the API response.
Hidden bool `form:"hidden" json:"hidden"`
// Presentable hints the Dashboard UI to use the underlying
// field record value in the relation preview label.
Presentable bool `form:"presentable" json:"presentable"`
// ---
// Required will require the field value to be always "true".
Required bool `form:"required" json:"required"`
}
// Type implements [Field.Type] interface method.
func (f *BoolField) Type() string {
return FieldTypeBool
}
// GetId implements [Field.GetId] interface method.
func (f *BoolField) GetId() string {
return f.Id
}
// SetId implements [Field.SetId] interface method.
func (f *BoolField) SetId(id string) {
f.Id = id
}
// GetName implements [Field.GetName] interface method.
func (f *BoolField) GetName() string {
return f.Name
}
// SetName implements [Field.SetName] interface method.
func (f *BoolField) SetName(name string) {
f.Name = name
}
// GetSystem implements [Field.GetSystem] interface method.
func (f *BoolField) GetSystem() bool {
return f.System
}
// SetSystem implements [Field.SetSystem] interface method.
func (f *BoolField) SetSystem(system bool) {
f.System = system
}
// GetHidden implements [Field.GetHidden] interface method.
func (f *BoolField) GetHidden() bool {
return f.Hidden
}
// SetHidden implements [Field.SetHidden] interface method.
func (f *BoolField) SetHidden(hidden bool) {
f.Hidden = hidden
}
// ColumnType implements [Field.ColumnType] interface method.
func (f *BoolField) ColumnType(app App) string {
return "BOOLEAN DEFAULT FALSE NOT NULL"
}
// PrepareValue implements [Field.PrepareValue] interface method.
func (f *BoolField) PrepareValue(record *Record, raw any) (any, error) {
return cast.ToBool(raw), nil
}
// ValidateValue implements [Field.ValidateValue] interface method.
func (f *BoolField) ValidateValue(ctx context.Context, app App, record *Record) error {
v, ok := record.GetRaw(f.Name).(bool)
if !ok {
return validators.ErrUnsupportedValueType
}
if f.Required {
return validation.Required.Validate(v)
}
return nil
}
// ValidateSettings implements [Field.ValidateSettings] interface method.
func (f *BoolField) ValidateSettings(ctx context.Context, app App, collection *Collection) error {
return validation.ValidateStruct(f,
validation.Field(&f.Id, validation.By(DefaultFieldIdValidationRule)),
validation.Field(&f.Name, validation.By(DefaultFieldNameValidationRule)),
)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/collection_model_view_options_test.go | core/collection_model_view_options_test.go | package core_test
import (
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestCollectionViewOptionsValidate(t *testing.T) {
t.Parallel()
scenarios := []struct {
name string
collection func(app core.App) (*core.Collection, error)
expectedErrors []string
}{
{
name: "view with empty query",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewViewCollection("new_auth")
return c, nil
},
expectedErrors: []string{"fields", "viewQuery"},
},
{
name: "view with invalid query",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewViewCollection("new_auth")
c.ViewQuery = "invalid"
return c, nil
},
expectedErrors: []string{"fields", "viewQuery"},
},
{
name: "view with valid query but missing id",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewViewCollection("new_auth")
c.ViewQuery = "select 1"
return c, nil
},
expectedErrors: []string{"fields", "viewQuery"},
},
{
name: "view with valid query",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewViewCollection("new_auth")
c.ViewQuery = "select demo1.id, text as example from demo1"
return c, nil
},
expectedErrors: []string{},
},
{
name: "update view query ",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("view2")
c.ViewQuery = "select demo1.id, text as example from demo1"
return c, nil
},
expectedErrors: []string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, err := s.collection(app)
if err != nil {
t.Fatalf("Failed to retrieve test collection: %v", err)
}
result := app.Validate(collection)
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/log_printer_test.go | core/log_printer_test.go | package core
import (
"context"
"database/sql"
"log/slog"
"os"
"testing"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/logger"
)
func TestBaseAppLoggerLevelDevPrint(t *testing.T) {
testLogLevel := 4
scenarios := []struct {
name string
isDev bool
levels []int
printedLevels []int
persistedLevels []int
}{
{
"dev mode",
true,
[]int{testLogLevel - 1, testLogLevel, testLogLevel + 1},
[]int{testLogLevel - 1, testLogLevel, testLogLevel + 1},
[]int{testLogLevel, testLogLevel + 1},
},
{
"nondev mode",
false,
[]int{testLogLevel - 1, testLogLevel, testLogLevel + 1},
[]int{},
[]int{testLogLevel, testLogLevel + 1},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
const testDataDir = "./pb_base_app_test_data_dir/"
defer os.RemoveAll(testDataDir)
app := NewBaseApp(BaseAppConfig{
DataDir: testDataDir,
IsDev: s.isDev,
})
defer app.ResetBootstrapState()
if err := app.Bootstrap(); err != nil {
t.Fatal(err)
}
// silence query logs
app.concurrentDB.(*dbx.DB).ExecLogFunc = func(ctx context.Context, t time.Duration, sql string, result sql.Result, err error) {}
app.concurrentDB.(*dbx.DB).QueryLogFunc = func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error) {}
app.nonconcurrentDB.(*dbx.DB).ExecLogFunc = func(ctx context.Context, t time.Duration, sql string, result sql.Result, err error) {}
app.nonconcurrentDB.(*dbx.DB).QueryLogFunc = func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error) {}
app.Settings().Logs.MinLevel = testLogLevel
if err := app.Save(app.Settings()); err != nil {
t.Fatal(err)
}
var printedLevels []int
var persistedLevels []int
ctx := context.Background()
// track printed logs
originalPrintLog := printLog
defer func() {
printLog = originalPrintLog
}()
printLog = func(log *logger.Log) {
printedLevels = append(printedLevels, int(log.Level))
}
// track persisted logs
app.OnModelAfterCreateSuccess("_logs").BindFunc(func(e *ModelEvent) error {
l, ok := e.Model.(*Log)
if ok {
persistedLevels = append(persistedLevels, l.Level)
}
return e.Next()
})
// write and persist logs
for _, l := range s.levels {
app.Logger().Log(ctx, slog.Level(l), "test")
}
handler, ok := app.Logger().Handler().(*logger.BatchHandler)
if !ok {
t.Fatalf("Expected BatchHandler, got %v", app.Logger().Handler())
}
if err := handler.WriteAll(ctx); err != nil {
t.Fatalf("Failed to write all logs: %v", err)
}
// check persisted log levels
if len(s.persistedLevels) != len(persistedLevels) {
t.Fatalf("Expected persisted levels \n%v\ngot\n%v", s.persistedLevels, persistedLevels)
}
for _, l := range persistedLevels {
if !list.ExistInSlice(l, s.persistedLevels) {
t.Fatalf("Missing expected persisted level %v in %v", l, persistedLevels)
}
}
// check printed log levels
if len(s.printedLevels) != len(printedLevels) {
t.Fatalf("Expected printed levels \n%v\ngot\n%v", s.printedLevels, printedLevels)
}
for _, l := range printedLevels {
if !list.ExistInSlice(l, s.printedLevels) {
t.Fatalf("Missing expected printed level %v in %v", l, printedLevels)
}
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/otp_model.go | core/otp_model.go | package core
import (
"context"
"errors"
"time"
"github.com/pocketbase/pocketbase/tools/types"
)
const CollectionNameOTPs = "_otps"
var (
_ Model = (*OTP)(nil)
_ PreValidator = (*OTP)(nil)
_ RecordProxy = (*OTP)(nil)
)
// OTP defines a Record proxy for working with the otps collection.
type OTP struct {
*Record
}
// NewOTP instantiates and returns a new blank *OTP model.
//
// Example usage:
//
// otp := core.NewOTP(app)
// otp.SetRecordRef(user.Id)
// otp.SetCollectionRef(user.Collection().Id)
// otp.SetPassword(security.RandomStringWithAlphabet(6, "1234567890"))
// app.Save(otp)
func NewOTP(app App) *OTP {
m := &OTP{}
c, err := app.FindCachedCollectionByNameOrId(CollectionNameOTPs)
if err != nil {
// this is just to make tests easier since otp is a system collection and it is expected to be always accessible
// (note: the loaded record is further checked on OTP.PreValidate())
c = NewBaseCollection("__invalid__")
}
m.Record = NewRecord(c)
return m
}
// PreValidate implements the [PreValidator] interface and checks
// whether the proxy is properly loaded.
func (m *OTP) PreValidate(ctx context.Context, app App) error {
if m.Record == nil || m.Record.Collection().Name != CollectionNameOTPs {
return errors.New("missing or invalid otp ProxyRecord")
}
return nil
}
// ProxyRecord returns the proxied Record model.
func (m *OTP) ProxyRecord() *Record {
return m.Record
}
// SetProxyRecord loads the specified record model into the current proxy.
func (m *OTP) SetProxyRecord(record *Record) {
m.Record = record
}
// CollectionRef returns the "collectionRef" field value.
func (m *OTP) CollectionRef() string {
return m.GetString("collectionRef")
}
// SetCollectionRef updates the "collectionRef" record field value.
func (m *OTP) SetCollectionRef(collectionId string) {
m.Set("collectionRef", collectionId)
}
// RecordRef returns the "recordRef" record field value.
func (m *OTP) RecordRef() string {
return m.GetString("recordRef")
}
// SetRecordRef updates the "recordRef" record field value.
func (m *OTP) SetRecordRef(recordId string) {
m.Set("recordRef", recordId)
}
// SentTo returns the "sentTo" record field value.
//
// It could be any string value (email, phone, message app id, etc.)
// and usually is used as part of the auth flow to update the verified
// user state in case for example the sentTo value matches with the user record email.
func (m *OTP) SentTo() string {
return m.GetString("sentTo")
}
// SetSentTo updates the "sentTo" record field value.
func (m *OTP) SetSentTo(val string) {
m.Set("sentTo", val)
}
// Created returns the "created" record field value.
func (m *OTP) Created() types.DateTime {
return m.GetDateTime("created")
}
// Updated returns the "updated" record field value.
func (m *OTP) Updated() types.DateTime {
return m.GetDateTime("updated")
}
// HasExpired checks if the otp is expired, aka. whether it has been
// more than maxElapsed time since its creation.
func (m *OTP) HasExpired(maxElapsed time.Duration) bool {
return time.Since(m.Created().Time()) > maxElapsed
}
func (app *BaseApp) registerOTPHooks() {
recordRefHooks[*OTP](app, CollectionNameOTPs, CollectionTypeAuth)
// run on every hour to cleanup expired otp sessions
app.Cron().Add("__pbOTPCleanup__", "0 * * * *", func() {
if err := app.DeleteExpiredOTPs(); err != nil {
app.Logger().Warn("Failed to delete expired OTP sessions", "error", err)
}
})
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_field_resolver.go | core/record_field_resolver.go | package core
import (
"encoding/json"
"errors"
"fmt"
"slices"
"strconv"
"strings"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/search"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/pocketbase/pocketbase/tools/types"
"github.com/spf13/cast"
)
// filter modifiers
const (
eachModifier string = "each"
issetModifier string = "isset"
lengthModifier string = "length"
lowerModifier string = "lower"
changedModifier string = "changed"
)
// ensure that `search.FieldResolver` interface is implemented
var _ search.FieldResolver = (*RecordFieldResolver)(nil)
// RecordFieldResolver defines a custom search resolver struct for
// managing Record model search fields.
//
// Usually used together with `search.Provider`.
// Example:
//
// resolver := resolvers.NewRecordFieldResolver(
// app,
// myCollection,
// &models.RequestInfo{...},
// true,
// )
// provider := search.NewProvider(resolver)
// ...
type RecordFieldResolver struct {
app App
baseCollection *Collection
requestInfo *RequestInfo
staticRequestInfo map[string]any
allowedFields []string
joins []*join
allowHiddenFields bool
// ---
listRuleJoins map[string]*Collection // tableAlias->collection
joinAliasSuffix string // used for uniqueness in the flatten collection list rule join
baseCollectionAlias string
}
// AllowedFields returns a copy of the resolver's allowed fields.
func (r *RecordFieldResolver) AllowedFields() []string {
return slices.Clone(r.allowedFields)
}
// SetAllowedFields replaces the resolver's allowed fields with the new ones.
func (r *RecordFieldResolver) SetAllowedFields(newAllowedFields []string) {
r.allowedFields = slices.Clone(newAllowedFields)
}
// AllowHiddenFields returns whether the current resolver allows filtering hidden fields.
func (r *RecordFieldResolver) AllowHiddenFields() bool {
return r.allowHiddenFields
}
// SetAllowHiddenFields enables or disables hidden fields filtering.
func (r *RecordFieldResolver) SetAllowHiddenFields(allowHiddenFields bool) {
r.allowHiddenFields = allowHiddenFields
}
// NewRecordFieldResolver creates and initializes a new `RecordFieldResolver`.
func NewRecordFieldResolver(
app App,
baseCollection *Collection,
requestInfo *RequestInfo,
allowHiddenFields bool,
) *RecordFieldResolver {
r := &RecordFieldResolver{
app: app,
baseCollection: baseCollection,
requestInfo: requestInfo,
allowHiddenFields: allowHiddenFields, // note: it is not based only on the requestInfo.auth since it could be used by a non-request internal method
joins: []*join{},
allowedFields: []string{
`^\w+[\w\.\:]*$`,
`^\@request\.context$`,
`^\@request\.method$`,
`^\@request\.auth\.[\w\.\:]*\w+$`,
`^\@request\.body\.[\w\.\:]*\w+$`,
`^\@request\.query\.[\w\.\:]*\w+$`,
`^\@request\.headers\.[\w\.\:]*\w+$`,
`^\@collection\.\w+(\:\w+)?\.[\w\.\:]*\w+$`,
},
}
r.staticRequestInfo = map[string]any{}
if r.requestInfo != nil {
r.staticRequestInfo["context"] = r.requestInfo.Context
r.staticRequestInfo["method"] = r.requestInfo.Method
r.staticRequestInfo["query"] = r.requestInfo.Query
r.staticRequestInfo["headers"] = r.requestInfo.Headers
r.staticRequestInfo["body"] = r.requestInfo.Body
r.staticRequestInfo["auth"] = nil
if r.requestInfo.Auth != nil {
authClone := r.requestInfo.Auth.Clone()
r.staticRequestInfo["auth"] = authClone.
Unhide(authClone.Collection().Fields.FieldNames()...).
IgnoreEmailVisibility(true).
PublicExport()
}
}
return r
}
// @todo think of a better a way how to call it automatically after BuildExpr
//
// UpdateQuery implements `search.FieldResolver` interface.
//
// Conditionally updates the provided search query based on the
// resolved fields (eg. dynamically joining relations).
func (r *RecordFieldResolver) UpdateQuery(query *dbx.SelectQuery) error {
if len(r.joins) > 0 {
query.Distinct(true)
for _, join := range r.joins {
query.LeftJoin(
(join.tableName + " " + join.tableAlias),
join.on,
)
}
}
// note: for now the joins are not applied for multi-match conditions to avoid excessive checks
if len(r.listRuleJoins) > 0 {
for alias, c := range r.listRuleJoins {
err := r.updateQueryWithCollectionListRule(c, alias, query)
if err != nil {
return err
}
}
}
return nil
}
func (r *RecordFieldResolver) updateQueryWithCollectionListRule(c *Collection, tableAlias string, query *dbx.SelectQuery) error {
if r.allowHiddenFields || c == nil || c.ListRule == nil || *c.ListRule == "" {
return nil
}
cloneR := *r
cloneR.joins = []*join{}
cloneR.baseCollection = c
cloneR.baseCollectionAlias = tableAlias
cloneR.allowHiddenFields = true
cloneR.joinAliasSuffix = security.PseudorandomString(6)
expr, err := search.FilterData(*c.ListRule).BuildExpr(&cloneR)
if err != nil {
return fmt.Errorf("to buld %q list rule join subquery filter expression: %w", c.Name, err)
}
query.AndWhere(expr)
if len(cloneR.joins) > 0 {
query.Distinct(true)
for _, j := range cloneR.joins {
query.LeftJoin(
(j.tableName + " " + j.tableAlias),
j.on,
)
}
}
return nil
}
// Resolve implements `search.FieldResolver` interface.
//
// Example of some resolvable fieldName formats:
//
// id
// someSelect.each
// project.screen.status
// screen.project_via_prototype.name
// @request.context
// @request.method
// @request.query.filter
// @request.headers.x_token
// @request.auth.someRelation.name
// @request.body.someRelation.name
// @request.body.someField
// @request.body.someSelect:each
// @request.body.someField:isset
// @collection.product.name
func (r *RecordFieldResolver) Resolve(fieldName string) (*search.ResolverResult, error) {
return parseAndRun(fieldName, r)
}
func (r *RecordFieldResolver) resolveStaticRequestField(path ...string) (*search.ResolverResult, error) {
if len(path) == 0 {
return nil, errors.New("at least one path key should be provided")
}
lastProp, modifier, err := splitModifier(path[len(path)-1])
if err != nil {
return nil, err
}
path[len(path)-1] = lastProp
// extract value
resultVal, err := extractNestedVal(r.staticRequestInfo, path...)
if err != nil {
r.app.Logger().Debug("resolveStaticRequestField graceful fallback", "error", err.Error())
}
if modifier == issetModifier {
if err != nil {
return &search.ResolverResult{Identifier: "FALSE"}, nil
}
return &search.ResolverResult{Identifier: "TRUE"}, nil
}
// note: we are ignoring the error because requestInfo is dynamic
// and some of the lookup keys may not be defined for the request
switch v := resultVal.(type) {
case nil:
// no further processing is needed...
case string:
// check if it is a number field and explicitly try to cast to
// float in case of a numeric string value was used
// (this usually the case when the data is from a multipart/form-data request)
field := r.baseCollection.Fields.GetByName(path[len(path)-1])
if field != nil && field.Type() == FieldTypeNumber {
if nv, err := strconv.ParseFloat(v, 64); err == nil {
resultVal = nv
}
}
// otherwise - no further processing is needed...
case bool, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64:
// no further processing is needed...
default:
// non-plain value
// try casting to string (in case for exampe fmt.Stringer is implemented)
val, castErr := cast.ToStringE(v)
// if that doesn't work, try encoding it
if castErr != nil {
encoded, jsonErr := json.Marshal(v)
if jsonErr == nil {
val = string(encoded)
}
}
resultVal = val
}
// unsupported modifier
// @todo consider deprecating with the introduction of filter functions
if modifier != "" && modifier != lowerModifier {
return nil, fmt.Errorf("invalid modifier sequence %s:%s", lastProp, modifier)
}
// no need to wrap as placeholder if we already know that it is null
if resultVal == nil {
return &search.ResolverResult{Identifier: "NULL"}, nil
}
placeholder := "f" + security.PseudorandomString(8)
// @todo consider deprecating with the introduction of filter functions
if modifier == lowerModifier {
return &search.ResolverResult{
Identifier: "LOWER({:" + placeholder + "})",
Params: dbx.Params{placeholder: resultVal},
}, nil
}
return &search.ResolverResult{
Identifier: "{:" + placeholder + "}",
Params: dbx.Params{placeholder: resultVal},
}, nil
}
func (r *RecordFieldResolver) loadCollection(collectionNameOrId string) (*Collection, error) {
if collectionNameOrId == r.baseCollection.Name || collectionNameOrId == r.baseCollection.Id {
return r.baseCollection, nil
}
return getCollectionByModelOrIdentifier(r.app, collectionNameOrId)
}
func (r *RecordFieldResolver) registerJoin(tableName string, tableAlias string, on dbx.Expression) error {
newJoin := &join{
tableName: tableName,
tableAlias: tableAlias,
on: on,
}
// (see updateQueryWithCollectionListRule)
if !r.allowHiddenFields {
c, _ := r.loadCollection(tableName)
// ignore non-collections since the table name could be an expression (e.g. json) or some other subquery
if c != nil {
// treat all fields as if they are hidden
if c.ListRule == nil {
return fmt.Errorf("%q fields can be accessed only when allowHiddenFields is enabled or by superusers", c.Name)
}
if r.listRuleJoins == nil {
r.listRuleJoins = map[string]*Collection{}
}
r.listRuleJoins[newJoin.tableAlias] = c
}
}
// replace existing join
for i, j := range r.joins {
if j.tableAlias == newJoin.tableAlias {
r.joins[i] = newJoin
return nil
}
}
// register new join
r.joins = append(r.joins, newJoin)
return nil
}
type mapExtractor interface {
AsMap() map[string]any
}
func extractNestedVal(rawData any, keys ...string) (any, error) {
if len(keys) == 0 {
return nil, errors.New("at least one key should be provided")
}
switch m := rawData.(type) {
// maps
case map[string]any:
return mapVal(m, keys...)
case map[string]string:
return mapVal(m, keys...)
case map[string]bool:
return mapVal(m, keys...)
case map[string]float32:
return mapVal(m, keys...)
case map[string]float64:
return mapVal(m, keys...)
case map[string]int:
return mapVal(m, keys...)
case map[string]int8:
return mapVal(m, keys...)
case map[string]int16:
return mapVal(m, keys...)
case map[string]int32:
return mapVal(m, keys...)
case map[string]int64:
return mapVal(m, keys...)
case map[string]uint:
return mapVal(m, keys...)
case map[string]uint8:
return mapVal(m, keys...)
case map[string]uint16:
return mapVal(m, keys...)
case map[string]uint32:
return mapVal(m, keys...)
case map[string]uint64:
return mapVal(m, keys...)
case mapExtractor:
return mapVal(m.AsMap(), keys...)
case types.JSONRaw:
var raw any
err := json.Unmarshal(m, &raw)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal raw JSON in order extract nested value from: %w", err)
}
return extractNestedVal(raw, keys...)
// slices
case []string:
return arrVal(m, keys...)
case []bool:
return arrVal(m, keys...)
case []float32:
return arrVal(m, keys...)
case []float64:
return arrVal(m, keys...)
case []int:
return arrVal(m, keys...)
case []int8:
return arrVal(m, keys...)
case []int16:
return arrVal(m, keys...)
case []int32:
return arrVal(m, keys...)
case []int64:
return arrVal(m, keys...)
case []uint:
return arrVal(m, keys...)
case []uint8:
return arrVal(m, keys...)
case []uint16:
return arrVal(m, keys...)
case []uint32:
return arrVal(m, keys...)
case []uint64:
return arrVal(m, keys...)
case []mapExtractor:
extracted := make([]any, len(m))
for i, v := range m {
extracted[i] = v.AsMap()
}
return arrVal(extracted, keys...)
case []any:
return arrVal(m, keys...)
case []types.JSONRaw:
return arrVal(m, keys...)
default:
return nil, fmt.Errorf("expected map or array, got %#v", rawData)
}
}
func mapVal[T any](m map[string]T, keys ...string) (any, error) {
result, ok := m[keys[0]]
if !ok {
return nil, fmt.Errorf("invalid key path - missing key %q", keys[0])
}
// end key reached
if len(keys) == 1 {
return result, nil
}
return extractNestedVal(result, keys[1:]...)
}
func arrVal[T any](m []T, keys ...string) (any, error) {
idx, err := strconv.Atoi(keys[0])
if err != nil || idx < 0 || idx >= len(m) {
return nil, fmt.Errorf("invalid key path - invalid or missing array index %q", keys[0])
}
result := m[idx]
// end key reached
if len(keys) == 1 {
return result, nil
}
return extractNestedVal(result, keys[1:]...)
}
func splitModifier(combined string) (string, string, error) {
parts := strings.Split(combined, ":")
if len(parts) != 2 {
return combined, "", nil
}
// validate modifier
switch parts[1] {
case issetModifier,
eachModifier,
lengthModifier,
lowerModifier,
changedModifier:
return parts[0], parts[1], nil
}
return "", "", fmt.Errorf("unknown modifier in %q", combined)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_geo_point.go | core/field_geo_point.go | package core
import (
"context"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
Fields[FieldTypeGeoPoint] = func() Field {
return &GeoPointField{}
}
}
const FieldTypeGeoPoint = "geoPoint"
var (
_ Field = (*GeoPointField)(nil)
)
// GeoPointField defines "geoPoint" type field for storing latitude and longitude GPS coordinates.
//
// You can set the record field value as [types.GeoPoint], map or serialized json object with lat-lon props.
// The stored value is always converted to [types.GeoPoint].
// Nil, empty map, empty bytes slice, etc. results in zero [types.GeoPoint].
//
// Examples of updating a record's GeoPointField value programmatically:
//
// record.Set("location", types.GeoPoint{Lat: 123, Lon: 456})
// record.Set("location", map[string]any{"lat":123, "lon":456})
// record.Set("location", []byte(`{"lat":123, "lon":456}`)
type GeoPointField struct {
// Name (required) is the unique name of the field.
Name string `form:"name" json:"name"`
// Id is the unique stable field identifier.
//
// It is automatically generated from the name when adding to a collection FieldsList.
Id string `form:"id" json:"id"`
// System prevents the renaming and removal of the field.
System bool `form:"system" json:"system"`
// Hidden hides the field from the API response.
Hidden bool `form:"hidden" json:"hidden"`
// Presentable hints the Dashboard UI to use the underlying
// field record value in the relation preview label.
Presentable bool `form:"presentable" json:"presentable"`
// ---
// Required will require the field coordinates to be non-zero (aka. not "Null Island").
Required bool `form:"required" json:"required"`
}
// Type implements [Field.Type] interface method.
func (f *GeoPointField) Type() string {
return FieldTypeGeoPoint
}
// GetId implements [Field.GetId] interface method.
func (f *GeoPointField) GetId() string {
return f.Id
}
// SetId implements [Field.SetId] interface method.
func (f *GeoPointField) SetId(id string) {
f.Id = id
}
// GetName implements [Field.GetName] interface method.
func (f *GeoPointField) GetName() string {
return f.Name
}
// SetName implements [Field.SetName] interface method.
func (f *GeoPointField) SetName(name string) {
f.Name = name
}
// GetSystem implements [Field.GetSystem] interface method.
func (f *GeoPointField) GetSystem() bool {
return f.System
}
// SetSystem implements [Field.SetSystem] interface method.
func (f *GeoPointField) SetSystem(system bool) {
f.System = system
}
// GetHidden implements [Field.GetHidden] interface method.
func (f *GeoPointField) GetHidden() bool {
return f.Hidden
}
// SetHidden implements [Field.SetHidden] interface method.
func (f *GeoPointField) SetHidden(hidden bool) {
f.Hidden = hidden
}
// ColumnType implements [Field.ColumnType] interface method.
func (f *GeoPointField) ColumnType(app App) string {
return `JSON DEFAULT '{"lon":0,"lat":0}' NOT NULL`
}
// PrepareValue implements [Field.PrepareValue] interface method.
func (f *GeoPointField) PrepareValue(record *Record, raw any) (any, error) {
point := types.GeoPoint{}
err := point.Scan(raw)
return point, err
}
// ValidateValue implements [Field.ValidateValue] interface method.
func (f *GeoPointField) ValidateValue(ctx context.Context, app App, record *Record) error {
val, ok := record.GetRaw(f.Name).(types.GeoPoint)
if !ok {
return validators.ErrUnsupportedValueType
}
// zero value
if val.Lat == 0 && val.Lon == 0 {
if f.Required {
return validation.ErrRequired
}
return nil
}
if val.Lat < -90 || val.Lat > 90 {
return validation.NewError("validation_invalid_latitude", "Latitude must be between -90 and 90 degrees.")
}
if val.Lon < -180 || val.Lon > 180 {
return validation.NewError("validation_invalid_longitude", "Longitude must be between -180 and 180 degrees.")
}
return nil
}
// ValidateSettings implements [Field.ValidateSettings] interface method.
func (f *GeoPointField) ValidateSettings(ctx context.Context, app App, collection *Collection) error {
return validation.ValidateStruct(f,
validation.Field(&f.Id, validation.By(DefaultFieldIdValidationRule)),
validation.Field(&f.Name, validation.By(DefaultFieldNameValidationRule)),
)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/collection_model.go | core/collection_model.go | package core
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/dbutils"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/pocketbase/pocketbase/tools/types"
"github.com/spf13/cast"
)
var (
_ Model = (*Collection)(nil)
_ DBExporter = (*Collection)(nil)
_ FilesManager = (*Collection)(nil)
)
const (
CollectionTypeBase = "base"
CollectionTypeAuth = "auth"
CollectionTypeView = "view"
)
const systemHookIdCollection = "__pbCollectionSystemHook__"
const defaultLowercaseRecordIdPattern = "^[a-z0-9]+$"
func (app *BaseApp) registerCollectionHooks() {
app.OnModelValidate().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdCollection,
Func: func(me *ModelEvent) error {
if ce, ok := newCollectionEventFromModelEvent(me); ok {
err := me.App.OnCollectionValidate().Trigger(ce, func(ce *CollectionEvent) error {
syncModelEventWithCollectionEvent(me, ce)
defer syncCollectionEventWithModelEvent(ce, me)
return me.Next()
})
syncModelEventWithCollectionEvent(me, ce)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelCreate().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdCollection,
Func: func(me *ModelEvent) error {
if ce, ok := newCollectionEventFromModelEvent(me); ok {
err := me.App.OnCollectionCreate().Trigger(ce, func(ce *CollectionEvent) error {
syncModelEventWithCollectionEvent(me, ce)
defer syncCollectionEventWithModelEvent(ce, me)
return me.Next()
})
syncModelEventWithCollectionEvent(me, ce)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelCreateExecute().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdCollection,
Func: func(me *ModelEvent) error {
if ce, ok := newCollectionEventFromModelEvent(me); ok {
err := me.App.OnCollectionCreateExecute().Trigger(ce, func(ce *CollectionEvent) error {
syncModelEventWithCollectionEvent(me, ce)
defer syncCollectionEventWithModelEvent(ce, me)
return me.Next()
})
syncModelEventWithCollectionEvent(me, ce)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelAfterCreateSuccess().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdCollection,
Func: func(me *ModelEvent) error {
if ce, ok := newCollectionEventFromModelEvent(me); ok {
err := me.App.OnCollectionAfterCreateSuccess().Trigger(ce, func(ce *CollectionEvent) error {
syncModelEventWithCollectionEvent(me, ce)
defer syncCollectionEventWithModelEvent(ce, me)
return me.Next()
})
syncModelEventWithCollectionEvent(me, ce)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelAfterCreateError().Bind(&hook.Handler[*ModelErrorEvent]{
Id: systemHookIdCollection,
Func: func(me *ModelErrorEvent) error {
if ce, ok := newCollectionErrorEventFromModelErrorEvent(me); ok {
err := me.App.OnCollectionAfterCreateError().Trigger(ce, func(ce *CollectionErrorEvent) error {
syncModelErrorEventWithCollectionErrorEvent(me, ce)
defer syncCollectionErrorEventWithModelErrorEvent(ce, me)
return me.Next()
})
syncModelErrorEventWithCollectionErrorEvent(me, ce)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelUpdate().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdCollection,
Func: func(me *ModelEvent) error {
if ce, ok := newCollectionEventFromModelEvent(me); ok {
err := me.App.OnCollectionUpdate().Trigger(ce, func(ce *CollectionEvent) error {
syncModelEventWithCollectionEvent(me, ce)
defer syncCollectionEventWithModelEvent(ce, me)
return me.Next()
})
syncModelEventWithCollectionEvent(me, ce)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelUpdateExecute().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdCollection,
Func: func(me *ModelEvent) error {
if ce, ok := newCollectionEventFromModelEvent(me); ok {
err := me.App.OnCollectionUpdateExecute().Trigger(ce, func(ce *CollectionEvent) error {
syncModelEventWithCollectionEvent(me, ce)
defer syncCollectionEventWithModelEvent(ce, me)
return me.Next()
})
syncModelEventWithCollectionEvent(me, ce)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelAfterUpdateSuccess().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdCollection,
Func: func(me *ModelEvent) error {
if ce, ok := newCollectionEventFromModelEvent(me); ok {
err := me.App.OnCollectionAfterUpdateSuccess().Trigger(ce, func(ce *CollectionEvent) error {
syncModelEventWithCollectionEvent(me, ce)
defer syncCollectionEventWithModelEvent(ce, me)
return me.Next()
})
syncModelEventWithCollectionEvent(me, ce)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelAfterUpdateError().Bind(&hook.Handler[*ModelErrorEvent]{
Id: systemHookIdCollection,
Func: func(me *ModelErrorEvent) error {
if ce, ok := newCollectionErrorEventFromModelErrorEvent(me); ok {
err := me.App.OnCollectionAfterUpdateError().Trigger(ce, func(ce *CollectionErrorEvent) error {
syncModelErrorEventWithCollectionErrorEvent(me, ce)
defer syncCollectionErrorEventWithModelErrorEvent(ce, me)
return me.Next()
})
syncModelErrorEventWithCollectionErrorEvent(me, ce)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelDelete().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdCollection,
Func: func(me *ModelEvent) error {
if ce, ok := newCollectionEventFromModelEvent(me); ok {
err := me.App.OnCollectionDelete().Trigger(ce, func(ce *CollectionEvent) error {
syncModelEventWithCollectionEvent(me, ce)
defer syncCollectionEventWithModelEvent(ce, me)
return me.Next()
})
syncModelEventWithCollectionEvent(me, ce)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelDeleteExecute().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdCollection,
Func: func(me *ModelEvent) error {
if ce, ok := newCollectionEventFromModelEvent(me); ok {
err := me.App.OnCollectionDeleteExecute().Trigger(ce, func(ce *CollectionEvent) error {
syncModelEventWithCollectionEvent(me, ce)
defer syncCollectionEventWithModelEvent(ce, me)
return me.Next()
})
syncModelEventWithCollectionEvent(me, ce)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelAfterDeleteSuccess().Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdCollection,
Func: func(me *ModelEvent) error {
if ce, ok := newCollectionEventFromModelEvent(me); ok {
err := me.App.OnCollectionAfterDeleteSuccess().Trigger(ce, func(ce *CollectionEvent) error {
syncModelEventWithCollectionEvent(me, ce)
defer syncCollectionEventWithModelEvent(ce, me)
return me.Next()
})
syncModelEventWithCollectionEvent(me, ce)
return err
}
return me.Next()
},
Priority: -99,
})
app.OnModelAfterDeleteError().Bind(&hook.Handler[*ModelErrorEvent]{
Id: systemHookIdCollection,
Func: func(me *ModelErrorEvent) error {
if ce, ok := newCollectionErrorEventFromModelErrorEvent(me); ok {
err := me.App.OnCollectionAfterDeleteError().Trigger(ce, func(ce *CollectionErrorEvent) error {
syncModelErrorEventWithCollectionErrorEvent(me, ce)
defer syncCollectionErrorEventWithModelErrorEvent(ce, me)
return me.Next()
})
syncModelErrorEventWithCollectionErrorEvent(me, ce)
return err
}
return me.Next()
},
Priority: -99,
})
// --------------------------------------------------------------
app.OnCollectionValidate().Bind(&hook.Handler[*CollectionEvent]{
Id: systemHookIdCollection,
Func: onCollectionValidate,
Priority: 99,
})
app.OnCollectionCreate().Bind(&hook.Handler[*CollectionEvent]{
Id: systemHookIdCollection,
Func: onCollectionSave,
Priority: -99,
})
app.OnCollectionUpdate().Bind(&hook.Handler[*CollectionEvent]{
Id: systemHookIdCollection,
Func: onCollectionSave,
Priority: -99,
})
app.OnCollectionCreateExecute().Bind(&hook.Handler[*CollectionEvent]{
Id: systemHookIdCollection,
Func: onCollectionSaveExecute,
// execute as latest as possible, aka. closer to the db action to minimize the transactions lock time
Priority: 99,
})
app.OnCollectionUpdateExecute().Bind(&hook.Handler[*CollectionEvent]{
Id: systemHookIdCollection,
Func: onCollectionSaveExecute,
Priority: 99, // execute as latest as possible, aka. closer to the db action to minimize the transactions lock time
})
app.OnCollectionDeleteExecute().Bind(&hook.Handler[*CollectionEvent]{
Id: systemHookIdCollection,
Func: onCollectionDeleteExecute,
Priority: 99, // execute as latest as possible, aka. closer to the db action to minimize the transactions lock time
})
// reload cache on failure
// ---
onErrorReloadCachedCollections := func(ce *CollectionErrorEvent) error {
if err := ce.App.ReloadCachedCollections(); err != nil {
ce.App.Logger().Warn("Failed to reload collections cache after collection change error", "error", err)
}
return ce.Next()
}
app.OnCollectionAfterCreateError().Bind(&hook.Handler[*CollectionErrorEvent]{
Id: systemHookIdCollection,
Func: onErrorReloadCachedCollections,
Priority: -99,
})
app.OnCollectionAfterUpdateError().Bind(&hook.Handler[*CollectionErrorEvent]{
Id: systemHookIdCollection,
Func: onErrorReloadCachedCollections,
Priority: -99,
})
app.OnCollectionAfterDeleteError().Bind(&hook.Handler[*CollectionErrorEvent]{
Id: systemHookIdCollection,
Func: onErrorReloadCachedCollections,
Priority: -99,
})
// ---
app.OnBootstrap().Bind(&hook.Handler[*BootstrapEvent]{
Id: systemHookIdCollection,
Func: func(e *BootstrapEvent) error {
if err := e.Next(); err != nil {
return err
}
if err := e.App.ReloadCachedCollections(); err != nil {
return fmt.Errorf("failed to load collections cache: %w", err)
}
return nil
},
Priority: 99, // execute as latest as possible
})
}
// @todo experiment eventually replacing the rules *string with a struct?
type baseCollection struct {
BaseModel
disableIntegrityChecks bool
autogeneratedId string
ListRule *string `db:"listRule" json:"listRule" form:"listRule"`
ViewRule *string `db:"viewRule" json:"viewRule" form:"viewRule"`
CreateRule *string `db:"createRule" json:"createRule" form:"createRule"`
UpdateRule *string `db:"updateRule" json:"updateRule" form:"updateRule"`
DeleteRule *string `db:"deleteRule" json:"deleteRule" form:"deleteRule"`
// RawOptions represents the raw serialized collection option loaded from the DB.
// NB! This field shouldn't be modified manually. It is automatically updated
// with the collection type specific option before save.
RawOptions types.JSONRaw `db:"options" json:"-" xml:"-" form:"-"`
Name string `db:"name" json:"name" form:"name"`
Type string `db:"type" json:"type" form:"type"`
Fields FieldsList `db:"fields" json:"fields" form:"fields"`
Indexes types.JSONArray[string] `db:"indexes" json:"indexes" form:"indexes"`
Created types.DateTime `db:"created" json:"created"`
Updated types.DateTime `db:"updated" json:"updated"`
// System prevents the collection rename, deletion and rules change.
// It is used primarily for internal purposes for collections like "_superusers", "_externalAuths", etc.
System bool `db:"system" json:"system" form:"system"`
}
// Collection defines the table, fields and various options related to a set of records.
type Collection struct {
baseCollection
collectionAuthOptions
collectionViewOptions
}
// NewCollection initializes and returns a new Collection model with the specified type and name.
//
// It also loads the minimal default configuration for the collection
// (eg. system fields, indexes, type specific options, etc.).
func NewCollection(typ, name string, optId ...string) *Collection {
switch typ {
case CollectionTypeAuth:
return NewAuthCollection(name, optId...)
case CollectionTypeView:
return NewViewCollection(name, optId...)
default:
return NewBaseCollection(name, optId...)
}
}
// NewBaseCollection initializes and returns a new "base" Collection model.
//
// It also loads the minimal default configuration for the collection
// (eg. system fields, indexes, type specific options, etc.).
func NewBaseCollection(name string, optId ...string) *Collection {
m := &Collection{}
m.Name = name
m.Type = CollectionTypeBase
// @todo consider removing once inferred composite literals are supported
if len(optId) > 0 {
m.Id = optId[0]
}
m.initDefaultId()
m.initDefaultFields()
return m
}
// NewViewCollection initializes and returns a new "view" Collection model.
//
// It also loads the minimal default configuration for the collection
// (eg. system fields, indexes, type specific options, etc.).
func NewViewCollection(name string, optId ...string) *Collection {
m := &Collection{}
m.Name = name
m.Type = CollectionTypeView
// @todo consider removing once inferred composite literals are supported
if len(optId) > 0 {
m.Id = optId[0]
}
m.initDefaultId()
m.initDefaultFields()
return m
}
// NewAuthCollection initializes and returns a new "auth" Collection model.
//
// It also loads the minimal default configuration for the collection
// (eg. system fields, indexes, type specific options, etc.).
func NewAuthCollection(name string, optId ...string) *Collection {
m := &Collection{}
m.Name = name
m.Type = CollectionTypeAuth
// @todo consider removing once inferred composite literals are supported
if len(optId) > 0 {
m.Id = optId[0]
}
m.initDefaultId()
m.initDefaultFields()
m.setDefaultAuthOptions()
return m
}
// TableName returns the Collection model SQL table name.
func (m *Collection) TableName() string {
return "_collections"
}
// BaseFilesPath returns the storage dir path used by the collection.
func (m *Collection) BaseFilesPath() string {
return m.Id
}
// IsBase checks if the current collection has "base" type.
func (m *Collection) IsBase() bool {
return m.Type == CollectionTypeBase
}
// IsAuth checks if the current collection has "auth" type.
func (m *Collection) IsAuth() bool {
return m.Type == CollectionTypeAuth
}
// IsView checks if the current collection has "view" type.
func (m *Collection) IsView() bool {
return m.Type == CollectionTypeView
}
// IntegrityChecks toggles the current collection integrity checks (ex. checking references on delete).
func (m *Collection) IntegrityChecks(enable bool) {
m.disableIntegrityChecks = !enable
}
// PostScan implements the [dbx.PostScanner] interface to auto unmarshal
// the raw serialized options into the concrete type specific fields.
func (m *Collection) PostScan() error {
if err := m.BaseModel.PostScan(); err != nil {
return err
}
return m.unmarshalRawOptions()
}
func (m *Collection) unmarshalRawOptions() error {
raw, err := m.RawOptions.MarshalJSON()
if err != nil {
return nil
}
switch m.Type {
case CollectionTypeView:
return json.Unmarshal(raw, &m.collectionViewOptions)
case CollectionTypeAuth:
return json.Unmarshal(raw, &m.collectionAuthOptions)
}
return nil
}
// UnmarshalJSON implements the [json.Unmarshaler] interface.
//
// For new/"blank" Collection models it replaces the model with a factory
// instance and then unmarshal the provided data one on top of it.
func (m *Collection) UnmarshalJSON(b []byte) error {
type alias *Collection
// initialize the default fields
// (e.g. in case the collection was NOT created using the designated factories)
if m.IsNew() && m.Type == "" {
minimal := &struct {
Type string `json:"type"`
Name string `json:"name"`
Id string `json:"id"`
}{}
if err := json.Unmarshal(b, minimal); err != nil {
return err
}
blank := NewCollection(minimal.Type, minimal.Name, minimal.Id)
*m = *blank
}
return json.Unmarshal(b, alias(m))
}
// MarshalJSON implements the [json.Marshaler] interface.
//
// Note that non-type related fields are ignored from the serialization
// (ex. for "view" colections the "auth" fields are skipped).
func (m Collection) MarshalJSON() ([]byte, error) {
switch m.Type {
case CollectionTypeView:
return json.Marshal(struct {
baseCollection
collectionViewOptions
}{m.baseCollection, m.collectionViewOptions})
case CollectionTypeAuth:
alias := struct {
baseCollection
collectionAuthOptions
}{m.baseCollection, m.collectionAuthOptions}
// ensure that it is always returned as array
if alias.OAuth2.Providers == nil {
alias.OAuth2.Providers = []OAuth2ProviderConfig{}
}
// hide secret keys from the serialization
alias.AuthToken.Secret = ""
alias.FileToken.Secret = ""
alias.PasswordResetToken.Secret = ""
alias.EmailChangeToken.Secret = ""
alias.VerificationToken.Secret = ""
for i := range alias.OAuth2.Providers {
alias.OAuth2.Providers[i].ClientSecret = ""
}
return json.Marshal(alias)
default:
return json.Marshal(m.baseCollection)
}
}
// String returns a string representation of the current collection.
func (m Collection) String() string {
raw, _ := json.Marshal(m)
return string(raw)
}
// DBExport prepares and exports the current collection data for db persistence.
func (m *Collection) DBExport(app App) (map[string]any, error) {
result := map[string]any{
"id": m.Id,
"type": m.Type,
"listRule": m.ListRule,
"viewRule": m.ViewRule,
"createRule": m.CreateRule,
"updateRule": m.UpdateRule,
"deleteRule": m.DeleteRule,
"name": m.Name,
"fields": m.Fields,
"indexes": m.Indexes,
"system": m.System,
"created": m.Created,
"updated": m.Updated,
"options": `{}`,
}
switch m.Type {
case CollectionTypeView:
if raw, err := types.ParseJSONRaw(m.collectionViewOptions); err == nil {
result["options"] = raw
} else {
return nil, err
}
case CollectionTypeAuth:
if raw, err := types.ParseJSONRaw(m.collectionAuthOptions); err == nil {
result["options"] = raw
} else {
return nil, err
}
}
return result, nil
}
// GetIndex returns s single Collection index expression by its name.
func (m *Collection) GetIndex(name string) string {
for _, idx := range m.Indexes {
if strings.EqualFold(dbutils.ParseIndex(idx).IndexName, name) {
return idx
}
}
return ""
}
// AddIndex adds a new index into the current collection.
//
// If the collection has an existing index matching the new name it will be replaced with the new one.
func (m *Collection) AddIndex(name string, unique bool, columnsExpr string, optWhereExpr string) {
m.RemoveIndex(name)
var idx strings.Builder
idx.WriteString("CREATE ")
if unique {
idx.WriteString("UNIQUE ")
}
idx.WriteString("INDEX `")
idx.WriteString(name)
idx.WriteString("` ")
idx.WriteString("ON `")
idx.WriteString(m.Name)
idx.WriteString("` (")
idx.WriteString(columnsExpr)
idx.WriteString(")")
if optWhereExpr != "" {
idx.WriteString(" WHERE ")
idx.WriteString(optWhereExpr)
}
m.Indexes = append(m.Indexes, idx.String())
}
// RemoveIndex removes a single index with the specified name from the current collection.
func (m *Collection) RemoveIndex(name string) {
for i, idx := range m.Indexes {
if strings.EqualFold(dbutils.ParseIndex(idx).IndexName, name) {
m.Indexes = append(m.Indexes[:i], m.Indexes[i+1:]...)
return
}
}
}
// delete hook
// -------------------------------------------------------------------
func onCollectionDeleteExecute(e *CollectionEvent) error {
if e.Collection.System {
return fmt.Errorf("[%s] system collections cannot be deleted", e.Collection.Name)
}
defer func() {
if err := e.App.ReloadCachedCollections(); err != nil {
e.App.Logger().Warn("Failed to reload collections cache", "error", err)
}
}()
if !e.Collection.disableIntegrityChecks {
// ensure that there aren't any existing references.
// note: the select is outside of the transaction to prevent SQLITE_LOCKED error when mixing read&write in a single transaction
references, err := e.App.FindCollectionReferences(e.Collection, e.Collection.Id)
if err != nil {
return fmt.Errorf("[%s] failed to check collection references: %w", e.Collection.Name, err)
}
if total := len(references); total > 0 {
names := make([]string, 0, len(references))
for ref := range references {
names = append(names, ref.Name)
}
return fmt.Errorf("[%s] failed to delete due to existing relation references: %s", e.Collection.Name, strings.Join(names, ", "))
}
}
originalApp := e.App
txErr := e.App.RunInTransaction(func(txApp App) error {
e.App = txApp
// delete the related view or records table
if e.Collection.IsView() {
if err := txApp.DeleteView(e.Collection.Name); err != nil {
return err
}
} else {
if err := txApp.DeleteTable(e.Collection.Name); err != nil {
return err
}
}
if !e.Collection.disableIntegrityChecks {
// trigger views resave to check for dependencies
if err := resaveViewsWithChangedFields(txApp, e.Collection.Id); err != nil {
return fmt.Errorf("[%s] failed to delete due to existing view dependency: %w", e.Collection.Name, err)
}
}
// delete
return e.Next()
})
e.App = originalApp
return txErr
}
// save hook
// -------------------------------------------------------------------
func (c *Collection) idChecksum() string {
return "pbc_" + crc32Checksum(c.Type+c.Name)
}
func (c *Collection) initDefaultId() {
if c.Id == "" {
c.Id = c.idChecksum()
c.autogeneratedId = c.Id
}
}
func (c *Collection) updateGeneratedIdIfExists(app App) {
if !c.IsNew() ||
// the id was explicitly cleared
c.Id == "" ||
// the id was manually set
c.Id != c.autogeneratedId {
return
}
// generate an up-to-date checksum
newId := c.idChecksum()
// add a number to the current id (if already exists)
for i := 2; i < 1000; i++ {
var exists int
_ = app.CollectionQuery().Select("(1)").AndWhere(dbx.HashExp{"id": newId}).Limit(1).Row(&exists)
if exists == 0 {
break
}
newId = c.idChecksum() + strconv.Itoa(i)
}
// no change
if c.Id == newId {
return
}
// replace the old id in the index names (if any)
for i, idx := range c.Indexes {
parsed := dbutils.ParseIndex(idx)
original := parsed.IndexName
parsed.IndexName = strings.ReplaceAll(parsed.IndexName, c.Id, newId)
if parsed.IndexName != original {
c.Indexes[i] = parsed.Build()
}
}
// update model id
c.Id = newId
}
func onCollectionSave(e *CollectionEvent) error {
if e.Collection.Type == "" {
e.Collection.Type = CollectionTypeBase
}
if e.Collection.IsNew() {
e.Collection.initDefaultId()
e.Collection.Created = types.NowDateTime()
}
e.Collection.Updated = types.NowDateTime()
// recreate the fields list to ensure that all normalizations
// like default field id are applied
e.Collection.Fields = NewFieldsList(e.Collection.Fields...)
e.Collection.initDefaultFields()
if e.Collection.IsAuth() {
e.Collection.unsetMissingOAuth2MappedFields()
}
e.Collection.updateGeneratedIdIfExists(e.App)
return e.Next()
}
func onCollectionSaveExecute(e *CollectionEvent) error {
defer func() {
if err := e.App.ReloadCachedCollections(); err != nil {
e.App.Logger().Warn("Failed to reload collections cache", "error", err)
}
}()
var oldCollection *Collection
if !e.Collection.IsNew() {
var err error
oldCollection, err = e.App.FindCachedCollectionByNameOrId(e.Collection.Id)
if err != nil {
return err
}
// invalidate previously issued auth tokens on auth rule change
if oldCollection.AuthRule != e.Collection.AuthRule &&
cast.ToString(oldCollection.AuthRule) != cast.ToString(e.Collection.AuthRule) {
e.Collection.AuthToken.Secret = security.RandomString(50)
}
}
originalApp := e.App
txErr := e.App.RunInTransaction(func(txApp App) error {
e.App = txApp
isView := e.Collection.IsView()
// ensures that the view collection shema is properly loaded
if isView {
query := e.Collection.ViewQuery
// generate collection fields list from the query
viewFields, err := e.App.CreateViewFields(query)
if err != nil {
return err
}
// delete old renamed view
if oldCollection != nil {
if err := e.App.DeleteView(oldCollection.Name); err != nil {
return err
}
}
// wrap view query if necessary
query, err = normalizeViewQueryId(e.App, query)
if err != nil {
return fmt.Errorf("failed to normalize view query id: %w", err)
}
// (re)create the view
if err := e.App.SaveView(e.Collection.Name, query); err != nil {
return err
}
// updates newCollection.Fields based on the generated view table info and query
e.Collection.Fields = viewFields
}
// save the Collection model
if err := e.Next(); err != nil {
return err
}
// sync the changes with the related records table
if !isView {
if err := e.App.SyncRecordTableSchema(e.Collection, oldCollection); err != nil {
// note: don't wrap to allow propagating indexes validation.Errors
return err
}
}
return nil
})
e.App = originalApp
if txErr != nil {
return txErr
}
// trigger an update for all views with changed fields as a result of the current collection save
// (ignoring view errors to allow users to update the query from the UI)
resaveViewsWithChangedFields(e.App, e.Collection.Id)
return nil
}
func (c *Collection) initDefaultFields() {
switch c.Type {
case CollectionTypeBase:
c.initIdField()
case CollectionTypeAuth:
c.initIdField()
c.initPasswordField()
c.initTokenKeyField()
c.initEmailField()
c.initEmailVisibilityField()
c.initVerifiedField()
case CollectionTypeView:
// view fields are autogenerated
}
}
func (c *Collection) initIdField() {
field, _ := c.Fields.GetByName(FieldNameId).(*TextField)
if field == nil {
// create default field
field = &TextField{
Name: FieldNameId,
System: true,
PrimaryKey: true,
Required: true,
Min: 15,
Max: 15,
Pattern: defaultLowercaseRecordIdPattern,
AutogeneratePattern: `[a-z0-9]{15}`,
}
// prepend it
c.Fields = NewFieldsList(append([]Field{field}, c.Fields...)...)
} else {
// enforce system defaults
field.System = true
field.Required = true
field.PrimaryKey = true
field.Hidden = false
if field.Pattern == "" {
field.Pattern = defaultLowercaseRecordIdPattern
}
}
}
func (c *Collection) initPasswordField() {
field, _ := c.Fields.GetByName(FieldNamePassword).(*PasswordField)
if field == nil {
// load default field
c.Fields.Add(&PasswordField{
Name: FieldNamePassword,
System: true,
Hidden: true,
Required: true,
Min: 8,
})
} else {
// enforce system defaults
field.System = true
field.Hidden = true
field.Required = true
}
}
func (c *Collection) initTokenKeyField() {
field, _ := c.Fields.GetByName(FieldNameTokenKey).(*TextField)
if field == nil {
// load default field
c.Fields.Add(&TextField{
Name: FieldNameTokenKey,
System: true,
Hidden: true,
Min: 30,
Max: 60,
Required: true,
AutogeneratePattern: `[a-zA-Z0-9]{50}`,
})
} else {
// enforce system defaults
field.System = true
field.Hidden = true
field.Required = true
}
// ensure that there is a unique index for the field
if _, ok := dbutils.FindSingleColumnUniqueIndex(c.Indexes, FieldNameTokenKey); !ok {
c.Indexes = append(c.Indexes, fmt.Sprintf(
"CREATE UNIQUE INDEX `%s` ON `%s` (`%s`)",
c.fieldIndexName(FieldNameTokenKey),
c.Name,
FieldNameTokenKey,
))
}
}
func (c *Collection) initEmailField() {
field, _ := c.Fields.GetByName(FieldNameEmail).(*EmailField)
if field == nil {
// load default field
c.Fields.Add(&EmailField{
Name: FieldNameEmail,
System: true,
Required: true,
})
} else {
// enforce system defaults
field.System = true
field.Hidden = false // managed by the emailVisibility flag
}
// ensure that there is a unique index for the email field
if _, ok := dbutils.FindSingleColumnUniqueIndex(c.Indexes, FieldNameEmail); !ok {
c.Indexes = append(c.Indexes, fmt.Sprintf(
"CREATE UNIQUE INDEX `%s` ON `%s` (`%s`) WHERE `%s` != ''",
c.fieldIndexName(FieldNameEmail),
c.Name,
FieldNameEmail,
FieldNameEmail,
))
}
}
func (c *Collection) initEmailVisibilityField() {
field, _ := c.Fields.GetByName(FieldNameEmailVisibility).(*BoolField)
if field == nil {
// load default field
c.Fields.Add(&BoolField{
Name: FieldNameEmailVisibility,
System: true,
})
} else {
// enforce system defaults
field.System = true
}
}
func (c *Collection) initVerifiedField() {
field, _ := c.Fields.GetByName(FieldNameVerified).(*BoolField)
if field == nil {
// load default field
c.Fields.Add(&BoolField{
Name: FieldNameVerified,
System: true,
})
} else {
// enforce system defaults
field.System = true
}
}
func (c *Collection) fieldIndexName(field string) string {
name := "idx_" + field + "_"
if c.Id != "" {
name += c.Id
} else if c.Name != "" {
name += c.Name
} else {
name += security.PseudorandomStringWithAlphabet(10, DefaultIdAlphabet)
}
if len(name) > 64 {
return name[:64]
}
return name
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/migrations_runner.go | core/migrations_runner.go | package core
import (
"fmt"
"strings"
"time"
"github.com/fatih/color"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/osutils"
"github.com/spf13/cast"
)
var AppMigrations MigrationsList
var SystemMigrations MigrationsList
const DefaultMigrationsTable = "_migrations"
// MigrationsRunner defines a simple struct for managing the execution of db migrations.
type MigrationsRunner struct {
app App
tableName string
migrationsList MigrationsList
inited bool
}
// NewMigrationsRunner creates and initializes a new db migrations MigrationsRunner instance.
func NewMigrationsRunner(app App, migrationsList MigrationsList) *MigrationsRunner {
return &MigrationsRunner{
app: app,
migrationsList: migrationsList,
tableName: DefaultMigrationsTable,
}
}
// Run interactively executes the current runner with the provided args.
//
// The following commands are supported:
// - up - applies all migrations
// - down [n] - reverts the last n (default 1) applied migrations
// - history-sync - syncs the migrations table with the runner's migrations list
func (r *MigrationsRunner) Run(args ...string) error {
if err := r.initMigrationsTable(); err != nil {
return err
}
cmd := "up"
if len(args) > 0 {
cmd = args[0]
}
switch cmd {
case "up":
applied, err := r.Up()
if err != nil {
return err
}
if len(applied) == 0 {
color.Green("No new migrations to apply.")
} else {
for _, file := range applied {
color.Green("Applied %s", file)
}
}
return nil
case "down":
toRevertCount := 1
if len(args) > 1 {
toRevertCount = cast.ToInt(args[1])
if toRevertCount < 0 {
// revert all applied migrations
toRevertCount = len(r.migrationsList.Items())
}
}
names, err := r.lastAppliedMigrations(toRevertCount)
if err != nil {
return err
}
confirm := osutils.YesNoPrompt(fmt.Sprintf(
"\n%v\nDo you really want to revert the last %d applied migration(s)?",
strings.Join(names, "\n"),
toRevertCount,
), false)
if !confirm {
fmt.Println("The command has been cancelled")
return nil
}
reverted, err := r.Down(toRevertCount)
if err != nil {
return err
}
if len(reverted) == 0 {
color.Green("No migrations to revert.")
} else {
for _, file := range reverted {
color.Green("Reverted %s", file)
}
}
return nil
case "history-sync":
if err := r.RemoveMissingAppliedMigrations(); err != nil {
return err
}
color.Green("The %s table was synced with the available migrations.", r.tableName)
return nil
default:
return fmt.Errorf("unsupported command: %q", cmd)
}
}
// Up executes all unapplied migrations for the provided runner.
//
// On success returns list with the applied migrations file names.
func (r *MigrationsRunner) Up() ([]string, error) {
if err := r.initMigrationsTable(); err != nil {
return nil, err
}
applied := []string{}
err := r.app.AuxRunInTransaction(func(txApp App) error {
return txApp.RunInTransaction(func(txApp App) error {
for _, m := range r.migrationsList.Items() {
// applied migrations check
if r.isMigrationApplied(txApp, m.File) {
if m.ReapplyCondition == nil {
continue // no need to reapply
}
shouldReapply, err := m.ReapplyCondition(txApp, r, m.File)
if err != nil {
return err
}
if !shouldReapply {
continue
}
// clear previous history stored entry
// (it will be recreated after successful execution)
r.saveRevertedMigration(txApp, m.File)
}
// ignore empty Up action
if m.Up != nil {
if err := m.Up(txApp); err != nil {
return fmt.Errorf("failed to apply migration %s: %w", m.File, err)
}
}
if err := r.saveAppliedMigration(txApp, m.File); err != nil {
return fmt.Errorf("failed to save applied migration info for %s: %w", m.File, err)
}
applied = append(applied, m.File)
}
return nil
})
})
if err != nil {
return nil, err
}
return applied, nil
}
// Down reverts the last `toRevertCount` applied migrations
// (in the order they were applied).
//
// On success returns list with the reverted migrations file names.
func (r *MigrationsRunner) Down(toRevertCount int) ([]string, error) {
if err := r.initMigrationsTable(); err != nil {
return nil, err
}
reverted := make([]string, 0, toRevertCount)
names, appliedErr := r.lastAppliedMigrations(toRevertCount)
if appliedErr != nil {
return nil, appliedErr
}
err := r.app.AuxRunInTransaction(func(txApp App) error {
return txApp.RunInTransaction(func(txApp App) error {
for _, name := range names {
for _, m := range r.migrationsList.Items() {
if m.File != name {
continue
}
// revert limit reached
if toRevertCount-len(reverted) <= 0 {
return nil
}
// ignore empty Down action
if m.Down != nil {
if err := m.Down(txApp); err != nil {
return fmt.Errorf("failed to revert migration %s: %w", m.File, err)
}
}
if err := r.saveRevertedMigration(txApp, m.File); err != nil {
return fmt.Errorf("failed to save reverted migration info for %s: %w", m.File, err)
}
reverted = append(reverted, m.File)
}
}
return nil
})
})
if err != nil {
return nil, err
}
return reverted, nil
}
// RemoveMissingAppliedMigrations removes the db entries of all applied migrations
// that are not listed in the runner's migrations list.
func (r *MigrationsRunner) RemoveMissingAppliedMigrations() error {
loadedMigrations := r.migrationsList.Items()
names := make([]any, len(loadedMigrations))
for i, migration := range loadedMigrations {
names[i] = migration.File
}
_, err := r.app.DB().Delete(r.tableName, dbx.Not(dbx.HashExp{
"file": names,
})).Execute()
return err
}
func (r *MigrationsRunner) initMigrationsTable() error {
if r.inited {
return nil // already inited
}
rawQuery := fmt.Sprintf(
"CREATE TABLE IF NOT EXISTS {{%s}} (file VARCHAR(255) PRIMARY KEY NOT NULL, applied INTEGER NOT NULL)",
r.tableName,
)
_, err := r.app.DB().NewQuery(rawQuery).Execute()
if err == nil {
r.inited = true
}
return err
}
func (r *MigrationsRunner) isMigrationApplied(txApp App, file string) bool {
var exists int
err := txApp.DB().Select("(1)").
From(r.tableName).
Where(dbx.HashExp{"file": file}).
Limit(1).
Row(&exists)
return err == nil && exists > 0
}
func (r *MigrationsRunner) saveAppliedMigration(txApp App, file string) error {
_, err := txApp.DB().Insert(r.tableName, dbx.Params{
"file": file,
"applied": time.Now().UnixMicro(),
}).Execute()
return err
}
func (r *MigrationsRunner) saveRevertedMigration(txApp App, file string) error {
_, err := txApp.DB().Delete(r.tableName, dbx.HashExp{"file": file}).Execute()
return err
}
func (r *MigrationsRunner) lastAppliedMigrations(limit int) ([]string, error) {
var files = make([]string, 0, limit)
loadedMigrations := r.migrationsList.Items()
names := make([]any, len(loadedMigrations))
for i, migration := range loadedMigrations {
names[i] = migration.File
}
err := r.app.DB().Select("file").
From(r.tableName).
Where(dbx.Not(dbx.HashExp{"applied": nil})).
AndWhere(dbx.HashExp{"file": names}).
// unify microseconds and seconds applied time for backward compatibility
OrderBy("substr(applied||'0000000000000000', 0, 17) DESC").
AndOrderBy("file DESC").
Limit(int64(limit)).
Column(&files)
if err != nil {
return nil, err
}
return files, nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_model_auth_test.go | core/record_model_auth_test.go | package core_test
import (
"context"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/security"
)
func TestRecordEmail(t *testing.T) {
record := core.NewRecord(core.NewAuthCollection("test"))
if record.Email() != "" {
t.Fatalf("Expected email %q, got %q", "", record.Email())
}
email := "test@example.com"
record.SetEmail(email)
if record.Email() != email {
t.Fatalf("Expected email %q, got %q", email, record.Email())
}
}
func TestRecordEmailVisibility(t *testing.T) {
record := core.NewRecord(core.NewAuthCollection("test"))
if record.EmailVisibility() != false {
t.Fatalf("Expected emailVisibility %v, got %v", false, record.EmailVisibility())
}
record.SetEmailVisibility(true)
if record.EmailVisibility() != true {
t.Fatalf("Expected emailVisibility %v, got %v", true, record.EmailVisibility())
}
}
func TestRecordVerified(t *testing.T) {
record := core.NewRecord(core.NewAuthCollection("test"))
if record.Verified() != false {
t.Fatalf("Expected verified %v, got %v", false, record.Verified())
}
record.SetVerified(true)
if record.Verified() != true {
t.Fatalf("Expected verified %v, got %v", true, record.Verified())
}
}
func TestRecordTokenKey(t *testing.T) {
record := core.NewRecord(core.NewAuthCollection("test"))
if record.TokenKey() != "" {
t.Fatalf("Expected tokenKey %q, got %q", "", record.TokenKey())
}
tokenKey := "example"
record.SetTokenKey(tokenKey)
if record.TokenKey() != tokenKey {
t.Fatalf("Expected tokenKey %q, got %q", tokenKey, record.TokenKey())
}
record.RefreshTokenKey()
if record.TokenKey() == tokenKey {
t.Fatalf("Expected tokenKey to be random generated, got %q", tokenKey)
}
if len(record.TokenKey()) != 50 {
t.Fatalf("Expected %d characters, got %d", 50, len(record.TokenKey()))
}
}
func TestRecordPassword(t *testing.T) {
scenarios := []struct {
name string
password string
expected bool
}{
{
"empty password",
"",
false,
},
{
"non-empty password",
"123456",
true,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
record := core.NewRecord(core.NewAuthCollection("test"))
if record.ValidatePassword(s.password) {
t.Fatal("[before set] Expected password to be invalid")
}
record.SetPassword(s.password)
result := record.ValidatePassword(s.password)
if result != s.expected {
t.Fatalf("[after set] Expected ValidatePassword %v, got %v", result, s.expected)
}
// try with a random string to ensure that not any string validates
if record.ValidatePassword(security.PseudorandomString(5)) {
t.Fatal("[random] Expected password to be invalid")
}
})
}
}
func TestRecordSetRandomPassword(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
oldTokenKey := "old_tokenKey"
record := core.NewRecord(core.NewAuthCollection("test"))
record.SetTokenKey(oldTokenKey)
pass := record.SetRandomPassword()
if pass == "" {
t.Fatal("Expected non-empty generated random password")
}
if !record.ValidatePassword(pass) {
t.Fatal("Expected the generated random password to be valid")
}
if record.TokenKey() == oldTokenKey {
t.Fatal("Expected token key to change")
}
f, ok := record.Collection().Fields.GetByName(core.FieldNamePassword).(*core.PasswordField)
if !ok {
t.Fatal("Expected *core.PasswordField")
}
// ensure that the field validators will be ignored
f.Min = 1
f.Max = 2
f.Pattern = `\d+`
if err := f.ValidateValue(context.Background(), app, record); err != nil {
t.Fatalf("Expected password field plain value validators to be ignored, got %v", err)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/external_auth_model_test.go | core/external_auth_model_test.go | package core_test
import (
"fmt"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestNewExternalAuth(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
ea := core.NewExternalAuth(app)
if ea.Collection().Name != core.CollectionNameExternalAuths {
t.Fatalf("Expected record with %q collection, got %q", core.CollectionNameExternalAuths, ea.Collection().Name)
}
}
func TestExternalAuthProxyRecord(t *testing.T) {
t.Parallel()
record := core.NewRecord(core.NewBaseCollection("test"))
record.Id = "test_id"
ea := core.ExternalAuth{}
ea.SetProxyRecord(record)
if ea.ProxyRecord() == nil || ea.ProxyRecord().Id != record.Id {
t.Fatalf("Expected proxy record with id %q, got %v", record.Id, ea.ProxyRecord())
}
}
func TestExternalAuthRecordRef(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
ea := core.NewExternalAuth(app)
testValues := []string{"test_1", "test2", ""}
for i, testValue := range testValues {
t.Run(fmt.Sprintf("%d_%q", i, testValue), func(t *testing.T) {
ea.SetRecordRef(testValue)
if v := ea.RecordRef(); v != testValue {
t.Fatalf("Expected getter %q, got %q", testValue, v)
}
if v := ea.GetString("recordRef"); v != testValue {
t.Fatalf("Expected field value %q, got %q", testValue, v)
}
})
}
}
func TestExternalAuthCollectionRef(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
ea := core.NewExternalAuth(app)
testValues := []string{"test_1", "test2", ""}
for i, testValue := range testValues {
t.Run(fmt.Sprintf("%d_%q", i, testValue), func(t *testing.T) {
ea.SetCollectionRef(testValue)
if v := ea.CollectionRef(); v != testValue {
t.Fatalf("Expected getter %q, got %q", testValue, v)
}
if v := ea.GetString("collectionRef"); v != testValue {
t.Fatalf("Expected field value %q, got %q", testValue, v)
}
})
}
}
func TestExternalAuthProvider(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
ea := core.NewExternalAuth(app)
testValues := []string{"test_1", "test2", ""}
for i, testValue := range testValues {
t.Run(fmt.Sprintf("%d_%q", i, testValue), func(t *testing.T) {
ea.SetProvider(testValue)
if v := ea.Provider(); v != testValue {
t.Fatalf("Expected getter %q, got %q", testValue, v)
}
if v := ea.GetString("provider"); v != testValue {
t.Fatalf("Expected field value %q, got %q", testValue, v)
}
})
}
}
func TestExternalAuthProviderId(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
ea := core.NewExternalAuth(app)
testValues := []string{"test_1", "test2", ""}
for i, testValue := range testValues {
t.Run(fmt.Sprintf("%d_%q", i, testValue), func(t *testing.T) {
ea.SetProviderId(testValue)
if v := ea.ProviderId(); v != testValue {
t.Fatalf("Expected getter %q, got %q", testValue, v)
}
if v := ea.GetString("providerId"); v != testValue {
t.Fatalf("Expected field value %q, got %q", testValue, v)
}
})
}
}
func TestExternalAuthCreated(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
ea := core.NewExternalAuth(app)
if v := ea.Created().String(); v != "" {
t.Fatalf("Expected empty created, got %q", v)
}
now := types.NowDateTime()
ea.SetRaw("created", now)
if v := ea.Created().String(); v != now.String() {
t.Fatalf("Expected %q created, got %q", now.String(), v)
}
}
func TestExternalAuthUpdated(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
ea := core.NewExternalAuth(app)
if v := ea.Updated().String(); v != "" {
t.Fatalf("Expected empty updated, got %q", v)
}
now := types.NowDateTime()
ea.SetRaw("updated", now)
if v := ea.Updated().String(); v != now.String() {
t.Fatalf("Expected %q updated, got %q", now.String(), v)
}
}
func TestExternalAuthPreValidate(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
externalAuthsCol, err := app.FindCollectionByNameOrId(core.CollectionNameExternalAuths)
if err != nil {
t.Fatal(err)
}
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
t.Run("no proxy record", func(t *testing.T) {
externalAuth := &core.ExternalAuth{}
if err := app.Validate(externalAuth); err == nil {
t.Fatal("Expected collection validation error")
}
})
t.Run("non-ExternalAuth collection", func(t *testing.T) {
externalAuth := &core.ExternalAuth{}
externalAuth.SetProxyRecord(core.NewRecord(core.NewBaseCollection("invalid")))
externalAuth.SetRecordRef(user.Id)
externalAuth.SetCollectionRef(user.Collection().Id)
externalAuth.SetProvider("gitlab")
externalAuth.SetProviderId("test123")
if err := app.Validate(externalAuth); err == nil {
t.Fatal("Expected collection validation error")
}
})
t.Run("ExternalAuth collection", func(t *testing.T) {
externalAuth := &core.ExternalAuth{}
externalAuth.SetProxyRecord(core.NewRecord(externalAuthsCol))
externalAuth.SetRecordRef(user.Id)
externalAuth.SetCollectionRef(user.Collection().Id)
externalAuth.SetProvider("gitlab")
externalAuth.SetProviderId("test123")
if err := app.Validate(externalAuth); err != nil {
t.Fatalf("Expected nil validation error, got %v", err)
}
})
}
func TestExternalAuthValidateHook(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
demo1, err := app.FindRecordById("demo1", "84nmscqy84lsi1t")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
externalAuth func() *core.ExternalAuth
expectErrors []string
}{
{
"empty",
func() *core.ExternalAuth {
return core.NewExternalAuth(app)
},
[]string{"collectionRef", "recordRef", "provider", "providerId"},
},
{
"non-auth collection",
func() *core.ExternalAuth {
ea := core.NewExternalAuth(app)
ea.SetCollectionRef(demo1.Collection().Id)
ea.SetRecordRef(demo1.Id)
ea.SetProvider("gitlab")
ea.SetProviderId("test123")
return ea
},
[]string{"collectionRef"},
},
{
"disabled provider",
func() *core.ExternalAuth {
ea := core.NewExternalAuth(app)
ea.SetCollectionRef(user.Collection().Id)
ea.SetRecordRef("missing")
ea.SetProvider("apple")
ea.SetProviderId("test123")
return ea
},
[]string{"recordRef"},
},
{
"missing record id",
func() *core.ExternalAuth {
ea := core.NewExternalAuth(app)
ea.SetCollectionRef(user.Collection().Id)
ea.SetRecordRef("missing")
ea.SetProvider("gitlab")
ea.SetProviderId("test123")
return ea
},
[]string{"recordRef"},
},
{
"valid ref",
func() *core.ExternalAuth {
ea := core.NewExternalAuth(app)
ea.SetCollectionRef(user.Collection().Id)
ea.SetRecordRef(user.Id)
ea.SetProvider("gitlab")
ea.SetProviderId("test123")
return ea
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
errs := app.Validate(s.externalAuth())
tests.TestValidationErrors(t, errs, s.expectErrors)
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_password.go | core/field_password.go | package core
import (
"context"
"database/sql/driver"
"fmt"
"regexp"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/spf13/cast"
"golang.org/x/crypto/bcrypt"
)
func init() {
Fields[FieldTypePassword] = func() Field {
return &PasswordField{}
}
}
const FieldTypePassword = "password"
var (
_ Field = (*PasswordField)(nil)
_ GetterFinder = (*PasswordField)(nil)
_ SetterFinder = (*PasswordField)(nil)
_ DriverValuer = (*PasswordField)(nil)
_ RecordInterceptor = (*PasswordField)(nil)
)
// PasswordField defines "password" type field for storing bcrypt hashed strings
// (usually used only internally for the "password" auth collection system field).
//
// If you want to set a direct bcrypt hash as record field value you can use the SetRaw method, for example:
//
// // generates a bcrypt hash of "123456" and set it as field value
// // (record.GetString("password") returns the plain password until persisted, otherwise empty string)
// record.Set("password", "123456")
//
// // set directly a bcrypt hash of "123456" as field value
// // (record.GetString("password") returns empty string)
// record.SetRaw("password", "$2a$10$.5Elh8fgxypNUWhpUUr/xOa2sZm0VIaE0qWuGGl9otUfobb46T1Pq")
//
// The following additional getter keys are available:
//
// - "fieldName:hash" - returns the bcrypt hash string of the record field value (if any). For example:
// record.GetString("password:hash")
type PasswordField struct {
// Name (required) is the unique name of the field.
Name string `form:"name" json:"name"`
// Id is the unique stable field identifier.
//
// It is automatically generated from the name when adding to a collection FieldsList.
Id string `form:"id" json:"id"`
// System prevents the renaming and removal of the field.
System bool `form:"system" json:"system"`
// Hidden hides the field from the API response.
Hidden bool `form:"hidden" json:"hidden"`
// Presentable hints the Dashboard UI to use the underlying
// field record value in the relation preview label.
Presentable bool `form:"presentable" json:"presentable"`
// ---
// Pattern specifies an optional regex pattern to match against the field value.
//
// Leave it empty to skip the pattern check.
Pattern string `form:"pattern" json:"pattern"`
// Min specifies an optional required field string length.
Min int `form:"min" json:"min"`
// Max specifies an optional required field string length.
//
// If zero, fallback to max 71 bytes.
Max int `form:"max" json:"max"`
// Cost specifies the cost/weight/iteration/etc. bcrypt factor.
//
// If zero, fallback to [bcrypt.DefaultCost].
//
// If explicitly set, must be between [bcrypt.MinCost] and [bcrypt.MaxCost].
Cost int `form:"cost" json:"cost"`
// Required will require the field value to be non-empty string.
Required bool `form:"required" json:"required"`
}
// Type implements [Field.Type] interface method.
func (f *PasswordField) Type() string {
return FieldTypePassword
}
// GetId implements [Field.GetId] interface method.
func (f *PasswordField) GetId() string {
return f.Id
}
// SetId implements [Field.SetId] interface method.
func (f *PasswordField) SetId(id string) {
f.Id = id
}
// GetName implements [Field.GetName] interface method.
func (f *PasswordField) GetName() string {
return f.Name
}
// SetName implements [Field.SetName] interface method.
func (f *PasswordField) SetName(name string) {
f.Name = name
}
// GetSystem implements [Field.GetSystem] interface method.
func (f *PasswordField) GetSystem() bool {
return f.System
}
// SetSystem implements [Field.SetSystem] interface method.
func (f *PasswordField) SetSystem(system bool) {
f.System = system
}
// GetHidden implements [Field.GetHidden] interface method.
func (f *PasswordField) GetHidden() bool {
return f.Hidden
}
// SetHidden implements [Field.SetHidden] interface method.
func (f *PasswordField) SetHidden(hidden bool) {
f.Hidden = hidden
}
// ColumnType implements [Field.ColumnType] interface method.
func (f *PasswordField) ColumnType(app App) string {
return "TEXT DEFAULT '' NOT NULL"
}
// DriverValue implements the [DriverValuer] interface.
func (f *PasswordField) DriverValue(record *Record) (driver.Value, error) {
fp := f.getPasswordValue(record)
return fp.Hash, fp.LastError
}
// PrepareValue implements [Field.PrepareValue] interface method.
func (f *PasswordField) PrepareValue(record *Record, raw any) (any, error) {
return &PasswordFieldValue{
Hash: cast.ToString(raw),
}, nil
}
// ValidateValue implements [Field.ValidateValue] interface method.
func (f *PasswordField) ValidateValue(ctx context.Context, app App, record *Record) error {
fp, ok := record.GetRaw(f.Name).(*PasswordFieldValue)
if !ok {
return validators.ErrUnsupportedValueType
}
if fp.LastError != nil {
return fp.LastError
}
if f.Required {
if err := validation.Required.Validate(fp.Hash); err != nil {
return err
}
}
if fp.Plain == "" {
return nil // nothing to check
}
// note: casted to []rune to count multi-byte chars as one for the
// sake of more intuitive UX and clearer user error messages
//
// note2: technically multi-byte strings could produce bigger length than the bcrypt limit
// but it should be fine as it will be just truncated (even if it cuts a byte sequence in the middle)
length := len([]rune(fp.Plain))
if length < f.Min {
return validation.NewError("validation_min_text_constraint", fmt.Sprintf("Must be at least %d character(s)", f.Min))
}
maxLength := f.Max
if maxLength <= 0 {
maxLength = 71
}
if length > maxLength {
return validation.NewError("validation_max_text_constraint", fmt.Sprintf("Must be less than %d character(s)", maxLength))
}
if f.Pattern != "" {
match, _ := regexp.MatchString(f.Pattern, fp.Plain)
if !match {
return validation.NewError("validation_invalid_format", "Invalid value format")
}
}
return nil
}
// ValidateSettings implements [Field.ValidateSettings] interface method.
func (f *PasswordField) ValidateSettings(ctx context.Context, app App, collection *Collection) error {
return validation.ValidateStruct(f,
validation.Field(&f.Id, validation.By(DefaultFieldIdValidationRule)),
validation.Field(&f.Name, validation.By(DefaultFieldNameValidationRule)),
validation.Field(&f.Min, validation.Min(1), validation.Max(71)),
validation.Field(&f.Max, validation.Min(f.Min), validation.Max(71)),
validation.Field(&f.Cost, validation.Min(bcrypt.MinCost), validation.Max(bcrypt.MaxCost)),
validation.Field(&f.Pattern, validation.By(validators.IsRegex)),
)
}
func (f *PasswordField) getPasswordValue(record *Record) *PasswordFieldValue {
raw := record.GetRaw(f.Name)
switch v := raw.(type) {
case *PasswordFieldValue:
return v
case string:
// we assume that any raw string starting with $2 is bcrypt hash
if strings.HasPrefix(v, "$2") {
return &PasswordFieldValue{Hash: v}
}
}
return &PasswordFieldValue{}
}
// Intercept implements the [RecordInterceptor] interface.
func (f *PasswordField) Intercept(
ctx context.Context,
app App,
record *Record,
actionName string,
actionFunc func() error,
) error {
switch actionName {
case InterceptorActionAfterCreate, InterceptorActionAfterUpdate:
// unset the plain field value after successful create/update
fp := f.getPasswordValue(record)
fp.Plain = ""
}
return actionFunc()
}
// FindGetter implements the [GetterFinder] interface.
func (f *PasswordField) FindGetter(key string) GetterFunc {
switch key {
case f.Name:
return func(record *Record) any {
return f.getPasswordValue(record).Plain
}
case f.Name + ":hash":
return func(record *Record) any {
return f.getPasswordValue(record).Hash
}
default:
return nil
}
}
// FindSetter implements the [SetterFinder] interface.
func (f *PasswordField) FindSetter(key string) SetterFunc {
switch key {
case f.Name:
return f.setValue
default:
return nil
}
}
func (f *PasswordField) setValue(record *Record, raw any) {
fv := &PasswordFieldValue{
Plain: cast.ToString(raw),
}
// hash the password
if fv.Plain != "" {
cost := f.Cost
if cost <= 0 {
cost = bcrypt.DefaultCost
}
hash, err := bcrypt.GenerateFromPassword([]byte(fv.Plain), cost)
if err != nil {
fv.LastError = err
}
fv.Hash = string(hash)
}
record.SetRaw(f.Name, fv)
}
// -------------------------------------------------------------------
type PasswordFieldValue struct {
LastError error
Hash string
Plain string
}
func (pv PasswordFieldValue) Validate(pass string) bool {
if pv.Hash == "" || pv.LastError != nil {
return false
}
err := bcrypt.CompareHashAndPassword([]byte(pv.Hash), []byte(pass))
return err == nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/db_builder.go | core/db_builder.go | package core
import (
"strings"
"unicode"
"unicode/utf8"
"github.com/pocketbase/dbx"
)
var _ dbx.Builder = (*dualDBBuilder)(nil)
// note: expects both builder to use the same driver
type dualDBBuilder struct {
concurrentDB dbx.Builder
nonconcurrentDB dbx.Builder
}
// Select implements the [dbx.Builder.Select] interface method.
func (b *dualDBBuilder) Select(cols ...string) *dbx.SelectQuery {
return b.concurrentDB.Select(cols...)
}
// Model implements the [dbx.Builder.Model] interface method.
func (b *dualDBBuilder) Model(data interface{}) *dbx.ModelQuery {
return b.nonconcurrentDB.Model(data)
}
// GeneratePlaceholder implements the [dbx.Builder.GeneratePlaceholder] interface method.
func (b *dualDBBuilder) GeneratePlaceholder(i int) string {
return b.concurrentDB.GeneratePlaceholder(i)
}
// Quote implements the [dbx.Builder.Quote] interface method.
func (b *dualDBBuilder) Quote(str string) string {
return b.concurrentDB.Quote(str)
}
// QuoteSimpleTableName implements the [dbx.Builder.QuoteSimpleTableName] interface method.
func (b *dualDBBuilder) QuoteSimpleTableName(table string) string {
return b.concurrentDB.QuoteSimpleTableName(table)
}
// QuoteSimpleColumnName implements the [dbx.Builder.QuoteSimpleColumnName] interface method.
func (b *dualDBBuilder) QuoteSimpleColumnName(col string) string {
return b.concurrentDB.QuoteSimpleColumnName(col)
}
// QueryBuilder implements the [dbx.Builder.QueryBuilder] interface method.
func (b *dualDBBuilder) QueryBuilder() dbx.QueryBuilder {
return b.concurrentDB.QueryBuilder()
}
// Insert implements the [dbx.Builder.Insert] interface method.
func (b *dualDBBuilder) Insert(table string, cols dbx.Params) *dbx.Query {
return b.nonconcurrentDB.Insert(table, cols)
}
// Upsert implements the [dbx.Builder.Upsert] interface method.
func (b *dualDBBuilder) Upsert(table string, cols dbx.Params, constraints ...string) *dbx.Query {
return b.nonconcurrentDB.Upsert(table, cols, constraints...)
}
// Update implements the [dbx.Builder.Update] interface method.
func (b *dualDBBuilder) Update(table string, cols dbx.Params, where dbx.Expression) *dbx.Query {
return b.nonconcurrentDB.Update(table, cols, where)
}
// Delete implements the [dbx.Builder.Delete] interface method.
func (b *dualDBBuilder) Delete(table string, where dbx.Expression) *dbx.Query {
return b.nonconcurrentDB.Delete(table, where)
}
// CreateTable implements the [dbx.Builder.CreateTable] interface method.
func (b *dualDBBuilder) CreateTable(table string, cols map[string]string, options ...string) *dbx.Query {
return b.nonconcurrentDB.CreateTable(table, cols, options...)
}
// RenameTable implements the [dbx.Builder.RenameTable] interface method.
func (b *dualDBBuilder) RenameTable(oldName, newName string) *dbx.Query {
return b.nonconcurrentDB.RenameTable(oldName, newName)
}
// DropTable implements the [dbx.Builder.DropTable] interface method.
func (b *dualDBBuilder) DropTable(table string) *dbx.Query {
return b.nonconcurrentDB.DropTable(table)
}
// TruncateTable implements the [dbx.Builder.TruncateTable] interface method.
func (b *dualDBBuilder) TruncateTable(table string) *dbx.Query {
return b.nonconcurrentDB.TruncateTable(table)
}
// AddColumn implements the [dbx.Builder.AddColumn] interface method.
func (b *dualDBBuilder) AddColumn(table, col, typ string) *dbx.Query {
return b.nonconcurrentDB.AddColumn(table, col, typ)
}
// DropColumn implements the [dbx.Builder.DropColumn] interface method.
func (b *dualDBBuilder) DropColumn(table, col string) *dbx.Query {
return b.nonconcurrentDB.DropColumn(table, col)
}
// RenameColumn implements the [dbx.Builder.RenameColumn] interface method.
func (b *dualDBBuilder) RenameColumn(table, oldName, newName string) *dbx.Query {
return b.nonconcurrentDB.RenameColumn(table, oldName, newName)
}
// AlterColumn implements the [dbx.Builder.AlterColumn] interface method.
func (b *dualDBBuilder) AlterColumn(table, col, typ string) *dbx.Query {
return b.nonconcurrentDB.AlterColumn(table, col, typ)
}
// AddPrimaryKey implements the [dbx.Builder.AddPrimaryKey] interface method.
func (b *dualDBBuilder) AddPrimaryKey(table, name string, cols ...string) *dbx.Query {
return b.nonconcurrentDB.AddPrimaryKey(table, name, cols...)
}
// DropPrimaryKey implements the [dbx.Builder.DropPrimaryKey] interface method.
func (b *dualDBBuilder) DropPrimaryKey(table, name string) *dbx.Query {
return b.nonconcurrentDB.DropPrimaryKey(table, name)
}
// AddForeignKey implements the [dbx.Builder.AddForeignKey] interface method.
func (b *dualDBBuilder) AddForeignKey(table, name string, cols, refCols []string, refTable string, options ...string) *dbx.Query {
return b.nonconcurrentDB.AddForeignKey(table, name, cols, refCols, refTable, options...)
}
// DropForeignKey implements the [dbx.Builder.DropForeignKey] interface method.
func (b *dualDBBuilder) DropForeignKey(table, name string) *dbx.Query {
return b.nonconcurrentDB.DropForeignKey(table, name)
}
// CreateIndex implements the [dbx.Builder.CreateIndex] interface method.
func (b *dualDBBuilder) CreateIndex(table, name string, cols ...string) *dbx.Query {
return b.nonconcurrentDB.CreateIndex(table, name, cols...)
}
// CreateUniqueIndex implements the [dbx.Builder.CreateUniqueIndex] interface method.
func (b *dualDBBuilder) CreateUniqueIndex(table, name string, cols ...string) *dbx.Query {
return b.nonconcurrentDB.CreateUniqueIndex(table, name, cols...)
}
// DropIndex implements the [dbx.Builder.DropIndex] interface method.
func (b *dualDBBuilder) DropIndex(table, name string) *dbx.Query {
return b.nonconcurrentDB.DropIndex(table, name)
}
// NewQuery implements the [dbx.Builder.NewQuery] interface method by
// routing the SELECT queries to the concurrent builder instance.
func (b *dualDBBuilder) NewQuery(str string) *dbx.Query {
// note: technically INSERT/UPDATE/DELETE could also have CTE but since
// it is rare for now this scase is ignored to avoid unnecessary complicating the checks
trimmed := trimLeftSpaces(str)
if hasPrefixFold(trimmed, "SELECT") || hasPrefixFold(trimmed, "WITH") {
return b.concurrentDB.NewQuery(str)
}
return b.nonconcurrentDB.NewQuery(str)
}
var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1}
// note: similar to strings.Space() but without the right trim because it is not needed in our case
func trimLeftSpaces(str string) string {
start := 0
for ; start < len(str); start++ {
c := str[start]
if c >= utf8.RuneSelf {
return strings.TrimLeftFunc(str[start:], unicode.IsSpace)
}
if asciiSpace[c] == 0 {
break
}
}
return str[start:]
}
// note: the prefix is expected to be ASCII
func hasPrefixFold(str, prefix string) bool {
if len(str) < len(prefix) {
return false
}
return strings.EqualFold(str[:len(prefix)], prefix)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/validators/file.go | core/validators/file.go | package validators
import (
"fmt"
"strings"
"github.com/gabriel-vasile/mimetype"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/tools/filesystem"
)
// UploadedFileSize checks whether the validated [*filesystem.File]
// size is no more than the provided maxBytes.
//
// Example:
//
// validation.Field(&form.File, validation.By(validators.UploadedFileSize(1000)))
func UploadedFileSize(maxBytes int64) validation.RuleFunc {
return func(value any) error {
v, ok := value.(*filesystem.File)
if !ok {
return ErrUnsupportedValueType
}
if v == nil {
return nil // nothing to validate
}
if v.Size > maxBytes {
return validation.NewError(
"validation_file_size_limit",
"Failed to upload {{.file}} - the maximum allowed file size is {{.maxSize}} bytes.",
).SetParams(map[string]any{
"file": v.OriginalName,
"maxSize": maxBytes,
})
}
return nil
}
}
// UploadedFileMimeType checks whether the validated [*filesystem.File]
// mimetype is within the provided allowed mime types.
//
// Example:
//
// validMimeTypes := []string{"test/plain","image/jpeg"}
// validation.Field(&form.File, validation.By(validators.UploadedFileMimeType(validMimeTypes)))
func UploadedFileMimeType(validTypes []string) validation.RuleFunc {
return func(value any) error {
v, ok := value.(*filesystem.File)
if !ok {
return ErrUnsupportedValueType
}
if v == nil {
return nil // nothing to validate
}
baseErr := validation.NewError(
"validation_invalid_mime_type",
fmt.Sprintf("Failed to upload %q due to unsupported file type.", v.OriginalName),
)
if len(validTypes) == 0 {
return baseErr
}
f, err := v.Reader.Open()
if err != nil {
return baseErr
}
defer f.Close()
filetype, err := mimetype.DetectReader(f)
if err != nil {
return baseErr
}
for _, t := range validTypes {
if filetype.Is(t) {
return nil // valid
}
}
return validation.NewError(
"validation_invalid_mime_type",
fmt.Sprintf(
"%q mime type must be one of: %s.",
v.Name,
strings.Join(validTypes, ", "),
),
)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/validators/validators.go | core/validators/validators.go | // Package validators implements some common custom PocketBase validators.
package validators
import (
"errors"
"maps"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
var ErrUnsupportedValueType = validation.NewError("validation_unsupported_value_type", "Invalid or unsupported value type.")
// JoinValidationErrors attempts to join the provided [validation.Errors] arguments.
//
// If only one of the arguments is [validation.Errors], it returns the first non-empty [validation.Errors].
//
// If both arguments are not [validation.Errors] then it returns a combined [errors.Join] error.
func JoinValidationErrors(errA, errB error) error {
vErrA, okA := errA.(validation.Errors)
vErrB, okB := errB.(validation.Errors)
// merge
if okA && okB {
result := maps.Clone(vErrA)
maps.Copy(result, vErrB)
if len(result) > 0 {
return result
}
}
if okA && len(vErrA) > 0 {
return vErrA
}
if okB && len(vErrB) > 0 {
return vErrB
}
return errors.Join(errA, errB)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/validators/equal.go | core/validators/equal.go | package validators
import (
"reflect"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
// Equal checks whether the validated value matches another one from the same type.
//
// It expects the compared values to be from the same type and works
// with booleans, numbers, strings and their pointer variants.
//
// If one of the value is pointer, the comparison is based on its
// underlying value (when possible to determine).
//
// Note that empty/zero values are also compared (this differ from other validation.RuleFunc).
//
// Example:
//
// validation.Field(&form.PasswordConfirm, validation.By(validators.Equal(form.Password)))
func Equal[T comparable](valueToCompare T) validation.RuleFunc {
return func(value any) error {
if compareValues(value, valueToCompare) {
return nil
}
return validation.NewError("validation_values_mismatch", "Values don't match.")
}
}
func compareValues(a, b any) bool {
if a == b {
return true
}
if checkIsNil(a) && checkIsNil(b) {
return true
}
var result bool
defer func() {
if err := recover(); err != nil {
result = false
}
}()
reflectA := reflect.ValueOf(a)
reflectB := reflect.ValueOf(b)
dereferencedA := dereference(reflectA)
dereferencedB := dereference(reflectB)
if dereferencedA.CanInterface() && dereferencedB.CanInterface() {
result = dereferencedA.Interface() == dereferencedB.Interface()
}
return result
}
// note https://github.com/golang/go/issues/51649
func checkIsNil(value any) bool {
if value == nil {
return true
}
var result bool
defer func() {
if err := recover(); err != nil {
result = false
}
}()
result = reflect.ValueOf(value).IsNil()
return result
}
func dereference(v reflect.Value) reflect.Value {
for v.Kind() == reflect.Pointer {
v = v.Elem()
}
return v
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/validators/file_test.go | core/validators/file_test.go | package validators_test
import (
"fmt"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tools/filesystem"
)
func TestUploadedFileSize(t *testing.T) {
t.Parallel()
file, err := filesystem.NewFileFromBytes([]byte("test"), "test.txt")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
maxBytes int64
file *filesystem.File
expectError bool
}{
{0, nil, false},
{4, nil, false},
{3, file, true}, // all test files have "test" as content
{4, file, false},
{5, file, false},
}
for _, s := range scenarios {
t.Run(fmt.Sprintf("%d", s.maxBytes), func(t *testing.T) {
err := validators.UploadedFileSize(s.maxBytes)(s.file)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
func TestUploadedFileMimeType(t *testing.T) {
t.Parallel()
file, err := filesystem.NewFileFromBytes([]byte("test"), "test.png") // the extension shouldn't matter
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
types []string
file *filesystem.File
expectError bool
}{
{nil, nil, false},
{[]string{"image/jpeg"}, nil, false},
{[]string{}, file, true},
{[]string{"image/jpeg"}, file, true},
// test files are detected as "text/plain; charset=utf-8" content type
{[]string{"image/jpeg", "text/plain; charset=utf-8"}, file, false},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, strings.Join(s.types, ";")), func(t *testing.T) {
err := validators.UploadedFileMimeType(s.types)(s.file)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/validators/db_test.go | core/validators/db_test.go | package validators_test
import (
"errors"
"fmt"
"testing"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tests"
)
func TestUniqueId(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
id string
tableName string
expectError bool
}{
{"", "", false},
{"test", "", true},
{"wsmn24bux7wo113", "_collections", true},
{"test_unique_id", "unknown_table", true},
{"test_unique_id", "_collections", false},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s_%s", i, s.id, s.tableName), func(t *testing.T) {
err := validators.UniqueId(app.DB(), s.tableName)(s.id)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
func TestNormalizeUniqueIndexError(t *testing.T) {
t.Parallel()
scenarios := []struct {
name string
err error
table string
names []string
expectedKeys []string
}{
{
"nil error (no changes)",
nil,
"test",
[]string{"a", "b"},
nil,
},
{
"non-unique index error (no changes)",
errors.New("abc"),
"test",
[]string{"a", "b"},
nil,
},
{
"validation error (no changes)",
validation.Errors{"c": errors.New("abc")},
"test",
[]string{"a", "b"},
[]string{"c"},
},
{
"unique index error but mismatched table name",
errors.New("UNIQUE constraint failed for fields test.a,test.b"),
"example",
[]string{"a", "b"},
nil,
},
{
"unique index error with table name suffix matching the specified one",
errors.New("UNIQUE constraint failed for fields test_suffix.a,test_suffix.b"),
"suffix",
[]string{"a", "b", "c"},
nil,
},
{
"unique index error but mismatched fields",
errors.New("UNIQUE constraint failed for fields test.a,test.b"),
"test",
[]string{"c", "d"},
nil,
},
{
"unique index error with matching table name and fields",
errors.New("UNIQUE constraint failed for fields test.a,test.b"),
"test",
[]string{"a", "b", "c"},
[]string{"a", "b"},
},
{
"unique index error with matching table name and field starting with the name of another non-unique field",
errors.New("UNIQUE constraint failed for fields test.a_2,test.c"),
"test",
[]string{"a", "a_2", "c"},
[]string{"a_2", "c"},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := validators.NormalizeUniqueIndexError(s.err, s.table, s.names)
if len(s.expectedKeys) == 0 {
if result != s.err {
t.Fatalf("Expected no error change, got %v", result)
}
return
}
tests.TestValidationErrors(t, result, s.expectedKeys)
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/validators/string.go | core/validators/string.go | package validators
import (
"regexp"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
// IsRegex checks whether the validated value is a valid regular expression pattern.
//
// Example:
//
// validation.Field(&form.Pattern, validation.By(validators.IsRegex))
func IsRegex(value any) error {
v, ok := value.(string)
if !ok {
return ErrUnsupportedValueType
}
if v == "" {
return nil // nothing to check
}
if _, err := regexp.Compile(v); err != nil {
return validation.NewError("validation_invalid_regex", err.Error())
}
return nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/validators/validators_test.go | core/validators/validators_test.go | package validators_test
import (
"errors"
"fmt"
"testing"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core/validators"
)
func TestJoinValidationErrors(t *testing.T) {
scenarios := []struct {
errA error
errB error
expected string
}{
{nil, nil, "<nil>"},
{errors.New("abc"), nil, "abc"},
{nil, errors.New("abc"), "abc"},
{errors.New("abc"), errors.New("456"), "abc\n456"},
{validation.Errors{"test1": errors.New("test1_err")}, nil, "test1: test1_err."},
{nil, validation.Errors{"test2": errors.New("test2_err")}, "test2: test2_err."},
{validation.Errors{}, errors.New("456"), "\n456"},
{errors.New("456"), validation.Errors{}, "456\n"},
{validation.Errors{"test1": errors.New("test1_err")}, errors.New("456"), "test1: test1_err."},
{errors.New("456"), validation.Errors{"test2": errors.New("test2_err")}, "test2: test2_err."},
{validation.Errors{"test1": errors.New("test1_err")}, validation.Errors{"test2": errors.New("test2_err")}, "test1: test1_err; test2: test2_err."},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#T_%T", i, s.errA, s.errB), func(t *testing.T) {
result := fmt.Sprintf("%v", validators.JoinValidationErrors(s.errA, s.errB))
if result != s.expected {
t.Fatalf("Expected\n%v\ngot\n%v", s.expected, result)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/validators/db.go | core/validators/db.go | package validators
import (
"database/sql"
"errors"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
)
// UniqueId checks whether a field string id already exists in the specified table.
//
// Example:
//
// validation.Field(&form.RelId, validation.By(validators.UniqueId(form.app.DB(), "tbl_example"))
func UniqueId(db dbx.Builder, tableName string) validation.RuleFunc {
return func(value any) error {
v, _ := value.(string)
if v == "" {
return nil // nothing to check
}
var foundId string
err := db.
Select("id").
From(tableName).
Where(dbx.HashExp{"id": v}).
Limit(1).
Row(&foundId)
if (err != nil && !errors.Is(err, sql.ErrNoRows)) || foundId != "" {
return validation.NewError("validation_invalid_or_existing_id", "The model id is invalid or already exists.")
}
return nil
}
}
// NormalizeUniqueIndexError attempts to convert a
// "unique constraint failed" error into a validation.Errors.
//
// The provided err is returned as it is without changes if:
// - err is nil
// - err is already validation.Errors
// - err is not "unique constraint failed" error
func NormalizeUniqueIndexError(err error, tableOrAlias string, fieldNames []string) error {
if err == nil {
return err
}
if _, ok := err.(validation.Errors); ok {
return err
}
msg := strings.ToLower(err.Error())
// check for unique constraint failure
if strings.Contains(msg, "unique constraint failed") {
// note: extra space to unify multi-columns lookup
msg = strings.ReplaceAll(strings.TrimSpace(msg), ",", " ") + " "
normalizedErrs := validation.Errors{}
for _, name := range fieldNames {
// note: extra spaces to exclude table name with suffix matching the current one
// OR other fields starting with the current field name
if strings.Contains(msg, strings.ToLower(" "+tableOrAlias+"."+name+" ")) {
normalizedErrs[name] = validation.NewError("validation_not_unique", "Value must be unique")
}
}
if len(normalizedErrs) > 0 {
return normalizedErrs
}
}
return err
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/validators/equal_test.go | core/validators/equal_test.go | package validators_test
import (
"fmt"
"testing"
"github.com/pocketbase/pocketbase/core/validators"
)
func Equal(t *testing.T) {
t.Parallel()
strA := "abc"
strB := "abc"
strC := "123"
var strNilPtr *string
var strNilPtr2 *string
scenarios := []struct {
valA any
valB any
expectError bool
}{
{nil, nil, false},
{"", "", false},
{"", "456", true},
{"123", "", true},
{"123", "456", true},
{"123", "123", false},
{true, false, true},
{false, true, true},
{false, false, false},
{true, true, false},
{0, 0, false},
{0, 1, true},
{1, 2, true},
{1, 1, false},
{&strA, &strA, false},
{&strA, &strB, false},
{&strA, &strC, true},
{"abc", &strA, false},
{&strA, "abc", false},
{"abc", &strC, true},
{"test", 123, true},
{nil, 123, true},
{nil, strA, true},
{nil, &strA, true},
{nil, strNilPtr, false},
{strNilPtr, strNilPtr2, false},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%v_%v", i, s.valA, s.valB), func(t *testing.T) {
err := validators.Equal(s.valA)(s.valB)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/validators/string_test.go | core/validators/string_test.go | package validators_test
import (
"fmt"
"testing"
"github.com/pocketbase/pocketbase/core/validators"
)
func TestIsRegex(t *testing.T) {
t.Parallel()
scenarios := []struct {
val string
expectError bool
}{
{"", false},
{`abc`, false},
{`\w+`, false},
{`\w*((abc+`, true},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.val), func(t *testing.T) {
err := validators.IsRegex(s.val)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/health.go | apis/health.go | package apis
import (
"net/http"
"slices"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/router"
)
// bindHealthApi registers the health api endpoint.
func bindHealthApi(app core.App, rg *router.RouterGroup[*core.RequestEvent]) {
subGroup := rg.Group("/health")
subGroup.GET("", healthCheck)
}
// healthCheck returns a 200 OK response if the server is healthy.
func healthCheck(e *core.RequestEvent) error {
resp := struct {
Message string `json:"message"`
Code int `json:"code"`
Data map[string]any `json:"data"`
}{
Code: http.StatusOK,
Message: "API is healthy.",
}
if e.HasSuperuserAuth() {
resp.Data = make(map[string]any, 3)
resp.Data["canBackup"] = !e.App.Store().Has(core.StoreKeyActiveBackup)
resp.Data["realIP"] = e.RealIP()
// loosely check if behind a reverse proxy
// (usually used in the dashboard to remind superusers in case deployed behind reverse-proxy)
possibleProxyHeader := ""
headersToCheck := append(
slices.Clone(e.App.Settings().TrustedProxy.Headers),
// common proxy headers
"CF-Connecting-IP", "Fly-Client-IP", "X‑Forwarded-For",
)
for _, header := range headersToCheck {
if e.Request.Header.Get(header) != "" {
possibleProxyHeader = header
break
}
}
resp.Data["possibleProxyHeader"] = possibleProxyHeader
} else {
resp.Data = map[string]any{} // ensure that it is returned as object
}
return e.JSON(http.StatusOK, resp)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/record_auth_with_oauth2_test.go | apis/record_auth_with_oauth2_test.go | package apis_test
import (
"bytes"
"errors"
"image"
"image/png"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/auth"
"github.com/pocketbase/pocketbase/tools/dbutils"
"golang.org/x/oauth2"
)
var _ auth.Provider = (*oauth2MockProvider)(nil)
type oauth2MockProvider struct {
auth.BaseProvider
AuthUser *auth.AuthUser
Token *oauth2.Token
}
func (p *oauth2MockProvider) FetchToken(code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error) {
if p.Token == nil {
return nil, errors.New("failed to fetch OAuth2 token")
}
return p.Token, nil
}
func (p *oauth2MockProvider) FetchAuthUser(token *oauth2.Token) (*auth.AuthUser, error) {
if p.AuthUser == nil {
return nil, errors.New("failed to fetch OAuth2 user")
}
return p.AuthUser, nil
}
func TestRecordAuthWithOAuth2(t *testing.T) {
t.Parallel()
// start a test server
server := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
buf := new(bytes.Buffer)
png.Encode(buf, image.Rect(0, 0, 1, 1)) // tiny 1x1 png
http.ServeContent(res, req, "test_avatar.png", time.Now(), bytes.NewReader(buf.Bytes()))
}))
defer server.Close()
scenarios := []tests.ApiScenario{
{
Name: "disabled OAuth2 auth",
Method: http.MethodPost,
URL: "/api/collections/nologin/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code": "123",
"codeVerifier": "456",
"redirectURL": "https://example.com"
}`),
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "invalid body",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{"provider"`),
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "trigger form validations (missing provider)",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "missing"
}`),
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"provider":`,
`"code":`,
`"redirectURL":`,
},
NotExpectedContent: []string{
`"codeVerifier":`, // should be optional
},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "trigger form validations (existing but disabled provider)",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "apple"
}`),
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"provider":`,
`"code":`,
`"redirectURL":`,
},
NotExpectedContent: []string{
`"codeVerifier":`, // should be optional
},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "existing linked OAuth2 (unverified user)",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code":"123",
"redirectURL": "https://example.com",
"createData": {
"name": "test_new"
}
}`),
Headers: map[string]string{
// users, test2@example.com
// (auth with some other user from the same collection to ensure that it is ignored)
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6Im9hcDY0MGNvdDR5cnUycyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.GfJo6EHIobgas_AXt-M-tj5IoQendPnrkMSe9ExuSEY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
if user.Verified() {
t.Fatalf("Expected user %q to be unverified", user.Email())
}
// ensure that the old password works
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected password %q to be valid", "1234567890")
}
// register the test provider
auth.Providers["test"] = func() auth.Provider {
return &oauth2MockProvider{
AuthUser: &auth.AuthUser{Id: "test_id"},
Token: &oauth2.Token{AccessToken: "abc"},
}
}
// add the test provider in the collection
user.Collection().MFA.Enabled = false
user.Collection().OAuth2.Enabled = true
user.Collection().OAuth2.Providers = []core.OAuth2ProviderConfig{{
Name: "test",
ClientId: "123",
ClientSecret: "456",
}}
if err := app.Save(user.Collection()); err != nil {
t.Fatal(err)
}
// stub linked provider
ea := core.NewExternalAuth(app)
ea.SetCollectionRef(user.Collection().Id)
ea.SetRecordRef(user.Id)
ea.SetProvider("test")
ea.SetProviderId("test_id")
if err := app.Save(ea); err != nil {
t.Fatal(err)
}
// test at least once that the correct request info context is properly loaded
app.OnRecordAuthRequest().BindFunc(func(e *core.RecordAuthRequestEvent) error {
info, err := e.RequestInfo()
if err != nil {
t.Fatal(err)
}
if info.Context != core.RequestInfoContextOAuth2 {
t.Fatalf("Expected request context %q, got %q", core.RequestInfoContextOAuth2, info.Context)
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"record":{`,
`"token":"`,
`"meta":{`,
`"email":"test@example.com"`,
`"id":"4q1xlclmfloku33"`,
`"id":"test_id"`,
`"verified":false`, // shouldn't change
},
NotExpectedContent: []string{
// hidden fields
`"tokenKey"`,
`"password"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
"OnRecordAuthRequest": 1,
"OnRecordEnrich": 1,
// ---
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnRecordCreate": 1,
"OnRecordCreateExecute": 1,
"OnRecordAfterCreateSuccess": 1,
// ---
"OnModelUpdate": 1,
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
// ---
"OnModelValidate": 2, // create + update
"OnRecordValidate": 2,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
if name := user.GetString("name"); name != "test1" {
t.Fatalf("Expected name to not change, got %q", name)
}
if user.ValidatePassword("1234567890") {
t.Fatalf("Expected password %q to be changed", "1234567890")
}
devices, err := app.FindAllAuthOriginsByRecord(user)
if len(devices) != 1 {
t.Fatalf("Expected only 1 auth origin to be created, got %d (%v)", len(devices), err)
}
},
},
{
Name: "existing linked OAuth2 (verified user)",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code":"123",
"redirectURL": "https://example.com"
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
user, err := app.FindAuthRecordByEmail("users", "test2@example.com")
if err != nil {
t.Fatal(err)
}
if !user.Verified() {
t.Fatalf("Expected user %q to be verified", user.Email())
}
// ensure that the old password works
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected password %q to be valid", "1234567890")
}
// register the test provider
auth.Providers["test"] = func() auth.Provider {
return &oauth2MockProvider{
AuthUser: &auth.AuthUser{Id: "test_id"},
Token: &oauth2.Token{AccessToken: "abc"},
}
}
// add the test provider in the collection
user.Collection().MFA.Enabled = false
user.Collection().OAuth2.Enabled = true
user.Collection().OAuth2.Providers = []core.OAuth2ProviderConfig{{
Name: "test",
ClientId: "123",
ClientSecret: "456",
}}
if err := app.Save(user.Collection()); err != nil {
t.Fatal(err)
}
// stub linked provider
ea := core.NewExternalAuth(app)
ea.SetCollectionRef(user.Collection().Id)
ea.SetRecordRef(user.Id)
ea.SetProvider("test")
ea.SetProviderId("test_id")
if err := app.Save(ea); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"record":{`,
`"token":"`,
`"meta":{`,
`"isNew":false`,
`"email":"test2@example.com"`,
`"id":"oap640cot4yru2s"`,
`"id":"test_id"`,
`"verified":true`,
},
NotExpectedContent: []string{
// hidden fields
`"tokenKey"`,
`"password"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
"OnRecordAuthRequest": 1,
"OnRecordEnrich": 1,
// ---
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnRecordCreate": 1,
"OnRecordCreateExecute": 1,
"OnRecordAfterCreateSuccess": 1,
// ---
"OnModelValidate": 1,
"OnRecordValidate": 1,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
user, err := app.FindAuthRecordByEmail("users", "test2@example.com")
if err != nil {
t.Fatal(err)
}
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected old password %q to be valid", "1234567890")
}
devices, err := app.FindAllAuthOriginsByRecord(user)
if len(devices) != 1 {
t.Fatalf("Expected only 1 auth origin to be created, got %d (%v)", len(devices), err)
}
},
},
{
Name: "link by email",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code":"123",
"redirectURL": "https://example.com"
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
if user.Verified() {
t.Fatalf("Expected user %q to be unverified", user.Email())
}
// ensure that the old password works
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected password %q to be valid", "1234567890")
}
// register the test provider
auth.Providers["test"] = func() auth.Provider {
return &oauth2MockProvider{
AuthUser: &auth.AuthUser{Id: "test_id", Email: "test@example.com"},
Token: &oauth2.Token{AccessToken: "abc"},
}
}
// add the test provider in the collection
user.Collection().MFA.Enabled = false
user.Collection().OAuth2.Enabled = true
user.Collection().OAuth2.Providers = []core.OAuth2ProviderConfig{{
Name: "test",
ClientId: "123",
ClientSecret: "456",
}}
if err := app.Save(user.Collection()); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"record":{`,
`"token":"`,
`"meta":{`,
`"isNew":false`,
`"email":"test@example.com"`,
`"id":"4q1xlclmfloku33"`,
`"id":"test_id"`,
`"verified":true`, // should be updated
},
NotExpectedContent: []string{
// hidden fields
`"tokenKey"`,
`"password"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
"OnRecordAuthRequest": 1,
"OnRecordEnrich": 1,
// ---
"OnModelCreate": 2, // authOrigins + externalAuths
"OnModelCreateExecute": 2,
"OnModelAfterCreateSuccess": 2,
"OnRecordCreate": 2,
"OnRecordCreateExecute": 2,
"OnRecordAfterCreateSuccess": 2,
// ---
"OnModelUpdate": 1, // record password and verified states
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
// ---
"OnModelValidate": 3, // record + authOrigins + externalAuths
"OnRecordValidate": 3,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
if user.ValidatePassword("1234567890") {
t.Fatalf("Expected password %q to be changed", "1234567890")
}
devices, err := app.FindAllAuthOriginsByRecord(user)
if len(devices) != 1 {
t.Fatalf("Expected only 1 auth origin to be created, got %d (%v)", len(devices), err)
}
},
},
{
Name: "link by fallback user (OAuth2 user with different email)",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code":"123",
"redirectURL": "https://example.com"
}`),
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
if user.Verified() {
t.Fatalf("Expected user %q to be unverified", user.Email())
}
// ensure that the old password works
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected password %q to be valid", "1234567890")
}
// register the test provider
auth.Providers["test"] = func() auth.Provider {
return &oauth2MockProvider{
AuthUser: &auth.AuthUser{
Id: "test_id",
Email: "test2@example.com", // different email -> should be ignored
},
Token: &oauth2.Token{AccessToken: "abc"},
}
}
// add the test provider in the collection
user.Collection().MFA.Enabled = false
user.Collection().OAuth2.Enabled = true
user.Collection().OAuth2.Providers = []core.OAuth2ProviderConfig{{
Name: "test",
ClientId: "123",
ClientSecret: "456",
}}
if err := app.Save(user.Collection()); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"record":{`,
`"token":"`,
`"meta":{`,
`"isNew":false`,
`"email":"test@example.com"`,
`"id":"4q1xlclmfloku33"`,
`"id":"test_id"`,
`"verified":false`, // shouldn't change because the OAuth2 user email is different
},
NotExpectedContent: []string{
// hidden fields
`"tokenKey"`,
`"password"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
"OnRecordAuthRequest": 1,
"OnRecordEnrich": 1,
// ---
"OnModelCreate": 2, // authOrigins + externalAuths
"OnModelCreateExecute": 2,
"OnModelAfterCreateSuccess": 2,
"OnRecordCreate": 2,
"OnRecordCreateExecute": 2,
"OnRecordAfterCreateSuccess": 2,
// ---
"OnModelValidate": 2,
"OnRecordValidate": 2,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected password %q not to be changed", "1234567890")
}
devices, err := app.FindAllAuthOriginsByRecord(user)
if len(devices) != 1 {
t.Fatalf("Expected only 1 auth origin to be created, got %d (%v)", len(devices), err)
}
},
},
{
Name: "link by fallback user (user without email)",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code":"123",
"redirectURL": "https://example.com"
}`),
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
if user.Verified() {
t.Fatalf("Expected user %q to be unverified", user.Email())
}
// ensure that the old password works
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected password %q to be valid", "1234567890")
}
oldTokenKey := user.TokenKey()
// manually unset the user email
user.SetEmail("")
if err = app.Save(user); err != nil {
t.Fatal(err)
}
// resave with the old token key since the email change above
// would change it and will make the password token invalid
user.SetTokenKey(oldTokenKey)
if err = app.Save(user); err != nil {
t.Fatalf("Failed to restore original user tokenKey: %v", err)
}
// register the test provider
auth.Providers["test"] = func() auth.Provider {
return &oauth2MockProvider{
AuthUser: &auth.AuthUser{
Id: "test_id",
Email: "test_oauth2@example.com",
},
Token: &oauth2.Token{AccessToken: "abc"},
}
}
// add the test provider in the collection
user.Collection().MFA.Enabled = false
user.Collection().OAuth2.Enabled = true
user.Collection().OAuth2.Providers = []core.OAuth2ProviderConfig{{
Name: "test",
ClientId: "123",
ClientSecret: "456",
}}
if err := app.Save(user.Collection()); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"record":{`,
`"token":"`,
`"meta":{`,
`"isNew":false`,
`"email":"test_oauth2@example.com"`,
`"id":"4q1xlclmfloku33"`,
`"id":"test_id"`,
`"verified":true`,
},
NotExpectedContent: []string{
// hidden fields
`"tokenKey"`,
`"password"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
"OnRecordAuthRequest": 1,
"OnRecordEnrich": 1,
// ---
"OnModelCreate": 2, // authOrigins + externalAuths
"OnModelCreateExecute": 2,
"OnModelAfterCreateSuccess": 2,
"OnRecordCreate": 2,
"OnRecordCreateExecute": 2,
"OnRecordAfterCreateSuccess": 2,
// ---
"OnModelUpdate": 1, // record email set
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
// ---
"OnModelValidate": 3, // record + authOrigins + externalAuths
"OnRecordValidate": 3,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
user, err := app.FindAuthRecordByEmail("users", "test_oauth2@example.com")
if err != nil {
t.Fatal(err)
}
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected password %q not to be changed", "1234567890")
}
devices, err := app.FindAllAuthOriginsByRecord(user)
if len(devices) != 1 {
t.Fatalf("Expected only 1 auth origin to be created, got %d (%v)", len(devices), err)
}
},
},
{
Name: "link by fallback user (unverified user with matching email)",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code":"123",
"redirectURL": "https://example.com"
}`),
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
if user.Verified() {
t.Fatalf("Expected user %q to be unverified", user.Email())
}
// ensure that the old password works
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected password %q to be valid", "1234567890")
}
// register the test provider
auth.Providers["test"] = func() auth.Provider {
return &oauth2MockProvider{
AuthUser: &auth.AuthUser{
Id: "test_id",
Email: "test@example.com", // matching email -> should be marked as verified
},
Token: &oauth2.Token{AccessToken: "abc"},
}
}
// add the test provider in the collection
user.Collection().MFA.Enabled = false
user.Collection().OAuth2.Enabled = true
user.Collection().OAuth2.Providers = []core.OAuth2ProviderConfig{{
Name: "test",
ClientId: "123",
ClientSecret: "456",
}}
if err := app.Save(user.Collection()); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"record":{`,
`"token":"`,
`"meta":{`,
`"isNew":false`,
`"email":"test@example.com"`,
`"id":"4q1xlclmfloku33"`,
`"id":"test_id"`,
`"verified":true`,
},
NotExpectedContent: []string{
// hidden fields
`"tokenKey"`,
`"password"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
"OnRecordAuthRequest": 1,
"OnRecordEnrich": 1,
// ---
"OnModelCreate": 2, // authOrigins + externalAuths
"OnModelCreateExecute": 2,
"OnModelAfterCreateSuccess": 2,
"OnRecordCreate": 2,
"OnRecordCreateExecute": 2,
"OnRecordAfterCreateSuccess": 2,
// ---
"OnModelUpdate": 1, // record verified update
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
// ---
"OnModelValidate": 3, // record + authOrigins + externalAuths
"OnRecordValidate": 3,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected password %q not to be changed", "1234567890")
}
devices, err := app.FindAllAuthOriginsByRecord(user)
if len(devices) != 1 {
t.Fatalf("Expected only 1 auth origin to be created, got %d (%v)", len(devices), err)
}
},
},
{
Name: "creating user (no extra create data or custom fields mapping)",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code":"123",
"redirectURL": "https://example.com"
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
usersCol, err := app.FindCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
// register the test provider
auth.Providers["test"] = func() auth.Provider {
return &oauth2MockProvider{
AuthUser: &auth.AuthUser{Id: "test_id"},
Token: &oauth2.Token{AccessToken: "abc"},
}
}
// add the test provider in the collection
usersCol.MFA.Enabled = false
usersCol.OAuth2.Enabled = true
usersCol.OAuth2.Providers = []core.OAuth2ProviderConfig{{
Name: "test",
ClientId: "123",
ClientSecret: "456",
}}
if err := app.Save(usersCol); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"record":{`,
`"token":"`,
`"meta":{`,
`"isNew":true`,
`"email":""`,
`"id":"test_id"`,
`"verified":true`,
},
NotExpectedContent: []string{
// hidden fields
`"tokenKey"`,
`"password"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
"OnRecordAuthRequest": 1,
"OnRecordCreateRequest": 1,
"OnRecordEnrich": 2, // the auth response and from the create request
// ---
"OnModelCreate": 3, // record + authOrigins + externalAuths
"OnModelCreateExecute": 3,
"OnModelAfterCreateSuccess": 3,
"OnRecordCreate": 3,
"OnRecordCreateExecute": 3,
"OnRecordAfterCreateSuccess": 3,
// ---
"OnModelUpdate": 1, // created record verified state change
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
// ---
"OnModelValidate": 4,
"OnRecordValidate": 4,
},
},
{
Name: "creating user (submit failure - form auth fields validator)",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code":"123",
"redirectURL": "https://example.com",
"createData": {
"verified": true,
"email": "invalid",
"rel": "invalid",
"file": "invalid"
}
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
usersCol, err := app.FindCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
// register the test provider
auth.Providers["test"] = func() auth.Provider {
return &oauth2MockProvider{
AuthUser: &auth.AuthUser{Id: "test_id"},
Token: &oauth2.Token{AccessToken: "abc"},
}
}
// add the test provider in the collection
usersCol.MFA.Enabled = false
usersCol.OAuth2.Enabled = true
usersCol.OAuth2.Providers = []core.OAuth2ProviderConfig{{
Name: "test",
ClientId: "123",
ClientSecret: "456",
}}
if err := app.Save(usersCol); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"verified":{"code":"validation_values_mismatch"`,
},
NotExpectedContent: []string{
`"email":`, // ignored because the record validator never ran
`"rel":`, // ignored because the record validator never ran
`"file":`, // ignored because the record validator never ran
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
"OnRecordCreateRequest": 1,
},
},
{
Name: "creating user (submit failure - record fields validator)",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code":"123",
"redirectURL": "https://example.com",
"createData": {
"email": "invalid",
"rel": "invalid",
"file": "invalid"
}
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
usersCol, err := app.FindCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
// register the test provider
auth.Providers["test"] = func() auth.Provider {
return &oauth2MockProvider{
AuthUser: &auth.AuthUser{Id: "test_id"},
Token: &oauth2.Token{AccessToken: "abc"},
}
}
// add the test provider in the collection
usersCol.MFA.Enabled = false
usersCol.OAuth2.Enabled = true
usersCol.OAuth2.Providers = []core.OAuth2ProviderConfig{{
Name: "test",
ClientId: "123",
ClientSecret: "456",
}}
if err := app.Save(usersCol); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"email":{"code":"validation_is_email"`,
`"rel":{"code":"validation_missing_rel_records"`,
`"file":{"code":"validation_invalid_file"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
"OnRecordCreateRequest": 1,
"OnModelValidate": 1,
"OnRecordValidate": 1,
"OnModelCreate": 1,
"OnModelAfterCreateError": 1,
"OnRecordCreate": 1,
"OnRecordAfterCreateError": 1,
},
},
{
Name: "creating user (valid create data with empty submitted email)",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code":"123",
"redirectURL": "https://example.com",
"createData": {
"email": "",
"emailVisibility": true,
"password": "1234567890",
"passwordConfirm": "1234567890",
"name": "test_name",
"username": "test_username",
"rel": "0yxhwia2amd8gec"
}
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
usersCol, err := app.FindCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
// register the test provider
auth.Providers["test"] = func() auth.Provider {
return &oauth2MockProvider{
AuthUser: &auth.AuthUser{Id: "test_id"},
Token: &oauth2.Token{AccessToken: "abc"},
}
}
// add the test provider in the collection
usersCol.MFA.Enabled = false
usersCol.OAuth2.Enabled = true
usersCol.OAuth2.Providers = []core.OAuth2ProviderConfig{{
Name: "test",
ClientId: "123",
ClientSecret: "456",
}}
if err := app.Save(usersCol); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"isNew":true`,
`"email":""`,
`"emailVisibility":true`,
`"name":"test_name"`,
`"username":"test_username"`,
`"verified":true`,
`"rel":"0yxhwia2amd8gec"`,
},
NotExpectedContent: []string{
// hidden fields
`"tokenKey"`,
`"password"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
"OnRecordAuthRequest": 1,
"OnRecordCreateRequest": 1,
"OnRecordEnrich": 2, // the auth response and from the create request
// ---
"OnModelCreate": 3, // record + authOrigins + externalAuths
"OnModelCreateExecute": 3,
"OnModelAfterCreateSuccess": 3,
"OnRecordCreate": 3,
"OnRecordCreateExecute": 3,
"OnRecordAfterCreateSuccess": 3,
// ---
"OnModelUpdate": 1, // created record verified state change
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
// ---
"OnModelValidate": 4,
"OnRecordValidate": 4,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
user, err := app.FindFirstRecordByData("users", "username", "test_username")
if err != nil {
t.Fatal(err)
}
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected password %q to be valid", "1234567890")
}
},
},
{
Name: "creating user (valid create data with non-empty valid submitted email)",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code":"123",
"redirectURL": "https://example.com",
"createData": {
"email": "test_create@example.com",
"emailVisibility": true,
"password": "1234567890",
"passwordConfirm": "1234567890",
"name": "test_name",
"username": "test_username",
"rel": "0yxhwia2amd8gec"
}
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
usersCol, err := app.FindCollectionByNameOrId("users")
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | true |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/record_auth_impersonate.go | apis/record_auth_impersonate.go | package apis
import (
"time"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core"
)
// note: for now allow superusers but it may change in the future to allow access
// also to users with "Manage API" rule access depending on the use cases that will arise
func recordAuthImpersonate(e *core.RequestEvent) error {
if !e.HasSuperuserAuth() {
return e.ForbiddenError("", nil)
}
collection, err := findAuthCollection(e)
if err != nil {
return err
}
record, err := e.App.FindRecordById(collection, e.Request.PathValue("id"))
if err != nil {
return e.NotFoundError("", err)
}
form := &impersonateForm{}
if err = e.BindBody(form); err != nil {
return e.BadRequestError("An error occurred while loading the submitted data.", err)
}
if err = form.validate(); err != nil {
return e.BadRequestError("An error occurred while validating the submitted data.", err)
}
token, err := record.NewStaticAuthToken(time.Duration(form.Duration) * time.Second)
if err != nil {
e.InternalServerError("Failed to generate static auth token", err)
}
return recordAuthResponse(e, record, token, "", nil)
}
// -------------------------------------------------------------------
type impersonateForm struct {
// Duration is the optional custom token duration in seconds.
Duration int64 `form:"duration" json:"duration"`
}
func (form *impersonateForm) validate() error {
return validation.ValidateStruct(form,
validation.Field(&form.Duration, validation.Min(0)),
)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/batch_test.go | apis/batch_test.go | package apis_test
import (
"net/http"
"strings"
"testing"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/router"
)
func TestBatchRequest(t *testing.T) {
t.Parallel()
formData, mp, err := tests.MockMultipartData(
map[string]string{
router.JSONPayloadKey: `{
"requests":[
{"method":"POST", "url":"/api/collections/demo3/records", "body": {"title": "batch1"}},
{"method":"POST", "url":"/api/collections/demo3/records", "body": {"title": "batch2"}},
{"method":"POST", "url":"/api/collections/demo3/records", "body": {"title": "batch3"}},
{"method":"PATCH", "url":"/api/collections/demo3/records/lcl9d87w22ml6jy", "body": {"files-": "test_FLurQTgrY8.txt"}}
]
}`,
},
"requests.0.files",
"requests.0.files",
"requests.0.files",
"requests[2].files",
)
if err != nil {
t.Fatal(err)
}
scenarios := []tests.ApiScenario{
{
Name: "disabled batch requets",
Method: http.MethodPost,
URL: "/api/batch",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.Settings().Batch.Enabled = false
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "max request limits reached",
Method: http.MethodPost,
URL: "/api/batch",
Body: strings.NewReader(`{
"requests": [
{"method":"GET", "url":"/test1"},
{"method":"GET", "url":"/test2"},
{"method":"GET", "url":"/test3"}
]
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.Settings().Batch.Enabled = true
app.Settings().Batch.MaxRequests = 2
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"requests":{"code":"validation_length_too_long"`,
},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "trigger requests validations",
Method: http.MethodPost,
URL: "/api/batch",
Body: strings.NewReader(`{
"requests": [
{},
{"method":"GET", "url":"/valid"},
{"method":"invalid", "url":"/valid"},
{"method":"POST", "url":"` + strings.Repeat("a", 2001) + `"}
]
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.Settings().Batch.Enabled = true
app.Settings().Batch.MaxRequests = 100
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"requests":{`,
`"0":{"method":{"code":"validation_required"`,
`"2":{"method":{"code":"validation_in_invalid"`,
`"3":{"url":{"code":"validation_length_too_long"`,
},
NotExpectedContent: []string{
`"1":`,
},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "unknown batch request action",
Method: http.MethodPost,
URL: "/api/batch",
Body: strings.NewReader(`{
"requests": [
{"method":"GET", "url":"/api/health"}
]
}`),
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"requests":{`,
`0":{"code":"batch_request_failed"`,
`"response":{`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnBatchRequest": 1,
},
},
{
Name: "base 2 successful and 1 failed (public collection)",
Method: http.MethodPost,
URL: "/api/batch",
Body: strings.NewReader(`{
"requests": [
{"method":"POST", "url":"/api/collections/demo2/records", "body": {"title": "batch1"}},
{"method":"POST", "url":"/api/collections/demo2/records", "body": {"title": "batch2"}},
{"method":"POST", "url":"/api/collections/demo2/records", "body": {"title": ""}}
]
}`),
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"response":{`,
`"2":{"code":"batch_request_failed"`,
`"response":{"data":{"title":{"code":"validation_required"`,
},
NotExpectedContent: []string{
`"0":`,
`"1":`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnBatchRequest": 1,
"OnRecordCreateRequest": 3,
"OnModelCreate": 3,
"OnModelCreateExecute": 2,
"OnModelAfterCreateError": 3,
"OnModelValidate": 3,
"OnRecordCreate": 3,
"OnRecordCreateExecute": 2,
"OnRecordAfterCreateError": 3,
"OnRecordValidate": 3,
"OnRecordEnrich": 2,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
records, err := app.FindRecordsByFilter("demo2", `title~"batch"`, "", 0, 0)
if err != nil {
t.Fatal(err)
}
if len(records) != 0 {
t.Fatalf("Expected no batch records to be persisted, got %d", len(records))
}
},
},
{
Name: "base 4 successful (public collection)",
Method: http.MethodPost,
URL: "/api/batch",
Body: strings.NewReader(`{
"requests": [
{"method":"POST", "url":"/api/collections/demo2/records", "body": {"title": "batch1"}},
{"method":"POST", "url":"/api/collections/demo2/records", "body": {"title": "batch2"}},
{"method":"PUT", "url":"/api/collections/demo2/records", "body": {"title": "batch3"}},
{"method":"PUT", "url":"/api/collections/demo2/records?fields=*,id:excerpt(4,true)", "body": {"id":"achvryl401bhse3","title": "batch4"}}
]
}`),
ExpectedStatus: 200,
ExpectedContent: []string{
`"title":"batch1"`,
`"title":"batch2"`,
`"title":"batch3"`,
`"title":"batch4"`,
`"id":"achv..."`,
`"active":false`,
`"active":true`,
`"status":200`,
`"body":{`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnBatchRequest": 1,
"OnModelValidate": 4,
"OnRecordValidate": 4,
"OnRecordEnrich": 4,
"OnRecordCreateRequest": 3,
"OnModelCreate": 3,
"OnModelCreateExecute": 3,
"OnModelAfterCreateSuccess": 3,
"OnRecordCreate": 3,
"OnRecordCreateExecute": 3,
"OnRecordAfterCreateSuccess": 3,
"OnRecordUpdateRequest": 1,
"OnModelUpdate": 1,
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
records, err := app.FindRecordsByFilter("demo2", `title~"batch"`, "", 0, 0)
if err != nil {
t.Fatal(err)
}
if len(records) != 4 {
t.Fatalf("Expected %d batch records to be persisted, got %d", 3, len(records))
}
},
},
{
Name: "mixed create/update/delete (rules failure)",
Method: http.MethodPost,
URL: "/api/batch",
Body: strings.NewReader(`{
"requests": [
{"method":"POST", "url":"/api/collections/demo2/records", "body": {"title": "batch_create"}},
{"method":"DELETE", "url":"/api/collections/demo2/records/achvryl401bhse3"},
{"method":"PATCH", "url":"/api/collections/demo3/records/1tmknxy2868d869", "body": {"title": "batch_update"}}
]
}`),
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"requests":{`,
`"2":{"code":"batch_request_failed"`,
`"response":{`,
},
NotExpectedContent: []string{
// only demo3 requires authentication
`"0":`,
`"1":`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnBatchRequest": 1,
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateError": 1,
"OnModelDelete": 1,
"OnModelDeleteExecute": 1,
"OnModelAfterDeleteError": 1,
"OnModelValidate": 1,
"OnRecordCreateRequest": 1,
"OnRecordCreate": 1,
"OnRecordCreateExecute": 1,
"OnRecordAfterCreateError": 1,
"OnRecordDeleteRequest": 1,
"OnRecordDelete": 1,
"OnRecordDeleteExecute": 1,
"OnRecordAfterDeleteError": 1,
"OnRecordEnrich": 1,
"OnRecordValidate": 1,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
_, err := app.FindFirstRecordByFilter("demo2", `title="batch_create"`)
if err == nil {
t.Fatal("Expected record to not be created")
}
_, err = app.FindFirstRecordByFilter("demo3", `title="batch_update"`)
if err == nil {
t.Fatal("Expected record to not be updated")
}
_, err = app.FindRecordById("demo2", "achvryl401bhse3")
if err != nil {
t.Fatal("Expected record to not be deleted")
}
},
},
{
Name: "mixed create/update/delete (rules success)",
Method: http.MethodPost,
URL: "/api/batch",
Headers: map[string]string{
// test@example.com, clients
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
},
Body: strings.NewReader(`{
"requests": [
{"method":"POST", "url":"/api/collections/demo2/records", "body": {"title": "batch_create"}, "headers": {"Authorization": "ignored"}},
{"method":"DELETE", "url":"/api/collections/demo2/records/achvryl401bhse3", "headers": {"Authorization": "ignored"}},
{"method":"PATCH", "url":"/api/collections/demo3/records/1tmknxy2868d869", "body": {"title": "batch_update"}, "headers": {"Authorization": "ignored"}}
]
}`),
ExpectedStatus: 200,
ExpectedContent: []string{
`"title":"batch_create"`,
`"title":"batch_update"`,
`"status":200`,
`"status":204`,
`"body":{`,
`"body":null`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnBatchRequest": 1,
// ---
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnModelDelete": 1,
"OnModelDeleteExecute": 1,
"OnModelAfterDeleteSuccess": 1,
"OnModelUpdate": 1,
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnModelValidate": 2,
// ---
"OnRecordCreateRequest": 1,
"OnRecordCreate": 1,
"OnRecordCreateExecute": 1,
"OnRecordAfterCreateSuccess": 1,
"OnRecordDeleteRequest": 1,
"OnRecordDelete": 1,
"OnRecordDeleteExecute": 1,
"OnRecordAfterDeleteSuccess": 1,
"OnRecordUpdateRequest": 1,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
"OnRecordValidate": 2,
"OnRecordEnrich": 2,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
_, err := app.FindFirstRecordByFilter("demo2", `title="batch_create"`)
if err != nil {
t.Fatal(err)
}
_, err = app.FindFirstRecordByFilter("demo3", `title="batch_update"`)
if err != nil {
t.Fatal(err)
}
_, err = app.FindRecordById("demo2", "achvryl401bhse3")
if err == nil {
t.Fatal("Expected record to be deleted")
}
},
},
{
Name: "mixed create/update/delete (superuser auth)",
Method: http.MethodPost,
URL: "/api/batch",
Headers: map[string]string{
// test@example.com, _superusers
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
Body: strings.NewReader(`{
"requests": [
{"method":"POST", "url":"/api/collections/demo2/records", "body": {"title": "batch_create"}},
{"method":"DELETE", "url":"/api/collections/demo2/records/achvryl401bhse3"},
{"method":"PATCH", "url":"/api/collections/demo3/records/1tmknxy2868d869", "body": {"title": "batch_update"}}
]
}`),
ExpectedStatus: 200,
ExpectedContent: []string{
`"title":"batch_create"`,
`"title":"batch_update"`,
`"status":200`,
`"status":204`,
`"body":{`,
`"body":null`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnBatchRequest": 1,
// ---
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnModelDelete": 1,
"OnModelDeleteExecute": 1,
"OnModelAfterDeleteSuccess": 1,
"OnModelUpdate": 1,
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnModelValidate": 2,
// ---
"OnRecordCreateRequest": 1,
"OnRecordCreate": 1,
"OnRecordCreateExecute": 1,
"OnRecordAfterCreateSuccess": 1,
"OnRecordDeleteRequest": 1,
"OnRecordDelete": 1,
"OnRecordDeleteExecute": 1,
"OnRecordAfterDeleteSuccess": 1,
"OnRecordUpdateRequest": 1,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
"OnRecordValidate": 2,
"OnRecordEnrich": 2,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
_, err := app.FindFirstRecordByFilter("demo2", `title="batch_create"`)
if err != nil {
t.Fatal(err)
}
_, err = app.FindFirstRecordByFilter("demo3", `title="batch_update"`)
if err != nil {
t.Fatal(err)
}
_, err = app.FindRecordById("demo2", "achvryl401bhse3")
if err == nil {
t.Fatal("Expected record to be deleted")
}
},
},
{
Name: "cascade delete/update",
Method: http.MethodPost,
URL: "/api/batch",
Headers: map[string]string{
// test@example.com, _superusers
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
Body: strings.NewReader(`{
"requests": [
{"method":"DELETE", "url":"/api/collections/demo3/records/1tmknxy2868d869"},
{"method":"DELETE", "url":"/api/collections/demo3/records/mk5fmymtx4wsprk"}
]
}`),
ExpectedStatus: 200,
ExpectedContent: []string{
`"status":204`,
`"body":null`,
},
NotExpectedContent: []string{
`"status":200`,
`"body":{`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnBatchRequest": 1,
// ---
"OnModelDelete": 3, // 2 batch + 1 cascade delete
"OnModelDeleteExecute": 3,
"OnModelAfterDeleteSuccess": 3,
"OnModelUpdate": 5, // 5 cascade update
"OnModelUpdateExecute": 5,
"OnModelAfterUpdateSuccess": 5,
// ---
"OnRecordDeleteRequest": 2,
"OnRecordDelete": 3,
"OnRecordDeleteExecute": 3,
"OnRecordAfterDeleteSuccess": 3,
"OnRecordUpdate": 5,
"OnRecordUpdateExecute": 5,
"OnRecordAfterUpdateSuccess": 5,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
ids := []string{
"1tmknxy2868d869",
"mk5fmymtx4wsprk",
"qzaqccwrmva4o1n",
}
for _, id := range ids {
_, err := app.FindRecordById("demo2", id)
if err == nil {
t.Fatalf("Expected record %q to be deleted", id)
}
}
},
},
{
Name: "transaction timeout",
Method: http.MethodPost,
URL: "/api/batch",
Body: strings.NewReader(`{
"requests": [
{"method":"POST", "url":"/api/collections/demo2/records", "body": {"title": "batch1"}},
{"method":"POST", "url":"/api/collections/demo2/records", "body": {"title": "batch2"}}
]
}`),
Headers: map[string]string{
// test@example.com, _superusers
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.Settings().Batch.Timeout = 1
app.OnRecordCreateRequest("demo2").BindFunc(func(e *core.RecordRequestEvent) error {
time.Sleep(600 * time.Millisecond) // < 1s so that the first request can succeed
return e.Next()
})
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{}`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnBatchRequest": 1,
"OnRecordCreateRequest": 2,
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateError": 1,
"OnModelValidate": 1,
"OnRecordCreate": 1,
"OnRecordCreateExecute": 1,
"OnRecordAfterCreateError": 1,
"OnRecordEnrich": 1,
"OnRecordValidate": 1,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
records, err := app.FindRecordsByFilter("demo2", `title~"batch"`, "", 0, 0)
if err != nil {
t.Fatal(err)
}
if len(records) != 0 {
t.Fatalf("Expected %d batch records to be persisted, got %d", 0, len(records))
}
},
},
{
Name: "multipart/form-data + file upload",
Method: http.MethodPost,
URL: "/api/batch",
Body: formData,
Headers: map[string]string{
// test@example.com, clients
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
"Content-Type": mp.FormDataContentType(),
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"title":"batch1"`,
`"title":"batch2"`,
`"title":"batch3"`,
`"id":"lcl9d87w22ml6jy"`,
`"files":["300_UhLKX91HVb.png"]`,
`"tmpfile_`,
`"status":200`,
`"body":{`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnBatchRequest": 1,
// ---
"OnModelCreate": 3,
"OnModelCreateExecute": 3,
"OnModelAfterCreateSuccess": 3,
"OnModelUpdate": 1,
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnModelValidate": 4,
// ---
"OnRecordCreateRequest": 3,
"OnRecordUpdateRequest": 1,
"OnRecordCreate": 3,
"OnRecordCreateExecute": 3,
"OnRecordAfterCreateSuccess": 3,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
"OnRecordValidate": 4,
"OnRecordEnrich": 4,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
batch1, err := app.FindFirstRecordByFilter("demo3", `title="batch1"`)
if err != nil {
t.Fatalf("missing batch1: %v", err)
}
batch1Files := batch1.GetStringSlice("files")
if len(batch1Files) != 3 {
t.Fatalf("Expected %d batch1 file(s), got %d", 3, len(batch1Files))
}
batch2, err := app.FindFirstRecordByFilter("demo3", `title="batch2"`)
if err != nil {
t.Fatalf("missing batch2: %v", err)
}
batch2Files := batch2.GetStringSlice("files")
if len(batch2Files) != 0 {
t.Fatalf("Expected %d batch2 file(s), got %d", 0, len(batch2Files))
}
batch3, err := app.FindFirstRecordByFilter("demo3", `title="batch3"`)
if err != nil {
t.Fatalf("missing batch3: %v", err)
}
batch3Files := batch3.GetStringSlice("files")
if len(batch3Files) != 1 {
t.Fatalf("Expected %d batch3 file(s), got %d", 1, len(batch3Files))
}
batch4, err := app.FindRecordById("demo3", "lcl9d87w22ml6jy")
if err != nil {
t.Fatalf("missing batch4: %v", err)
}
batch4Files := batch4.GetStringSlice("files")
if len(batch4Files) != 1 {
t.Fatalf("Expected %d batch4 file(s), got %d", 1, len(batch4Files))
}
},
},
{
Name: "create/update with expand query params",
Method: http.MethodPost,
URL: "/api/batch",
Headers: map[string]string{
// test@example.com, _superusers
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
Body: strings.NewReader(`{
"requests": [
{"method":"POST", "url":"/api/collections/demo5/records?expand=rel_one", "body": {"total": 9, "rel_one":"qzaqccwrmva4o1n"}},
{"method":"PATCH", "url":"/api/collections/demo5/records/qjeql998mtp1azp?expand=rel_many", "body": {"total": 10}}
]
}`),
ExpectedStatus: 200,
ExpectedContent: []string{
`"body":{`,
`"id":"qjeql998mtp1azp"`,
`"id":"qzaqccwrmva4o1n"`,
`"id":"i9naidtvr6qsgb4"`,
`"expand":{"rel_one"`,
`"expand":{"rel_many"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnBatchRequest": 1,
// ---
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnModelUpdate": 1,
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnModelValidate": 2,
// ---
"OnRecordCreateRequest": 1,
"OnRecordUpdateRequest": 1,
"OnRecordCreate": 1,
"OnRecordCreateExecute": 1,
"OnRecordAfterCreateSuccess": 1,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
"OnRecordValidate": 2,
"OnRecordEnrich": 5,
},
},
{
Name: "check body limit middleware",
Method: http.MethodPost,
URL: "/api/batch",
Headers: map[string]string{
// test@example.com, _superusers
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
Body: strings.NewReader(`{
"requests": [
{"method":"POST", "url":"/api/collections/demo5/records?expand=rel_one", "body": {"total": 9, "rel_one":"qzaqccwrmva4o1n"}},
{"method":"PATCH", "url":"/api/collections/demo5/records/qjeql998mtp1azp?expand=rel_many", "body": {"total": 10}}
]
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.Settings().Batch.MaxBodySize = 10
},
ExpectedStatus: 413,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/base.go | apis/base.go | package apis
import (
"errors"
"fmt"
"io/fs"
"net/http"
"path/filepath"
"strings"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/router"
)
// StaticWildcardParam is the name of Static handler wildcard parameter.
const StaticWildcardParam = "path"
// NewRouter returns a new router instance loaded with the default app middlewares and api routes.
func NewRouter(app core.App) (*router.Router[*core.RequestEvent], error) {
pbRouter := router.NewRouter(func(w http.ResponseWriter, r *http.Request) (*core.RequestEvent, router.EventCleanupFunc) {
event := new(core.RequestEvent)
event.Response = w
event.Request = r
event.App = app
return event, nil
})
// register default middlewares
pbRouter.Bind(activityLogger())
pbRouter.Bind(panicRecover())
pbRouter.Bind(rateLimit())
pbRouter.Bind(loadAuthToken())
pbRouter.Bind(securityHeaders())
pbRouter.Bind(BodyLimit(DefaultMaxBodySize))
apiGroup := pbRouter.Group("/api")
bindSettingsApi(app, apiGroup)
bindCollectionApi(app, apiGroup)
bindRecordCrudApi(app, apiGroup)
bindRecordAuthApi(app, apiGroup)
bindLogsApi(app, apiGroup)
bindBackupApi(app, apiGroup)
bindCronApi(app, apiGroup)
bindFileApi(app, apiGroup)
bindBatchApi(app, apiGroup)
bindRealtimeApi(app, apiGroup)
bindHealthApi(app, apiGroup)
return pbRouter, nil
}
// WrapStdHandler wraps Go [http.Handler] into a PocketBase handler func.
func WrapStdHandler(h http.Handler) func(*core.RequestEvent) error {
return func(e *core.RequestEvent) error {
h.ServeHTTP(e.Response, e.Request)
return nil
}
}
// WrapStdMiddleware wraps Go [func(http.Handler) http.Handle] into a PocketBase middleware func.
func WrapStdMiddleware(m func(http.Handler) http.Handler) func(*core.RequestEvent) error {
return func(e *core.RequestEvent) (err error) {
m(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
e.Response = w
e.Request = r
err = e.Next()
})).ServeHTTP(e.Response, e.Request)
return err
}
}
// MustSubFS returns an [fs.FS] corresponding to the subtree rooted at fsys's dir.
//
// This is similar to [fs.Sub] but panics on failure.
func MustSubFS(fsys fs.FS, dir string) fs.FS {
dir = filepath.ToSlash(filepath.Clean(dir)) // ToSlash in case of Windows path
sub, err := fs.Sub(fsys, dir)
if err != nil {
panic(fmt.Errorf("failed to create sub FS: %w", err))
}
return sub
}
// Static is a handler function to serve static directory content from fsys.
//
// If a file resource is missing and indexFallback is set, the request
// will be forwarded to the base index.html (useful for SPA with pretty urls).
//
// NB! Expects the route to have a "{path...}" wildcard parameter.
//
// Special redirects:
// - if "path" is a file that ends in index.html, it is redirected to its non-index.html version (eg. /test/index.html -> /test/)
// - if "path" is a directory that has index.html, the index.html file is rendered,
// otherwise if missing - returns 404 or fallback to the root index.html if indexFallback is set
//
// Example:
//
// fsys := os.DirFS("./pb_public")
// router.GET("/files/{path...}", apis.Static(fsys, false))
func Static(fsys fs.FS, indexFallback bool) func(*core.RequestEvent) error {
if fsys == nil {
panic("Static: the provided fs.FS argument is nil")
}
return func(e *core.RequestEvent) error {
// disable the activity logger to avoid flooding with messages
//
// note: errors are still logged
if e.Get(requestEventKeySkipSuccessActivityLog) == nil {
e.Set(requestEventKeySkipSuccessActivityLog, true)
}
filename := e.Request.PathValue(StaticWildcardParam)
filename = filepath.ToSlash(filepath.Clean(strings.TrimPrefix(filename, "/")))
// eagerly check for directory traversal
//
// note: this is just out of an abundance of caution because the fs.FS implementation could be non-std,
// but usually shouldn't be necessary since os.DirFS.Open is expected to fail if the filename starts with dots
if len(filename) > 2 && filename[0] == '.' && filename[1] == '.' && (filename[2] == '/' || filename[2] == '\\') {
if indexFallback && filename != router.IndexPage {
return e.FileFS(fsys, router.IndexPage)
}
return router.ErrFileNotFound
}
fi, err := fs.Stat(fsys, filename)
if err != nil {
if indexFallback && filename != router.IndexPage {
return e.FileFS(fsys, router.IndexPage)
}
return router.ErrFileNotFound
}
if fi.IsDir() {
// redirect to a canonical dir url, aka. with trailing slash
if !strings.HasSuffix(e.Request.URL.Path, "/") {
return e.Redirect(http.StatusMovedPermanently, safeRedirectPath(e.Request.URL.Path+"/"))
}
} else {
urlPath := e.Request.URL.Path
if strings.HasSuffix(urlPath, "/") {
// redirect to a non-trailing slash file route
urlPath = strings.TrimRight(urlPath, "/")
if len(urlPath) > 0 {
return e.Redirect(http.StatusMovedPermanently, safeRedirectPath(urlPath))
}
} else if stripped, ok := strings.CutSuffix(urlPath, router.IndexPage); ok {
// redirect without the index.html
return e.Redirect(http.StatusMovedPermanently, safeRedirectPath(stripped))
}
}
fileErr := e.FileFS(fsys, filename)
if fileErr != nil && indexFallback && filename != router.IndexPage && errors.Is(fileErr, router.ErrFileNotFound) {
return e.FileFS(fsys, router.IndexPage)
}
return fileErr
}
}
// safeRedirectPath normalizes the path string by replacing all beginning slashes
// (`\\`, `//`, `\/`) with a single forward slash to prevent open redirect attacks
func safeRedirectPath(path string) string {
if len(path) > 1 && (path[0] == '\\' || path[0] == '/') && (path[1] == '\\' || path[1] == '/') {
path = "/" + strings.TrimLeft(path, `/\`)
}
return path
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/backup_test.go | apis/backup_test.go | package apis_test
import (
"archive/zip"
"bytes"
"context"
"io"
"mime/multipart"
"net/http"
"strings"
"testing"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/filesystem/blob"
)
func TestBackupsList(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "unauthorized",
Method: http.MethodGet,
URL: "/api/backups",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as regular user",
Method: http.MethodGet,
URL: "/api/backups",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser (empty list)",
Method: http.MethodGet,
URL: "/api/backups",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{`[]`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser",
Method: http.MethodGet,
URL: "/api/backups",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"test1.zip"`,
`"test2.zip"`,
`"test3.zip"`,
},
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestBackupsCreate(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "unauthorized",
Method: http.MethodPost,
URL: "/api/backups",
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
ensureNoBackups(t, app)
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as regular user",
Method: http.MethodPost,
URL: "/api/backups",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
ensureNoBackups(t, app)
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser (pending backup)",
Method: http.MethodPost,
URL: "/api/backups",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.Store().Set(core.StoreKeyActiveBackup, "")
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
ensureNoBackups(t, app)
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser (autogenerated name)",
Method: http.MethodPost,
URL: "/api/backups",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
files, err := getBackupFiles(app)
if err != nil {
t.Fatal(err)
}
if total := len(files); total != 1 {
t.Fatalf("Expected 1 backup file, got %d", total)
}
expected := "pb_backup_"
if !strings.HasPrefix(files[0].Key, expected) {
t.Fatalf("Expected backup file with prefix %q, got %q", expected, files[0].Key)
}
},
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnBackupCreate": 1,
},
},
{
Name: "authorized as superuser (invalid name)",
Method: http.MethodPost,
URL: "/api/backups",
Body: strings.NewReader(`{"name":"!test.zip"}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
ensureNoBackups(t, app)
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"name":{"code":"validation_match_invalid"`,
},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser (valid name)",
Method: http.MethodPost,
URL: "/api/backups",
Body: strings.NewReader(`{"name":"test.zip"}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
files, err := getBackupFiles(app)
if err != nil {
t.Fatal(err)
}
if total := len(files); total != 1 {
t.Fatalf("Expected 1 backup file, got %d", total)
}
expected := "test.zip"
if files[0].Key != expected {
t.Fatalf("Expected backup file %q, got %q", expected, files[0].Key)
}
},
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnBackupCreate": 1,
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestBackupUpload(t *testing.T) {
t.Parallel()
// create dummy form data bodies
type body struct {
buffer io.Reader
contentType string
}
bodies := make([]body, 10)
for i := 0; i < 10; i++ {
func() {
zb := new(bytes.Buffer)
zw := zip.NewWriter(zb)
if err := zw.Close(); err != nil {
t.Fatal(err)
}
b := new(bytes.Buffer)
mw := multipart.NewWriter(b)
mfw, err := mw.CreateFormFile("file", "test")
if err != nil {
t.Fatal(err)
}
if _, err := io.Copy(mfw, zb); err != nil {
t.Fatal(err)
}
mw.Close()
bodies[i] = body{
buffer: b,
contentType: mw.FormDataContentType(),
}
}()
}
// ---
scenarios := []tests.ApiScenario{
{
Name: "unauthorized",
Method: http.MethodPost,
URL: "/api/backups/upload",
Body: bodies[0].buffer,
Headers: map[string]string{
"Content-Type": bodies[0].contentType,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
ensureNoBackups(t, app)
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as regular user",
Method: http.MethodPost,
URL: "/api/backups/upload",
Body: bodies[1].buffer,
Headers: map[string]string{
"Content-Type": bodies[1].contentType,
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
ensureNoBackups(t, app)
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser (missing file)",
Method: http.MethodPost,
URL: "/api/backups/upload",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
ensureNoBackups(t, app)
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser (existing backup name)",
Method: http.MethodPost,
URL: "/api/backups/upload",
Body: bodies[3].buffer,
Headers: map[string]string{
"Content-Type": bodies[3].contentType,
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
fsys, err := app.NewBackupsFilesystem()
if err != nil {
t.Fatal(err)
}
defer fsys.Close()
// create a dummy backup file to simulate existing backups
if err := fsys.Upload([]byte("123"), "test"); err != nil {
t.Fatal(err)
}
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
files, _ := getBackupFiles(app)
if total := len(files); total != 1 {
t.Fatalf("Expected %d backup file, got %d", 1, total)
}
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{"file":{`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser (valid file)",
Method: http.MethodPost,
URL: "/api/backups/upload",
Body: bodies[4].buffer,
Headers: map[string]string{
"Content-Type": bodies[4].contentType,
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
files, _ := getBackupFiles(app)
if total := len(files); total != 1 {
t.Fatalf("Expected %d backup file, got %d", 1, total)
}
},
ExpectedStatus: 204,
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "ensure that the default body limit is skipped",
Method: http.MethodPost,
URL: "/api/backups/upload",
Body: bytes.NewBuffer(make([]byte, apis.DefaultMaxBodySize+100)),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 400, // it doesn't matter as long as it is not 413
ExpectedContent: []string{`"data":{`},
NotExpectedContent: []string{"entity too large"},
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestBackupsDownload(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "unauthorized",
Method: http.MethodGet,
URL: "/api/backups/test1.zip",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "with record auth header",
Method: http.MethodGet,
URL: "/api/backups/test1.zip",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "with superuser auth header",
Method: http.MethodGet,
URL: "/api/backups/test1.zip",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "with empty or invalid token",
Method: http.MethodGet,
URL: "/api/backups/test1.zip?token=",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "with valid record auth token",
Method: http.MethodGet,
URL: "/api/backups/test1.zip?token=eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "with valid record file token",
Method: http.MethodGet,
URL: "/api/backups/test1.zip?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6ImZpbGUiLCJjb2xsZWN0aW9uSWQiOiJfcGJfdXNlcnNfYXV0aF8ifQ.nSTLuCPcGpWn2K2l-BFkC3Vlzc-ZTDPByYq8dN1oPSo",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "with valid superuser auth token",
Method: http.MethodGet,
URL: "/api/backups/test1.zip?token=eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "with expired superuser file token",
Method: http.MethodGet,
URL: "/api/backups/test1.zip?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsImV4cCI6MTY0MDk5MTY2MSwidHlwZSI6ImZpbGUiLCJjb2xsZWN0aW9uSWQiOiJwYmNfMzE0MjYzNTgyMyJ9.nqqtqpPhxU0045F4XP_ruAkzAidYBc5oPy9ErN3XBq0",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "with valid superuser file token but missing backup name",
Method: http.MethodGet,
URL: "/api/backups/missing?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6ImZpbGUiLCJjb2xsZWN0aW9uSWQiOiJwYmNfMzE0MjYzNTgyMyJ9.Lupz541xRvrktwkrl55p5pPCF77T69ZRsohsIcb2dxc",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "with valid superuser file token",
Method: http.MethodGet,
URL: "/api/backups/test1.zip?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6ImZpbGUiLCJjb2xsZWN0aW9uSWQiOiJwYmNfMzE0MjYzNTgyMyJ9.Lupz541xRvrktwkrl55p5pPCF77T69ZRsohsIcb2dxc",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
"storage/",
"data.db",
"auxiliary.db",
},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "with valid superuser file token and backup name with escaped char",
Method: http.MethodGet,
URL: "/api/backups/%40test4.zip?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6ImZpbGUiLCJjb2xsZWN0aW9uSWQiOiJwYmNfMzE0MjYzNTgyMyJ9.Lupz541xRvrktwkrl55p5pPCF77T69ZRsohsIcb2dxc",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
"storage/",
"data.db",
"auxiliary.db",
},
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestBackupsDelete(t *testing.T) {
t.Parallel()
noTestBackupFilesChanges := func(t testing.TB, app *tests.TestApp) {
files, err := getBackupFiles(app)
if err != nil {
t.Fatal(err)
}
expected := 4
if total := len(files); total != expected {
t.Fatalf("Expected %d backup(s), got %d", expected, total)
}
}
scenarios := []tests.ApiScenario{
{
Name: "unauthorized",
Method: http.MethodDelete,
URL: "/api/backups/test1.zip",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
noTestBackupFilesChanges(t, app)
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as regular user",
Method: http.MethodDelete,
URL: "/api/backups/test1.zip",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
noTestBackupFilesChanges(t, app)
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser (missing file)",
Method: http.MethodDelete,
URL: "/api/backups/missing.zip",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
noTestBackupFilesChanges(t, app)
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser (existing file with matching active backup)",
Method: http.MethodDelete,
URL: "/api/backups/test1.zip",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
// mock active backup with the same name to delete
app.Store().Set(core.StoreKeyActiveBackup, "test1.zip")
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
noTestBackupFilesChanges(t, app)
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser (existing file and no matching active backup)",
Method: http.MethodDelete,
URL: "/api/backups/test1.zip",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
// mock active backup with different name
app.Store().Set(core.StoreKeyActiveBackup, "new.zip")
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
files, err := getBackupFiles(app)
if err != nil {
t.Fatal(err)
}
if total := len(files); total != 3 {
t.Fatalf("Expected %d backup files, got %d", 3, total)
}
deletedFile := "test1.zip"
for _, f := range files {
if f.Key == deletedFile {
t.Fatalf("Expected backup %q to be deleted", deletedFile)
}
}
},
ExpectedStatus: 204,
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser (backup with escaped character)",
Method: http.MethodDelete,
URL: "/api/backups/%40test4.zip",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
files, err := getBackupFiles(app)
if err != nil {
t.Fatal(err)
}
if total := len(files); total != 3 {
t.Fatalf("Expected %d backup files, got %d", 3, total)
}
deletedFile := "@test4.zip"
for _, f := range files {
if f.Key == deletedFile {
t.Fatalf("Expected backup %q to be deleted", deletedFile)
}
}
},
ExpectedStatus: 204,
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestBackupsRestore(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "unauthorized",
Method: http.MethodPost,
URL: "/api/backups/test1.zip/restore",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as regular user",
Method: http.MethodPost,
URL: "/api/backups/test1.zip/restore",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser (missing file)",
Method: http.MethodPost,
URL: "/api/backups/missing.zip/restore",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser (active backup process)",
Method: http.MethodPost,
URL: "/api/backups/test1.zip/restore",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := createTestBackups(app); err != nil {
t.Fatal(err)
}
app.Store().Set(core.StoreKeyActiveBackup, "")
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
// -------------------------------------------------------------------
func createTestBackups(app core.App) error {
ctx := context.Background()
if err := app.CreateBackup(ctx, "test1.zip"); err != nil {
return err
}
if err := app.CreateBackup(ctx, "test2.zip"); err != nil {
return err
}
if err := app.CreateBackup(ctx, "test3.zip"); err != nil {
return err
}
if err := app.CreateBackup(ctx, "@test4.zip"); err != nil {
return err
}
return nil
}
func getBackupFiles(app core.App) ([]*blob.ListObject, error) {
fsys, err := app.NewBackupsFilesystem()
if err != nil {
return nil, err
}
defer fsys.Close()
return fsys.List("")
}
func ensureNoBackups(t testing.TB, app *tests.TestApp) {
files, err := getBackupFiles(app)
if err != nil {
t.Fatal(err)
}
if total := len(files); total != 0 {
t.Fatalf("Expected 0 backup files, got %d", total)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/file.go | apis/file.go | package apis
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"runtime"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/router"
"github.com/spf13/cast"
"golang.org/x/sync/semaphore"
"golang.org/x/sync/singleflight"
)
var imageContentTypes = []string{"image/png", "image/jpg", "image/jpeg", "image/gif", "image/webp"}
var defaultThumbSizes = []string{"100x100"}
// bindFileApi registers the file api endpoints and the corresponding handlers.
func bindFileApi(app core.App, rg *router.RouterGroup[*core.RequestEvent]) {
maxWorkers := cast.ToInt64(os.Getenv("PB_THUMBS_MAX_WORKERS"))
if maxWorkers <= 0 {
maxWorkers = int64(runtime.NumCPU() + 2) // the value is arbitrary chosen and may change in the future
}
maxWait := cast.ToInt64(os.Getenv("PB_THUMBS_MAX_WAIT"))
if maxWait <= 0 {
maxWait = 60
}
api := fileApi{
thumbGenPending: new(singleflight.Group),
thumbGenSem: semaphore.NewWeighted(maxWorkers),
thumbGenMaxWait: time.Duration(maxWait) * time.Second,
}
sub := rg.Group("/files")
sub.POST("/token", api.fileToken).Bind(RequireAuth())
sub.GET("/{collection}/{recordId}/{filename}", api.download).Bind(collectionPathRateLimit("", "file"))
}
type fileApi struct {
// thumbGenSem is a semaphore to prevent too much concurrent
// requests generating new thumbs at the same time.
thumbGenSem *semaphore.Weighted
// thumbGenPending represents a group of currently pending
// thumb generation processes.
thumbGenPending *singleflight.Group
// thumbGenMaxWait is the maximum waiting time for starting a new
// thumb generation process.
thumbGenMaxWait time.Duration
}
func (api *fileApi) fileToken(e *core.RequestEvent) error {
if e.Auth == nil {
return e.UnauthorizedError("Missing auth context.", nil)
}
token, err := e.Auth.NewFileToken()
if err != nil {
return e.InternalServerError("Failed to generate file token", err)
}
event := new(core.FileTokenRequestEvent)
event.RequestEvent = e
event.Token = token
event.Record = e.Auth
return e.App.OnFileTokenRequest().Trigger(event, func(e *core.FileTokenRequestEvent) error {
return execAfterSuccessTx(true, e.App, func() error {
return e.JSON(http.StatusOK, map[string]string{"token": e.Token})
})
})
}
func (api *fileApi) download(e *core.RequestEvent) error {
collection, err := e.App.FindCachedCollectionByNameOrId(e.Request.PathValue("collection"))
if err != nil {
return e.NotFoundError("", nil)
}
recordId := e.Request.PathValue("recordId")
if recordId == "" {
return e.NotFoundError("", nil)
}
record, err := e.App.FindRecordById(collection, recordId)
if err != nil {
return e.NotFoundError("", err)
}
filename := e.Request.PathValue("filename")
fileField := record.FindFileFieldByFile(filename)
if fileField == nil {
return e.NotFoundError("", nil)
}
// check whether the request is authorized to view the protected file
if fileField.Protected {
originalRequestInfo, err := e.RequestInfo()
if err != nil {
return e.InternalServerError("Failed to load request info", err)
}
token := e.Request.URL.Query().Get("token")
authRecord, _ := e.App.FindAuthRecordByToken(token, core.TokenTypeFile)
// create a shallow copy of the cached request data and adjust it to the current auth record (if any)
requestInfo := *originalRequestInfo
requestInfo.Context = core.RequestInfoContextProtectedFile
requestInfo.Auth = authRecord
if ok, _ := e.App.CanAccessRecord(record, &requestInfo, record.Collection().ViewRule); !ok {
return e.NotFoundError("", errors.New("insufficient permissions to access the file resource"))
}
}
baseFilesPath := record.BaseFilesPath()
// fetch the original view file field related record
if collection.IsView() {
fileRecord, err := e.App.FindRecordByViewFile(collection.Id, fileField.Name, filename)
if err != nil {
return e.NotFoundError("", fmt.Errorf("failed to fetch view file field record: %w", err))
}
baseFilesPath = fileRecord.BaseFilesPath()
}
fsys, err := e.App.NewFilesystem()
if err != nil {
return e.InternalServerError("Filesystem initialization failure.", err)
}
defer fsys.Close()
originalPath := baseFilesPath + "/" + filename
event := new(core.FileDownloadRequestEvent)
event.RequestEvent = e
event.Collection = collection
event.Record = record
event.FileField = fileField
event.ServedPath = originalPath
event.ServedName = filename
// check for valid thumb size param
thumbSize := e.Request.URL.Query().Get("thumb")
if thumbSize != "" && (list.ExistInSlice(thumbSize, defaultThumbSizes) || list.ExistInSlice(thumbSize, fileField.Thumbs)) {
// extract the original file meta attributes and check it existence
oAttrs, oAttrsErr := fsys.Attributes(originalPath)
if oAttrsErr != nil {
return e.NotFoundError("", err)
}
// check if it is an image
if list.ExistInSlice(oAttrs.ContentType, imageContentTypes) {
// add thumb size as file suffix
event.ServedName = thumbSize + "_" + filename
event.ServedPath = baseFilesPath + "/thumbs_" + filename + "/" + event.ServedName
// create a new thumb if it doesn't exist
if exists, _ := fsys.Exists(event.ServedPath); !exists {
if err := api.createThumb(e, fsys, originalPath, event.ServedPath, thumbSize); err != nil {
e.App.Logger().Warn(
"Fallback to original - failed to create thumb "+event.ServedName,
slog.Any("error", err),
slog.String("original", originalPath),
slog.String("thumb", event.ServedPath),
)
// fallback to the original
event.ThumbError = err
event.ServedName = filename
event.ServedPath = originalPath
}
}
}
}
if thumbSize != "" && event.ThumbError == nil && event.ServedPath == originalPath {
event.ThumbError = fmt.Errorf("the thumb size %q or the original file format are not supported", thumbSize)
}
// clickjacking shouldn't be a concern when serving uploaded files,
// so it safe to unset the global X-Frame-Options to allow files embedding
// (note: it is out of the hook to allow users to customize the behavior)
e.Response.Header().Del("X-Frame-Options")
return e.App.OnFileDownloadRequest().Trigger(event, func(e *core.FileDownloadRequestEvent) error {
err = execAfterSuccessTx(true, e.App, func() error {
return fsys.Serve(e.Response, e.Request, e.ServedPath, e.ServedName)
})
if err != nil {
return e.NotFoundError("", err)
}
return nil
})
}
func (api *fileApi) createThumb(
e *core.RequestEvent,
fsys *filesystem.System,
originalPath string,
thumbPath string,
thumbSize string,
) error {
ch := api.thumbGenPending.DoChan(thumbPath, func() (any, error) {
ctx, cancel := context.WithTimeout(e.Request.Context(), api.thumbGenMaxWait)
defer cancel()
if err := api.thumbGenSem.Acquire(ctx, 1); err != nil {
return nil, err
}
defer api.thumbGenSem.Release(1)
return nil, fsys.CreateThumb(originalPath, thumbPath, thumbSize)
})
res := <-ch
api.thumbGenPending.Forget(thumbPath)
return res.Err
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/realtime_test.go | apis/realtime_test.go | package apis_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/subscriptions"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestRealtimeConnect(t *testing.T) {
scenarios := []tests.ApiScenario{
{
Method: http.MethodGet,
URL: "/api/realtime",
Timeout: 100 * time.Millisecond,
ExpectedStatus: 200,
ExpectedContent: []string{
`id:`,
`event:PB_CONNECT`,
`data:{"clientId":`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRealtimeConnectRequest": 1,
"OnRealtimeMessageSend": 1,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
if len(app.SubscriptionsBroker().Clients()) != 0 {
t.Errorf("Expected the subscribers to be removed after connection close, found %d", len(app.SubscriptionsBroker().Clients()))
}
},
},
{
Name: "PB_CONNECT interrupt",
Method: http.MethodGet,
URL: "/api/realtime",
Timeout: 100 * time.Millisecond,
ExpectedStatus: 200,
ExpectedEvents: map[string]int{
"*": 0,
"OnRealtimeConnectRequest": 1,
"OnRealtimeMessageSend": 1,
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnRealtimeMessageSend().BindFunc(func(e *core.RealtimeMessageEvent) error {
if e.Message.Name == "PB_CONNECT" {
return errors.New("PB_CONNECT error")
}
return e.Next()
})
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
if len(app.SubscriptionsBroker().Clients()) != 0 {
t.Errorf("Expected the subscribers to be removed after connection close, found %d", len(app.SubscriptionsBroker().Clients()))
}
},
},
{
Name: "Skipping/ignoring messages",
Method: http.MethodGet,
URL: "/api/realtime",
Timeout: 100 * time.Millisecond,
ExpectedStatus: 200,
ExpectedEvents: map[string]int{
"*": 0,
"OnRealtimeConnectRequest": 1,
"OnRealtimeMessageSend": 1,
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnRealtimeMessageSend().BindFunc(func(e *core.RealtimeMessageEvent) error {
return nil
})
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
if len(app.SubscriptionsBroker().Clients()) != 0 {
t.Errorf("Expected the subscribers to be removed after connection close, found %d", len(app.SubscriptionsBroker().Clients()))
}
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestRealtimeSubscribe(t *testing.T) {
client := subscriptions.NewDefaultClient()
resetClient := func() {
client.Unsubscribe()
client.Set(apis.RealtimeClientAuthKey, nil)
}
validSubscriptionsLimit := make([]string, 1000)
for i := 0; i < len(validSubscriptionsLimit); i++ {
validSubscriptionsLimit[i] = fmt.Sprintf(`"%d"`, i)
}
invalidSubscriptionsLimit := make([]string, 1001)
for i := 0; i < len(invalidSubscriptionsLimit); i++ {
invalidSubscriptionsLimit[i] = fmt.Sprintf(`"%d"`, i)
}
scenarios := []tests.ApiScenario{
{
Name: "missing client",
Method: http.MethodPost,
URL: "/api/realtime",
Body: strings.NewReader(`{"clientId":"missing","subscriptions":["test1", "test2"]}`),
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "empty data",
Method: http.MethodPost,
URL: "/api/realtime",
Body: strings.NewReader(`{}`),
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"clientId":{"code":"validation_required`,
},
NotExpectedContent: []string{
`"subscriptions"`,
},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "existing client with invalid subscriptions limit",
Method: http.MethodPost,
URL: "/api/realtime",
Body: strings.NewReader(`{
"clientId": "` + client.Id() + `",
"subscriptions": [` + strings.Join(invalidSubscriptionsLimit, ",") + `]
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.SubscriptionsBroker().Register(client)
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
resetClient()
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"subscriptions":{"code":"validation_length_too_long"`,
},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "existing client with valid subscriptions limit",
Method: http.MethodPost,
URL: "/api/realtime",
Body: strings.NewReader(`{
"clientId": "` + client.Id() + `",
"subscriptions": [` + strings.Join(validSubscriptionsLimit, ",") + `]
}`),
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnRealtimeSubscribeRequest": 1,
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
client.Subscribe("test0") // should be replaced
app.SubscriptionsBroker().Register(client)
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
if len(client.Subscriptions()) != len(validSubscriptionsLimit) {
t.Errorf("Expected %d subscriptions, got %d", len(validSubscriptionsLimit), len(client.Subscriptions()))
}
if client.HasSubscription("test0") {
t.Errorf("Expected old subscriptions to be replaced")
}
resetClient()
},
},
{
Name: "existing client with invalid topic length",
Method: http.MethodPost,
URL: "/api/realtime",
Body: strings.NewReader(`{
"clientId": "` + client.Id() + `",
"subscriptions": ["abc", "` + strings.Repeat("a", 2501) + `"]
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.SubscriptionsBroker().Register(client)
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
resetClient()
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"subscriptions":{"1":{"code":"validation_length_too_long"`,
},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "existing client with valid topic length",
Method: http.MethodPost,
URL: "/api/realtime",
Body: strings.NewReader(`{
"clientId": "` + client.Id() + `",
"subscriptions": ["abc", "` + strings.Repeat("a", 2500) + `"]
}`),
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnRealtimeSubscribeRequest": 1,
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
client.Subscribe("test0")
app.SubscriptionsBroker().Register(client)
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
if len(client.Subscriptions()) != 2 {
t.Errorf("Expected %d subscriptions, got %d", 2, len(client.Subscriptions()))
}
if client.HasSubscription("test0") {
t.Errorf("Expected old subscriptions to be replaced")
}
resetClient()
},
},
{
Name: "existing client - empty subscriptions",
Method: http.MethodPost,
URL: "/api/realtime",
Body: strings.NewReader(`{"clientId":"` + client.Id() + `","subscriptions":[]}`),
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnRealtimeSubscribeRequest": 1,
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
client.Subscribe("test0")
app.SubscriptionsBroker().Register(client)
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
if len(client.Subscriptions()) != 0 {
t.Errorf("Expected no subscriptions, got %d", len(client.Subscriptions()))
}
resetClient()
},
},
{
Name: "existing client - 2 new subscriptions",
Method: http.MethodPost,
URL: "/api/realtime",
Body: strings.NewReader(`{"clientId":"` + client.Id() + `","subscriptions":["test1", "test2"]}`),
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnRealtimeSubscribeRequest": 1,
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
client.Subscribe("test0")
app.SubscriptionsBroker().Register(client)
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
expectedSubs := []string{"test1", "test2"}
if len(expectedSubs) != len(client.Subscriptions()) {
t.Errorf("Expected subscriptions %v, got %v", expectedSubs, client.Subscriptions())
}
for _, s := range expectedSubs {
if !client.HasSubscription(s) {
t.Errorf("Cannot find %q subscription in %v", s, client.Subscriptions())
}
}
resetClient()
},
},
{
Name: "existing client - guest -> authorized superuser",
Method: http.MethodPost,
URL: "/api/realtime",
Body: strings.NewReader(`{"clientId":"` + client.Id() + `","subscriptions":["test1", "test2"]}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnRealtimeSubscribeRequest": 1,
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.SubscriptionsBroker().Register(client)
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
authRecord, _ := client.Get(apis.RealtimeClientAuthKey).(*core.Record)
if authRecord == nil || !authRecord.IsSuperuser() {
t.Errorf("Expected superuser auth record, got %v", authRecord)
}
resetClient()
},
},
{
Name: "existing client - guest -> authorized regular auth record",
Method: http.MethodPost,
URL: "/api/realtime",
Body: strings.NewReader(`{"clientId":"` + client.Id() + `","subscriptions":["test1", "test2"]}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnRealtimeSubscribeRequest": 1,
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.SubscriptionsBroker().Register(client)
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
authRecord, _ := client.Get(apis.RealtimeClientAuthKey).(*core.Record)
if authRecord == nil {
t.Errorf("Expected regular user auth record, got %v", authRecord)
}
resetClient()
},
},
{
Name: "existing client - same auth",
Method: http.MethodPost,
URL: "/api/realtime",
Body: strings.NewReader(`{"clientId":"` + client.Id() + `","subscriptions":["test1", "test2"]}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnRealtimeSubscribeRequest": 1,
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
// the same user as the auth token
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
client.Set(apis.RealtimeClientAuthKey, user)
app.SubscriptionsBroker().Register(client)
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
authRecord, _ := client.Get(apis.RealtimeClientAuthKey).(*core.Record)
if authRecord == nil {
t.Errorf("Expected auth record model, got nil")
}
resetClient()
},
},
{
Name: "existing client - mismatched auth",
Method: http.MethodPost,
URL: "/api/realtime",
Body: strings.NewReader(`{"clientId":"` + client.Id() + `","subscriptions":["test1", "test2"]}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
user, err := app.FindAuthRecordByEmail("users", "test2@example.com")
if err != nil {
t.Fatal(err)
}
client.Set(apis.RealtimeClientAuthKey, user)
app.SubscriptionsBroker().Register(client)
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
authRecord, _ := client.Get(apis.RealtimeClientAuthKey).(*core.Record)
if authRecord == nil {
t.Errorf("Expected auth record model, got nil")
}
resetClient()
},
},
{
Name: "existing client - unauthorized client",
Method: http.MethodPost,
URL: "/api/realtime",
Body: strings.NewReader(`{"clientId":"` + client.Id() + `","subscriptions":["test1", "test2"]}`),
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
user, err := app.FindAuthRecordByEmail("users", "test2@example.com")
if err != nil {
t.Fatal(err)
}
client.Set(apis.RealtimeClientAuthKey, user)
app.SubscriptionsBroker().Register(client)
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
authRecord, _ := client.Get(apis.RealtimeClientAuthKey).(*core.Record)
if authRecord == nil {
t.Errorf("Expected auth record model, got nil")
}
resetClient()
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestRealtimeAuthRecordDeleteEvent(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
// init realtime handlers
apis.NewRouter(testApp)
authRecord1, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
authRecord2, err := testApp.FindAuthRecordByEmail("users", "test2@example.com")
if err != nil {
t.Fatal(err)
}
client1 := subscriptions.NewDefaultClient()
client1.Set(apis.RealtimeClientAuthKey, authRecord1)
testApp.SubscriptionsBroker().Register(client1)
client2 := subscriptions.NewDefaultClient()
client2.Set(apis.RealtimeClientAuthKey, authRecord1)
testApp.SubscriptionsBroker().Register(client2)
client3 := subscriptions.NewDefaultClient()
client3.Set(apis.RealtimeClientAuthKey, authRecord2)
testApp.SubscriptionsBroker().Register(client3)
// mock delete event
e := new(core.ModelEvent)
e.App = testApp
e.Type = core.ModelEventTypeDelete
e.Context = context.Background()
e.Model = authRecord1
testApp.OnModelAfterDeleteSuccess().Trigger(e)
if total := len(testApp.SubscriptionsBroker().Clients()); total != 3 {
t.Fatalf("Expected %d subscription clients, found %d", 3, total)
}
if auth := client1.Get(apis.RealtimeClientAuthKey); auth != nil {
t.Fatalf("[client1] Expected the auth state to be unset, found %#v", auth)
}
if auth := client2.Get(apis.RealtimeClientAuthKey); auth != nil {
t.Fatalf("[client2] Expected the auth state to be unset, found %#v", auth)
}
if auth := client3.Get(apis.RealtimeClientAuthKey); auth == nil || auth.(*core.Record).Id != authRecord2.Id {
t.Fatalf("[client3] Expected the auth state to be left unchanged, found %#v", auth)
}
}
func TestRealtimeAuthRecordUpdateEvent(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
// init realtime handlers
apis.NewRouter(testApp)
authRecord1, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
client := subscriptions.NewDefaultClient()
client.Set(apis.RealtimeClientAuthKey, authRecord1)
testApp.SubscriptionsBroker().Register(client)
// refetch the authRecord and change its email
authRecord2, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
authRecord2.SetEmail("new@example.com")
// mock update event
e := new(core.ModelEvent)
e.App = testApp
e.Type = core.ModelEventTypeUpdate
e.Context = context.Background()
e.Model = authRecord2
testApp.OnModelAfterUpdateSuccess().Trigger(e)
clientAuthRecord, _ := client.Get(apis.RealtimeClientAuthKey).(*core.Record)
if clientAuthRecord.Email() != authRecord2.Email() {
t.Fatalf("Expected authRecord with email %q, got %q", authRecord2.Email(), clientAuthRecord.Email())
}
}
// Custom auth record model struct
// -------------------------------------------------------------------
var _ core.Model = (*CustomUser)(nil)
type CustomUser struct {
core.BaseModel
Email string `db:"email" json:"email"`
}
func (m *CustomUser) TableName() string {
return "users"
}
func findCustomUserByEmail(app core.App, email string) (*CustomUser, error) {
model := &CustomUser{}
err := app.ModelQuery(model).
AndWhere(dbx.HashExp{"email": email}).
Limit(1).
One(model)
if err != nil {
return nil, err
}
return model, nil
}
func TestRealtimeCustomAuthModelDeleteEvent(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
// init realtime handlers
apis.NewRouter(testApp)
authRecord1, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
authRecord2, err := testApp.FindAuthRecordByEmail("users", "test2@example.com")
if err != nil {
t.Fatal(err)
}
client1 := subscriptions.NewDefaultClient()
client1.Set(apis.RealtimeClientAuthKey, authRecord1)
testApp.SubscriptionsBroker().Register(client1)
client2 := subscriptions.NewDefaultClient()
client2.Set(apis.RealtimeClientAuthKey, authRecord1)
testApp.SubscriptionsBroker().Register(client2)
client3 := subscriptions.NewDefaultClient()
client3.Set(apis.RealtimeClientAuthKey, authRecord2)
testApp.SubscriptionsBroker().Register(client3)
// refetch the authRecord as CustomUser
customUser, err := findCustomUserByEmail(testApp, authRecord1.Email())
if err != nil {
t.Fatal(err)
}
// delete the custom user (should unset the client auth record)
if err := testApp.Delete(customUser); err != nil {
t.Fatal(err)
}
if total := len(testApp.SubscriptionsBroker().Clients()); total != 3 {
t.Fatalf("Expected %d subscription clients, found %d", 3, total)
}
if auth := client1.Get(apis.RealtimeClientAuthKey); auth != nil {
t.Fatalf("[client1] Expected the auth state to be unset, found %#v", auth)
}
if auth := client2.Get(apis.RealtimeClientAuthKey); auth != nil {
t.Fatalf("[client2] Expected the auth state to be unset, found %#v", auth)
}
if auth := client3.Get(apis.RealtimeClientAuthKey); auth == nil || auth.(*core.Record).Id != authRecord2.Id {
t.Fatalf("[client3] Expected the auth state to be left unchanged, found %#v", auth)
}
}
func TestRealtimeCustomAuthModelUpdateEvent(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
// init realtime handlers
apis.NewRouter(testApp)
authRecord, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
client := subscriptions.NewDefaultClient()
client.Set(apis.RealtimeClientAuthKey, authRecord)
testApp.SubscriptionsBroker().Register(client)
// refetch the authRecord as CustomUser
customUser, err := findCustomUserByEmail(testApp, "test@example.com")
if err != nil {
t.Fatal(err)
}
// change its email
customUser.Email = "new@example.com"
if err := testApp.Save(customUser); err != nil {
t.Fatal(err)
}
clientAuthRecord, _ := client.Get(apis.RealtimeClientAuthKey).(*core.Record)
if clientAuthRecord.Email() != customUser.Email {
t.Fatalf("Expected authRecord with email %q, got %q", customUser.Email, clientAuthRecord.Email())
}
}
// -------------------------------------------------------------------
var _ core.Model = (*CustomModelResolve)(nil)
type CustomModelResolve struct {
core.BaseModel
tableName string
Created string `db:"created"`
}
func (m *CustomModelResolve) TableName() string {
return m.tableName
}
func TestRealtimeRecordResolve(t *testing.T) {
t.Parallel()
const testCollectionName = "realtime_test_collection"
testRecordId := core.GenerateDefaultRandomId()
client0 := subscriptions.NewDefaultClient()
client0.Subscribe(testCollectionName + "/*")
client0.Discard()
// ---
client1 := subscriptions.NewDefaultClient()
client1.Subscribe(testCollectionName + "/*")
// ---
client2 := subscriptions.NewDefaultClient()
client2.Subscribe(testCollectionName + "/" + testRecordId)
// ---
client3 := subscriptions.NewDefaultClient()
client3.Subscribe("demo1/*")
scenarios := []struct {
name string
op func(testApp core.App) error
expected map[string][]string // clientId -> [events]
}{
{
"core.Record",
func(testApp core.App) error {
c, err := testApp.FindCollectionByNameOrId(testCollectionName)
if err != nil {
return err
}
r := core.NewRecord(c)
r.Id = testRecordId
// create
err = testApp.Save(r)
if err != nil {
return err
}
// update
err = testApp.Save(r)
if err != nil {
return err
}
// delete
err = testApp.Delete(r)
if err != nil {
return err
}
return nil
},
map[string][]string{
client1.Id(): {"create", "update", "delete"},
client2.Id(): {"create", "update", "delete"},
},
},
{
"core.RecordProxy",
func(testApp core.App) error {
c, err := testApp.FindCollectionByNameOrId(testCollectionName)
if err != nil {
return err
}
r := core.NewRecord(c)
proxy := &struct {
core.BaseRecordProxy
}{}
proxy.SetProxyRecord(r)
proxy.Id = testRecordId
// create
err = testApp.Save(proxy)
if err != nil {
return err
}
// update
err = testApp.Save(proxy)
if err != nil {
return err
}
// delete
err = testApp.Delete(proxy)
if err != nil {
return err
}
return nil
},
map[string][]string{
client1.Id(): {"create", "update", "delete"},
client2.Id(): {"create", "update", "delete"},
},
},
{
"custom model struct",
func(testApp core.App) error {
m := &CustomModelResolve{tableName: testCollectionName}
m.Id = testRecordId
// create
err := testApp.Save(m)
if err != nil {
return err
}
// update
m.Created = "123"
err = testApp.Save(m)
if err != nil {
return err
}
// delete
err = testApp.Delete(m)
if err != nil {
return err
}
return nil
},
map[string][]string{
client1.Id(): {"create", "update", "delete"},
client2.Id(): {"create", "update", "delete"},
},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
// init realtime handlers
apis.NewRouter(testApp)
// create new test collection with public read access
testCollection := core.NewBaseCollection(testCollectionName)
testCollection.Fields.Add(&core.AutodateField{Name: "created", OnCreate: true, OnUpdate: true})
testCollection.ListRule = types.Pointer("")
testCollection.ViewRule = types.Pointer("")
err := testApp.Save(testCollection)
if err != nil {
t.Fatal(err)
}
testApp.SubscriptionsBroker().Register(client0)
testApp.SubscriptionsBroker().Register(client1)
testApp.SubscriptionsBroker().Register(client2)
testApp.SubscriptionsBroker().Register(client3)
var wg sync.WaitGroup
var notifications = map[string][]string{}
var mu sync.Mutex
notify := func(clientId string, eventData []byte) {
data := struct{ Action string }{}
_ = json.Unmarshal(eventData, &data)
mu.Lock()
defer mu.Unlock()
if notifications[clientId] == nil {
notifications[clientId] = []string{}
}
notifications[clientId] = append(notifications[clientId], data.Action)
}
wg.Add(1)
go func() {
defer wg.Done()
timeout := time.After(250 * time.Millisecond)
for {
select {
case e, ok := <-client0.Channel():
if ok {
notify(client0.Id(), e.Data)
}
case e, ok := <-client1.Channel():
if ok {
notify(client1.Id(), e.Data)
}
case e, ok := <-client2.Channel():
if ok {
notify(client2.Id(), e.Data)
}
case e, ok := <-client3.Channel():
if ok {
notify(client3.Id(), e.Data)
}
case <-timeout:
return
}
}
}()
err = s.op(testApp)
if err != nil {
t.Fatal(err)
}
wg.Wait()
if len(s.expected) != len(notifications) {
t.Fatalf("Expected %d notified clients, got %d:\n%v", len(s.expected), len(notifications), notifications)
}
for id, events := range s.expected {
if len(events) != len(notifications[id]) {
t.Fatalf("[%s] Expected %d events, got %d:\n%v\n%v", id, len(events), len(notifications[id]), s.expected, notifications)
}
for _, event := range events {
if !slices.Contains(notifications[id], event) {
t.Fatalf("[%s] Missing expected event %q in %v", id, event, notifications[id])
}
}
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/record_crud_auth_origin_test.go | apis/record_crud_auth_origin_test.go | package apis_test
import (
"net/http"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestRecordCrudAuthOriginList(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "guest",
Method: http.MethodGet,
URL: "/api/collections/" + core.CollectionNameAuthOrigins + "/records",
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalItems":0`,
`"totalPages":0`,
`"items":[]`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
},
},
{
Name: "regular auth with authOrigins",
Method: http.MethodGet,
URL: "/api/collections/" + core.CollectionNameAuthOrigins + "/records",
Headers: map[string]string{
// clients, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalItems":1`,
`"totalPages":1`,
`"id":"9r2j0m74260ur8i"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 1,
},
},
{
Name: "regular auth without authOrigins",
Method: http.MethodGet,
URL: "/api/collections/" + core.CollectionNameAuthOrigins + "/records",
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalItems":0`,
`"totalPages":0`,
`"items":[]`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestRecordCrudAuthOriginView(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "guest",
Method: http.MethodGet,
URL: "/api/collections/" + core.CollectionNameAuthOrigins + "/records/9r2j0m74260ur8i",
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "non-owner",
Method: http.MethodGet,
URL: "/api/collections/" + core.CollectionNameAuthOrigins + "/records/9r2j0m74260ur8i",
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "owner",
Method: http.MethodGet,
URL: "/api/collections/" + core.CollectionNameAuthOrigins + "/records/9r2j0m74260ur8i",
Headers: map[string]string{
// clients, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
},
ExpectedStatus: 200,
ExpectedContent: []string{`"id":"9r2j0m74260ur8i"`},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordViewRequest": 1,
"OnRecordEnrich": 1,
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestRecordCrudAuthOriginDelete(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "guest",
Method: http.MethodDelete,
URL: "/api/collections/" + core.CollectionNameAuthOrigins + "/records/9r2j0m74260ur8i",
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "non-owner",
Method: http.MethodDelete,
URL: "/api/collections/" + core.CollectionNameAuthOrigins + "/records/9r2j0m74260ur8i",
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "owner",
Method: http.MethodDelete,
URL: "/api/collections/" + core.CollectionNameAuthOrigins + "/records/9r2j0m74260ur8i",
Headers: map[string]string{
// clients, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
},
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordDeleteRequest": 1,
"OnModelDelete": 1,
"OnModelDeleteExecute": 1,
"OnModelAfterDeleteSuccess": 1,
"OnRecordDelete": 1,
"OnRecordDeleteExecute": 1,
"OnRecordAfterDeleteSuccess": 1,
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestRecordCrudAuthOriginCreate(t *testing.T) {
t.Parallel()
body := func() *strings.Reader {
return strings.NewReader(`{
"recordRef": "4q1xlclmfloku33",
"collectionRef": "_pb_users_auth_",
"fingerprint": "abc"
}`)
}
scenarios := []tests.ApiScenario{
{
Name: "guest",
Method: http.MethodPost,
URL: "/api/collections/" + core.CollectionNameAuthOrigins + "/records",
Body: body(),
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "owner regular auth",
Method: http.MethodPost,
URL: "/api/collections/" + core.CollectionNameAuthOrigins + "/records",
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
Body: body(),
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "superusers auth",
Method: http.MethodPost,
URL: "/api/collections/" + core.CollectionNameAuthOrigins + "/records",
Headers: map[string]string{
// superusers, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
Body: body(),
ExpectedContent: []string{
`"fingerprint":"abc"`,
},
ExpectedStatus: 200,
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordCreateRequest": 1,
"OnRecordEnrich": 1,
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnModelValidate": 1,
"OnRecordCreate": 1,
"OnRecordCreateExecute": 1,
"OnRecordAfterCreateSuccess": 1,
"OnRecordValidate": 1,
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestRecordCrudAuthOriginUpdate(t *testing.T) {
t.Parallel()
body := func() *strings.Reader {
return strings.NewReader(`{
"fingerprint":"abc"
}`)
}
scenarios := []tests.ApiScenario{
{
Name: "guest",
Method: http.MethodPatch,
URL: "/api/collections/" + core.CollectionNameAuthOrigins + "/records/9r2j0m74260ur8i",
Body: body(),
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "owner regular auth",
Method: http.MethodPatch,
URL: "/api/collections/" + core.CollectionNameAuthOrigins + "/records/9r2j0m74260ur8i",
Headers: map[string]string{
// clients, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
},
Body: body(),
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "superusers auth",
Method: http.MethodPatch,
URL: "/api/collections/" + core.CollectionNameAuthOrigins + "/records/9r2j0m74260ur8i",
Headers: map[string]string{
// superusers, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
Body: body(),
ExpectedContent: []string{
`"id":"9r2j0m74260ur8i"`,
`"fingerprint":"abc"`,
},
ExpectedStatus: 200,
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordUpdateRequest": 1,
"OnRecordEnrich": 1,
"OnModelUpdate": 1,
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnModelValidate": 1,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
"OnRecordValidate": 1,
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/record_auth_with_oauth2_redirect_test.go | apis/record_auth_with_oauth2_redirect_test.go | package apis_test
import (
"context"
"net/http"
"net/url"
"strings"
"testing"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/subscriptions"
)
func TestRecordAuthWithOAuth2Redirect(t *testing.T) {
t.Parallel()
clientStubs := make([]map[string]subscriptions.Client, 0, 10)
for i := 0; i < 10; i++ {
c1 := subscriptions.NewDefaultClient()
c2 := subscriptions.NewDefaultClient()
c2.Subscribe("@oauth2")
c3 := subscriptions.NewDefaultClient()
c3.Subscribe("test1", "@oauth2")
c4 := subscriptions.NewDefaultClient()
c4.Subscribe("test1", "test2")
c5 := subscriptions.NewDefaultClient()
c5.Subscribe("@oauth2")
c5.Discard()
clientStubs = append(clientStubs, map[string]subscriptions.Client{
"c1": c1,
"c2": c2,
"c3": c3,
"c4": c4,
"c5": c5,
})
}
checkFailureRedirect := func(t testing.TB, app *tests.TestApp, res *http.Response) {
loc := res.Header.Get("Location")
if !strings.Contains(loc, "/oauth2-redirect-failure") {
t.Fatalf("Expected failure redirect, got %q", loc)
}
}
checkSuccessRedirect := func(t testing.TB, app *tests.TestApp, res *http.Response) {
loc := res.Header.Get("Location")
if !strings.Contains(loc, "/oauth2-redirect-success") {
t.Fatalf("Expected success redirect, got %q", loc)
}
}
// note: don't exit because it is usually called as part of a separate goroutine
checkClientMessages := func(t testing.TB, clientId string, msg subscriptions.Message, expectedMessages map[string][]string) {
if len(expectedMessages[clientId]) == 0 {
t.Errorf("Unexpected client %q message, got %q:\n%q", clientId, msg.Name, msg.Data)
return
}
if msg.Name != "@oauth2" {
t.Errorf("Expected @oauth2 msg.Name, got %q", msg.Name)
return
}
for _, txt := range expectedMessages[clientId] {
if !strings.Contains(string(msg.Data), txt) {
t.Errorf("Failed to find %q in \n%s", txt, msg.Data)
return
}
}
}
beforeTestFunc := func(
clients map[string]subscriptions.Client,
expectedMessages map[string][]string,
) func(testing.TB, *tests.TestApp, *core.ServeEvent) {
return func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
for _, client := range clients {
app.SubscriptionsBroker().Register(client)
}
ctx, cancelFunc := context.WithTimeout(context.Background(), 100*time.Millisecond)
// add to the app store so that it can be cancelled manually after test completion
app.Store().Set("cancelFunc", cancelFunc)
go func() {
defer cancelFunc()
for {
select {
case msg, ok := <-clients["c1"].Channel():
if ok {
checkClientMessages(t, "c1", msg, expectedMessages)
} else {
t.Errorf("Unexpected c1 closed channel")
}
case msg, ok := <-clients["c2"].Channel():
if ok {
checkClientMessages(t, "c2", msg, expectedMessages)
} else {
t.Errorf("Unexpected c2 closed channel")
}
case msg, ok := <-clients["c3"].Channel():
if ok {
checkClientMessages(t, "c3", msg, expectedMessages)
} else {
t.Errorf("Unexpected c3 closed channel")
}
case msg, ok := <-clients["c4"].Channel():
if ok {
checkClientMessages(t, "c4", msg, expectedMessages)
} else {
t.Errorf("Unexpected c4 closed channel")
}
case _, ok := <-clients["c5"].Channel():
if ok {
t.Errorf("Expected c5 channel to be closed")
}
case <-ctx.Done():
for _, c := range clients {
c.Discard()
}
return
}
}
}()
}
}
scenarios := []tests.ApiScenario{
{
Name: "no state query param",
Method: http.MethodGet,
URL: "/api/oauth2-redirect?code=123",
BeforeTestFunc: beforeTestFunc(clientStubs[0], nil),
ExpectedStatus: http.StatusTemporaryRedirect,
ExpectedEvents: map[string]int{"*": 0},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
app.Store().Get("cancelFunc").(context.CancelFunc)()
checkFailureRedirect(t, app, res)
},
},
{
Name: "invalid or missing client",
Method: http.MethodGet,
URL: "/api/oauth2-redirect?code=123&state=missing",
BeforeTestFunc: beforeTestFunc(clientStubs[1], nil),
ExpectedStatus: http.StatusTemporaryRedirect,
ExpectedEvents: map[string]int{"*": 0},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
app.Store().Get("cancelFunc").(context.CancelFunc)()
checkFailureRedirect(t, app, res)
},
},
{
Name: "no code query param",
Method: http.MethodGet,
URL: "/api/oauth2-redirect?state=" + clientStubs[2]["c3"].Id(),
BeforeTestFunc: beforeTestFunc(clientStubs[2], map[string][]string{
"c3": {`"state":"` + clientStubs[2]["c3"].Id(), `"code":""`},
}),
ExpectedStatus: http.StatusTemporaryRedirect,
ExpectedEvents: map[string]int{"*": 0},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
app.Store().Get("cancelFunc").(context.CancelFunc)()
checkFailureRedirect(t, app, res)
if clientStubs[2]["c3"].HasSubscription("@oauth2") {
t.Fatalf("Expected oauth2 subscription to be removed")
}
},
},
{
Name: "error query param",
Method: http.MethodGet,
URL: "/api/oauth2-redirect?error=example&code=123&state=" + clientStubs[3]["c3"].Id(),
BeforeTestFunc: beforeTestFunc(clientStubs[3], map[string][]string{
"c3": {`"state":"` + clientStubs[3]["c3"].Id(), `"code":"123"`, `"error":"example"`},
}),
ExpectedStatus: http.StatusTemporaryRedirect,
ExpectedEvents: map[string]int{"*": 0},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
app.Store().Get("cancelFunc").(context.CancelFunc)()
checkFailureRedirect(t, app, res)
if clientStubs[3]["c3"].HasSubscription("@oauth2") {
t.Fatalf("Expected oauth2 subscription to be removed")
}
},
},
{
Name: "discarded client with @oauth2 subscription",
Method: http.MethodGet,
URL: "/api/oauth2-redirect?code=123&state=" + clientStubs[4]["c5"].Id(),
BeforeTestFunc: beforeTestFunc(clientStubs[4], nil),
ExpectedStatus: http.StatusTemporaryRedirect,
ExpectedEvents: map[string]int{"*": 0},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
app.Store().Get("cancelFunc").(context.CancelFunc)()
checkFailureRedirect(t, app, res)
},
},
{
Name: "client without @oauth2 subscription",
Method: http.MethodGet,
URL: "/api/oauth2-redirect?code=123&state=" + clientStubs[4]["c4"].Id(),
BeforeTestFunc: beforeTestFunc(clientStubs[5], nil),
ExpectedStatus: http.StatusTemporaryRedirect,
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
app.Store().Get("cancelFunc").(context.CancelFunc)()
checkFailureRedirect(t, app, res)
},
},
{
Name: "client with @oauth2 subscription",
Method: http.MethodGet,
URL: "/api/oauth2-redirect?code=123&state=" + clientStubs[6]["c3"].Id(),
BeforeTestFunc: beforeTestFunc(clientStubs[6], map[string][]string{
"c3": {`"state":"` + clientStubs[6]["c3"].Id(), `"code":"123"`},
}),
ExpectedStatus: http.StatusTemporaryRedirect,
ExpectedEvents: map[string]int{"*": 0},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
app.Store().Get("cancelFunc").(context.CancelFunc)()
checkSuccessRedirect(t, app, res)
if clientStubs[6]["c3"].HasSubscription("@oauth2") {
t.Fatalf("Expected oauth2 subscription to be removed")
}
},
},
{
Name: "(POST) client with @oauth2 subscription",
Method: http.MethodPost,
URL: "/api/oauth2-redirect",
Body: strings.NewReader("code=123&state=" + clientStubs[7]["c3"].Id()),
Headers: map[string]string{
"content-type": "application/x-www-form-urlencoded",
},
BeforeTestFunc: beforeTestFunc(clientStubs[7], map[string][]string{
"c3": {`"state":"` + clientStubs[7]["c3"].Id(), `"code":"123"`},
}),
ExpectedStatus: http.StatusSeeOther,
ExpectedEvents: map[string]int{"*": 0},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
app.Store().Get("cancelFunc").(context.CancelFunc)()
checkSuccessRedirect(t, app, res)
if clientStubs[7]["c3"].HasSubscription("@oauth2") {
t.Fatalf("Expected oauth2 subscription to be removed")
}
},
},
{
Name: "(POST) Apple user's name json (nameKey error)",
Method: http.MethodPost,
URL: "/api/oauth2-redirect",
Body: strings.NewReader(url.Values{
"code": []string{strings.Repeat("a", 986)},
"state": []string{clientStubs[8]["c3"].Id()},
"user": []string{
`{"name":{"firstName":"aaa","lastName":"` + strings.Repeat("b", 200) + `"}}`,
},
}.Encode()),
Headers: map[string]string{
"content-type": "application/x-www-form-urlencoded",
},
BeforeTestFunc: beforeTestFunc(clientStubs[8], map[string][]string{
"c3": {`"state":"` + clientStubs[8]["c3"].Id(), `"code":"` + strings.Repeat("a", 986) + `"`},
}),
ExpectedStatus: http.StatusSeeOther,
ExpectedEvents: map[string]int{"*": 0},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
app.Store().Get("cancelFunc").(context.CancelFunc)()
checkSuccessRedirect(t, app, res)
if clientStubs[8]["c3"].HasSubscription("@oauth2") {
t.Fatalf("Expected oauth2 subscription to be removed")
}
if storedName := app.Store().Get("@redirect_name_" + strings.Repeat("a", 986)); storedName != nil {
t.Fatalf("Didn't expect stored name, got %q", storedName)
}
},
},
{
Name: "(POST) Apple user's name json",
Method: http.MethodPost,
URL: "/api/oauth2-redirect",
Body: strings.NewReader(url.Values{
"code": []string{strings.Repeat("a", 985)},
"state": []string{clientStubs[9]["c3"].Id()},
"user": []string{
`{"name":{"firstName":"aaa","lastName":"` + strings.Repeat("b", 200) + `"}}`,
},
}.Encode()),
Headers: map[string]string{
"content-type": "application/x-www-form-urlencoded",
},
BeforeTestFunc: beforeTestFunc(clientStubs[9], map[string][]string{
"c3": {`"state":"` + clientStubs[9]["c3"].Id(), `"code":"` + strings.Repeat("a", 985) + `"`},
}),
ExpectedStatus: http.StatusSeeOther,
ExpectedEvents: map[string]int{"*": 0},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
app.Store().Get("cancelFunc").(context.CancelFunc)()
checkSuccessRedirect(t, app, res)
if clientStubs[9]["c3"].HasSubscription("@oauth2") {
t.Fatalf("Expected oauth2 subscription to be removed")
}
storedName, _ := app.Store().Get("@redirect_name_" + strings.Repeat("a", 985)).(string)
expectedName := "aaa " + strings.Repeat("b", 146)
if storedName != expectedName {
t.Fatalf("Expected stored name\n%q\ngot\n%q", expectedName, storedName)
}
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/record_auth_methods_test.go | apis/record_auth_methods_test.go | package apis_test
import (
"net/http"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestRecordAuthMethodsList(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "missing collection",
Method: http.MethodGet,
URL: "/api/collections/missing/auth-methods",
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "non auth collection",
Method: http.MethodGet,
URL: "/api/collections/demo1/auth-methods",
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "auth collection with none auth methods allowed",
Method: http.MethodGet,
URL: "/api/collections/nologin/auth-methods",
ExpectedStatus: 200,
ExpectedContent: []string{
`"password":{"identityFields":[],"enabled":false}`,
`"oauth2":{"providers":[],"enabled":false}`,
`"mfa":{"enabled":false,"duration":0}`,
`"otp":{"enabled":false,"duration":0}`,
},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "auth collection with all auth methods allowed",
Method: http.MethodGet,
URL: "/api/collections/users/auth-methods",
ExpectedStatus: 200,
ExpectedContent: []string{
`"password":{"identityFields":["email","username"],"enabled":true}`,
`"mfa":{"enabled":true,"duration":1800}`,
`"otp":{"enabled":true,"duration":300}`,
`"oauth2":{`,
`"providers":[{`,
`"name":"google"`,
`"name":"gitlab"`,
`"state":`,
`"displayName":`,
`"codeVerifier":`,
`"codeChallenge":`,
`"codeChallengeMethod":`,
`"authURL":`,
`redirect_uri="`, // ensures that the redirect_uri is the last url param
},
ExpectedEvents: map[string]int{"*": 0},
},
// rate limit checks
// -----------------------------------------------------------
{
Name: "RateLimit rule - nologin:listAuthMethods",
Method: http.MethodGet,
URL: "/api/collections/nologin/auth-methods",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.Settings().RateLimits.Enabled = true
app.Settings().RateLimits.Rules = []core.RateLimitRule{
{MaxRequests: 100, Label: "abc"},
{MaxRequests: 100, Label: "*:listAuthMethods"},
{MaxRequests: 0, Label: "nologin:listAuthMethods"},
}
},
ExpectedStatus: 429,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "RateLimit rule - *:listAuthMethods",
Method: http.MethodGet,
URL: "/api/collections/nologin/auth-methods",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.Settings().RateLimits.Enabled = true
app.Settings().RateLimits.Rules = []core.RateLimitRule{
{MaxRequests: 100, Label: "abc"},
{MaxRequests: 0, Label: "*:listAuthMethods"},
}
},
ExpectedStatus: 429,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/record_crud_test.go | apis/record_crud_test.go | package apis_test
import (
"bytes"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/router"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestRecordCrudList(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "missing collection",
Method: http.MethodGet,
URL: "/api/collections/missing/records",
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "unauthenticated trying to access nil rule collection (aka. need superuser auth)",
Method: http.MethodGet,
URL: "/api/collections/demo1/records",
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authenticated record trying to access nil rule collection (aka. need superuser auth)",
Method: http.MethodGet,
URL: "/api/collections/demo1/records",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "public collection but with superuser only filter param (aka. @collection, @request, etc.)",
Method: http.MethodGet,
URL: "/api/collections/demo2/records?filter=%40collection.demo2.title='test1'",
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "public collection but with superuser only sort param (aka. @collection, @request, etc.)",
Method: http.MethodGet,
URL: "/api/collections/demo2/records?sort=@request.auth.title",
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "public collection but with ENCODED superuser only filter/sort (aka. @collection)",
Method: http.MethodGet,
URL: "/api/collections/demo2/records?filter=%40collection.demo2.title%3D%27test1%27",
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "public collection",
Method: http.MethodGet,
URL: "/api/collections/demo2/records",
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":3`,
`"items":[{`,
`"id":"0yxhwia2amd8gec"`,
`"id":"achvryl401bhse3"`,
`"id":"llvuca81nly1qls"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 3,
},
},
{
Name: "public collection (using the collection id)",
Method: http.MethodGet,
URL: "/api/collections/sz5l5z67tg7gku0/records",
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":3`,
`"items":[{`,
`"id":"0yxhwia2amd8gec"`,
`"id":"achvryl401bhse3"`,
`"id":"llvuca81nly1qls"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 3,
},
},
{
Name: "authorized as superuser trying to access nil rule collection (aka. need superuser auth)",
Method: http.MethodGet,
URL: "/api/collections/demo1/records",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":3`,
`"items":[{`,
`"id":"al1h9ijdeojtsjy"`,
`"id":"84nmscqy84lsi1t"`,
`"id":"imy661ixudk5izi"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 3,
},
},
{
Name: "valid query params",
Method: http.MethodGet,
URL: "/api/collections/demo1/records?filter=text~'test'&sort=-bool",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalItems":2`,
`"items":[{`,
`"id":"al1h9ijdeojtsjy"`,
`"id":"84nmscqy84lsi1t"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 2,
},
},
{
Name: "invalid filter",
Method: http.MethodGet,
URL: "/api/collections/demo1/records?filter=invalid~'test'",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "expand relations",
Method: http.MethodGet,
URL: "/api/collections/demo1/records?expand=rel_one,rel_many.rel,missing&perPage=2&sort=created",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":2`,
`"totalPages":2`,
`"totalItems":3`,
`"items":[{`,
`"collectionName":"demo1"`,
`"id":"84nmscqy84lsi1t"`,
`"id":"al1h9ijdeojtsjy"`,
`"expand":{`,
`"rel_one":""`,
`"rel_one":{"`,
`"rel_many":[{`,
`"rel":{`,
`"rel":""`,
`"json":[1,2,3]`,
`"select_many":["optionB","optionC"]`,
`"select_many":["optionB"]`,
// subrel items
`"id":"0yxhwia2amd8gec"`,
`"id":"llvuca81nly1qls"`,
// email visibility should be ignored for superusers even in expanded rels
`"email":"test@example.com"`,
`"email":"test2@example.com"`,
`"email":"test3@example.com"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 8,
},
},
{
Name: "authenticated record model that DOESN'T match the collection list rule",
Method: http.MethodGet,
URL: "/api/collections/demo3/records",
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalItems":0`,
`"items":[]`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
},
},
{
Name: "authenticated record that matches the collection list rule",
Method: http.MethodGet,
URL: "/api/collections/demo3/records",
Headers: map[string]string{
// clients, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":4`,
`"items":[{`,
`"id":"1tmknxy2868d869"`,
`"id":"lcl9d87w22ml6jy"`,
`"id":"7nwo8tuiatetxdm"`,
`"id":"mk5fmymtx4wsprk"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 4,
},
},
{
Name: "authenticated regular record that matches the collection list rule with hidden field",
Method: http.MethodGet,
URL: "/api/collections/demo3/records",
Headers: map[string]string{
// clients, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
col, err := app.FindCollectionByNameOrId("demo3")
if err != nil {
t.Fatal(err)
}
// mock hidden field
col.Fields.GetByName("title").SetHidden(true)
col.ListRule = types.Pointer("title ~ 'test'")
if err = app.Save(col); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":4`,
`"items":[{`,
`"id":"1tmknxy2868d869"`,
`"id":"lcl9d87w22ml6jy"`,
`"id":"7nwo8tuiatetxdm"`,
`"id":"mk5fmymtx4wsprk"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 4,
},
},
{
Name: "authenticated regular record filtering with a hidden field",
Method: http.MethodGet,
URL: "/api/collections/demo3/records?filter=title~'test'",
Headers: map[string]string{
// clients, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
col, err := app.FindCollectionByNameOrId("demo3")
if err != nil {
t.Fatal(err)
}
// mock hidden field
col.Fields.GetByName("title").SetHidden(true)
if err = app.Save(col); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "superuser filtering with a hidden field",
Method: http.MethodGet,
URL: "/api/collections/demo3/records?filter=title~'test'",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
col, err := app.FindCollectionByNameOrId("demo3")
if err != nil {
t.Fatal(err)
}
// mock hidden field
col.Fields.GetByName("title").SetHidden(true)
if err = app.Save(col); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":4`,
`"items":[{`,
`"id":"1tmknxy2868d869"`,
`"id":"lcl9d87w22ml6jy"`,
`"id":"7nwo8tuiatetxdm"`,
`"id":"mk5fmymtx4wsprk"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 4,
},
},
{
Name: ":rule modifer",
Method: http.MethodGet,
URL: "/api/collections/demo5/records",
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":1`,
`"items":[{`,
`"id":"qjeql998mtp1azp"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 1,
},
},
{
Name: "multi-match - at least one of (guest - non-satisfied relation filter API rule)",
Method: http.MethodGet,
URL: "/api/collections/demo4/records?filter=" + url.QueryEscape("rel_many_no_cascade_required.files:length?=2"),
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":0`,
`"totalItems":0`,
`"items":[]`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 0,
},
},
{
Name: "multi-match - at least one of (clients)",
Method: http.MethodGet,
URL: "/api/collections/demo4/records?filter=" + url.QueryEscape("rel_many_no_cascade_required.files:length?=2"),
Headers: map[string]string{
// clients, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":1`,
`"items":[{`,
`"id":"qzaqccwrmva4o1n"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 1,
},
},
{
Name: "multi-match - all (clients)",
Method: http.MethodGet,
URL: "/api/collections/demo4/records?filter=" + url.QueryEscape("rel_many_no_cascade_required.files:length=2"),
Headers: map[string]string{
// clients, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":0`,
`"totalItems":0`,
`"items":[]`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
},
},
{
Name: "OnRecordsListRequest tx body write check",
Method: http.MethodGet,
URL: "/api/collections/demo4/records",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnRecordsListRequest().BindFunc(func(e *core.RecordsListRequestEvent) error {
original := e.App
return e.App.RunInTransaction(func(txApp core.App) error {
e.App = txApp
defer func() { e.App = original }()
if err := e.Next(); err != nil {
return err
}
return e.BadRequestError("TX_ERROR", nil)
})
})
},
ExpectedStatus: 400,
ExpectedEvents: map[string]int{"OnRecordsListRequest": 1},
ExpectedContent: []string{"TX_ERROR"},
},
// auth collection
// -----------------------------------------------------------
{
Name: "check email visibility as guest",
Method: http.MethodGet,
URL: "/api/collections/nologin/records",
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":3`,
`"items":[{`,
`"id":"phhq3wr65cap535"`,
`"id":"dc49k6jgejn40h3"`,
`"id":"oos036e9xvqeexy"`,
`"email":"test2@example.com"`,
`"emailVisibility":true`,
`"emailVisibility":false`,
},
NotExpectedContent: []string{
`"tokenKey"`,
`"password"`,
`"email":"test@example.com"`,
`"email":"test3@example.com"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 3,
},
},
{
Name: "check email visibility as any authenticated record",
Method: http.MethodGet,
URL: "/api/collections/nologin/records",
Headers: map[string]string{
// clients, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":3`,
`"items":[{`,
`"id":"phhq3wr65cap535"`,
`"id":"dc49k6jgejn40h3"`,
`"id":"oos036e9xvqeexy"`,
`"email":"test2@example.com"`,
`"emailVisibility":true`,
`"emailVisibility":false`,
},
NotExpectedContent: []string{
`"tokenKey":"`,
`"password":""`,
`"email":"test@example.com"`,
`"email":"test3@example.com"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 3,
},
},
{
Name: "check email visibility as manage auth record",
Method: http.MethodGet,
URL: "/api/collections/nologin/records",
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":3`,
`"items":[{`,
`"id":"phhq3wr65cap535"`,
`"id":"dc49k6jgejn40h3"`,
`"id":"oos036e9xvqeexy"`,
`"email":"test@example.com"`,
`"email":"test2@example.com"`,
`"email":"test3@example.com"`,
`"emailVisibility":true`,
`"emailVisibility":false`,
},
NotExpectedContent: []string{
`"tokenKey"`,
`"password"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 3,
},
},
{
Name: "check email visibility as superuser",
Method: http.MethodGet,
URL: "/api/collections/nologin/records",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":3`,
`"items":[{`,
`"id":"phhq3wr65cap535"`,
`"id":"dc49k6jgejn40h3"`,
`"id":"oos036e9xvqeexy"`,
`"email":"test@example.com"`,
`"email":"test2@example.com"`,
`"email":"test3@example.com"`,
`"emailVisibility":true`,
`"emailVisibility":false`,
},
NotExpectedContent: []string{
`"tokenKey"`,
`"password"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 3,
},
},
{
Name: "check self email visibility resolver",
Method: http.MethodGet,
URL: "/api/collections/nologin/records",
Headers: map[string]string{
// nologin, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImRjNDlrNmpnZWpuNDBoMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoia3B2NzA5c2sybHFicWs4IiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.fdUPFLDx5b6RM_XFqnqsyiyNieyKA2HIIkRmUh9kIoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":3`,
`"items":[{`,
`"id":"phhq3wr65cap535"`,
`"id":"dc49k6jgejn40h3"`,
`"id":"oos036e9xvqeexy"`,
`"email":"test2@example.com"`,
`"email":"test@example.com"`,
`"emailVisibility":true`,
`"emailVisibility":false`,
},
NotExpectedContent: []string{
`"tokenKey"`,
`"password"`,
`"email":"test3@example.com"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 3,
},
},
// view collection
// -----------------------------------------------------------
{
Name: "public view records",
Method: http.MethodGet,
URL: "/api/collections/view2/records?filter=state=false",
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":2`,
`"items":[{`,
`"id":"al1h9ijdeojtsjy"`,
`"id":"imy661ixudk5izi"`,
},
NotExpectedContent: []string{
`"created"`,
`"updated"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 2,
},
},
{
Name: "guest that doesn't match the view collection list rule",
Method: http.MethodGet,
URL: "/api/collections/view1/records",
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":0`,
`"totalItems":0`,
`"items":[]`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
},
},
{
Name: "authenticated record that matches the view collection list rule",
Method: http.MethodGet,
URL: "/api/collections/view1/records",
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":1`,
`"items":[{`,
`"id":"84nmscqy84lsi1t"`,
`"bool":true`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 1,
},
},
{
Name: "view collection with numeric ids",
Method: http.MethodGet,
URL: "/api/collections/numeric_id_view/records",
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":2`,
`"items":[{`,
`"id":"1"`,
`"id":"2"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 2,
},
},
// rate limit checks
// -----------------------------------------------------------
{
Name: "RateLimit rule - view2:list",
Method: http.MethodGet,
URL: "/api/collections/view2/records",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.Settings().RateLimits.Enabled = true
app.Settings().RateLimits.Rules = []core.RateLimitRule{
{MaxRequests: 100, Label: "abc"},
{MaxRequests: 100, Label: "*:list"},
{MaxRequests: 0, Label: "view2:list"},
}
},
ExpectedStatus: 429,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "RateLimit rule - *:list",
Method: http.MethodGet,
URL: "/api/collections/view2/records",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.Settings().RateLimits.Enabled = true
app.Settings().RateLimits.Rules = []core.RateLimitRule{
{MaxRequests: 100, Label: "abc"},
{MaxRequests: 0, Label: "*:list"},
}
},
ExpectedStatus: 429,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestRecordCrudView(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "missing collection",
Method: http.MethodGet,
URL: "/api/collections/missing/records/0yxhwia2amd8gec",
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "missing record",
Method: http.MethodGet,
URL: "/api/collections/demo2/records/missing",
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "unauthenticated trying to access nil rule collection (aka. need superuser auth)",
Method: http.MethodGet,
URL: "/api/collections/demo1/records/imy661ixudk5izi",
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authenticated record trying to access nil rule collection (aka. need superuser auth)",
Method: http.MethodGet,
URL: "/api/collections/demo1/records/imy661ixudk5izi",
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authenticated record that doesn't match the collection view rule",
Method: http.MethodGet,
URL: "/api/collections/users/records/bgs820n361vj1qd",
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "public collection view",
Method: http.MethodGet,
URL: "/api/collections/demo2/records/0yxhwia2amd8gec",
ExpectedStatus: 200,
ExpectedContent: []string{
`"id":"0yxhwia2amd8gec"`,
`"collectionName":"demo2"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordViewRequest": 1,
"OnRecordEnrich": 1,
},
},
{
Name: "public collection view (using the collection id)",
Method: http.MethodGet,
URL: "/api/collections/sz5l5z67tg7gku0/records/0yxhwia2amd8gec",
ExpectedStatus: 200,
ExpectedContent: []string{
`"id":"0yxhwia2amd8gec"`,
`"collectionName":"demo2"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordViewRequest": 1,
"OnRecordEnrich": 1,
},
},
{
Name: "authorized as superuser trying to access nil rule collection view (aka. need superuser auth)",
Method: http.MethodGet,
URL: "/api/collections/demo1/records/imy661ixudk5izi",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"id":"imy661ixudk5izi"`,
`"collectionName":"demo1"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordViewRequest": 1,
"OnRecordEnrich": 1,
},
},
{
Name: "authenticated record that does match the collection view rule",
Method: http.MethodGet,
URL: "/api/collections/users/records/4q1xlclmfloku33",
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"id":"4q1xlclmfloku33"`,
`"collectionName":"users"`,
// owners can always view their email
`"emailVisibility":false`,
`"email":"test@example.com"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordViewRequest": 1,
"OnRecordEnrich": 1,
},
},
{
Name: "expand relations",
Method: http.MethodGet,
URL: "/api/collections/demo1/records/al1h9ijdeojtsjy?expand=rel_one,rel_many.rel,missing&perPage=2&sort=created",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"id":"al1h9ijdeojtsjy"`,
`"collectionName":"demo1"`,
`"rel_many":[{`,
`"rel_one":{`,
`"collectionName":"users"`,
`"id":"bgs820n361vj1qd"`,
`"expand":{"rel":{`,
`"id":"0yxhwia2amd8gec"`,
`"collectionName":"demo2"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordViewRequest": 1,
"OnRecordEnrich": 7,
},
},
{
Name: "OnRecordViewRequest tx body write check",
Method: http.MethodGet,
URL: "/api/collections/demo1/records/al1h9ijdeojtsjy",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnRecordViewRequest().BindFunc(func(e *core.RecordRequestEvent) error {
original := e.App
return e.App.RunInTransaction(func(txApp core.App) error {
e.App = txApp
defer func() { e.App = original }()
if err := e.Next(); err != nil {
return err
}
return e.BadRequestError("TX_ERROR", nil)
})
})
},
ExpectedStatus: 400,
ExpectedEvents: map[string]int{"OnRecordViewRequest": 1},
ExpectedContent: []string{"TX_ERROR"},
},
// auth collection
// -----------------------------------------------------------
{
Name: "check email visibility as guest",
Method: http.MethodGet,
URL: "/api/collections/nologin/records/oos036e9xvqeexy",
ExpectedStatus: 200,
ExpectedContent: []string{
`"id":"oos036e9xvqeexy"`,
`"emailVisibility":false`,
`"verified":true`,
},
NotExpectedContent: []string{
`"tokenKey"`,
`"password"`,
`"email":"test3@example.com"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordViewRequest": 1,
"OnRecordEnrich": 1,
},
},
{
Name: "check email visibility as any authenticated record",
Method: http.MethodGet,
URL: "/api/collections/nologin/records/oos036e9xvqeexy",
Headers: map[string]string{
// clients, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"id":"oos036e9xvqeexy"`,
`"emailVisibility":false`,
`"verified":true`,
},
NotExpectedContent: []string{
`"tokenKey"`,
`"password"`,
`"email":"test3@example.com"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordViewRequest": 1,
"OnRecordEnrich": 1,
},
},
{
Name: "check email visibility as manage auth record",
Method: http.MethodGet,
URL: "/api/collections/nologin/records/oos036e9xvqeexy",
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 200,
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | true |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/cron.go | apis/cron.go | package apis
import (
"net/http"
"slices"
"strings"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/cron"
"github.com/pocketbase/pocketbase/tools/router"
"github.com/pocketbase/pocketbase/tools/routine"
)
// bindCronApi registers the crons api endpoint.
func bindCronApi(app core.App, rg *router.RouterGroup[*core.RequestEvent]) {
subGroup := rg.Group("/crons").Bind(RequireSuperuserAuth())
subGroup.GET("", cronsList)
subGroup.POST("/{id}", cronRun)
}
func cronsList(e *core.RequestEvent) error {
jobs := e.App.Cron().Jobs()
slices.SortStableFunc(jobs, func(a, b *cron.Job) int {
if strings.HasPrefix(a.Id(), "__pb") {
return 1
}
if strings.HasPrefix(b.Id(), "__pb") {
return -1
}
return strings.Compare(a.Id(), b.Id())
})
return e.JSON(http.StatusOK, jobs)
}
func cronRun(e *core.RequestEvent) error {
cronId := e.Request.PathValue("id")
var foundJob *cron.Job
jobs := e.App.Cron().Jobs()
for _, j := range jobs {
if j.Id() == cronId {
foundJob = j
break
}
}
if foundJob == nil {
return e.NotFoundError("Missing or invalid cron job", nil)
}
routine.FireAndForget(func() {
foundJob.Run()
})
return e.NoContent(http.StatusNoContent)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/record_auth_otp_request_test.go | apis/record_auth_otp_request_test.go | package apis_test
import (
"net/http"
"strconv"
"strings"
"testing"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestRecordRequestOTP(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "not an auth collection",
Method: http.MethodPost,
URL: "/api/collections/demo1/request-otp",
Body: strings.NewReader(`{"email":"test@example.com"}`),
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "auth collection with disabled otp",
Method: http.MethodPost,
URL: "/api/collections/users/request-otp",
Body: strings.NewReader(`{"email":"test@example.com"}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
usersCol, err := app.FindCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
usersCol.OTP.Enabled = false
if err := app.Save(usersCol); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "empty body",
Method: http.MethodPost,
URL: "/api/collections/users/request-otp",
Body: strings.NewReader(``),
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{"email":{"code":"validation_required","message":"Cannot be blank."}}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "invalid body",
Method: http.MethodPost,
URL: "/api/collections/users/request-otp",
Body: strings.NewReader(`{"email`),
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "invalid request data",
Method: http.MethodPost,
URL: "/api/collections/users/request-otp",
Body: strings.NewReader(`{"email":"invalid"}`),
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"email":{"code":"validation_is_email`,
},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "missing auth record",
Method: http.MethodPost,
URL: "/api/collections/users/request-otp",
Body: strings.NewReader(`{"email":"missing@example.com"}`),
Delay: 100 * time.Millisecond,
ExpectedStatus: 200,
ExpectedContent: []string{
`"otpId":"`, // some fake random generated string
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordRequestOTPRequest": 1,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
if app.TestMailer.TotalSend() != 0 {
t.Fatalf("Expected zero emails, got %d", app.TestMailer.TotalSend())
}
},
},
{
Name: "existing auth record (with < 9 non-expired)",
Method: http.MethodPost,
URL: "/api/collections/users/request-otp",
Body: strings.NewReader(`{"email":"test@example.com"}`),
Delay: 100 * time.Millisecond,
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
// insert 8 non-expired and 2 expired
for i := 0; i < 10; i++ {
otp := core.NewOTP(app)
otp.Id = "otp_" + strconv.Itoa(i)
otp.SetCollectionRef(user.Collection().Id)
otp.SetRecordRef(user.Id)
otp.SetPassword("123456")
if i >= 8 {
expiredDate := types.NowDateTime().AddDate(-3, 0, 0)
otp.SetRaw("created", expiredDate)
otp.SetRaw("updated", expiredDate)
}
if err := app.SaveNoValidate(otp); err != nil {
t.Fatal(err)
}
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"otpId":"`,
},
NotExpectedContent: []string{
`"otpId":"otp_`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordRequestOTPRequest": 1,
"OnMailerSend": 1,
"OnMailerRecordOTPSend": 1,
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnModelValidate": 2, // + 1 for the OTP update after the email send
"OnRecordCreate": 1,
"OnRecordCreateExecute": 1,
"OnRecordAfterCreateSuccess": 1,
"OnRecordValidate": 2,
// OTP update
"OnModelUpdate": 1,
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
if app.TestMailer.TotalSend() != 1 {
t.Fatalf("Expected 1 email, got %d", app.TestMailer.TotalSend())
}
// ensure that sentTo is set
otps, err := app.FindRecordsByFilter(core.CollectionNameOTPs, "sentTo='test@example.com'", "", 0, 0)
if err != nil || len(otps) != 1 {
t.Fatalf("Expected to find 1 OTP with sentTo %q, found %d", "test@example.com", len(otps))
}
},
},
{
Name: "existing auth record with intercepted email (with < 9 non-expired)",
Method: http.MethodPost,
URL: "/api/collections/users/request-otp",
Body: strings.NewReader(`{"email":"test@example.com"}`),
Delay: 100 * time.Millisecond,
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
// prevent email sent
app.OnMailerRecordOTPSend("users").BindFunc(func(e *core.MailerRecordEvent) error {
return nil
})
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"otpId":"`,
},
NotExpectedContent: []string{
`"otpId":"otp_`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordRequestOTPRequest": 1,
"OnMailerRecordOTPSend": 1,
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnModelValidate": 1,
"OnRecordCreate": 1,
"OnRecordCreateExecute": 1,
"OnRecordAfterCreateSuccess": 1,
"OnRecordValidate": 1,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
if app.TestMailer.TotalSend() != 0 {
t.Fatalf("Expected 0 emails, got %d", app.TestMailer.TotalSend())
}
// ensure that there is no OTP with user email as sentTo
otps, err := app.FindRecordsByFilter(core.CollectionNameOTPs, "sentTo='test@example.com'", "", 0, 0)
if err != nil || len(otps) != 0 {
t.Fatalf("Expected to find 0 OTPs with sentTo %q, found %d", "test@example.com", len(otps))
}
},
},
{
Name: "existing auth record (with > 9 non-expired)",
Method: http.MethodPost,
URL: "/api/collections/users/request-otp",
Body: strings.NewReader(`{"email":"test@example.com"}`),
Delay: 100 * time.Millisecond,
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
// insert 10 non-expired
for i := 0; i < 10; i++ {
otp := core.NewOTP(app)
otp.Id = "otp_" + strconv.Itoa(i)
otp.SetCollectionRef(user.Collection().Id)
otp.SetRecordRef(user.Id)
otp.SetPassword("123456")
if err := app.SaveNoValidate(otp); err != nil {
t.Fatal(err)
}
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"otpId":"otp_9"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordRequestOTPRequest": 1,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
if app.TestMailer.TotalSend() != 0 {
t.Fatalf("Expected 0 sent emails, got %d", app.TestMailer.TotalSend())
}
},
},
{
Name: "OnRecordRequestOTPRequest tx body write check",
Method: http.MethodPost,
URL: "/api/collections/users/request-otp",
Body: strings.NewReader(`{"email":"test@example.com"}`),
Delay: 100 * time.Millisecond,
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnRecordRequestOTPRequest().BindFunc(func(e *core.RecordCreateOTPRequestEvent) error {
original := e.App
return e.App.RunInTransaction(func(txApp core.App) error {
e.App = txApp
defer func() { e.App = original }()
if err := e.Next(); err != nil {
return err
}
return e.BadRequestError("TX_ERROR", nil)
})
})
},
ExpectedStatus: 400,
ExpectedEvents: map[string]int{"OnRecordRequestOTPRequest": 1},
ExpectedContent: []string{"TX_ERROR"},
},
// rate limit checks
// -----------------------------------------------------------
{
Name: "RateLimit rule - users:requestOTP",
Method: http.MethodPost,
URL: "/api/collections/users/request-otp",
Body: strings.NewReader(`{"email":"test@example.com"}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.Settings().RateLimits.Enabled = true
app.Settings().RateLimits.Rules = []core.RateLimitRule{
{MaxRequests: 100, Label: "abc"},
{MaxRequests: 100, Label: "*:requestOTP"},
{MaxRequests: 0, Label: "users:requestOTP"},
}
},
ExpectedStatus: 429,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "RateLimit rule - *:requestOTP",
Method: http.MethodPost,
URL: "/api/collections/users/request-otp",
Body: strings.NewReader(`{"email":"test@example.com"}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.Settings().RateLimits.Enabled = true
app.Settings().RateLimits.Rules = []core.RateLimitRule{
{MaxRequests: 100, Label: "abc"},
{MaxRequests: 0, Label: "*:requestOTP"},
}
},
ExpectedStatus: 429,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/record_auth_verification_confirm_test.go | apis/record_auth_verification_confirm_test.go | package apis_test
import (
"net/http"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestRecordConfirmVerification(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "empty data",
Method: http.MethodPost,
URL: "/api/collections/users/confirm-verification",
Body: strings.NewReader(``),
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"token":{"code":"validation_required"`,
},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "invalid data format",
Method: http.MethodPost,
URL: "/api/collections/users/confirm-verification",
Body: strings.NewReader(`{"password`),
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "expired token",
Method: http.MethodPost,
URL: "/api/collections/users/confirm-verification",
Body: strings.NewReader(`{
"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsImV4cCI6MTY0MDk5MTY2MSwidHlwZSI6InZlcmlmaWNhdGlvbiIsImNvbGxlY3Rpb25JZCI6Il9wYl91c2Vyc19hdXRoXyIsImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSJ9.qqelNNL2Udl6K_TJ282sNHYCpASgA6SIuSVKGfBHMZU"
}`),
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"token":{"code":"validation_invalid_token"`,
},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "non-verification token",
Method: http.MethodPost,
URL: "/api/collections/users/confirm-verification",
Body: strings.NewReader(`{
"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6InBhc3N3b3JkUmVzZXQiLCJjb2xsZWN0aW9uSWQiOiJfcGJfdXNlcnNfYXV0aF8iLCJlbWFpbCI6InRlc3RAZXhhbXBsZS5jb20ifQ.xR-xq1oHDy0D8Q4NDOAEyYKGHWd_swzoiSoL8FLFBHY"
}`),
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"token":{"code":"validation_invalid_token"`,
},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "non auth collection",
Method: http.MethodPost,
URL: "/api/collections/demo1/confirm-verification?expand=rel,missing",
Body: strings.NewReader(`{
"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6InZlcmlmaWNhdGlvbiIsImNvbGxlY3Rpb25JZCI6Il9wYl91c2Vyc19hdXRoXyIsImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSJ9.SetHpu2H-x-q4TIUz-xiQjwi7MNwLCLvSs4O0hUSp0E"
}`),
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "different auth collection",
Method: http.MethodPost,
URL: "/api/collections/clients/confirm-verification?expand=rel,missing",
Body: strings.NewReader(`{
"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6InZlcmlmaWNhdGlvbiIsImNvbGxlY3Rpb25JZCI6Il9wYl91c2Vyc19hdXRoXyIsImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSJ9.SetHpu2H-x-q4TIUz-xiQjwi7MNwLCLvSs4O0hUSp0E"
}`),
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{"token":{"code":"validation_token_collection_mismatch"`,
},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "valid token",
Method: http.MethodPost,
URL: "/api/collections/users/confirm-verification",
Body: strings.NewReader(`{
"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6InZlcmlmaWNhdGlvbiIsImNvbGxlY3Rpb25JZCI6Il9wYl91c2Vyc19hdXRoXyIsImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSJ9.SetHpu2H-x-q4TIUz-xiQjwi7MNwLCLvSs4O0hUSp0E"
}`),
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordConfirmVerificationRequest": 1,
"OnModelUpdate": 1,
"OnModelValidate": 1,
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnRecordUpdate": 1,
"OnRecordValidate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
},
},
{
Name: "valid token (already verified)",
Method: http.MethodPost,
URL: "/api/collections/users/confirm-verification",
Body: strings.NewReader(`{
"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Im9hcDY0MGNvdDR5cnUycyIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6InZlcmlmaWNhdGlvbiIsImNvbGxlY3Rpb25JZCI6Il9wYl91c2Vyc19hdXRoXyIsImVtYWlsIjoidGVzdDJAZXhhbXBsZS5jb20ifQ.QQmM3odNFVk6u4J4-5H8IBM3dfk9YCD7mPW-8PhBAI8"
}`),
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordConfirmVerificationRequest": 1,
},
},
{
Name: "valid verification token from a collection without allowed login",
Method: http.MethodPost,
URL: "/api/collections/nologin/confirm-verification",
Body: strings.NewReader(`{
"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImRjNDlrNmpnZWpuNDBoMyIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6InZlcmlmaWNhdGlvbiIsImNvbGxlY3Rpb25JZCI6ImtwdjcwOXNrMmxxYnFrOCIsImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSJ9.5GmuZr4vmwk3Cb_3ZZWNxwbE75KZC-j71xxIPR9AsVw"
}`),
ExpectedStatus: 204,
ExpectedContent: []string{},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordConfirmVerificationRequest": 1,
"OnModelUpdate": 1,
"OnModelValidate": 1,
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnRecordUpdate": 1,
"OnRecordValidate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
},
},
{
Name: "OnRecordConfirmVerificationRequest tx body write check",
Method: http.MethodPost,
URL: "/api/collections/users/confirm-verification",
Body: strings.NewReader(`{
"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6InZlcmlmaWNhdGlvbiIsImNvbGxlY3Rpb25JZCI6Il9wYl91c2Vyc19hdXRoXyIsImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSJ9.SetHpu2H-x-q4TIUz-xiQjwi7MNwLCLvSs4O0hUSp0E"
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnRecordConfirmVerificationRequest().BindFunc(func(e *core.RecordConfirmVerificationRequestEvent) error {
original := e.App
return e.App.RunInTransaction(func(txApp core.App) error {
e.App = txApp
defer func() { e.App = original }()
if err := e.Next(); err != nil {
return err
}
return e.BadRequestError("TX_ERROR", nil)
})
})
},
ExpectedStatus: 400,
ExpectedEvents: map[string]int{"OnRecordConfirmVerificationRequest": 1},
ExpectedContent: []string{"TX_ERROR"},
},
// rate limit checks
// -----------------------------------------------------------
{
Name: "RateLimit rule - nologin:confirmVerification",
Method: http.MethodPost,
URL: "/api/collections/nologin/confirm-verification",
Body: strings.NewReader(`{
"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImRjNDlrNmpnZWpuNDBoMyIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6InZlcmlmaWNhdGlvbiIsImNvbGxlY3Rpb25JZCI6ImtwdjcwOXNrMmxxYnFrOCIsImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSJ9.5GmuZr4vmwk3Cb_3ZZWNxwbE75KZC-j71xxIPR9AsVw"
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.Settings().RateLimits.Enabled = true
app.Settings().RateLimits.Rules = []core.RateLimitRule{
{MaxRequests: 100, Label: "abc"},
{MaxRequests: 100, Label: "*:confirmVerification"},
{MaxRequests: 0, Label: "nologin:confirmVerification"},
}
},
ExpectedStatus: 429,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "RateLimit rule - *:confirmVerification",
Method: http.MethodPost,
URL: "/api/collections/nologin/confirm-verification",
Body: strings.NewReader(`{
"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImRjNDlrNmpnZWpuNDBoMyIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6InZlcmlmaWNhdGlvbiIsImNvbGxlY3Rpb25JZCI6ImtwdjcwOXNrMmxxYnFrOCIsImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSJ9.5GmuZr4vmwk3Cb_3ZZWNxwbE75KZC-j71xxIPR9AsVw"
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.Settings().RateLimits.Enabled = true
app.Settings().RateLimits.Rules = []core.RateLimitRule{
{MaxRequests: 100, Label: "abc"},
{MaxRequests: 0, Label: "*:confirmVerification"},
}
},
ExpectedStatus: 429,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/middlewares_test.go | apis/middlewares_test.go | package apis_test
import (
"net/http"
"testing"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestPanicRecover(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "panic from route",
Method: http.MethodGet,
URL: "/my/test",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
panic("123")
})
},
ExpectedStatus: 500,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "panic from middleware",
Method: http.MethodGet,
URL: "/my/test",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
return e.String(http.StatusOK, "test")
}).BindFunc(func(e *core.RequestEvent) error {
panic(123)
})
},
ExpectedStatus: 500,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestRequireGuestOnly(t *testing.T) {
t.Parallel()
beforeTestFunc := func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireGuestOnly())
}
scenarios := []tests.ApiScenario{
{
Name: "valid regular user token",
Method: http.MethodGet,
URL: "/my/test",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: beforeTestFunc,
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "valid superuser auth token",
Method: http.MethodGet,
URL: "/my/test",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: beforeTestFunc,
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "expired/invalid token",
Method: http.MethodGet,
URL: "/my/test",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoxNjQwOTkxNjYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.2D3tmqPn3vc5LoqqCz8V-iCDVXo9soYiH0d32G7FQT4",
},
BeforeTestFunc: beforeTestFunc,
ExpectedStatus: 200,
ExpectedContent: []string{"test123"},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "guest",
Method: http.MethodGet,
URL: "/my/test",
BeforeTestFunc: beforeTestFunc,
ExpectedStatus: 200,
ExpectedContent: []string{"test123"},
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestRequireAuth(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "guest",
Method: http.MethodGet,
URL: "/my/test",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireAuth())
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "expired token",
Method: http.MethodGet,
URL: "/my/test",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoxNjQwOTkxNjYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.2D3tmqPn3vc5LoqqCz8V-iCDVXo9soYiH0d32G7FQT4",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireAuth())
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "invalid token",
Method: http.MethodGet,
URL: "/my/test",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6ImZpbGUiLCJjb2xsZWN0aW9uSWQiOiJwYmNfMzE0MjYzNTgyMyJ9.Lupz541xRvrktwkrl55p5pPCF77T69ZRsohsIcb2dxc",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireAuth())
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "valid record auth token with no collection restrictions",
Method: http.MethodGet,
URL: "/my/test",
Headers: map[string]string{
// regular user
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireAuth())
},
ExpectedStatus: 200,
ExpectedContent: []string{"test123"},
},
{
Name: "valid record static auth token",
Method: http.MethodGet,
URL: "/my/test",
Headers: map[string]string{
// regular user
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6ZmFsc2V9.4IsO6YMsR19crhwl_YWzvRH8pfq2Ri4Gv2dzGyneLak",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireAuth())
},
ExpectedStatus: 200,
ExpectedContent: []string{"test123"},
},
{
Name: "valid record auth token with collection not in the restricted list",
Method: http.MethodGet,
URL: "/my/test",
Headers: map[string]string{
// superuser
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireAuth("users", "demo1"))
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "valid record auth token with collection in the restricted list",
Method: http.MethodGet,
URL: "/my/test",
Headers: map[string]string{
// superuser
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireAuth("users", core.CollectionNameSuperusers))
},
ExpectedStatus: 200,
ExpectedContent: []string{"test123"},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestRequireSuperuserAuth(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "guest",
Method: http.MethodGet,
URL: "/my/test",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSuperuserAuth())
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "expired/invalid token",
Method: http.MethodGet,
URL: "/my/test",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjE2NDA5OTE2NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.0pDcBPGDpL2Khh76ivlRi7ugiLBSYvasct3qpHV3rfs",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSuperuserAuth())
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "valid regular user auth token",
Method: http.MethodGet,
URL: "/my/test",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSuperuserAuth())
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "valid superuser auth token",
Method: http.MethodGet,
URL: "/my/test",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSuperuserAuth())
},
ExpectedStatus: 200,
ExpectedContent: []string{"test123"},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestRequireSuperuserOrOwnerAuth(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "guest",
Method: http.MethodGet,
URL: "/my/test/4q1xlclmfloku33",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test/{id}", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSuperuserOrOwnerAuth(""))
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "expired/invalid token",
Method: http.MethodGet,
URL: "/my/test/4q1xlclmfloku33",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjE2NDA5OTE2NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.0pDcBPGDpL2Khh76ivlRi7ugiLBSYvasct3qpHV3rfs",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test/{id}", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSuperuserOrOwnerAuth(""))
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "valid record auth token (different user)",
Method: http.MethodGet,
URL: "/my/test/oap640cot4yru2s",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test/{id}", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSuperuserOrOwnerAuth(""))
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "valid record auth token (owner)",
Method: http.MethodGet,
URL: "/my/test/4q1xlclmfloku33",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test/{id}", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSuperuserOrOwnerAuth(""))
},
ExpectedStatus: 200,
ExpectedContent: []string{"test123"},
},
{
Name: "valid record auth token (owner + non-matching custom owner param)",
Method: http.MethodGet,
URL: "/my/test/4q1xlclmfloku33",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test/{id}", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSuperuserOrOwnerAuth("test"))
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "valid record auth token (owner + matching custom owner param)",
Method: http.MethodGet,
URL: "/my/test/4q1xlclmfloku33",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test/{test}", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSuperuserOrOwnerAuth("test"))
},
ExpectedStatus: 200,
ExpectedContent: []string{"test123"},
},
{
Name: "valid superuser auth token",
Method: http.MethodGet,
URL: "/my/test/4q1xlclmfloku33",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test/{id}", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSuperuserOrOwnerAuth(""))
},
ExpectedStatus: 200,
ExpectedContent: []string{"test123"},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestRequireSameCollectionContextAuth(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "guest",
Method: http.MethodGet,
URL: "/my/test/_pb_users_auth_",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test/{collection}", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSameCollectionContextAuth(""))
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "expired/invalid token",
Method: http.MethodGet,
URL: "/my/test/_pb_users_auth_",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoxNjQwOTkxNjYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.2D3tmqPn3vc5LoqqCz8V-iCDVXo9soYiH0d32G7FQT4",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test/{collection}", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSameCollectionContextAuth(""))
},
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "valid record auth token (different collection)",
Method: http.MethodGet,
URL: "/my/test/clients",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test/{collection}", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSameCollectionContextAuth(""))
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "valid record auth token (same collection)",
Method: http.MethodGet,
URL: "/my/test/_pb_users_auth_",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test/{collection}", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSameCollectionContextAuth(""))
},
ExpectedStatus: 200,
ExpectedContent: []string{"test123"},
},
{
Name: "valid record auth token (non-matching/missing collection param)",
Method: http.MethodGet,
URL: "/my/test/_pb_users_auth_",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test/{id}", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSuperuserOrOwnerAuth(""))
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "valid record auth token (matching custom collection param)",
Method: http.MethodGet,
URL: "/my/test/_pb_users_auth_",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test/{test}", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSuperuserOrOwnerAuth("test"))
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "superuser no exception check",
Method: http.MethodGet,
URL: "/my/test/_pb_users_auth_",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test/{collection}", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireSameCollectionContextAuth(""))
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/record_crud_superuser_test.go | apis/record_crud_superuser_test.go | package apis_test
import (
"net/http"
"strings"
"testing"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestRecordCrudSuperuserList(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "guest",
Method: http.MethodGet,
URL: "/api/collections/" + core.CollectionNameSuperusers + "/records",
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "non-superusers auth",
Method: http.MethodGet,
URL: "/api/collections/" + core.CollectionNameSuperusers + "/records",
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "superusers auth",
Method: http.MethodGet,
URL: "/api/collections/" + core.CollectionNameSuperusers + "/records",
Headers: map[string]string{
// _superusers, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":1`,
`"totalItems":4`,
`"items":[{`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 4,
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestRecordCrudSuperuserView(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "guest",
Method: http.MethodGet,
URL: "/api/collections/" + core.CollectionNameSuperusers + "/records/sywbhecnh46rhm0",
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "non-superusers auth",
Method: http.MethodGet,
URL: "/api/collections/" + core.CollectionNameSuperusers + "/records/sywbhecnh46rhm0",
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "superusers auth",
Method: http.MethodGet,
URL: "/api/collections/" + core.CollectionNameSuperusers + "/records/sywbhecnh46rhm0",
Headers: map[string]string{
// _superusers, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"id":"sywbhecnh46rhm0"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordViewRequest": 1,
"OnRecordEnrich": 1,
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestRecordCrudSuperuserDelete(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "guest",
Method: http.MethodDelete,
URL: "/api/collections/" + core.CollectionNameSuperusers + "/records/sbmbsdb40jyxf7h",
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "non-superusers auth",
Method: http.MethodDelete,
URL: "/api/collections/" + core.CollectionNameSuperusers + "/records/sbmbsdb40jyxf7h",
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "superusers auth",
Method: http.MethodDelete,
URL: "/api/collections/" + core.CollectionNameSuperusers + "/records/sbmbsdb40jyxf7h",
Headers: map[string]string{
// _superusers, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordDeleteRequest": 1,
"OnModelDelete": 4, // + 3 AuthOrigins
"OnModelDeleteExecute": 4,
"OnModelAfterDeleteSuccess": 4,
"OnRecordDelete": 4,
"OnRecordDeleteExecute": 4,
"OnRecordAfterDeleteSuccess": 4,
},
},
{
Name: "delete the last superuser",
Method: http.MethodDelete,
URL: "/api/collections/" + core.CollectionNameSuperusers + "/records/sywbhecnh46rhm0",
Headers: map[string]string{
// _superusers, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
// delete all other superusers
superusers, err := app.FindAllRecords(core.CollectionNameSuperusers, dbx.Not(dbx.HashExp{"id": "sywbhecnh46rhm0"}))
if err != nil {
t.Fatal(err)
}
for _, superuser := range superusers {
if err = app.Delete(superuser); err != nil {
t.Fatal(err)
}
}
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordDeleteRequest": 1,
"OnModelDelete": 1,
"OnModelAfterDeleteError": 1,
"OnRecordDelete": 1,
"OnRecordAfterDeleteError": 1,
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestRecordCrudSuperuserCreate(t *testing.T) {
t.Parallel()
body := func() *strings.Reader {
return strings.NewReader(`{
"email": "test_new@example.com",
"password": "1234567890",
"passwordConfirm": "1234567890",
"verified": false
}`)
}
scenarios := []tests.ApiScenario{
{
Name: "guest",
Method: http.MethodPost,
URL: "/api/collections/" + core.CollectionNameSuperusers + "/records",
Body: body(),
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "non-superusers auth",
Method: http.MethodPost,
URL: "/api/collections/" + core.CollectionNameSuperusers + "/records",
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
Body: body(),
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "superusers auth",
Method: http.MethodPost,
URL: "/api/collections/" + core.CollectionNameSuperusers + "/records",
Headers: map[string]string{
// _superusers, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
Body: body(),
ExpectedContent: []string{
`"collectionName":"_superusers"`,
`"email":"test_new@example.com"`,
`"verified":true`,
},
ExpectedStatus: 200,
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordCreateRequest": 1,
"OnRecordEnrich": 1,
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnModelValidate": 1,
"OnRecordCreate": 1,
"OnRecordCreateExecute": 1,
"OnRecordAfterCreateSuccess": 1,
"OnRecordValidate": 1,
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestRecordCrudSuperuserUpdate(t *testing.T) {
t.Parallel()
body := func() *strings.Reader {
return strings.NewReader(`{
"email": "test_new@example.com",
"verified": true
}`)
}
scenarios := []tests.ApiScenario{
{
Name: "guest",
Method: http.MethodPatch,
URL: "/api/collections/" + core.CollectionNameSuperusers + "/records/sywbhecnh46rhm0",
Body: body(),
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "non-superusers auth",
Method: http.MethodPatch,
URL: "/api/collections/" + core.CollectionNameSuperusers + "/records/sywbhecnh46rhm0",
Headers: map[string]string{
// users, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
Body: body(),
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "superusers auth",
Method: http.MethodPatch,
URL: "/api/collections/" + core.CollectionNameSuperusers + "/records/sywbhecnh46rhm0",
Headers: map[string]string{
// _superusers, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
Body: body(),
ExpectedContent: []string{
`"collectionName":"_superusers"`,
`"id":"sywbhecnh46rhm0"`,
`"email":"test_new@example.com"`,
`"verified":true`,
},
ExpectedStatus: 200,
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordUpdateRequest": 1,
"OnRecordEnrich": 1,
"OnModelUpdate": 1,
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnModelValidate": 1,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
"OnRecordValidate": 1,
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/record_auth_password_reset_request_test.go | apis/record_auth_password_reset_request_test.go | package apis_test
import (
"net/http"
"strings"
"testing"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestRecordRequestPasswordReset(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "not an auth collection",
Method: http.MethodPost,
URL: "/api/collections/demo1/request-password-reset",
Body: strings.NewReader(``),
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "empty data",
Method: http.MethodPost,
URL: "/api/collections/users/request-password-reset",
Body: strings.NewReader(``),
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{"email":{"code":"validation_required","message":"Cannot be blank."}}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "invalid data",
Method: http.MethodPost,
URL: "/api/collections/users/request-password-reset",
Body: strings.NewReader(`{"email`),
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "existing auth record in a collection with disabled password login",
Method: http.MethodPost,
URL: "/api/collections/nologin/request-password-reset",
Body: strings.NewReader(`{"email":"test@example.com"}`),
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "missing auth record",
Method: http.MethodPost,
URL: "/api/collections/users/request-password-reset",
Body: strings.NewReader(`{"email":"missing@example.com"}`),
Delay: 100 * time.Millisecond,
ExpectedStatus: 204,
ExpectedEvents: map[string]int{"*": 0},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
if app.TestMailer.TotalSend() != 0 {
t.Fatalf("Expected zero emails, got %d", app.TestMailer.TotalSend())
}
},
},
{
Name: "existing auth record",
Method: http.MethodPost,
URL: "/api/collections/users/request-password-reset",
Body: strings.NewReader(`{"email":"test@example.com"}`),
Delay: 100 * time.Millisecond,
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordRequestPasswordResetRequest": 1,
"OnMailerSend": 1,
"OnMailerRecordPasswordResetSend": 1,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
if !strings.Contains(app.TestMailer.LastMessage().HTML, "/auth/confirm-password-reset") {
t.Fatalf("Expected password reset email, got\n%v", app.TestMailer.LastMessage().HTML)
}
},
},
{
Name: "existing auth record (after already sent)",
Method: http.MethodPost,
URL: "/api/collections/users/request-password-reset",
Body: strings.NewReader(`{"email":"test@example.com"}`),
Delay: 100 * time.Millisecond,
ExpectedStatus: 204,
ExpectedEvents: map[string]int{"*": 0},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
// simulate recent verification sent
authRecord, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
resendKey := "@limitPasswordResetEmail_" + authRecord.Collection().Id + authRecord.Id
app.Store().Set(resendKey, struct{}{})
},
},
{
Name: "OnRecordRequestPasswordResetRequest tx body write check",
Method: http.MethodPost,
URL: "/api/collections/users/request-password-reset",
Body: strings.NewReader(`{"email":"test@example.com"}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnRecordRequestPasswordResetRequest().BindFunc(func(e *core.RecordRequestPasswordResetRequestEvent) error {
original := e.App
return e.App.RunInTransaction(func(txApp core.App) error {
e.App = txApp
defer func() { e.App = original }()
if err := e.Next(); err != nil {
return err
}
return e.BadRequestError("TX_ERROR", nil)
})
})
},
ExpectedStatus: 400,
ExpectedEvents: map[string]int{"OnRecordRequestPasswordResetRequest": 1},
ExpectedContent: []string{"TX_ERROR"},
},
// rate limit checks
// -----------------------------------------------------------
{
Name: "RateLimit rule - users:requestPasswordReset",
Method: http.MethodPost,
URL: "/api/collections/users/request-password-reset",
Body: strings.NewReader(`{"email":"missing@example.com"}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.Settings().RateLimits.Enabled = true
app.Settings().RateLimits.Rules = []core.RateLimitRule{
{MaxRequests: 100, Label: "abc"},
{MaxRequests: 100, Label: "*:requestPasswordReset"},
{MaxRequests: 0, Label: "users:requestPasswordReset"},
}
},
ExpectedStatus: 429,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "RateLimit rule - *:requestPasswordReset",
Method: http.MethodPost,
URL: "/api/collections/users/request-password-reset",
Body: strings.NewReader(`{"email":"missing@example.com"}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.Settings().RateLimits.Enabled = true
app.Settings().RateLimits.Rules = []core.RateLimitRule{
{MaxRequests: 100, Label: "abc"},
{MaxRequests: 0, Label: "*:requestPasswordReset"},
}
},
ExpectedStatus: 429,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/collection_test.go | apis/collection_test.go | package apis_test
import (
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/list"
)
func TestCollectionsList(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "unauthorized",
Method: http.MethodGet,
URL: "/api/collections",
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as regular user",
Method: http.MethodGet,
URL: "/api/collections",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser",
Method: http.MethodGet,
URL: "/api/collections",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalItems":16`,
`"items":[{`,
`"name":"` + core.CollectionNameSuperusers + `"`,
`"name":"` + core.CollectionNameAuthOrigins + `"`,
`"name":"` + core.CollectionNameExternalAuths + `"`,
`"name":"` + core.CollectionNameMFAs + `"`,
`"name":"` + core.CollectionNameOTPs + `"`,
`"name":"users"`,
`"name":"nologin"`,
`"name":"clients"`,
`"name":"demo1"`,
`"name":"demo2"`,
`"name":"demo3"`,
`"name":"demo4"`,
`"name":"demo5"`,
`"name":"numeric_id_view"`,
`"name":"view1"`,
`"name":"view2"`,
`"type":"auth"`,
`"type":"base"`,
`"type":"view"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionsListRequest": 1,
},
},
{
Name: "authorized as superuser + paging and sorting",
Method: http.MethodGet,
URL: "/api/collections?page=2&perPage=2&sort=-created",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":2`,
`"perPage":2`,
`"totalItems":16`,
`"items":[{`,
`"name":"` + core.CollectionNameMFAs + `"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionsListRequest": 1,
},
},
{
Name: "authorized as superuser + invalid filter",
Method: http.MethodGet,
URL: "/api/collections?filter=invalidfield~'demo2'",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser + valid filter",
Method: http.MethodGet,
URL: "/api/collections?filter=name~'demo'",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalItems":5`,
`"items":[{`,
`"name":"demo1"`,
`"name":"demo2"`,
`"name":"demo3"`,
`"name":"demo4"`,
`"name":"demo5"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionsListRequest": 1,
},
},
{
Name: "OnCollectionsListRequest tx body write check",
Method: http.MethodGet,
URL: "/api/collections",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnCollectionsListRequest().BindFunc(func(e *core.CollectionsListRequestEvent) error {
original := e.App
return e.App.RunInTransaction(func(txApp core.App) error {
e.App = txApp
defer func() { e.App = original }()
if err := e.Next(); err != nil {
return err
}
return e.BadRequestError("TX_ERROR", nil)
})
})
},
ExpectedStatus: 400,
ExpectedEvents: map[string]int{"OnCollectionsListRequest": 1},
ExpectedContent: []string{"TX_ERROR"},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestCollectionView(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "unauthorized",
Method: http.MethodGet,
URL: "/api/collections/demo1",
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as regular user",
Method: http.MethodGet,
URL: "/api/collections/demo1",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser + nonexisting collection identifier",
Method: http.MethodGet,
URL: "/api/collections/missing",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser + using the collection name",
Method: http.MethodGet,
URL: "/api/collections/demo1",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"id":"wsmn24bux7wo113"`,
`"name":"demo1"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionViewRequest": 1,
},
},
{
Name: "authorized as superuser + using the collection id",
Method: http.MethodGet,
URL: "/api/collections/wsmn24bux7wo113",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"id":"wsmn24bux7wo113"`,
`"name":"demo1"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionViewRequest": 1,
},
},
{
Name: "OnCollectionViewRequest tx body write check",
Method: http.MethodGet,
URL: "/api/collections/wsmn24bux7wo113",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnCollectionViewRequest().BindFunc(func(e *core.CollectionRequestEvent) error {
original := e.App
return e.App.RunInTransaction(func(txApp core.App) error {
e.App = txApp
defer func() { e.App = original }()
if err := e.Next(); err != nil {
return err
}
return e.BadRequestError("TX_ERROR", nil)
})
})
},
ExpectedStatus: 400,
ExpectedEvents: map[string]int{"OnCollectionViewRequest": 1},
ExpectedContent: []string{"TX_ERROR"},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestCollectionDelete(t *testing.T) {
t.Parallel()
ensureDeletedFiles := func(app *tests.TestApp, collectionId string) {
storageDir := filepath.Join(app.DataDir(), "storage", collectionId)
entries, _ := os.ReadDir(storageDir)
if len(entries) != 0 {
t.Errorf("Expected empty/deleted dir, found %d", len(entries))
}
}
scenarios := []tests.ApiScenario{
{
Name: "unauthorized",
Method: http.MethodDelete,
URL: "/api/collections/demo1",
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as regular user",
Method: http.MethodDelete,
URL: "/api/collections/demo1",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser + nonexisting collection identifier",
Method: http.MethodDelete,
URL: "/api/collections/missing",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser + using the collection name",
Method: http.MethodDelete,
URL: "/api/collections/demo5",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
Delay: 100 * time.Millisecond,
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionDeleteRequest": 1,
"OnCollectionDelete": 1,
"OnCollectionDeleteExecute": 1,
"OnCollectionAfterDeleteSuccess": 1,
"OnModelDelete": 1,
"OnModelDeleteExecute": 1,
"OnModelAfterDeleteSuccess": 1,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
ensureDeletedFiles(app, "9n89pl5vkct6330")
},
},
{
Name: "authorized as superuser + using the collection id",
Method: http.MethodDelete,
URL: "/api/collections/9n89pl5vkct6330",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
Delay: 100 * time.Millisecond,
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionDeleteRequest": 1,
"OnCollectionDelete": 1,
"OnCollectionDeleteExecute": 1,
"OnCollectionAfterDeleteSuccess": 1,
"OnModelDelete": 1,
"OnModelDeleteExecute": 1,
"OnModelAfterDeleteSuccess": 1,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
ensureDeletedFiles(app, "9n89pl5vkct6330")
},
},
{
Name: "authorized as superuser + trying to delete a system collection",
Method: http.MethodDelete,
URL: "/api/collections/" + core.CollectionNameMFAs,
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionDeleteRequest": 1,
"OnCollectionDelete": 1,
"OnCollectionDeleteExecute": 1,
"OnCollectionAfterDeleteError": 1,
"OnModelDelete": 1,
"OnModelDeleteExecute": 1,
"OnModelAfterDeleteError": 1,
},
},
{
Name: "authorized as superuser + trying to delete a referenced collection",
Method: http.MethodDelete,
URL: "/api/collections/demo2",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionDeleteRequest": 1,
"OnCollectionDelete": 1,
"OnCollectionDeleteExecute": 1,
"OnCollectionAfterDeleteError": 1,
"OnModelDelete": 1,
"OnModelDeleteExecute": 1,
"OnModelAfterDeleteError": 1,
},
},
{
Name: "authorized as superuser + deleting a view",
Method: http.MethodDelete,
URL: "/api/collections/view2",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 204,
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionDeleteRequest": 1,
"OnCollectionDelete": 1,
"OnCollectionDeleteExecute": 1,
"OnCollectionAfterDeleteSuccess": 1,
"OnModelDelete": 1,
"OnModelDeleteExecute": 1,
"OnModelAfterDeleteSuccess": 1,
},
},
{
Name: "OnCollectionDeleteRequest tx body write check",
Method: http.MethodDelete,
URL: "/api/collections/view2",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnCollectionDeleteRequest().BindFunc(func(e *core.CollectionRequestEvent) error {
original := e.App
return e.App.RunInTransaction(func(txApp core.App) error {
e.App = txApp
defer func() { e.App = original }()
if err := e.Next(); err != nil {
return err
}
return e.BadRequestError("TX_ERROR", nil)
})
})
},
ExpectedStatus: 400,
ExpectedEvents: map[string]int{"OnCollectionDeleteRequest": 1},
ExpectedContent: []string{"TX_ERROR"},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestCollectionCreate(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "unauthorized",
Method: http.MethodPost,
URL: "/api/collections",
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as regular user",
Method: http.MethodPost,
URL: "/api/collections",
Body: strings.NewReader(`{"name":"new","type":"base","fields":[{"type":"text","name":"test"}]}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser + empty data",
Method: http.MethodPost,
URL: "/api/collections",
Body: strings.NewReader(``),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"name":{"code":"validation_required"`,
},
NotExpectedContent: []string{
`"fields":{`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionCreateRequest": 1,
"OnCollectionCreate": 1,
"OnCollectionAfterCreateError": 1,
"OnCollectionValidate": 1,
"OnModelCreate": 1,
"OnModelAfterCreateError": 1,
"OnModelValidate": 1,
},
},
{
Name: "authorized as superuser + invalid data (eg. existing name)",
Method: http.MethodPost,
URL: "/api/collections",
Body: strings.NewReader(`{"name":"demo1","type":"base","fields":[{"type":"text","name":""}]}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"fields":{`,
`"name":{"code":"validation_collection_name_exists"`,
`"name":{"code":"validation_required"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionCreateRequest": 1,
"OnCollectionCreate": 1,
"OnCollectionAfterCreateError": 1,
"OnCollectionValidate": 1,
"OnModelCreate": 1,
"OnModelAfterCreateError": 1,
"OnModelValidate": 1,
},
},
{
Name: "authorized as superuser + valid data",
Method: http.MethodPost,
URL: "/api/collections",
Body: strings.NewReader(`{"name":"new","type":"base","fields":[{"type":"text","id":"12345789","name":"test"}]}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"id":`,
`"name":"new"`,
`"type":"base"`,
`"system":false`,
// ensures that id field was prepended
`"fields":[{"autogeneratePattern":"[a-z0-9]{15}","hidden":false,"id":"text3208210256","max":15,"min":15,"name":"id","pattern":"^[a-z0-9]+$","presentable":false,"primaryKey":true,"required":true,"system":true,"type":"text"},{"autogeneratePattern":"","hidden":false,"id":"12345789","max":0,"min":0,"name":"test","pattern":"","presentable":false,"primaryKey":false,"required":false,"system":false,"type":"text"}]`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionCreateRequest": 1,
"OnCollectionCreate": 1,
"OnCollectionCreateExecute": 1,
"OnCollectionAfterCreateSuccess": 1,
"OnCollectionValidate": 1,
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnModelValidate": 1,
},
},
{
Name: "creating auth collection (default settings merge test)",
Method: http.MethodPost,
URL: "/api/collections",
Body: strings.NewReader(`{
"name":"new",
"type":"auth",
"emailChangeToken":{"duration":123},
"fields":[
{"type":"text","id":"12345789","name":"test"},
{"type":"text","name":"tokenKey","system":true,"required":false,"min":10}
]
}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"id":`,
`"name":"new"`,
`"type":"auth"`,
`"system":false`,
`"passwordAuth":{"enabled":true,"identityFields":["email"]}`,
`"authRule":""`,
`"manageRule":null`,
`"name":"test"`,
`"name":"id"`,
`"name":"tokenKey"`,
`"name":"password"`,
`"name":"email"`,
`"name":"emailVisibility"`,
`"name":"verified"`,
`"duration":123`,
// should overwrite the user required option but keep the min value
`{"autogeneratePattern":"","hidden":true,"id":"text2504183744","max":0,"min":10,"name":"tokenKey","pattern":"","presentable":false,"primaryKey":false,"required":true,"system":true,"type":"text"}`,
},
NotExpectedContent: []string{
`"secret":"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionCreateRequest": 1,
"OnCollectionCreate": 1,
"OnCollectionCreateExecute": 1,
"OnCollectionAfterCreateSuccess": 1,
"OnCollectionValidate": 1,
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnModelValidate": 1,
},
},
{
Name: "creating base collection with reserved auth fields",
Method: http.MethodPost,
URL: "/api/collections",
Body: strings.NewReader(`{
"name":"new",
"type":"base",
"fields":[
{"type":"text","name":"email"},
{"type":"text","name":"username"},
{"type":"text","name":"verified"},
{"type":"text","name":"emailVisibility"},
{"type":"text","name":"lastResetSentAt"},
{"type":"text","name":"lastVerificationSentAt"},
{"type":"text","name":"tokenKey"},
{"type":"text","name":"passwordHash"},
{"type":"text","name":"password"},
{"type":"text","name":"passwordConfirm"},
{"type":"text","name":"oldPassword"}
]
}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"name":"new"`,
`"type":"base"`,
`"fields":[{`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionCreateRequest": 1,
"OnCollectionCreate": 1,
"OnCollectionCreateExecute": 1,
"OnCollectionAfterCreateSuccess": 1,
"OnCollectionValidate": 1,
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnModelValidate": 1,
},
},
{
Name: "trying to create base collection with reserved system fields",
Method: http.MethodPost,
URL: "/api/collections",
Body: strings.NewReader(`{
"name":"new",
"type":"base",
"fields":[
{"type":"text","name":"id"},
{"type":"text","name":"expand"},
{"type":"text","name":"collectionId"},
{"type":"text","name":"collectionName"}
]
}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{"fields":{`,
`"1":{"name":{"code":"validation_not_in_invalid`,
`"2":{"name":{"code":"validation_not_in_invalid`,
`"3":{"name":{"code":"validation_not_in_invalid`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionCreateRequest": 1,
"OnCollectionCreate": 1,
"OnCollectionAfterCreateError": 1,
"OnCollectionValidate": 1,
"OnModelCreate": 1,
"OnModelAfterCreateError": 1,
"OnModelValidate": 1,
},
},
{
Name: "trying to create auth collection with reserved auth fields",
Method: http.MethodPost,
URL: "/api/collections",
Body: strings.NewReader(`{
"name":"new",
"type":"auth",
"fields":[
{"type":"text","name":"oldPassword"},
{"type":"text","name":"passwordConfirm"}
]
}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{"fields":{`,
`"1":{"name":{"code":"validation_reserved_field_name`,
`"2":{"name":{"code":"validation_reserved_field_name`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionCreateRequest": 1,
"OnCollectionCreate": 1,
"OnCollectionAfterCreateError": 1,
"OnCollectionValidate": 1,
"OnModelCreate": 1,
"OnModelAfterCreateError": 1,
"OnModelValidate": 1,
},
},
{
Name: "OnCollectionCreateRequest tx body write check",
Method: http.MethodPost,
URL: "/api/collections",
Body: strings.NewReader(`{"name":"new","type":"base"}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnCollectionCreateRequest().BindFunc(func(e *core.CollectionRequestEvent) error {
original := e.App
return e.App.RunInTransaction(func(txApp core.App) error {
e.App = txApp
defer func() { e.App = original }()
if err := e.Next(); err != nil {
return err
}
return e.BadRequestError("TX_ERROR", nil)
})
})
},
ExpectedStatus: 400,
ExpectedEvents: map[string]int{"OnCollectionCreateRequest": 1},
ExpectedContent: []string{"TX_ERROR"},
},
// view
// -----------------------------------------------------------
{
Name: "trying to create view collection with invalid options",
Method: http.MethodPost,
URL: "/api/collections",
Body: strings.NewReader(`{
"name":"new",
"type":"view",
"fields":[{"type":"text","id":"12345789","name":"ignored!@#$"}],
"viewQuery":"invalid"
}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"viewQuery":{"code":"validation_invalid_view_query`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionCreateRequest": 1,
"OnCollectionCreate": 1,
"OnCollectionAfterCreateError": 1,
"OnCollectionValidate": 1,
"OnModelCreate": 1,
"OnModelAfterCreateError": 1,
"OnModelValidate": 1,
},
},
{
Name: "creating view collection",
Method: http.MethodPost,
URL: "/api/collections",
Body: strings.NewReader(`{
"name":"new",
"type":"view",
"fields":[{"type":"text","id":"12345789","name":"ignored!@#$"}],
"viewQuery": "select 1 as id from ` + core.CollectionNameSuperusers + `"
}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"name":"new"`,
`"type":"view"`,
`"fields":[{"autogeneratePattern":"","hidden":false,"id":"text3208210256","max":0,"min":0,"name":"id","pattern":"^[a-z0-9]+$","presentable":false,"primaryKey":true,"required":true,"system":true,"type":"text"}]`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionCreateRequest": 1,
"OnCollectionCreate": 1,
"OnCollectionCreateExecute": 1,
"OnCollectionAfterCreateSuccess": 1,
"OnCollectionValidate": 1,
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnModelValidate": 1,
},
},
// indexes
// -----------------------------------------------------------
{
Name: "creating base collection with invalid indexes",
Method: http.MethodPost,
URL: "/api/collections",
Body: strings.NewReader(`{
"name":"new",
"type":"base",
"fields":[
{"type":"text","name":"test"}
],
"indexes": [
"create index idx_test1 on new (test)",
"create index idx_test2 on new (missing)"
]
}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"indexes":{"1":{"code":"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionCreateRequest": 1,
"OnCollectionCreate": 1,
"OnCollectionCreateExecute": 1,
"OnCollectionAfterCreateError": 1,
"OnCollectionValidate": 1,
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateError": 1,
"OnModelValidate": 1,
},
},
{
Name: "creating base collection with index name from another collection",
Method: http.MethodPost,
URL: "/api/collections",
Body: strings.NewReader(`{
"name":"new",
"type":"base",
"fields":[
{"type":"text","name":"test"}
],
"indexes": [
"create index exist_test on new (test)"
]
}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
demo1, err := app.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
demo1.AddIndex("exist_test", false, "updated", "")
if err = app.Save(demo1); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"indexes":{`,
`"0":{"code":"validation_existing_index_name"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionCreateRequest": 1,
"OnCollectionCreate": 1,
"OnCollectionAfterCreateError": 1,
"OnCollectionValidate": 1,
"OnModelCreate": 1,
"OnModelAfterCreateError": 1,
"OnModelValidate": 1,
},
},
{
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | true |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/middlewares_gzip.go | apis/middlewares_gzip.go | package apis
// -------------------------------------------------------------------
// This middleware is ported from echo/middleware to minimize the breaking
// changes and differences in the API behavior from earlier PocketBase versions
// (https://github.com/labstack/echo/blob/ec5b858dab6105ab4c3ed2627d1ebdfb6ae1ecb8/middleware/compress.go).
// -------------------------------------------------------------------
import (
"bufio"
"bytes"
"compress/gzip"
"errors"
"io"
"net"
"net/http"
"strings"
"sync"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/router"
)
const (
gzipScheme = "gzip"
)
const (
DefaultGzipMiddlewareId = "pbGzip"
)
// GzipConfig defines the config for Gzip middleware.
type GzipConfig struct {
// Gzip compression level.
// Optional. Default value -1.
Level int
// Length threshold before gzip compression is applied.
// Optional. Default value 0.
//
// Most of the time you will not need to change the default. Compressing
// a short response might increase the transmitted data because of the
// gzip format overhead. Compressing the response will also consume CPU
// and time on the server and the client (for decompressing). Depending on
// your use case such a threshold might be useful.
//
// See also:
// https://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits
MinLength int
}
// Gzip returns a middleware which compresses HTTP response using Gzip compression scheme.
func Gzip() *hook.Handler[*core.RequestEvent] {
return GzipWithConfig(GzipConfig{})
}
// GzipWithConfig returns a middleware which compresses HTTP response using gzip compression scheme.
func GzipWithConfig(config GzipConfig) *hook.Handler[*core.RequestEvent] {
if config.Level < -2 || config.Level > 9 { // these are consts: gzip.HuffmanOnly and gzip.BestCompression
panic(errors.New("invalid gzip level"))
}
if config.Level == 0 {
config.Level = -1
}
if config.MinLength < 0 {
config.MinLength = 0
}
pool := sync.Pool{
New: func() interface{} {
w, err := gzip.NewWriterLevel(io.Discard, config.Level)
if err != nil {
return err
}
return w
},
}
bpool := sync.Pool{
New: func() interface{} {
b := &bytes.Buffer{}
return b
},
}
return &hook.Handler[*core.RequestEvent]{
Id: DefaultGzipMiddlewareId,
Func: func(e *core.RequestEvent) error {
e.Response.Header().Add("Vary", "Accept-Encoding")
if strings.Contains(e.Request.Header.Get("Accept-Encoding"), gzipScheme) {
w, ok := pool.Get().(*gzip.Writer)
if !ok {
return e.InternalServerError("", errors.New("failed to get gzip.Writer"))
}
rw := e.Response
w.Reset(rw)
buf := bpool.Get().(*bytes.Buffer)
buf.Reset()
grw := &gzipResponseWriter{Writer: w, ResponseWriter: rw, minLength: config.MinLength, buffer: buf}
defer func() {
// There are different reasons for cases when we have not yet written response to the client and now need to do so.
// a) handler response had only response code and no response body (ala 404 or redirects etc). Response code need to be written now.
// b) body is shorter than our minimum length threshold and being buffered currently and needs to be written
if !grw.wroteBody {
if rw.Header().Get("Content-Encoding") == gzipScheme {
rw.Header().Del("Content-Encoding")
}
if grw.wroteHeader {
rw.WriteHeader(grw.code)
}
// We have to reset response to it's pristine state when
// nothing is written to body or error is returned.
// See issue echo#424, echo#407.
e.Response = rw
w.Reset(io.Discard)
} else if !grw.minLengthExceeded {
// Write uncompressed response
e.Response = rw
if grw.wroteHeader {
rw.WriteHeader(grw.code)
}
grw.buffer.WriteTo(rw)
w.Reset(io.Discard)
}
w.Close()
bpool.Put(buf)
pool.Put(w)
}()
e.Response = grw
}
return e.Next()
},
}
}
type gzipResponseWriter struct {
http.ResponseWriter
io.Writer
buffer *bytes.Buffer
minLength int
code int
wroteHeader bool
wroteBody bool
minLengthExceeded bool
}
func (w *gzipResponseWriter) WriteHeader(code int) {
w.Header().Del("Content-Length") // Issue echo#444
w.wroteHeader = true
// Delay writing of the header until we know if we'll actually compress the response
w.code = code
}
func (w *gzipResponseWriter) Write(b []byte) (int, error) {
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", http.DetectContentType(b))
}
w.wroteBody = true
if !w.minLengthExceeded {
n, err := w.buffer.Write(b)
if w.buffer.Len() >= w.minLength {
w.minLengthExceeded = true
// The minimum length is exceeded, add Content-Encoding header and write the header
w.Header().Set("Content-Encoding", gzipScheme)
if w.wroteHeader {
w.ResponseWriter.WriteHeader(w.code)
}
return w.Writer.Write(w.buffer.Bytes())
}
return n, err
}
return w.Writer.Write(b)
}
func (w *gzipResponseWriter) Flush() {
if !w.minLengthExceeded {
// Enforce compression because we will not know how much more data will come
w.minLengthExceeded = true
w.Header().Set("Content-Encoding", gzipScheme)
if w.wroteHeader {
w.ResponseWriter.WriteHeader(w.code)
}
_, _ = w.Writer.Write(w.buffer.Bytes())
}
_ = w.Writer.(*gzip.Writer).Flush()
_ = http.NewResponseController(w.ResponseWriter).Flush()
}
func (w *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return http.NewResponseController(w.ResponseWriter).Hijack()
}
func (w *gzipResponseWriter) Push(target string, opts *http.PushOptions) error {
rw := w.ResponseWriter
for {
switch p := rw.(type) {
case http.Pusher:
return p.Push(target, opts)
case router.RWUnwrapper:
rw = p.Unwrap()
default:
return http.ErrNotSupported
}
}
}
// Note: Disable the implementation for now because in case the platform
// supports the sendfile fast-path it won't run gzipResponseWriter.Write,
// preventing compression on the fly.
//
// func (w *gzipResponseWriter) ReadFrom(r io.Reader) (n int64, err error) {
// if w.wroteHeader {
// w.ResponseWriter.WriteHeader(w.code)
// }
// rw := w.ResponseWriter
// for {
// switch rf := rw.(type) {
// case io.ReaderFrom:
// return rf.ReadFrom(r)
// case router.RWUnwrapper:
// rw = rf.Unwrap()
// default:
// return io.Copy(w.ResponseWriter, r)
// }
// }
// }
func (w *gzipResponseWriter) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/record_auth_otp_request.go | apis/record_auth_otp_request.go | package apis
import (
"database/sql"
"errors"
"fmt"
"net/http"
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/tools/routine"
"github.com/pocketbase/pocketbase/tools/security"
)
func recordRequestOTP(e *core.RequestEvent) error {
collection, err := findAuthCollection(e)
if err != nil {
return err
}
if !collection.OTP.Enabled {
return e.ForbiddenError("The collection is not configured to allow OTP authentication.", nil)
}
form := &createOTPForm{}
if err = e.BindBody(form); err != nil {
return firstApiError(err, e.BadRequestError("An error occurred while loading the submitted data.", err))
}
if err = form.validate(); err != nil {
return firstApiError(err, e.BadRequestError("An error occurred while validating the submitted data.", err))
}
record, err := e.App.FindAuthRecordByEmail(collection, form.Email)
// ignore not found errors to allow custom record find implementations
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return e.InternalServerError("", err)
}
event := new(core.RecordCreateOTPRequestEvent)
event.RequestEvent = e
event.Password = security.RandomStringWithAlphabet(collection.OTP.Length, "1234567890")
event.Collection = collection
event.Record = record
originalApp := e.App
return e.App.OnRecordRequestOTPRequest().Trigger(event, func(e *core.RecordCreateOTPRequestEvent) error {
if e.Record == nil {
// write a dummy 200 response as a very rudimentary emails enumeration "protection"
e.JSON(http.StatusOK, map[string]string{
"otpId": core.GenerateDefaultRandomId(),
})
return fmt.Errorf("missing or invalid %s OTP auth record with email %s", collection.Name, form.Email)
}
var otp *core.OTP
// limit the new OTP creations for a single user
if !e.App.IsDev() {
otps, err := e.App.FindAllOTPsByRecord(e.Record)
if err != nil {
return firstApiError(err, e.InternalServerError("Failed to fetch previous record OTPs.", err))
}
totalRecent := 0
for _, existingOTP := range otps {
if !existingOTP.HasExpired(collection.OTP.DurationTime()) {
totalRecent++
}
// use the last issued one
if totalRecent > 9 {
otp = otps[0] // otps are DESC sorted
e.App.Logger().Warn(
"Too many OTP requests - reusing the last issued",
"email", form.Email,
"recordId", e.Record.Id,
"otpId", existingOTP.Id,
)
break
}
}
}
if otp == nil {
// create new OTP
// ---
otp = core.NewOTP(e.App)
otp.SetCollectionRef(e.Record.Collection().Id)
otp.SetRecordRef(e.Record.Id)
otp.SetPassword(e.Password)
err = e.App.Save(otp)
if err != nil {
return err
}
// send OTP email
// (in the background as a very basic timing attacks and emails enumeration protection)
// ---
routine.FireAndForget(func() {
err = mails.SendRecordOTP(originalApp, e.Record, otp.Id, e.Password)
if err != nil {
originalApp.Logger().Error("Failed to send OTP email", "error", errors.Join(err, originalApp.Delete(otp)))
}
})
}
return execAfterSuccessTx(true, e.App, func() error {
return e.JSON(http.StatusOK, map[string]string{"otpId": otp.Id})
})
})
}
// -------------------------------------------------------------------
type createOTPForm struct {
Email string `form:"email" json:"email"`
}
func (form createOTPForm) validate() error {
return validation.ValidateStruct(&form,
validation.Field(&form.Email, validation.Required, validation.Length(1, 255), is.EmailFormat),
)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/middlewares_body_limit.go | apis/middlewares_body_limit.go | package apis
import (
"io"
"net/http"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/router"
)
var ErrRequestEntityTooLarge = router.NewApiError(http.StatusRequestEntityTooLarge, "Request entity too large", nil)
const DefaultMaxBodySize int64 = 32 << 20
const (
DefaultBodyLimitMiddlewareId = "pbBodyLimit"
DefaultBodyLimitMiddlewarePriority = DefaultRateLimitMiddlewarePriority + 10
)
// BodyLimit returns a middleware handler that changes the default request body size limit.
//
// If limitBytes <= 0, no limit is applied.
//
// Otherwise, if the request body size exceeds the configured limitBytes,
// it sends 413 error response.
func BodyLimit(limitBytes int64) *hook.Handler[*core.RequestEvent] {
return &hook.Handler[*core.RequestEvent]{
Id: DefaultBodyLimitMiddlewareId,
Priority: DefaultBodyLimitMiddlewarePriority,
Func: func(e *core.RequestEvent) error {
err := applyBodyLimit(e, limitBytes)
if err != nil {
return err
}
return e.Next()
},
}
}
func dynamicCollectionBodyLimit(collectionPathParam string) *hook.Handler[*core.RequestEvent] {
if collectionPathParam == "" {
collectionPathParam = "collection"
}
return &hook.Handler[*core.RequestEvent]{
Id: DefaultBodyLimitMiddlewareId,
Priority: DefaultBodyLimitMiddlewarePriority,
Func: func(e *core.RequestEvent) error {
collection, err := e.App.FindCachedCollectionByNameOrId(e.Request.PathValue(collectionPathParam))
if err != nil {
return e.NotFoundError("Missing or invalid collection context.", err)
}
limitBytes := DefaultMaxBodySize
if !collection.IsView() {
for _, f := range collection.Fields {
if calc, ok := f.(core.MaxBodySizeCalculator); ok {
limitBytes += calc.CalculateMaxBodySize()
}
}
}
err = applyBodyLimit(e, limitBytes)
if err != nil {
return err
}
return e.Next()
},
}
}
func applyBodyLimit(e *core.RequestEvent, limitBytes int64) error {
// no limit
if limitBytes <= 0 {
return nil
}
// optimistically check the submitted request content length
if e.Request.ContentLength > limitBytes {
return ErrRequestEntityTooLarge
}
// replace the request body
//
// note: we don't use sync.Pool since the size of the elements could vary too much
// and it might not be efficient (see https://github.com/golang/go/issues/23199)
e.Request.Body = &limitedReader{ReadCloser: e.Request.Body, limit: limitBytes}
return nil
}
type limitedReader struct {
io.ReadCloser
limit int64
totalRead int64
}
func (r *limitedReader) Read(b []byte) (int, error) {
n, err := r.ReadCloser.Read(b)
if err != nil {
return n, err
}
r.totalRead += int64(n)
if r.totalRead > r.limit {
return n, ErrRequestEntityTooLarge
}
return n, nil
}
func (r *limitedReader) Reread() {
rr, ok := r.ReadCloser.(router.Rereader)
if ok {
rr.Reread()
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/apis/record_auth_with_password.go | apis/record_auth_with_password.go | package apis
import (
"database/sql"
"errors"
"slices"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/dbutils"
"github.com/pocketbase/pocketbase/tools/list"
)
func recordAuthWithPassword(e *core.RequestEvent) error {
collection, err := findAuthCollection(e)
if err != nil {
return err
}
if !collection.PasswordAuth.Enabled {
return e.ForbiddenError("The collection is not configured to allow password authentication.", nil)
}
form := &authWithPasswordForm{}
if err = e.BindBody(form); err != nil {
return firstApiError(err, e.BadRequestError("An error occurred while loading the submitted data.", err))
}
if err = form.validate(collection); err != nil {
return firstApiError(err, e.BadRequestError("An error occurred while validating the submitted data.", err))
}
e.Set(core.RequestEventKeyInfoContext, core.RequestInfoContextPasswordAuth)
var foundRecord *core.Record
var foundErr error
if form.IdentityField != "" {
foundRecord, foundErr = findRecordByIdentityField(e.App, collection, form.IdentityField, form.Identity)
} else {
identityFields := collection.PasswordAuth.IdentityFields
// @todo consider removing with the stable release or moving it in the collection save
//
// prioritize email lookup to minimize breaking changes with earlier versions
if len(identityFields) > 1 && identityFields[0] != core.FieldNameEmail {
identityFields = slices.Clone(identityFields)
slices.SortStableFunc(identityFields, func(a, b string) int {
if a == "email" {
return -1
}
if b == "email" {
return 1
}
return 0
})
}
for _, name := range identityFields {
if name == core.FieldNameEmail && is.EmailFormat.Validate(form.Identity) != nil {
continue // no need to query the database if we know that the submitted value is not an email
}
foundRecord, foundErr = findRecordByIdentityField(e.App, collection, name, form.Identity)
if foundErr == nil {
break
}
}
}
// ignore not found errors to allow custom record find implementations
if foundErr != nil && !errors.Is(foundErr, sql.ErrNoRows) {
return e.InternalServerError("", foundErr)
}
event := new(core.RecordAuthWithPasswordRequestEvent)
event.RequestEvent = e
event.Collection = collection
event.Record = foundRecord
event.Identity = form.Identity
event.Password = form.Password
event.IdentityField = form.IdentityField
return e.App.OnRecordAuthWithPasswordRequest().Trigger(event, func(e *core.RecordAuthWithPasswordRequestEvent) error {
if e.Record == nil || !e.Record.ValidatePassword(e.Password) {
return e.BadRequestError("Failed to authenticate.", errors.New("invalid login credentials"))
}
return RecordAuthResponse(e.RequestEvent, e.Record, core.MFAMethodPassword, nil)
})
}
// -------------------------------------------------------------------
type authWithPasswordForm struct {
Identity string `form:"identity" json:"identity"`
Password string `form:"password" json:"password"`
// IdentityField specifies the field to use to search for the identity
// (leave it empty for "auto" detection).
IdentityField string `form:"identityField" json:"identityField"`
}
func (form *authWithPasswordForm) validate(collection *core.Collection) error {
return validation.ValidateStruct(form,
validation.Field(&form.Identity, validation.Required, validation.Length(1, 255)),
validation.Field(&form.Password, validation.Required, validation.Length(1, 255)),
validation.Field(
&form.IdentityField,
validation.Length(1, 255),
validation.In(list.ToInterfaceSlice(collection.PasswordAuth.IdentityFields)...),
),
)
}
func findRecordByIdentityField(app core.App, collection *core.Collection, field string, value any) (*core.Record, error) {
if !slices.Contains(collection.PasswordAuth.IdentityFields, field) {
return nil, errors.New("invalid identity field " + field)
}
index, ok := dbutils.FindSingleColumnUniqueIndex(collection.Indexes, field)
if !ok {
return nil, errors.New("missing " + field + " unique index constraint")
}
var expr dbx.Expression
if strings.EqualFold(index.Columns[0].Collate, "nocase") {
// case-insensitive search
expr = dbx.NewExp("[["+field+"]] = {:identity} COLLATE NOCASE", dbx.Params{"identity": value})
} else {
expr = dbx.HashExp{field: value}
}
record := &core.Record{}
err := app.RecordQuery(collection).AndWhere(expr).Limit(1).One(record)
if err != nil {
return nil, err
}
return record, nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.