You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
774 B
Go

package auth
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
)
func GetUser() gin.HandlerFunc {
return func(c *gin.Context) {
tokenCookie, err := c.Cookie("token")
if err != nil || tokenCookie == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
token, err := jwt.ParseWithClaims(tokenCookie, &jwt.MapClaims{}, func(t *jwt.Token) (interface{}, error) {
return secretKey, nil
})
if err != nil || !token.Valid {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
claims := token.Claims.(jwt.MapClaims)
c.Set("user_id", claims["user_id"])
c.Set("username", claims["username"])
c.Set("user_email", claims["email"])
c.Next()
}
}