encrypted_params.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package middleware
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "net/http"
  7. "github.com/0xJacky/Nginx-UI/internal/crypto"
  8. "github.com/gin-gonic/gin"
  9. "github.com/uozi-tech/cosy"
  10. )
  11. var (
  12. e = cosy.NewErrorScope("middleware")
  13. ErrInvalidRequestFormat = e.New(40000, "invalid request format")
  14. ErrDecryptionFailed = e.New(40001, "decryption failed")
  15. )
  16. func EncryptedParams() gin.HandlerFunc {
  17. return func(c *gin.Context) {
  18. // read the encrypted payload
  19. var encryptedReq struct {
  20. EncryptedParams string `json:"encrypted_params"`
  21. }
  22. if err := c.ShouldBindJSON(&encryptedReq); err != nil {
  23. c.AbortWithStatusJSON(http.StatusBadRequest, ErrInvalidRequestFormat)
  24. return
  25. }
  26. // decrypt the parameters
  27. decryptedData, err := crypto.Decrypt(encryptedReq.EncryptedParams)
  28. if err != nil {
  29. c.AbortWithStatusJSON(http.StatusBadRequest, ErrDecryptionFailed)
  30. return
  31. }
  32. // replace request body with decrypted data
  33. newBody, _ := json.Marshal(decryptedData)
  34. c.Request.Body = io.NopCloser(bytes.NewReader(newBody))
  35. c.Request.ContentLength = int64(len(newBody))
  36. c.Next()
  37. }
  38. }