fusenapi/goctl_template/api/context.tpl
2023-06-12 15:17:42 +08:00

48 lines
1.2 KiB
Smarty

package svc
import (
{{.configImport}}
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type ServiceContext struct {
Config {{.config}}
{{.middleware}}
MysqlConn sqlx.SqlConn
}
func NewServiceContext(c {{.config}}) *ServiceContext {
return &ServiceContext{
Config: c,
MysqlConn: sqlx.NewMysql(c.SourceMysql),
{{.middlewareAssignment}}
}
}
func (svcCxt *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) {
AuthKey := r.Header.Get("Authorization")
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 svcCxt.Config.Auth.AccessSecret, nil
})
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))
}