app/auth/user.go

74 lines
1.5 KiB
Go

package auth
import (
"time"
"github.com/rs/xid"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
// User User model
type User struct {
ID string `gorm:"primaryKey"`
Username string `gorm:"unique;not null"`
Password string `json:"-"`
SSOEnabled bool
SSOTok string
Activated bool
LastLogin time.Time
LastLoginIP string
LoginFailed int
Groups []*Group `gorm:"many2many:user_groups;"`
Profile Profile
CreatedAt time.Time
UpdatedAt time.Time
}
// Profile user extended information
type Profile struct {
ID uint `gorm:"primaryKey"`
UserID string
DisplayName string
Email string
CreatedAt time.Time
UpdatedAt time.Time
}
// BeforeCreate set UID
func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
if u.ID == "" {
u.ID = xid.New().String()
}
// u.Activated = true
u.LastLogin = time.Now()
u.LoginFailed = 0
return
}
// ChangePassword Change user password to *to*, return nil if success.
func (usr *User) ChangePassword(db *gorm.DB, to string) (err error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(to), 14)
if err != nil {
return err
}
err = db.Transaction(func(tx *gorm.DB) error {
return tx.Model(usr).Update("password", string(bytes)).Error
})
if err != nil {
l.Error().Err(err).Msg("ChangePassword")
}
return err
}
// ValidatePassword validates user pass word ,return nil if correct.
func (usr *User) ValidatePassword(pwd string) error {
return bcrypt.CompareHashAndPassword([]byte(usr.Password), []byte(pwd))
}