58 lines
1.1 KiB
Go
58 lines
1.1 KiB
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt/v4"
|
|
)
|
|
|
|
type TokenData struct {
|
|
Token string `json:"JWTToken"`
|
|
}
|
|
|
|
const key = "stronk"
|
|
|
|
func validateToken(tStr string) (bool, error) {
|
|
token, err := jwt.Parse(tStr, func(token *jwt.Token) (any, error) {
|
|
return []byte(key), nil
|
|
}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
if _, ok := token.Claims.(jwt.MapClaims); ok {
|
|
return true, nil
|
|
}
|
|
|
|
return false, nil
|
|
}
|
|
|
|
func APIAuthMiddleWare() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
auth := c.GetHeader("Authorization")
|
|
if !strings.HasPrefix(auth, "Bearer ") {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "missing token"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
tokenStr := strings.TrimPrefix(auth, "Bearer ")
|
|
validateToken, err := validateToken(tokenStr)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
if !validateToken {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "token is not valid"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|