package core
import (
"context"
"errors"
"fmt"
"time"
"ganigeorgiev.com/pocketbase/pocketbase/tools/hook"
"ganigeorgiev.com/pocketbase/pocketbase/tools/types"
)
const CollectionNameOTPs = "_otps"
var (
_ Model = (*OTP)(nil)
_ PreValidator = (*OTP)(nil)
_ RecordProxy = (*OTP)(nil)
)
type OTP struct {
*Record
}
func NewOTP(app App) *OTP {
m := &OTP{}
c, err := app.FindCachedCollectionByNameOrId(CollectionNameOTPs)
if err != nil {
c = NewBaseCollection("__invalid__")
}
m.Record = NewRecord(c)
return m
}
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
}
func (m *OTP) ProxyRecord() *Record {
return m.Record
}
func (m *OTP) SetProxyRecord(record *Record) {
m.Record = record
}
func (m *OTP) CollectionRef() string {
return m.GetString("collectionRef")
}
func (m *OTP) SetCollectionRef(collectionId string) {
m.Set("collectionRef", collectionId)
}
func (m *OTP) RecordRef() string {
return m.GetString("recordRef")
}
func (m *OTP) SetRecordRef(recordId string) {
m.Set("recordRef", recordId)
}
func (m *OTP) SentTo() string {
return m.GetString("sentTo")
}
func (m *OTP) SetSentTo(val string) {
m.Set("sentTo", val)
}
func (m *OTP) Created() types.DateTime {
return m.GetDateTime("created")
}
func (m *OTP) Updated() types.DateTime {
return m.GetDateTime("updated")
}
func (m *OTP) HasExpired(maxElapsed time.Duration) bool {
return time.Since(m.Created().Time()) > maxElapsed
}
func (app *BaseApp) registerOTPHooks() {
recordRefHooks[*OTP](app, CollectionNameOTPs, CollectionTypeAuth)
app.Cron().Add("__pbOTPCleanup__", "0 * * * *", func() {
if err := app.DeleteExpiredOTPs(); err != nil {
app.Logger().Warn("Failed to delete expired OTP sessions", "error", err)
}
})
app.OnRecordUpdateExecute().Bind(&hook.Handler[*RecordEvent]{
Func: func(e *RecordEvent) error {
err := e.Next()
if err != nil || !e.Record.Collection().IsAuth() {
return err
}
if !e.Record.Original().IsNew() && e.Record.Original().TokenKey() != e.Record.TokenKey() {
err := e.App.DeleteAllOTPsByRecord(e.Record)
if err != nil {
return fmt.Errorf(
"[%s] failed to delete all previous OTPs for record %q: %w",
e.Record.Collection().Name,
e.Record.Id,
err,
)
}
}
return nil
},
Priority: 99,
})
}