add jwt / complete the rotation verification

This commit is contained in:
landaiqing
2024-08-12 22:05:59 +08:00
parent 54f6256c00
commit 48c5aeb0f4
31 changed files with 1702 additions and 44 deletions

67
utils/cache.go Normal file
View File

@@ -0,0 +1,67 @@
package utils
import (
"sync"
"time"
)
type cachedata = struct {
data []byte
createAt time.Time
}
var mux sync.Mutex
var cachemaps = make(map[string]*cachedata)
// WriteCache .
func WriteCache(key string, data []byte) {
mux.Lock()
defer mux.Unlock()
cachemaps[key] = &cachedata{
createAt: time.Now(),
data: data,
}
}
// ReadCache .
func ReadCache(key string) []byte {
mux.Lock()
defer mux.Unlock()
if cd, ok := cachemaps[key]; ok {
return cd.data
}
return []byte{}
}
// ClearCache .
func ClearCache(key string) {
mux.Lock()
defer mux.Unlock()
delete(cachemaps, key)
}
// RunTimedTask .
func RunTimedTask() {
ticker := time.NewTicker(time.Minute * 5)
go func() {
for range ticker.C {
checkCacheOvertimeFile()
}
}()
}
func checkCacheOvertimeFile() {
var keys = make([]string, 0)
for key, data := range cachemaps {
ex := time.Now().Unix() - data.createAt.Unix()
if ex > (60 * 30) {
keys = append(keys, key)
}
}
for _, key := range keys {
ClearCache(key)
}
}

20
utils/genValidateCode.go Normal file
View File

@@ -0,0 +1,20 @@
package utils
import (
"fmt"
"math/rand"
"strings"
"time"
)
func GenValidateCode(width int) string {
numeric := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
r := len(numeric)
rand.New(rand.NewSource(time.Now().UnixNano()))
var sb strings.Builder
for i := 0; i < width; i++ {
fmt.Fprintf(&sb, "%d", numeric[rand.Intn(r)])
}
return sb.String()
}

49
utils/jwt.go Normal file
View File

@@ -0,0 +1,49 @@
package utils
import (
"github.com/golang-jwt/jwt/v5"
"schisandra-cloud-album/global"
"time"
)
type JWTPayload struct {
UserID int `json:"user_id"`
Role string `json:"role"`
Username string `json:"username"`
}
type JWTClaims struct {
JWTPayload
jwt.RegisteredClaims
}
var MySecret = []byte(global.CONFIG.JWT.Secret)
// GenerateToken generates a JWT token with the given payload
func GenerateToken(payload JWTPayload) (string, error) {
claims := JWTClaims{
JWTPayload: payload,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)),
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(MySecret)
}
// ParseToken parses a JWT token and returns the payload
func ParseToken(tokenString string) (*JWTPayload, error) {
token, err := jwt.ParseWithClaims(tokenString, &JWTClaims{}, func(token *jwt.Token) (interface{}, error) {
return MySecret, nil
})
if err != nil {
global.LOG.Error(err)
return nil, err
}
if claims, ok := token.Claims.(*JWTClaims); ok && token.Valid {
return &claims.JWTPayload, nil
}
return nil, err
}