fusenapi/goctl_template/api/context.tpl

64 lines
1.4 KiB
Smarty
Raw Normal View History

2023-06-05 09:56:55 +00:00
package svc
import (
{{.configImport}}
2023-06-21 04:21:56 +00:00
"errors"
"fmt"
"net/http"
2023-06-12 06:05:35 +00:00
"fusenapi/initalize"
2023-06-21 04:21:56 +00:00
"fusenapi/model/gmodel"
2023-06-12 06:05:35 +00:00
"gorm.io/gorm"
2023-06-13 04:15:06 +00:00
"github.com/golang-jwt/jwt"
2023-06-05 09:56:55 +00:00
)
type ServiceContext struct {
Config {{.config}}
{{.middleware}}
2023-06-12 06:05:35 +00:00
MysqlConn *gorm.DB
2023-06-21 04:21:56 +00:00
AllModels *gmodel.AllModelsGen
2023-06-05 09:56:55 +00:00
}
func NewServiceContext(c {{.config}}) *ServiceContext {
2023-06-12 07:17:42 +00:00
2023-06-05 09:56:55 +00:00
return &ServiceContext{
Config: c,
2023-06-14 07:45:56 +00:00
MysqlConn: initalize.InitMysql(c.SourceMysql),
2023-06-21 04:21:56 +00:00
AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)),
2023-06-05 09:56:55 +00:00
{{.middlewareAssignment}}
}
}
2023-06-12 07:17:42 +00:00
2023-06-20 11:36:28 +00:00
func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) {
2023-06-12 07:17:42 +00:00
AuthKey := r.Header.Get("Authorization")
if AuthKey == "" {
return nil, nil
}
2023-07-10 09:54:10 +00:00
AuthKey = AuthKey[7:]
2023-06-12 07:17:42 +00:00
if len(AuthKey) <= 50 {
return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey)))
}
token, err := jwt.Parse(AuthKey, func(token *jwt.Token) (interface{}, error) {
// 检查签名方法是否为 HS256
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
// 返回用于验证签名的密钥
return []byte(svcCtx.Config.Auth.AccessSecret), nil
2023-06-12 07:17:42 +00:00
})
if err != nil {
return nil, errors.New(fmt.Sprint("Error parsing token:", err))
}
// 验证成功返回
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return claims, nil
}
return nil, errors.New(fmt.Sprint("Invalid token", err))
}