pocketbase/forms/admin_login.go

65 lines
1.7 KiB
Go
Raw Normal View History

2022-07-07 05:19:05 +08:00
package forms
import (
"errors"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core"
2022-08-07 16:14:49 +08:00
"github.com/pocketbase/pocketbase/daos"
2022-07-07 05:19:05 +08:00
"github.com/pocketbase/pocketbase/models"
)
2022-10-30 16:28:14 +08:00
// AdminLogin is an admin email/pass login form.
2022-07-07 05:19:05 +08:00
type AdminLogin struct {
2022-10-30 16:28:14 +08:00
app core.App
dao *daos.Dao
2022-07-07 05:19:05 +08:00
2022-10-30 16:28:14 +08:00
Identity string `form:"identity" json:"identity"`
2022-07-07 05:19:05 +08:00
Password string `form:"password" json:"password"`
}
2022-10-30 16:28:14 +08:00
// NewAdminLogin creates a new [AdminLogin] form initialized with
// the provided [core.App] instance.
2022-08-07 16:14:49 +08:00
//
2022-10-30 16:28:14 +08:00
// If you want to submit the form as part of a transaction,
// you can change the default Dao via [SetDao()].
2022-07-07 05:19:05 +08:00
func NewAdminLogin(app core.App) *AdminLogin {
2022-10-30 16:28:14 +08:00
return &AdminLogin{
app: app,
dao: app.Dao(),
2022-08-07 16:14:49 +08:00
}
2022-10-30 16:28:14 +08:00
}
2022-08-07 16:14:49 +08:00
2022-10-30 16:28:14 +08:00
// SetDao replaces the default form Dao instance with the provided one.
func (form *AdminLogin) SetDao(dao *daos.Dao) {
form.dao = dao
2022-07-07 05:19:05 +08:00
}
// Validate makes the form validatable by implementing [validation.Validatable] interface.
func (form *AdminLogin) Validate() error {
return validation.ValidateStruct(form,
2022-10-30 16:28:14 +08:00
validation.Field(&form.Identity, validation.Required, validation.Length(1, 255), is.EmailFormat),
2022-07-07 05:19:05 +08:00
validation.Field(&form.Password, validation.Required, validation.Length(1, 255)),
)
}
// Submit validates and submits the admin form.
// On success returns the authorized admin model.
func (form *AdminLogin) Submit() (*models.Admin, error) {
if err := form.Validate(); err != nil {
return nil, err
}
2022-10-30 16:28:14 +08:00
admin, err := form.dao.FindAdminByEmail(form.Identity)
2022-07-07 05:19:05 +08:00
if err != nil {
return nil, err
}
if admin.ValidatePassword(form.Password) {
return admin, nil
}
return nil, errors.New("Invalid login credentials.")
}