Add JWT authentication for admin dashboard login

This commit is contained in:
2025-05-16 14:41:16 +03:30
parent 855c778654
commit 1abc05ecd9
6 changed files with 93 additions and 13 deletions

View File

@@ -1,2 +1,58 @@
package auth
import (
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
type JwtTokenGenerator struct {
Key string
Issuer string
Audience string
}
func NewJwtTokenGenerator(key string, issuer string, audience string) *JwtTokenGenerator {
return &JwtTokenGenerator{
Key: key,
Issuer: issuer,
Audience: audience,
}
}
func (j *JwtTokenGenerator) GenerateToken(claims map[string]interface{}) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"exp": time.Now().AddDate(0, 0, 3).Unix(),
"iat": time.Now().Unix(),
"iss": j.Issuer,
"aud": j.Audience,
})
for k, v := range claims {
token.Claims.(jwt.MapClaims)[k] = v
}
return token.SignedString([]byte(j.Key))
}
// Gin middleware
func (j *JwtTokenGenerator) GinMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
token, err := c.Request.Cookie("token")
if err != nil {
c.AbortWithStatusJSON(401, gin.H{"error": "Unauthorized"})
return
}
_, err = jwt.Parse(token.Value, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.ErrSignatureInvalid
}
return []byte(j.Key), nil
})
if err != nil {
c.AbortWithStatusJSON(401, gin.H{"error": "Unauthorized"})
return
}
c.Next()
}
}