2021-12-16 04:11:33 +00:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/rs/xid"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
)
|
|
|
|
|
|
|
|
//User User model
|
|
|
|
type User struct {
|
2021-12-19 06:17:10 +00:00
|
|
|
ID string `gorm:"primaryKey"`
|
2021-12-16 04:11:33 +00:00
|
|
|
|
|
|
|
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
|
2021-12-19 06:17:10 +00:00
|
|
|
|
|
|
|
CreatedAt time.Time
|
|
|
|
UpdatedAt time.Time
|
2021-12-16 04:11:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Profile user extended information
|
|
|
|
type Profile struct {
|
2021-12-19 06:17:10 +00:00
|
|
|
ID uint `gorm:"primaryKey"`
|
|
|
|
UserID string
|
2021-12-16 04:11:33 +00:00
|
|
|
|
|
|
|
DisplayName string
|
|
|
|
Email string
|
2021-12-19 06:17:10 +00:00
|
|
|
|
|
|
|
CreatedAt time.Time
|
|
|
|
UpdatedAt time.Time
|
2021-12-16 04:11:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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 {
|
2021-12-20 02:23:08 +00:00
|
|
|
l.Error().Err(err).Msg("ChangePassword")
|
2021-12-16 04:11:33 +00:00
|
|
|
}
|
|
|
|
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))
|
|
|
|
}
|