This commit is contained in:
yml2213
2026-07-20 14:58:57 +08:00
commit 45db0aa4b9
50 changed files with 5861 additions and 0 deletions
+58
View File
@@ -0,0 +1,58 @@
package jwt
import (
"errors"
"time"
"github.com/golang-jwt/jwt/v5"
)
type Claims struct {
UserID uint `json:"user_id"`
Username string `json:"username"`
Role string `json:"role"`
jwt.RegisteredClaims
}
type Manager struct {
secret []byte
expire time.Duration
}
func NewManager(secret string) *Manager {
return &Manager{
secret: []byte(secret),
expire: 7 * 24 * time.Hour,
}
}
func (m *Manager) Generate(userID uint, username, role string) (string, error) {
claims := Claims{
UserID: userID,
Username: username,
Role: role,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(m.expire)),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(m.secret)
}
func (m *Manager) Parse(tokenStr string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, errors.New("unexpected signing method")
}
return m.secret, nil
})
if err != nil {
return nil, err
}
claims, ok := token.Claims.(*Claims)
if !ok || !token.Valid {
return nil, errors.New("invalid token")
}
return claims, nil
}
+52
View File
@@ -0,0 +1,52 @@
package response
import (
"net/http"
"github.com/gin-gonic/gin"
)
type Body struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
func OK(c *gin.Context, data interface{}) {
c.JSON(http.StatusOK, Body{Code: 0, Message: "ok", Data: data})
}
func Fail(c *gin.Context, httpStatus int, code int, message string) {
c.JSON(httpStatus, Body{Code: code, Message: message})
}
func BadRequest(c *gin.Context, message string) {
Fail(c, http.StatusBadRequest, 400, message)
}
func Unauthorized(c *gin.Context, message string) {
Fail(c, http.StatusUnauthorized, 401, message)
}
func Forbidden(c *gin.Context, message string) {
Fail(c, http.StatusForbidden, 403, message)
}
func NotFound(c *gin.Context, message string) {
Fail(c, http.StatusNotFound, 404, message)
}
func ServerError(c *gin.Context, message string) {
Fail(c, http.StatusInternalServerError, 500, message)
}
type PageData struct {
List interface{} `json:"list"`
Total int64 `json:"total"`
Page int `json:"page"`
Size int `json:"size"`
}
func Page(c *gin.Context, list interface{}, total int64, page, size int) {
OK(c, PageData{List: list, Total: total, Page: page, Size: size})
}