usermngmt/cache/role.go

78 lines
1.6 KiB
Go
Raw Normal View History

2021-11-11 08:16:17 +00:00
package cache
import (
"context"
"encoding/json"
2021-12-07 07:28:52 +00:00
"log"
2021-11-11 08:16:17 +00:00
"sync"
"github.com/Selly-Modules/logger"
"github.com/Selly-Modules/usermngmt/model"
"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
entry, _ := json.Marshal(CachedRole{
Role: role.Code,
IsAdmin: role.IsAdmin,
Permissions: rolePermissions,
})
2021-11-11 09:58:44 +00:00
if err := mc.Set(role.ID.Hex(), entry); err != nil {
2021-11-11 08:16:17 +00:00
logger.Error("usermngmt - CacheRole", logger.LogData{
"err": err.Error(),
})
return
}
2021-12-07 11:18:44 +00:00
log.Println("set role", CachedRole{
2021-12-07 09:45:38 +00:00
Role: role.Code,
IsAdmin: role.IsAdmin,
Permissions: rolePermissions,
2021-12-07 11:18:44 +00:00
}) // TODO remove
2021-11-11 08:16:17 +00:00
}(value)
}
wg.Wait()
return
}
// GetCachedRole ...
func GetCachedRole(key string) CachedRole {
2021-11-11 09:58:44 +00:00
entry, err := mc.Get(key)
2021-11-11 08:16:17 +00:00
if err != nil {
Roles()
2021-11-11 09:58:44 +00:00
entry, _ = mc.Get(key)
2021-11-11 08:16:17 +00:00
}
var cachedRole CachedRole
if err = json.Unmarshal(entry, &cachedRole); err != nil {
logger.Error("usermngmt - GetCachedRole - Unmarshal", logger.LogData{
"err": err.Error(),
})
}
2021-12-07 11:18:44 +00:00
log.Println("get role", cachedRole) // TODO remove
2021-11-11 08:16:17 +00:00
return cachedRole
}