app/auth/user.go

73 lines
1.5 KiB
Go
Raw Permalink Normal View History

2021-12-16 04:11:33 +00:00
package auth
import (
"time"
"github.com/rs/xid"
"github.com/rs/zerolog/log"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
//User User model
type User struct {
ID string `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
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
}
// Profile user extended information
type Profile struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
UserID string
DisplayName string
Email string
}
// 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 {
log.Error().Str("mod", "auth").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))
}