Spaces:
Runtime error
Runtime error
File size: 1,170 Bytes
2196bfe |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
package middleware
import (
"fmt"
"net/http"
"os"
"time"
"uptime/backend/database"
"uptime/backend/models"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
func RequireAuth(c *gin.Context) {
tokenString, err := c.Cookie("Authorization")
if err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
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"])
}
return []byte(os.Getenv("SECRET")), nil
})
if err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
if float64(time.Now().Unix()) > claims["exp"].(float64) {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
var user models.User
database.DB.First(&user, claims["sub"])
if user.ID == 0 {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
c.Set("user", user)
c.Next()
} else {
c.AbortWithStatus(http.StatusUnauthorized)
}
} |