v2
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
package convertor
|
||||
|
||||
import "strconv"
|
||||
import (
|
||||
"net/url"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func ConvertInt[T int | int16 | int32 | int64](value string, defaultValue T) T {
|
||||
i, err := strconv.Atoi(value)
|
||||
@@ -9,3 +12,17 @@ func ConvertInt[T int | int16 | int32 | int64](value string, defaultValue T) T {
|
||||
}
|
||||
return T(i)
|
||||
}
|
||||
|
||||
func QueryInt[T int | int16 | int32 | int64](vars url.Values, key string, defaultValue T) T {
|
||||
v := vars.Get(key)
|
||||
if len(v) == 0 {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
i, err := strconv.Atoi(v)
|
||||
if err != nil {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
return T(i)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,27 @@ import (
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func New(prod bool) {
|
||||
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||
logRotate := &lumberjack.Logger{
|
||||
Filename: "./log/run.log", // 日志文件的位置
|
||||
MaxSize: 10, // 在进行切割之前,日志文件的最大大小(以MB为单位)
|
||||
MaxBackups: 100, // 保留旧文件的最大个数
|
||||
MaxAge: 30, // 保留旧文件的最大天数
|
||||
Compress: true,
|
||||
}
|
||||
zerolog.TimeFieldFormat = time.DateTime
|
||||
log.Logger = log.With().Caller().Logger()
|
||||
|
||||
if prod {
|
||||
log.Logger = log.Output(logRotate)
|
||||
} else {
|
||||
consoleWriter := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.DateTime}
|
||||
multi := zerolog.MultiLevelWriter(consoleWriter, logRotate)
|
||||
log.Logger = log.Output(multi)
|
||||
}
|
||||
}
|
||||
|
||||
func Init() {
|
||||
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||
logRotate := &lumberjack.Logger{
|
||||
|
||||
73
internal/pkg/middleware/audit.go
Normal file
73
internal/pkg/middleware/audit.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
db "management/internal/db/sqlc"
|
||||
|
||||
"github.com/zhang2092/browser"
|
||||
)
|
||||
|
||||
func (m *middleware) Audit(next http.Handler) http.Handler {
|
||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
defer func(res http.ResponseWriter, req *http.Request) {
|
||||
// 记录审计日志
|
||||
go m.writeLog(req, start)
|
||||
}(w, r)
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
return http.HandlerFunc(fn)
|
||||
}
|
||||
|
||||
func (m *middleware) writeLog(req *http.Request, start time.Time) {
|
||||
end := time.Now()
|
||||
duration := end.Sub(start)
|
||||
var params string
|
||||
method := req.Method
|
||||
if method == "GET" {
|
||||
params = req.URL.Query().Encode()
|
||||
} else if method == "POST" {
|
||||
contentType := req.Header.Get("Content-Type")
|
||||
if strings.Contains(contentType, "application/json") {
|
||||
body := make([]byte, req.ContentLength)
|
||||
req.Body.Read(body)
|
||||
params = string(body)
|
||||
} else if strings.Contains(contentType, "application/x-www-form-urlencoded") {
|
||||
params = req.Form.Encode()
|
||||
}
|
||||
}
|
||||
|
||||
ctx := req.Context()
|
||||
au := m.AuthUser(ctx)
|
||||
arg := &db.CreateSysAuditLogParams{
|
||||
CreatedAt: time.Now(),
|
||||
Email: au.Email,
|
||||
Username: au.Username,
|
||||
UserUuid: au.Uuid,
|
||||
StartAt: start,
|
||||
EndAt: end,
|
||||
Duration: strconv.FormatInt(duration.Milliseconds(), 10),
|
||||
Url: req.URL.RequestURI(),
|
||||
Method: method,
|
||||
Parameters: params,
|
||||
RefererUrl: req.Header.Get("Referer"),
|
||||
Ip: req.RemoteAddr,
|
||||
Remark: "",
|
||||
}
|
||||
br, err := browser.NewBrowser(req.Header.Get("User-Agent"))
|
||||
if err == nil {
|
||||
arg.Os = br.Platform().Name()
|
||||
arg.Browser = br.Name()
|
||||
}
|
||||
|
||||
c, cancel := context.WithTimeout(context.Background(), time.Second*3)
|
||||
defer cancel()
|
||||
|
||||
_ = m.biz.AuditBiz().Create(c, arg)
|
||||
}
|
||||
81
internal/pkg/middleware/authorize.go
Normal file
81
internal/pkg/middleware/authorize.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"management/internal/db/model/dto"
|
||||
"management/internal/global/auth"
|
||||
)
|
||||
|
||||
var defaultMenus = map[string]bool{
|
||||
"/home.html": true,
|
||||
"/system/menus": true,
|
||||
"/upload/img": true,
|
||||
"/upload/file": true,
|
||||
"/upload/mutilfile": true,
|
||||
"/pear.json": true,
|
||||
}
|
||||
|
||||
func (m *middleware) Authorize(next http.Handler) http.Handler {
|
||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
user, ok := m.isLogin(ctx)
|
||||
if !ok {
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
if user == nil {
|
||||
http.Error(w, "user not found", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// 登陆成功 判断权限
|
||||
|
||||
// 默认权限判断
|
||||
path := r.URL.Path
|
||||
if b, ok := defaultMenus[path]; ok && b {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
menus, err := m.biz.MenuBiz().MapOwnerMenuByRoleID(ctx, user.RoleID)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if _, ok := menus[path]; ok {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
return http.HandlerFunc(fn)
|
||||
}
|
||||
|
||||
func (m *middleware) isLogin(ctx context.Context) (*dto.AuthorizeUser, bool) {
|
||||
if exists := m.session.Exists(ctx, auth.StoreName); exists {
|
||||
b := m.session.GetBytes(ctx, auth.StoreName)
|
||||
var user dto.AuthorizeUser
|
||||
if err := json.Unmarshal(b, &user); err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return &user, true
|
||||
}
|
||||
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func (m *middleware) AuthUser(ctx context.Context) dto.AuthorizeUser {
|
||||
var user dto.AuthorizeUser
|
||||
if exists := m.session.Exists(ctx, auth.StoreName); exists {
|
||||
b := m.session.GetBytes(ctx, auth.StoreName)
|
||||
_ = json.Unmarshal(b, &user)
|
||||
}
|
||||
return user
|
||||
}
|
||||
29
internal/pkg/middleware/middleware.go
Normal file
29
internal/pkg/middleware/middleware.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
systemv1 "management/internal/erpserver/biz/v1/system"
|
||||
"management/internal/pkg/session"
|
||||
)
|
||||
|
||||
type IMiddleware interface {
|
||||
Audit(next http.Handler) http.Handler
|
||||
NoSurf(next http.Handler) http.Handler
|
||||
LoadSession(next http.Handler) http.Handler
|
||||
Authorize(next http.Handler) http.Handler
|
||||
}
|
||||
|
||||
type middleware struct {
|
||||
biz systemv1.SystemBiz
|
||||
session session.ISession
|
||||
}
|
||||
|
||||
var _ IMiddleware = (*middleware)(nil)
|
||||
|
||||
func New(biz systemv1.SystemBiz, session session.ISession) IMiddleware {
|
||||
return &middleware{
|
||||
biz: biz,
|
||||
session: session,
|
||||
}
|
||||
}
|
||||
11
internal/pkg/middleware/nocsrf.go
Normal file
11
internal/pkg/middleware/nocsrf.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/justinas/nosurf"
|
||||
)
|
||||
|
||||
func (m *middleware) NoSurf(next http.Handler) http.Handler {
|
||||
return nosurf.New(next)
|
||||
}
|
||||
9
internal/pkg/middleware/session.go
Normal file
9
internal/pkg/middleware/session.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (m *middleware) LoadSession(next http.Handler) http.Handler {
|
||||
return m.session.LoadAndSave(next)
|
||||
}
|
||||
@@ -13,31 +13,42 @@ import (
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var (
|
||||
engine *redis.Client
|
||||
ErrRedisKeyNotFound = errors.New("redis key not found")
|
||||
)
|
||||
var ErrRedisKeyNotFound = errors.New("redis key not found")
|
||||
|
||||
// func GetRedis() *redis.Client {
|
||||
// return rd
|
||||
// }
|
||||
type IRedis interface {
|
||||
Encode(a any) ([]byte, error)
|
||||
Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error
|
||||
Del(ctx context.Context, keys ...string) error
|
||||
Get(ctx context.Context, key string) (string, error)
|
||||
GetBytes(ctx context.Context, key string) ([]byte, error)
|
||||
Scan(ctx context.Context, cursor uint64, match string, count int64) *redis.ScanCmd
|
||||
Keys(ctx context.Context, pattern string) ([]string, error)
|
||||
ListKeys(ctx context.Context, pattern string, pageID int, pageSize int) ([]string, int, error)
|
||||
}
|
||||
|
||||
func Init() error {
|
||||
type redisCache struct {
|
||||
engine *redis.Client
|
||||
}
|
||||
|
||||
var _ IRedis = (*redisCache)(nil)
|
||||
|
||||
func New(conf config.Redis) (*redisCache, error) {
|
||||
rdb := redis.NewClient(&redis.Options{
|
||||
Addr: fmt.Sprintf("%s:%d", config.File.Redis.Host, config.File.Redis.Port),
|
||||
Password: config.File.Redis.Password,
|
||||
DB: config.File.Redis.DB,
|
||||
Addr: fmt.Sprintf("%s:%d", conf.Host, conf.Port),
|
||||
Password: conf.Password,
|
||||
DB: conf.DB,
|
||||
})
|
||||
_, err := rdb.Ping(context.Background()).Result()
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
engine = rdb
|
||||
return nil
|
||||
return &redisCache{
|
||||
engine: rdb,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func Encode(a any) ([]byte, error) {
|
||||
func (r *redisCache) Encode(a any) ([]byte, error) {
|
||||
var b bytes.Buffer
|
||||
if err := gob.NewEncoder(&b).Encode(a); err != nil {
|
||||
return nil, err
|
||||
@@ -47,18 +58,18 @@ func Encode(a any) ([]byte, error) {
|
||||
}
|
||||
|
||||
// Set 设置值
|
||||
func Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error {
|
||||
return engine.Set(ctx, key, value, expiration).Err()
|
||||
func (r *redisCache) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error {
|
||||
return r.engine.Set(ctx, key, value, expiration).Err()
|
||||
}
|
||||
|
||||
// Del 删除键值
|
||||
func Del(ctx context.Context, keys ...string) error {
|
||||
return engine.Del(ctx, keys...).Err()
|
||||
func (r *redisCache) Del(ctx context.Context, keys ...string) error {
|
||||
return r.engine.Del(ctx, keys...).Err()
|
||||
}
|
||||
|
||||
// Get 获取值
|
||||
func Get(ctx context.Context, key string) (string, error) {
|
||||
val, err := engine.Get(ctx, key).Result()
|
||||
func (r *redisCache) Get(ctx context.Context, key string) (string, error) {
|
||||
val, err := r.engine.Get(ctx, key).Result()
|
||||
if err == redis.Nil {
|
||||
return "", ErrRedisKeyNotFound
|
||||
} else if err != nil {
|
||||
@@ -69,8 +80,8 @@ func Get(ctx context.Context, key string) (string, error) {
|
||||
}
|
||||
|
||||
// GetBytes 获取值
|
||||
func GetBytes(ctx context.Context, key string) ([]byte, error) {
|
||||
val, err := engine.Get(ctx, key).Bytes()
|
||||
func (r *redisCache) GetBytes(ctx context.Context, key string) ([]byte, error) {
|
||||
val, err := r.engine.Get(ctx, key).Bytes()
|
||||
if err == redis.Nil {
|
||||
return nil, ErrRedisKeyNotFound
|
||||
} else if err != nil {
|
||||
@@ -80,16 +91,16 @@ func GetBytes(ctx context.Context, key string) ([]byte, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func Scan(ctx context.Context, cursor uint64, match string, count int64) *redis.ScanCmd {
|
||||
return engine.Scan(ctx, cursor, match, count)
|
||||
func (r *redisCache) Scan(ctx context.Context, cursor uint64, match string, count int64) *redis.ScanCmd {
|
||||
return r.engine.Scan(ctx, cursor, match, count)
|
||||
}
|
||||
|
||||
func Keys(ctx context.Context, pattern string) ([]string, error) {
|
||||
return engine.Keys(ctx, pattern).Result()
|
||||
func (r *redisCache) Keys(ctx context.Context, pattern string) ([]string, error) {
|
||||
return r.engine.Keys(ctx, pattern).Result()
|
||||
}
|
||||
|
||||
func ListKeys(ctx context.Context, pattern string, pageID int, pageSize int) ([]string, int, error) {
|
||||
all, err := engine.Keys(ctx, pattern).Result()
|
||||
func (r *redisCache) ListKeys(ctx context.Context, pattern string, pageID int, pageSize int) ([]string, int, error) {
|
||||
all, err := r.engine.Keys(ctx, pattern).Result()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
@@ -104,7 +115,7 @@ func ListKeys(ctx context.Context, pattern string, pageID int, pageSize int) ([]
|
||||
for {
|
||||
var scanResult []string
|
||||
var err error
|
||||
scanResult, cursor, err = engine.Scan(ctx, cursor, pattern, int64(pageSize)).Result()
|
||||
scanResult, cursor, err = r.engine.Scan(ctx, cursor, pattern, int64(pageSize)).Result()
|
||||
if err != nil {
|
||||
return nil, count, err
|
||||
}
|
||||
@@ -124,3 +135,36 @@ func ListKeys(ctx context.Context, pattern string, pageID int, pageSize int) ([]
|
||||
}
|
||||
return keys[startIndex:endIndex], count, nil
|
||||
}
|
||||
|
||||
// ==========================
|
||||
func Encode(a any) ([]byte, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func Del(ctx context.Context, keys ...string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func Get(ctx context.Context, key string) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func GetBytes(ctx context.Context, key string) ([]byte, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func Scan(ctx context.Context, cursor uint64, match string, count int64) *redis.ScanCmd {
|
||||
return nil
|
||||
}
|
||||
|
||||
func Keys(ctx context.Context, pattern string) ([]string, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func ListKeys(ctx context.Context, pattern string, pageID int, pageSize int) ([]string, int, error) {
|
||||
return nil, 0, nil
|
||||
}
|
||||
|
||||
@@ -1,83 +1,83 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
// import (
|
||||
// "context"
|
||||
// "time"
|
||||
|
||||
"management/internal/pkg/redis"
|
||||
)
|
||||
// "management/internal/pkg/redis"
|
||||
// )
|
||||
|
||||
var (
|
||||
storePrefix = "scs:session:"
|
||||
ctx = context.Background()
|
||||
DefaultRedisStore = newRedisStore()
|
||||
)
|
||||
// var (
|
||||
// storePrefix = "scs:session:"
|
||||
// ctx = context.Background()
|
||||
// DefaultRedisStore = newRedisStore()
|
||||
// )
|
||||
|
||||
type redisStore struct{}
|
||||
// type redisStore struct{}
|
||||
|
||||
func newRedisStore() *redisStore {
|
||||
return &redisStore{}
|
||||
}
|
||||
// func newRedisStore() *redisStore {
|
||||
// return &redisStore{}
|
||||
// }
|
||||
|
||||
// Delete should remove the session token and corresponding data from the
|
||||
// session store. If the token does not exist then Delete should be a no-op
|
||||
// and return nil (not an error).
|
||||
func (s *redisStore) Delete(token string) error {
|
||||
return redis.Del(ctx, storePrefix+token)
|
||||
}
|
||||
// // Delete should remove the session token and corresponding data from the
|
||||
// // session store. If the token does not exist then Delete should be a no-op
|
||||
// // and return nil (not an error).
|
||||
// func (s *redisStore) Delete(token string) error {
|
||||
// return redis.Del(ctx, storePrefix+token)
|
||||
// }
|
||||
|
||||
// Find should return the data for a session token from the store. If the
|
||||
// session token is not found or is expired, the found return value should
|
||||
// be false (and the err return value should be nil). Similarly, tampered
|
||||
// or malformed tokens should result in a found return value of false and a
|
||||
// nil err value. The err return value should be used for system errors only.
|
||||
func (s *redisStore) Find(token string) (b []byte, found bool, err error) {
|
||||
val, err := redis.GetBytes(ctx, storePrefix+token)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
} else {
|
||||
return val, true, nil
|
||||
}
|
||||
}
|
||||
// // Find should return the data for a session token from the store. If the
|
||||
// // session token is not found or is expired, the found return value should
|
||||
// // be false (and the err return value should be nil). Similarly, tampered
|
||||
// // or malformed tokens should result in a found return value of false and a
|
||||
// // nil err value. The err return value should be used for system errors only.
|
||||
// func (s *redisStore) Find(token string) (b []byte, found bool, err error) {
|
||||
// val, err := redis.GetBytes(ctx, storePrefix+token)
|
||||
// if err != nil {
|
||||
// return nil, false, err
|
||||
// } else {
|
||||
// return val, true, nil
|
||||
// }
|
||||
// }
|
||||
|
||||
// Commit should add the session token and data to the store, with the given
|
||||
// expiry time. If the session token already exists, then the data and
|
||||
// expiry time should be overwritten.
|
||||
func (s *redisStore) Commit(token string, b []byte, expiry time.Time) error {
|
||||
// TODO: 这边可以调整时间
|
||||
exp, err := time.ParseInLocation(time.DateTime, time.Now().Format("2006-01-02")+" 23:59:59", time.Local)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// // Commit should add the session token and data to the store, with the given
|
||||
// // expiry time. If the session token already exists, then the data and
|
||||
// // expiry time should be overwritten.
|
||||
// func (s *redisStore) Commit(token string, b []byte, expiry time.Time) error {
|
||||
// // TODO: 这边可以调整时间
|
||||
// exp, err := time.ParseInLocation(time.DateTime, time.Now().Format("2006-01-02")+" 23:59:59", time.Local)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
|
||||
t := time.Now()
|
||||
expired := exp.Sub(t)
|
||||
return redis.Set(ctx, storePrefix+token, b, expired)
|
||||
}
|
||||
// t := time.Now()
|
||||
// expired := exp.Sub(t)
|
||||
// return redis.Set(ctx, storePrefix+token, b, expired)
|
||||
// }
|
||||
|
||||
// All should return a map containing data for all active sessions (i.e.
|
||||
// sessions which have not expired). The map key should be the session
|
||||
// token and the map value should be the session data. If no active
|
||||
// sessions exist this should return an empty (not nil) map.
|
||||
func (s *redisStore) All() (map[string][]byte, error) {
|
||||
sessions := make(map[string][]byte)
|
||||
// // All should return a map containing data for all active sessions (i.e.
|
||||
// // sessions which have not expired). The map key should be the session
|
||||
// // token and the map value should be the session data. If no active
|
||||
// // sessions exist this should return an empty (not nil) map.
|
||||
// func (s *redisStore) All() (map[string][]byte, error) {
|
||||
// sessions := make(map[string][]byte)
|
||||
|
||||
iter := redis.Scan(ctx, 0, storePrefix+"*", 0).Iterator()
|
||||
for iter.Next(ctx) {
|
||||
key := iter.Val()
|
||||
token := key[len(storePrefix):]
|
||||
data, exists, err := s.Find(token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// iter := redis.Scan(ctx, 0, storePrefix+"*", 0).Iterator()
|
||||
// for iter.Next(ctx) {
|
||||
// key := iter.Val()
|
||||
// token := key[len(storePrefix):]
|
||||
// data, exists, err := s.Find(token)
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
|
||||
if exists {
|
||||
sessions[token] = data
|
||||
}
|
||||
}
|
||||
if err := iter.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// if exists {
|
||||
// sessions[token] = data
|
||||
// }
|
||||
// }
|
||||
// if err := iter.Err(); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
|
||||
return sessions, nil
|
||||
}
|
||||
// return sessions, nil
|
||||
// }
|
||||
|
||||
@@ -5,55 +5,68 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"management/internal/config"
|
||||
db "management/internal/db/sqlc"
|
||||
|
||||
"github.com/alexedwards/scs/pgxstore"
|
||||
"github.com/alexedwards/scs/v2"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
var sessionManager *scs.SessionManager
|
||||
type ISession interface {
|
||||
Destroy(ctx context.Context) error
|
||||
LoadAndSave(next http.Handler) http.Handler
|
||||
Put(ctx context.Context, key string, val any)
|
||||
GetBytes(ctx context.Context, key string) []byte
|
||||
Exists(ctx context.Context, key string) bool
|
||||
RenewToken(ctx context.Context) error
|
||||
}
|
||||
|
||||
func Init() {
|
||||
sessionManager = scs.New()
|
||||
type session struct {
|
||||
sessionManager *scs.SessionManager
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool, prod bool) ISession {
|
||||
sessionManager := scs.New()
|
||||
sessionManager.Lifetime = 24 * time.Hour
|
||||
sessionManager.IdleTimeout = 2 * time.Hour
|
||||
sessionManager.Cookie.Name = "token"
|
||||
sessionManager.Cookie.HttpOnly = true
|
||||
sessionManager.Cookie.Persist = true
|
||||
sessionManager.Cookie.SameSite = http.SameSiteStrictMode
|
||||
sessionManager.Cookie.Secure = config.File.App.Prod
|
||||
sessionManager.Cookie.Secure = prod
|
||||
|
||||
// postgres
|
||||
// github.com/alexedwards/scs/postgresstore
|
||||
// sessionManager.Store = postgresstore.New(db)
|
||||
// pgx
|
||||
// github.com/alexedwards/scs/pgxstore
|
||||
sessionManager.Store = pgxstore.New(db.Engine.Pool())
|
||||
sessionManager.Store = pgxstore.New(pool)
|
||||
// redis
|
||||
// sessionManager.Store = newRedisStore()
|
||||
|
||||
return &session{
|
||||
sessionManager: sessionManager,
|
||||
}
|
||||
}
|
||||
|
||||
func Destroy(ctx context.Context) error {
|
||||
return sessionManager.Destroy(ctx)
|
||||
func (s *session) Destroy(ctx context.Context) error {
|
||||
return s.sessionManager.Destroy(ctx)
|
||||
}
|
||||
|
||||
func LoadAndSave(next http.Handler) http.Handler {
|
||||
return sessionManager.LoadAndSave(next)
|
||||
func (s *session) LoadAndSave(next http.Handler) http.Handler {
|
||||
return s.sessionManager.LoadAndSave(next)
|
||||
}
|
||||
|
||||
func Put(ctx context.Context, key string, val interface{}) {
|
||||
sessionManager.Put(ctx, key, val)
|
||||
func (s *session) Put(ctx context.Context, key string, val any) {
|
||||
s.sessionManager.Put(ctx, key, val)
|
||||
}
|
||||
|
||||
func GetBytes(ctx context.Context, key string) []byte {
|
||||
return sessionManager.GetBytes(ctx, key)
|
||||
func (s *session) GetBytes(ctx context.Context, key string) []byte {
|
||||
return s.sessionManager.GetBytes(ctx, key)
|
||||
}
|
||||
|
||||
func Exists(ctx context.Context, key string) bool {
|
||||
return sessionManager.Exists(ctx, key)
|
||||
func (s *session) Exists(ctx context.Context, key string) bool {
|
||||
return s.sessionManager.Exists(ctx, key)
|
||||
}
|
||||
|
||||
func RenewToken(ctx context.Context) error {
|
||||
return sessionManager.RenewToken(ctx)
|
||||
func (s *session) RenewToken(ctx context.Context) error {
|
||||
return s.sessionManager.RenewToken(ctx)
|
||||
}
|
||||
|
||||
48
internal/pkg/tpl/html.go
Normal file
48
internal/pkg/tpl/html.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package tpl
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"management/internal/db/model/dto"
|
||||
)
|
||||
|
||||
type TemplateConfig struct {
|
||||
Root string
|
||||
Extension string
|
||||
Layout string
|
||||
Partial string
|
||||
}
|
||||
|
||||
type HtmlData struct {
|
||||
IsAuthenticated bool
|
||||
AuthorizeUser dto.AuthorizeUser
|
||||
AuthorizeMenus []*dto.OwnerMenuDto
|
||||
Data any
|
||||
}
|
||||
|
||||
func (r *render) HTML(w http.ResponseWriter, req *http.Request, tpl string, data map[string]any) {
|
||||
name := strings.ReplaceAll(tpl, "/", "_")
|
||||
t, ok := r.templates[name]
|
||||
if !ok {
|
||||
http.Error(w, "template is empty", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
hd := r.setDefaultData(req, data)
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
err := t.ExecuteTemplate(buf, filepath.Base(tpl), hd)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
_, err = buf.WriteTo(w)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
91
internal/pkg/tpl/html_btn.go
Normal file
91
internal/pkg/tpl/html_btn.go
Normal file
@@ -0,0 +1,91 @@
|
||||
package tpl
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"management/internal/db/model/dto"
|
||||
)
|
||||
|
||||
func (r *render) btnFuncs() map[string]any {
|
||||
res := make(map[string]any, 3)
|
||||
|
||||
res["genBtn"] = func(btns []*dto.OwnerMenuDto, actionNames ...string) template.HTML {
|
||||
if len(btns) == 0 {
|
||||
return template.HTML("")
|
||||
}
|
||||
|
||||
var res string
|
||||
for _, action := range actionNames {
|
||||
for _, btn := range btns {
|
||||
btn.Style = strings.ReplaceAll(btn.Style, "pear", "layui")
|
||||
base := filepath.Base(btn.Url)
|
||||
if base == action {
|
||||
res += `<button type="button" class="layui-btn ` + btn.Style + `" lay-event="` + firstLower(action) + `" lay-on="` + firstLower(action) + `">`
|
||||
if len(btn.Avatar) > 0 {
|
||||
res += `<i class="` + btn.Avatar + `"></i> `
|
||||
}
|
||||
res += btn.DisplayName + `</button>`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return template.HTML(res)
|
||||
}
|
||||
|
||||
res["genLink"] = func(btns []*dto.OwnerMenuDto, actionNames ...string) template.HTML {
|
||||
if len(btns) == 0 {
|
||||
return template.HTML("")
|
||||
}
|
||||
|
||||
var res string
|
||||
for _, action := range actionNames {
|
||||
for _, btn := range btns {
|
||||
btn.Style = strings.ReplaceAll(btn.Style, "pear", "layui")
|
||||
base := filepath.Base(btn.Url)
|
||||
if base == action {
|
||||
res += `<button type="button" style="font-size:12px !important;" class="layui-btn ` + btn.Style + `" lay-event="` + firstLower(action) + `" lay-on="` + firstLower(action) + `">`
|
||||
if len(btn.Avatar) > 0 {
|
||||
res += `<i class="` + btn.Avatar + `"></i> `
|
||||
}
|
||||
res += btn.DisplayName + `</button>`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return template.HTML(res)
|
||||
}
|
||||
|
||||
res["previewPicture"] = func(name string) template.HTML {
|
||||
var res string
|
||||
res += `<a><img src="https://school-1251542740.cos.ap-shanghai.myqcloud.com{{` + name + `}}" data-type="1" height="30" width="30" class="preview-all screenshot" onclick="previewPicture('https://school-1251542740.cos.ap-shanghai.myqcloud.com/{{` + name + `}}')"/></a>`
|
||||
|
||||
return template.HTML(res)
|
||||
}
|
||||
|
||||
res["submitBtn"] = func(btns []*dto.OwnerMenuDto, actionNames ...string) template.HTML {
|
||||
if len(btns) == 0 {
|
||||
return template.HTML("")
|
||||
}
|
||||
|
||||
var res string
|
||||
for _, action := range actionNames {
|
||||
for _, btn := range btns {
|
||||
btn.Style = strings.ReplaceAll(btn.Style, "pear", "layui")
|
||||
base := filepath.Base(btn.Url)
|
||||
if base == action {
|
||||
res += `<button type="submit" class="layui-btn ` + btn.Style + `" lay-submit lay-filter="` + firstLower(action) + `">`
|
||||
if len(btn.Avatar) > 0 {
|
||||
res += `<i class="` + btn.Avatar + `"></i> `
|
||||
}
|
||||
res += btn.DisplayName + `</button>`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return template.HTML(res)
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
57
internal/pkg/tpl/html_method.go
Normal file
57
internal/pkg/tpl/html_method.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package tpl
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (r *render) Methods() map[string]any {
|
||||
res := make(map[string]any, 1)
|
||||
|
||||
res["dateFormat"] = func(dt time.Time) template.HTML {
|
||||
return template.HTML(dt.Format(time.DateTime))
|
||||
}
|
||||
|
||||
res["today"] = func() template.HTML {
|
||||
return template.HTML(time.Now().Format("2006-01-02"))
|
||||
}
|
||||
|
||||
res["threeMonth"] = func() template.HTML {
|
||||
return template.HTML(time.Now().AddDate(0, 3, 0).Format("2006-01-02"))
|
||||
}
|
||||
|
||||
res["yearBegin"] = func() template.HTML {
|
||||
dt := time.Now()
|
||||
t := dt.AddDate(0, -int(dt.Month())+1, -dt.Day()+1)
|
||||
return template.HTML(t.Format("2006-01-02") + " 00:00:00")
|
||||
}
|
||||
|
||||
res["monthBegin"] = func() template.HTML {
|
||||
dt := time.Now()
|
||||
t := dt.AddDate(0, 0, -dt.Day()+1)
|
||||
return template.HTML(t.Format("2006-01-02") + " 00:00:00")
|
||||
}
|
||||
|
||||
res["monthEnd"] = func() template.HTML {
|
||||
dt := time.Now()
|
||||
t := dt.AddDate(0, 0, -dt.Day()+1).AddDate(0, 1, -1)
|
||||
return template.HTML(t.Format("2006-01-02") + " 23:59:59")
|
||||
}
|
||||
|
||||
res["trimSpace"] = func(s string) template.HTML {
|
||||
return template.HTML(strings.TrimSpace(s))
|
||||
}
|
||||
|
||||
res["expandTags"] = func(s []string) template.HTML {
|
||||
if len(s) == 0 {
|
||||
return template.HTML("")
|
||||
}
|
||||
if len(s) == 1 && s[0] == "all" {
|
||||
return template.HTML("")
|
||||
}
|
||||
return template.HTML(strings.Join(s, ","))
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
57
internal/pkg/tpl/json.go
Normal file
57
internal/pkg/tpl/json.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package tpl
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Response struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"msg"`
|
||||
Data any `json:"data"`
|
||||
}
|
||||
|
||||
type ResponseDtree struct {
|
||||
Status ResponseDtreeStatus `json:"status"`
|
||||
Data any `json:"data"`
|
||||
}
|
||||
|
||||
type ResponseDtreeStatus struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type ResponseList struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"msg"`
|
||||
Count int64 `json:"count"`
|
||||
Data any `json:"data"`
|
||||
}
|
||||
|
||||
func (r *render) JSONF(w http.ResponseWriter, success bool, message string) {
|
||||
r.JSON(w, Response{Success: success, Message: message})
|
||||
}
|
||||
|
||||
func (r *render) JSONOK(w http.ResponseWriter, message string) {
|
||||
r.JSON(w, Response{Success: true, Message: message})
|
||||
}
|
||||
|
||||
func (r *render) JSONERR(w http.ResponseWriter, message string) {
|
||||
r.JSON(w, Response{Success: false, Message: message})
|
||||
}
|
||||
|
||||
func (r *render) JSON(w http.ResponseWriter, data any) {
|
||||
v, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, err = w.Write(v)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
46
internal/pkg/tpl/render.go
Normal file
46
internal/pkg/tpl/render.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package tpl
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"net/http"
|
||||
|
||||
systemv1 "management/internal/erpserver/biz/v1/system"
|
||||
"management/internal/pkg/session"
|
||||
)
|
||||
|
||||
type Renderer interface {
|
||||
HTML(w http.ResponseWriter, req *http.Request, name string, data map[string]any)
|
||||
JSON(w http.ResponseWriter, data any)
|
||||
JSONF(w http.ResponseWriter, success bool, message string)
|
||||
JSONOK(w http.ResponseWriter, message string)
|
||||
JSONERR(w http.ResponseWriter, message string)
|
||||
}
|
||||
|
||||
type render struct {
|
||||
session session.ISession
|
||||
config *TemplateConfig
|
||||
templates map[string]*template.Template
|
||||
|
||||
menuBiz systemv1.MenuBiz
|
||||
}
|
||||
|
||||
func New(session session.ISession, menuBiz systemv1.MenuBiz) (Renderer, error) {
|
||||
render := &render{
|
||||
session: session,
|
||||
menuBiz: menuBiz,
|
||||
config: &TemplateConfig{
|
||||
Root: ".",
|
||||
Extension: ".tmpl",
|
||||
Layout: "base",
|
||||
Partial: "partial",
|
||||
},
|
||||
}
|
||||
|
||||
templates, err := render.createTemplateCache()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
render.templates = templates
|
||||
return render, nil
|
||||
}
|
||||
181
internal/pkg/tpl/util.go
Normal file
181
internal/pkg/tpl/util.go
Normal file
@@ -0,0 +1,181 @@
|
||||
package tpl
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"management/internal/db/model/dto"
|
||||
"management/internal/global/auth"
|
||||
templates "management/web/templates/manage"
|
||||
|
||||
"github.com/justinas/nosurf"
|
||||
)
|
||||
|
||||
func (r *render) setDefaultData(req *http.Request, data map[string]any) map[string]any {
|
||||
if data == nil {
|
||||
data = make(map[string]any)
|
||||
}
|
||||
|
||||
ctx := req.Context()
|
||||
isAuth := r.session.Exists(ctx, auth.StoreName)
|
||||
data["IsAuthenticated"] = isAuth
|
||||
if isAuth {
|
||||
var authUser dto.AuthorizeUser
|
||||
u := r.session.GetBytes(ctx, auth.StoreName)
|
||||
_ = json.Unmarshal(u, &authUser)
|
||||
|
||||
data["AuthorizeMenus"] = r.getCurrentPathBtns(ctx, authUser.RoleID, req.URL.Path)
|
||||
}
|
||||
token := nosurf.Token(req)
|
||||
data["CsrfToken"] = token
|
||||
data["CsrfTokenField"] = template.HTML(fmt.Sprintf(`<input type="hidden" name="csrf_token" value="%s" />`, token))
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
func (r *render) getCurrentPathBtns(ctx context.Context, roleID int32, path string) []*dto.OwnerMenuDto {
|
||||
var res []*dto.OwnerMenuDto
|
||||
|
||||
// 获取当前path的菜单
|
||||
menu, err := r.menuBiz.GetSysMenuByUrl(ctx, path)
|
||||
if err != nil {
|
||||
return res
|
||||
}
|
||||
|
||||
// 获取权限
|
||||
menus, err := r.menuBiz.ListOwnerMenuByRoleID(ctx, roleID)
|
||||
if err != nil {
|
||||
return res
|
||||
}
|
||||
|
||||
for _, item := range menus {
|
||||
if menu.IsList {
|
||||
if item.ParentID == menu.ID || item.ID == menu.ID {
|
||||
res = append(res, item)
|
||||
}
|
||||
} else {
|
||||
if item.ParentID == menu.ParentID {
|
||||
res = append(res, item)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
func (r *render) createTemplateCache() (map[string]*template.Template, error) {
|
||||
cache := make(map[string]*template.Template)
|
||||
pages, err := getFiles(r.config.Root, r.config.Extension)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
layoutAndPartial, err := r.getLayoutAndPartials()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, page := range pages {
|
||||
if strings.HasPrefix(page, "base") || strings.HasSuffix(page, "partial") {
|
||||
continue
|
||||
}
|
||||
|
||||
name := filepath.Base(page)
|
||||
pathArr := strings.Split(page, "/")
|
||||
dir := pathArr[len(pathArr)-2 : len(pathArr)-1]
|
||||
templateName := fmt.Sprintf("%s_%s", dir[0], name)
|
||||
ts := template.Must(template.New(templateName).Funcs(r.btnFuncs()).Funcs(r.Methods()).ParseFS(templates.TemplateFS, page))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ts, err = ts.ParseFS(templates.TemplateFS, layoutAndPartial...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cache[templateName] = ts
|
||||
}
|
||||
|
||||
return cache, nil
|
||||
}
|
||||
|
||||
func (r *render) getLayoutAndPartials() ([]string, error) {
|
||||
layouts, err := getFiles(r.config.Layout, r.config.Extension)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
partials, err := getFiles(r.config.Partial, r.config.Extension)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return slices.Concat(layouts, partials), nil
|
||||
}
|
||||
|
||||
func getFiles(path string, stuffix string) ([]string, error) {
|
||||
files := make([]string, 0)
|
||||
b, err := pathExists(templates.TemplateFS, path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !b {
|
||||
return files, nil
|
||||
}
|
||||
|
||||
err = fs.WalkDir(templates.TemplateFS, path, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
if strings.HasSuffix(path, stuffix) {
|
||||
files = append(files, path)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
// err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
|
||||
// if info == nil {
|
||||
// return err
|
||||
// }
|
||||
// if info.IsDir() {
|
||||
// return nil
|
||||
// }
|
||||
// // 将模板后缀的文件放到列表
|
||||
// if strings.HasSuffix(path, stuffix) {
|
||||
// files = append(files, path)
|
||||
// }
|
||||
// return nil
|
||||
// })
|
||||
return files, err
|
||||
}
|
||||
|
||||
func pathExists(fs fs.FS, path string) (bool, error) {
|
||||
_, err := fs.Open(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
return true, err
|
||||
}
|
||||
|
||||
func firstLower(s string) string {
|
||||
if len(s) == 0 {
|
||||
return s
|
||||
}
|
||||
|
||||
return strings.ToLower(s[:1]) + s[1:]
|
||||
}
|
||||
Reference in New Issue
Block a user