initial v0.8 pre-release
This commit is contained in:
@@ -2,11 +2,8 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/pocketbase/pocketbase/tools/security"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -103,6 +100,9 @@ func (m *BaseModel) GetUpdated() types.DateTime {
|
||||
//
|
||||
// The generated id is a cryptographically random 15 characters length string.
|
||||
func (m *BaseModel) RefreshId() {
|
||||
if m.Id == "" { // no previous id
|
||||
m.MarkAsNew()
|
||||
}
|
||||
m.Id = security.RandomStringWithAlphabet(DefaultIdLength, DefaultIdAlphabet)
|
||||
}
|
||||
|
||||
@@ -115,57 +115,3 @@ func (m *BaseModel) RefreshCreated() {
|
||||
func (m *BaseModel) RefreshUpdated() {
|
||||
m.Updated = types.NowDateTime()
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// BaseAccount
|
||||
// -------------------------------------------------------------------
|
||||
|
||||
// BaseAccount defines common fields and methods used by auth models (aka. users and admins).
|
||||
type BaseAccount struct {
|
||||
BaseModel
|
||||
|
||||
Email string `db:"email" json:"email"`
|
||||
TokenKey string `db:"tokenKey" json:"-"`
|
||||
PasswordHash string `db:"passwordHash" json:"-"`
|
||||
LastResetSentAt types.DateTime `db:"lastResetSentAt" json:"lastResetSentAt"`
|
||||
}
|
||||
|
||||
// ValidatePassword validates a plain password against the model's password.
|
||||
func (m *BaseAccount) ValidatePassword(password string) bool {
|
||||
bytePassword := []byte(password)
|
||||
bytePasswordHash := []byte(m.PasswordHash)
|
||||
|
||||
// comparing the password with the hash
|
||||
err := bcrypt.CompareHashAndPassword(bytePasswordHash, bytePassword)
|
||||
|
||||
// nil means it is a match
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// SetPassword sets cryptographically secure string to `model.Password`.
|
||||
//
|
||||
// Additionally this method also resets the LastResetSentAt and the TokenKey fields.
|
||||
func (m *BaseAccount) SetPassword(password string) error {
|
||||
if password == "" {
|
||||
return errors.New("The provided plain password is empty")
|
||||
}
|
||||
|
||||
// hash the password
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 13)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
m.PasswordHash = string(hashedPassword)
|
||||
m.LastResetSentAt = types.DateTime{} // reset
|
||||
|
||||
// invalidate previously issued tokens
|
||||
m.RefreshTokenKey()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// RefreshTokenKey generates and sets new random token key.
|
||||
func (m *BaseAccount) RefreshTokenKey() {
|
||||
m.TokenKey = security.RandomString(50)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user