init: taotie-api 项目初始化
This commit is contained in:
42
utils/sctx/sctx.go
Normal file
42
utils/sctx/sctx.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package sctx
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type MyKey string
|
||||
|
||||
const CurrentKey MyKey = "taotie"
|
||||
|
||||
type CurrentUser struct {
|
||||
UserId string
|
||||
UserName string
|
||||
TenantId string
|
||||
}
|
||||
|
||||
func SetCurrentUser(ctx context.Context, cuser *CurrentUser) context.Context {
|
||||
if c, ok := ctx.(*gin.Context); ok {
|
||||
c.Set(CurrentKey, cuser)
|
||||
return c
|
||||
}
|
||||
|
||||
return context.WithValue(ctx, CurrentKey, cuser)
|
||||
}
|
||||
|
||||
func GetCurrentUser(ctx context.Context) *CurrentUser {
|
||||
if c, ok := ctx.(*gin.Context); ok {
|
||||
if user, ok := c.Get(CurrentKey); ok {
|
||||
if cuser, ok := user.(*CurrentUser); ok {
|
||||
return cuser
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if cuser, ok := ctx.Value(CurrentKey).(*CurrentUser); ok {
|
||||
return cuser
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
50
utils/sjwt/sjwt.go
Normal file
50
utils/sjwt/sjwt.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package sjwt
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type MyClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
TenantId string `json:"tenantId"`
|
||||
UserId string `json:"userId"`
|
||||
UserName string `json:"userName"`
|
||||
}
|
||||
|
||||
// 生成 token
|
||||
func GenerateToken(tenantId string, userId string, userName string, timeOut int, signedString string) (string, error) {
|
||||
// 创建一个claims
|
||||
claims := jwt.NewWithClaims(jwt.SigningMethodHS256, MyClaims{
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Second * time.Duration(timeOut))),
|
||||
Issuer: "taotie",
|
||||
},
|
||||
TenantId: tenantId,
|
||||
UserId: userId,
|
||||
UserName: userName,
|
||||
})
|
||||
|
||||
// 生成 token
|
||||
return claims.SignedString([]byte(signedString))
|
||||
}
|
||||
|
||||
// 解析 token
|
||||
func ParseToken(tokenString string, signedString string) (*MyClaims, error) {
|
||||
// 解析token
|
||||
token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(token *jwt.Token) (any, error) {
|
||||
return []byte(signedString), nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 对token进行断言
|
||||
if claims, ok := token.Claims.(*MyClaims); ok {
|
||||
return claims, nil
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user