feat: implement new structure
This commit is contained in:
37
models/users.go
Normal file
37
models/users.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"quyun/v2/pkg/consts"
|
||||
|
||||
"github.com/samber/lo"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func (m *User) ComparePassword(ctx context.Context, password string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(m.Password), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (m *User) HasRole(ctx context.Context, role consts.Role) bool {
|
||||
// m.Roles is types.Array[string] (aliased from text[]), so we need to cast/check manually if lo.Contains fails on type match
|
||||
// or cast role to string.
|
||||
// Error said: m.Roles is types.Array[string].
|
||||
// lo.Contains expects []T, val T.
|
||||
// If m.Roles is []string, and role is consts.Role (string), it fails.
|
||||
// We should cast m.Roles to []string (it likely already is) and role to string.
|
||||
return lo.Contains([]string(m.Roles), string(role))
|
||||
}
|
||||
|
||||
// BeforeCreate
|
||||
func (m *User) BeforeCreate(tx *gorm.DB) error {
|
||||
bytes, err := bcrypt.GenerateFromPassword([]byte(m.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m.Password = string(bytes)
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user