68 lines
1.4 KiB
Go
68 lines
1.4 KiB
Go
package auth
|
|
|
|
import (
|
|
"kon/config"
|
|
"kon/utils"
|
|
"log"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/dchest/uniuri"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
var Hashes = map[string]time.Time{}
|
|
var HashesMutex = sync.RWMutex{}
|
|
|
|
func CreateToken() string {
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256,
|
|
jwt.MapClaims{
|
|
"reqHash": uniuri.New(),
|
|
"exp": time.Now().Add(time.Hour * 24).Unix(),
|
|
})
|
|
|
|
tokenString, err := token.SignedString(config.AuthSecret)
|
|
utils.CheckError(err)
|
|
|
|
return tokenString
|
|
}
|
|
|
|
func VerifyToken(tokenString string) bool {
|
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
|
return config.AuthSecret, nil
|
|
})
|
|
|
|
if err != nil {
|
|
return false
|
|
}
|
|
|
|
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
|
_, does_claim_have_req_hash := claims["reqHash"]
|
|
if does_claim_have_req_hash {
|
|
HashesMutex.RLock()
|
|
val, exists := Hashes[claims["reqHash"].(string)]
|
|
HashesMutex.RUnlock()
|
|
if exists {
|
|
if time.Since(val) > 48*time.Hour {
|
|
HashesMutex.Lock()
|
|
Hashes[claims["reqHash"].(string)] = time.Now()
|
|
HashesMutex.Unlock()
|
|
return true
|
|
} else {
|
|
return false
|
|
}
|
|
} else {
|
|
HashesMutex.Lock()
|
|
Hashes[claims["reqHash"].(string)] = time.Now()
|
|
HashesMutex.Unlock()
|
|
return true
|
|
}
|
|
} else {
|
|
return false
|
|
}
|
|
} else {
|
|
log.Printf("Invalid JWT Token")
|
|
return false
|
|
}
|
|
}
|