39 lines
791 B
Go
39 lines
791 B
Go
package utils
|
|
|
|
import (
|
|
"app/models"
|
|
"os"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"github.com/joho/godotenv"
|
|
"github.com/labstack/echo/v4"
|
|
)
|
|
|
|
func CheckToken(c echo.Context) error {
|
|
err := godotenv.Load("./config/.env")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
secret := os.Getenv("SECRET")
|
|
|
|
cookie, err := c.Cookie("authorization")
|
|
if err != nil {
|
|
return echo.ErrUnauthorized
|
|
}
|
|
|
|
token, err := jwt.ParseWithClaims(cookie.Value, &models.JwtClaims{}, func(token *jwt.Token) (interface{}, error) {
|
|
// Provide the same key used for signing the token
|
|
return []byte(secret), nil
|
|
})
|
|
if err != nil {
|
|
// Handle error, failed to parse the token
|
|
return echo.ErrUnauthorized
|
|
}
|
|
|
|
if _, ok := token.Claims.(*models.JwtClaims); !ok || !token.Valid {
|
|
return echo.ErrUnauthorized
|
|
}
|
|
|
|
return nil
|
|
}
|