This simple go program creates jwt tokens based on gin.

This commit is contained in:
2023-03-30 00:01:31 +02:00
parent bfc2c3584c
commit f53fc43920
13 changed files with 434 additions and 1 deletions

61
middleware/requireAuth.go Normal file
View File

@@ -0,0 +1,61 @@
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)
}
}