usermngmt/cache/role.go

77 lines
1.6 KiB
Go
Raw Permalink Normal View History

2021-11-11 08:16:17 +00:00
package cache
import (
"context"
"encoding/json"
"sync"
2022-10-10 03:46:33 +00:00
"git.selly.red/Selly-Modules/logger"
"git.selly.red/Selly-Modules/usermngmt/model"
2021-11-11 08:16:17 +00:00
"go.mongodb.org/mongo-driver/bson"
)
// Roles ...
func Roles() {
var (
ctx = context.Background()
wg sync.WaitGroup
cond = bson.M{}
)
// Find
roles := roleFindByCondition(ctx, cond)
permissions := permissionFindByCondition(ctx, cond)
wg.Add(len(roles))
for _, value := range roles {
go func(role model.DBRole) {
defer wg.Done()
rolePermissions := make([]string, 0)
// Get role permissions
for _, permission := range permissions {
if permission.RoleID == role.ID {
rolePermissions = append(rolePermissions, permission.Code)
}
}
// Cache Role
2021-12-08 04:42:31 +00:00
entry := CachedRole{
2021-11-11 08:16:17 +00:00
Role: role.Code,
IsAdmin: role.IsAdmin,
Permissions: rolePermissions,
2021-12-08 04:42:31 +00:00
}
if err := SetKeyValue(role.ID.Hex(), entry, 0); err != nil {
2021-11-11 08:16:17 +00:00
logger.Error("usermngmt - CacheRole", logger.LogData{
2022-10-06 02:14:45 +00:00
Source: "usermngmt.cache.Roles",
Message: err.Error(),
Data: entry,
2021-11-11 08:16:17 +00:00
})
return
}
}(value)
}
wg.Wait()
return
}
// GetCachedRole ...
func GetCachedRole(key string) CachedRole {
2021-12-08 04:42:31 +00:00
value, err := GetValueByKey(key)
2021-11-11 08:16:17 +00:00
if err != nil {
Roles()
2021-12-08 04:42:31 +00:00
value, _ = GetValueByKey(key)
2021-11-11 08:16:17 +00:00
}
2021-12-08 04:42:31 +00:00
// Unmarshal data
2021-11-11 08:16:17 +00:00
var cachedRole CachedRole
2021-12-08 04:42:31 +00:00
if err := json.Unmarshal(value, &cachedRole); err != nil {
2021-11-11 08:16:17 +00:00
logger.Error("usermngmt - GetCachedRole - Unmarshal", logger.LogData{
2022-10-06 02:14:45 +00:00
Source: "usermngmt.cache.GetCachedRole",
Message: err.Error(),
Data: cachedRole,
2021-11-11 08:16:17 +00:00
})
}
return cachedRole
}