teldrive/routes/middleware.go

43 lines
731 B
Go
Raw Normal View History

2023-08-12 19:21:42 +08:00
package routes
import (
"net/http"
"time"
2023-08-16 05:53:02 +08:00
"github.com/divyam234/teldrive/utils/auth"
2023-08-12 19:21:42 +08:00
"github.com/gin-gonic/gin"
"github.com/go-jose/go-jose/v3/jwt"
)
func Authmiddleware(c *gin.Context) {
2023-08-26 15:51:04 +08:00
cookie, err := c.Request.Cookie("user-session")
2023-08-12 19:21:42 +08:00
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing session cookie"})
2023-08-17 23:32:40 +08:00
c.Abort()
return
2023-08-12 19:21:42 +08:00
}
now := time.Now().UTC()
jwePayload, err := auth.Decode(cookie.Value)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
2023-08-17 23:32:40 +08:00
c.Abort()
return
2023-08-12 19:21:42 +08:00
}
if *jwePayload.Expiry < *jwt.NewNumericDate(now) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "token expired"})
2023-08-17 23:32:40 +08:00
c.Abort()
return
2023-08-12 19:21:42 +08:00
}
c.Set("jwtUser", jwePayload)
c.Next()
}