96 lines
1.9 KiB
Go
96 lines
1.9 KiB
Go
package mid
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"management/internal/erpserver/model/dto"
|
|
"management/internal/pkg/sqldb"
|
|
"management/internal/pkg/token"
|
|
|
|
"github.com/a-h/templ"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type userKey struct{}
|
|
|
|
func setUser(ctx *gin.Context, payload *token.Payload) {
|
|
ctx.Set(authorizationPayloadKey, payload)
|
|
}
|
|
|
|
// GetUser returns the user from the context.
|
|
func GetUser(ctx *gin.Context) *token.Payload {
|
|
value, exists := ctx.Get(authorizationPayloadKey)
|
|
if !exists {
|
|
return nil
|
|
}
|
|
|
|
return value.(*token.Payload)
|
|
}
|
|
|
|
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
|
|
}
|