You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

68 lines
1.8 KiB

package models
import (
"git.devices.local/mawas/golang-api-skeleton/lib/cache"
"git.devices.local/mawas/golang-api-skeleton/lib/common"
"gorm.io/gorm"
)
// User data model
type User struct {
common.ModelHiddenGUIDPK
Username string `gorm:"unique_index:username" json:"username,omitempty"`
Firstname string `json:"firstname,omitempty"`
Lastname string `json:"lastname,omitempty"`
Email string `json:"email,omitempty"`
TokensRef []Token `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"-"`
Tokens []string `gorm:"-" json:"tokens"`
PasswordHash string `json:"-"`
Active bool `json:"active"`
}
func (user *User) AfterCreate(tx *gorm.DB) error {
if username, ok := tx.Get("username"); ok {
if name, ok := username.(string); ok {
user.CreatedByJSON = name
user.UpdatedByJSON = name
}
}
user.Tokens = []string{}
return nil
}
func (user *User) AfterFind(tx *gorm.DB) error {
if user.DeletedAtDB.Valid {
user.DeletedAtJSON = &user.DeletedAtDB.Time
}
user.Tokens = []string{}
for i := range user.TokensRef {
user.Tokens = append(user.Tokens, user.TokensRef[i].Token.String())
}
if cc, ok := tx.Get("cache"); ok {
if c, ok := cc.(cache.Cache); ok {
if username, err := c.Get("user:" + user.CreatedByDB.String()); err != nil {
return err
} else if username != nil {
user.CreatedByJSON = *username
}
if username, err := c.Get("user:" + user.UpdatedByDB.String()); err != nil {
return err
} else if username != nil {
user.UpdatedByJSON = *username
}
}
}
return nil
}
// func (user *User) BeforeCreate(tx *gorm.DB) error {
// // ctx := tx.Statement.Context
// // username := ctx.Value("username")
// // switch v := username.(type) {
// // case nil:
// // case string:
// // user.CreatedBy = v
// // }
// //
// return nil
// }