github.com/dhax/go-base@v0.0.0-20231004214136-8be7e5c1972b/auth/pwdless/account.go (about) 1 package pwdless 2 3 import ( 4 "strings" 5 "time" 6 7 validation "github.com/go-ozzo/ozzo-validation" 8 "github.com/go-ozzo/ozzo-validation/is" 9 "github.com/go-pg/pg/orm" 10 11 "github.com/dhax/go-base/auth/jwt" 12 ) 13 14 // Account represents an authenticated application user 15 type Account struct { 16 ID int `json:"id"` 17 CreatedAt time.Time `json:"created_at,omitempty"` 18 UpdatedAt time.Time `json:"updated_at,omitempty"` 19 LastLogin time.Time `json:"last_login,omitempty"` 20 21 Email string `json:"email"` 22 Name string `json:"name"` 23 Active bool `sql:",notnull" json:"active"` 24 Roles []string `pg:",array" json:"roles,omitempty"` 25 26 Token []jwt.Token `json:"token,omitempty"` 27 } 28 29 // BeforeInsert hook executed before database insert operation. 30 func (a *Account) BeforeInsert(db orm.DB) error { 31 now := time.Now() 32 if a.CreatedAt.IsZero() { 33 a.CreatedAt = now 34 a.UpdatedAt = now 35 } 36 return a.Validate() 37 } 38 39 // BeforeUpdate hook executed before database update operation. 40 func (a *Account) BeforeUpdate(db orm.DB) error { 41 a.UpdatedAt = time.Now() 42 return a.Validate() 43 } 44 45 // BeforeDelete hook executed before database delete operation. 46 func (a *Account) BeforeDelete(db orm.DB) error { 47 return nil 48 } 49 50 // Validate validates Account struct and returns validation errors. 51 func (a *Account) Validate() error { 52 a.Email = strings.TrimSpace(a.Email) 53 a.Email = strings.ToLower(a.Email) 54 a.Name = strings.TrimSpace(a.Name) 55 56 return validation.ValidateStruct(a, 57 validation.Field(&a.Email, validation.Required, is.Email, is.LowerCase), 58 validation.Field(&a.Name, validation.Required, is.ASCII), 59 ) 60 } 61 62 // CanLogin returns true if user is allowed to login. 63 func (a *Account) CanLogin() bool { 64 return a.Active 65 } 66 67 // Claims returns the account's claims to be signed 68 func (a *Account) Claims() jwt.AppClaims { 69 return jwt.AppClaims{ 70 ID: a.ID, 71 Sub: a.Name, 72 Roles: a.Roles, 73 } 74 }