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.
69 lines
1.7 KiB
69 lines
1.7 KiB
package models
|
|
|
|
import (
|
|
"database/sql"
|
|
"time"
|
|
|
|
"git.devices.local/mawas/golang-api-skeleton/lib/cache"
|
|
"git.devices.local/mawas/golang-api-skeleton/lib/common"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// Token data model
|
|
type Token struct {
|
|
common.BasicFields
|
|
Token common.GUID `gorm:"primaryKey" json:"token"`
|
|
LastUsedDB sql.NullTime `gorm:"column:last_used" json:"-"`
|
|
LastUsedJSON *time.Time `gorm:"-" json:"last_used,omitempty"`
|
|
ExpiresAt time.Time `json:"expires_at"`
|
|
UserID common.GUID `json:"-"`
|
|
Username string `gorm:"-" json:"username"`
|
|
Active bool `json:"active"`
|
|
}
|
|
|
|
func (token *Token) BeforeCreate(tx *gorm.DB) error {
|
|
id, err := common.NewGUID()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
token.Token = id
|
|
if userID, ok := tx.Get("userID"); ok {
|
|
if guidString, ok := userID.(string); ok {
|
|
guid, err := common.StringToGUID(guidString)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
token.CreatedByDB = guid
|
|
token.UpdatedByDB = guid
|
|
}
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (token *Token) AfterFind(tx *gorm.DB) error {
|
|
if token.LastUsedDB.Valid {
|
|
token.LastUsedJSON = &token.LastUsedDB.Time
|
|
}
|
|
if token.DeletedAtDB.Valid {
|
|
token.DeletedAtJSON = &token.DeletedAtDB.Time
|
|
}
|
|
if cc, ok := tx.Get("cache"); ok {
|
|
if c, ok := cc.(cache.Cache); ok {
|
|
if username, err := c.Get("user:" + token.CreatedByDB.String()); err != nil {
|
|
return err
|
|
} else if username != nil {
|
|
token.CreatedByJSON = *username
|
|
}
|
|
if username, err := c.Get("user:" + token.UpdatedByDB.String()); err != nil {
|
|
return err
|
|
} else if username != nil {
|
|
token.UpdatedByJSON = *username
|
|
}
|
|
if username, err := c.Get("user:" + token.UserID.String()); err != nil {
|
|
} else if username != nil {
|
|
token.Username = *username
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|