Go-JWT-Tests/middleware/requireAuth.go

62 lines
1.3 KiB
Go
Raw Permalink Normal View History

package middleware
import (
"fmt"
"net/http"
"os"
"time"
"gitea.voser.cloud/janic/Go-JWT-Tests/initializers"
"gitea.voser.cloud/janic/Go-JWT-Tests/models"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
func RequireAuth(c *gin.Context) {
// Get the cookie from request
tokenString, err := c.Cookie("Authorization")
if err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
}
// Decode & validate
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return []byte(os.Getenv("SECRET")), nil
})
// Abort if no token is set
if token == nil {
c.AbortWithStatus(http.StatusUnauthorized)
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
// Check the expiration date
if float64(time.Now().Unix()) > claims["exp"].(float64) {
c.AbortWithStatus(http.StatusUnauthorized)
}
// Lookup the user with the token
var user models.User
initializers.DB.First(&user, claims["sub"])
if user.ID == 0 {
c.AbortWithStatus(http.StatusUnauthorized)
}
// Attach to request
c.Set("user", user)
// Continue
c.Next()
} else {
fmt.Println(err)
}
}