add basic jwt auth
This commit is contained in:
70
middlewares/requireAuth.go
Normal file
70
middlewares/requireAuth.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package middlewares
|
||||
|
||||
import(
|
||||
"os"
|
||||
"fmt"
|
||||
"time"
|
||||
"net/http"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"example.com/gin/test/models"
|
||||
)
|
||||
|
||||
type AuthValidator struct {
|
||||
DB *gorm.DB
|
||||
}
|
||||
|
||||
func (av *AuthValidator) RequireAuth(c *gin.Context) {
|
||||
// Get Cookie
|
||||
tokenString, err := c.Cookie("Authorization")
|
||||
|
||||
if err != nil {
|
||||
c.AbortWithStatus(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
//Validate
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
// Don't forget to validate the alg is what you expect:
|
||||
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
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
c.AbortWithStatus(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if claims, ok := token.Claims.(jwt.MapClaims); ok {
|
||||
//Check Expiration
|
||||
if float64(time.Now().Unix()) > claims["exp"].(float64) {
|
||||
//expired
|
||||
c.AbortWithStatus(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
//Find user
|
||||
var user models.User
|
||||
result := av.DB.First(&user, claims["sub"])
|
||||
|
||||
if result.Error != nil {
|
||||
c.AbortWithStatus(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
//Attach to req
|
||||
c.Set("user", user)
|
||||
|
||||
// Coninue
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
c.AbortWithStatus(http.StatusUnauthorized)
|
||||
}
|
||||
Reference in New Issue
Block a user