busniess-user-center/pkg/utils/context/context.go

90 lines
1.7 KiB
Go

package context
import (
"context"
"errors"
pkgErrors "busniess-user-center/pkg/errors"
"busniess-user-center/pkg/utils/session"
"github.com/gin-gonic/gin"
)
const (
JwtIdentityKey = "id"
)
type contextSessionKey struct{}
type ContextSessionKey struct{}
func MustGetSessionAccount(ctx context.Context) string {
if account, err := GetSessionAccount(ctx); err == nil {
return account
}
return ""
}
func GetSessionAccount(ctx context.Context) (account string, err error) {
sess, err := GetSession(ctx)
if err != nil {
return "", errors.New(pkgErrors.UNAUTH)
}
return sess.Account, nil
}
func GetSessionUserID(ctx context.Context) (userID uint, err error) {
sess, err := GetSession(ctx)
if err != nil {
return 0, errors.New(pkgErrors.UNAUTH)
}
return sess.ID, nil
}
func GetSession(ctx context.Context) (sess *session.Session, err error) {
switch c := ctx.(type) {
case *gin.Context:
if sessionI, ok := c.Get(JwtIdentityKey); ok {
if sess, ok = sessionI.(*session.Session); ok {
return sess, nil
}
}
default:
if sess, ok := ctx.Value(contextSessionKey{}).(*session.Session); ok {
return sess, nil
}
}
return nil, errors.New(pkgErrors.UNAUTH)
}
func PutSession(ctx context.Context, sess *session.Session) context.Context {
switch c := ctx.(type) {
case *gin.Context:
c.Set(JwtIdentityKey, sess)
return ctx
default:
return context.WithValue(ctx, contextSessionKey{}, sess)
}
}
func GetHost(ctx context.Context) string {
switch c := ctx.(type) {
case *gin.Context:
return c.Request.Host
default:
return ""
}
}
func GetPath(ctx context.Context) string {
switch c := ctx.(type) {
case *gin.Context:
return c.Request.URL.Path
default:
return ""
}
}