Files
cpdaily_xiaozhushou/backed/internal/service/admin_jwt.go
T
becomer 2e2c161770 feat: init cpdaily-xiaozhushou with blue-green deploy
- backed/: Go Fiber backend with cpdaily integration
- frondend/: Vue 3 + Vite frontend
- Dockerfile: multi-stage build (Node → Go → Alpine)
- deploy/docker-compose.yml: production compose file
- .woodpecker/build.yml: CI/CD with blue-green zero-downtime deploy
- /health endpoint for deployment health checks
- Port 8884/8885 blue-green swap via 1Panel OpenResty
2026-07-03 15:37:55 +08:00

64 lines
1.6 KiB
Go

package service
import (
"cpdaily-new/internal/config"
"errors"
"time"
"github.com/golang-jwt/jwt/v5"
)
// AdminClaims 管理员/代理 JWT 声明
type AdminClaims struct {
AgentID uint `json:"agentId"`
Username string `json:"username"`
Role string `json:"role"`
jwt.RegisteredClaims
}
// GenerateAdminToken 生成管理员/代理 token
func GenerateAdminToken(agentID uint, username, role string) (string, int64, error) {
now := time.Now()
jwtCfg := config.Global.Jwt
expiresIn := int64(86400 * 7) // 7天有效期
claims := AdminClaims{
AgentID: agentID,
Username: username,
Role: role,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now.Add(time.Duration(expiresIn) * time.Second)),
IssuedAt: jwt.NewNumericDate(now),
Issuer: "cpdaily-new-admin",
},
}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(jwtCfg.Secret))
if err != nil {
return "", 0, err
}
return token, expiresIn, nil
}
// ValidateAdminToken 验证管理员/代理 token
func ValidateAdminToken(tokenString string) (*AdminClaims, error) {
claims := &AdminClaims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, errors.New("unexpected signing method")
}
return []byte(config.Global.Jwt.Secret), nil
})
if err != nil {
return nil, err
}
if !token.Valid {
return nil, errors.New("invalid token")
}
if claims.Issuer != "cpdaily-new-admin" {
return nil, errors.New("invalid token type")
}
return claims, nil
}