95 lines
2.0 KiB
Go
95 lines
2.0 KiB
Go
package utils
|
|
|
|
import (
|
|
"fmt"
|
|
"math/rand/v2"
|
|
"strings"
|
|
"time"
|
|
"yintai-api/app/common/cache"
|
|
"yintai-api/app/common/dao"
|
|
"yintai-api/app/common/model"
|
|
"yintai-api/base/config"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
"github.com/spf13/cast"
|
|
)
|
|
|
|
func Distinct[T comparable](params []T) []T {
|
|
seed := make(map[T]struct{})
|
|
res := make([]T, 0, len(params))
|
|
for _, param := range params {
|
|
if _, ok := seed[param]; ok {
|
|
continue
|
|
}
|
|
res = append(res, param)
|
|
}
|
|
|
|
return res
|
|
}
|
|
|
|
func SourceFormat(method, urls string) string {
|
|
member := fmt.Sprintf("%s_%s", method, urls)
|
|
member = strings.TrimRight(member, "/")
|
|
member = strings.Replace(member, "/", "_", -1)
|
|
return member
|
|
}
|
|
|
|
func PermissionInit() {
|
|
roles, _, err := dao.NewRole().List("", "", 1, 999999, "")
|
|
if err != nil {
|
|
panic(config.ErrDb.New())
|
|
}
|
|
|
|
for _, role := range roles {
|
|
if err = LazyLoadPermission(role.ID); err != nil {
|
|
panic(config.ErrDb.New().Append("init permission err:" + err.Error()))
|
|
}
|
|
}
|
|
}
|
|
|
|
// LazyLoadPermission 只有当角色的权限发生变化时,才需要。
|
|
// 比如新增,修改,删除
|
|
func LazyLoadPermission(roleID int64) error {
|
|
resources, err := dao.NewResource().RoleGet(roleID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
res := make([]string, 0)
|
|
for _, resource := range resources {
|
|
if resource.Type != model.ResourceTypeApi {
|
|
continue
|
|
}
|
|
res = append(res, SourceFormat(resource.Method, resource.Path))
|
|
}
|
|
|
|
redix := cache.GetRedis()
|
|
key := cache.NewKeys().Api(roleID)
|
|
if len(res) == 0 {
|
|
res = append(res, " ")
|
|
}
|
|
return redix.SAdd(key, res).Err()
|
|
}
|
|
|
|
func AutoIncrementNews() {
|
|
ticker := time.NewTicker(time.Hour * 18)
|
|
defer ticker.Stop()
|
|
run := func() {
|
|
all, err := dao.NewNews().PureAll()
|
|
if err != nil {
|
|
log.Errorf("auto increment news: query failed: %v", err)
|
|
return
|
|
}
|
|
|
|
for _, v := range all {
|
|
if err := dao.NewNews().Incr(cast.ToInt64(v.ID), rand.IntN(9)+1); err != nil {
|
|
log.Errorf("auto increment news: incr news id=%v failed: %v", v.ID, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
for range ticker.C {
|
|
run()
|
|
}
|
|
}
|