2022-08-16 23:30:23 +08:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2022-10-17 16:32:31 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/global"
|
2022-08-16 23:30:23 +08:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/gorilla/csrf"
|
|
|
|
adapter "github.com/gwatts/gin-adapter"
|
|
|
|
)
|
|
|
|
|
|
|
|
func CSRF() gin.HandlerFunc {
|
|
|
|
csrfMd := csrf.Protect(
|
|
|
|
[]byte(global.CONF.Csrf.Key),
|
2022-08-17 15:02:17 +08:00
|
|
|
csrf.Path("/api"),
|
2022-08-16 23:30:23 +08:00
|
|
|
csrf.ErrorHandler(http.HandlerFunc(
|
|
|
|
func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.WriteHeader(http.StatusForbidden)
|
2022-08-17 11:47:56 +08:00
|
|
|
_, _ = w.Write([]byte("csrf token invalid"))
|
2022-08-16 23:30:23 +08:00
|
|
|
})),
|
|
|
|
)
|
|
|
|
return adapter.Wrap(csrfMd)
|
|
|
|
}
|
|
|
|
|
|
|
|
func LoadCsrfToken() gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
c.Header("X-CSRF-TOKEN", csrf.Token(c.Request))
|
|
|
|
}
|
|
|
|
}
|