2025-06-25 16:11:03 +08:00

95 lines
1.9 KiB
Go

package mid
import (
"context"
"errors"
"management/internal/erpserver/model/dto"
"management/internal/erpserver/model/system"
"management/internal/pkg/sqldb"
"github.com/a-h/templ"
)
type userKey struct{}
func setUser(ctx context.Context, usr system.AuthorizeUser) context.Context {
return context.WithValue(ctx, userKey{}, usr)
}
// GetUser returns the user from the context.
func GetUser(ctx context.Context) system.AuthorizeUser {
v, ok := ctx.Value(userKey{}).(system.AuthorizeUser)
if !ok {
return system.AuthorizeUser{}
}
return v
}
type menuKey struct{}
func setCurMenus(ctx context.Context, ms []dto.OwnerMenuDto) context.Context {
return context.WithValue(ctx, menuKey{}, ms)
}
func GetCurMenus(ctx context.Context) []dto.OwnerMenuDto {
v, ok := ctx.Value(menuKey{}).([]dto.OwnerMenuDto)
if !ok {
return []dto.OwnerMenuDto{}
}
return v
}
type NoSurfToken struct {
Token string
HtmlToken string
}
type csrfKey struct{}
func setCsrfToken(ctx context.Context, token string) context.Context {
return context.WithValue(ctx, csrfKey{}, token)
}
func GetCsrfToken(ctx context.Context) string {
v, ok := ctx.Value(csrfKey{}).(string)
if !ok {
return ""
}
return v
}
type htmlCsrfKey struct{}
func setHtmlCsrfToken(ctx context.Context, token string) context.Context {
return context.WithValue(ctx, htmlCsrfKey{}, templ.Raw(token))
}
func GetHtmlCsrfToken(ctx context.Context) templ.Component {
v, ok := ctx.Value(htmlCsrfKey{}).(templ.Component)
if !ok {
return templ.Raw("")
}
return v
}
type trkey struct{}
func setTran(ctx context.Context, tx sqldb.CommitRollbacker) context.Context {
return context.WithValue(ctx, trkey{}, tx)
}
// GetTran retrieves the value that can manage a transaction.
func GetTran(ctx context.Context) (sqldb.CommitRollbacker, error) {
v, ok := ctx.Value(trkey{}).(sqldb.CommitRollbacker)
if !ok {
return nil, errors.New("transaction not found in context")
}
return v, nil
}