AuthMiddleware.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package middleware
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "io/ioutil"
  6. "lims-extend/response"
  7. "net/http"
  8. "strings"
  9. "time"
  10. )
  11. var (
  12. pyBackendIp string
  13. pyPort string
  14. )
  15. func InitMiddleware(ip string, port string) {
  16. pyBackendIp = ip
  17. pyPort = port
  18. }
  19. func AuthMiddleware() gin.HandlerFunc {
  20. return func(c *gin.Context) {
  21. //获取authorization header
  22. accessToken := c.GetHeader("accessToken")
  23. client := &http.Client{Timeout: 1 * time.Second}
  24. req, _ := http.NewRequest("GET",
  25. fmt.Sprintf("http://%s:%s/api/v1/users/TestLaboratory_V1_User_1", pyBackendIp, pyPort), nil)
  26. req.Header.Add("accessToken", accessToken)
  27. resp, err := client.Do(req)
  28. if err != nil || resp.StatusCode != 200 {
  29. response.Fail(c, nil, "无法连接Python_Backend权限认证服务器")
  30. c.Abort()
  31. return
  32. }
  33. defer resp.Body.Close()
  34. body, _ := ioutil.ReadAll(resp.Body)
  35. res := string(body)
  36. if strings.Contains(res, "username") {
  37. } else {
  38. response.Fail(c, nil, "权限不足")
  39. c.Abort()
  40. return
  41. }
  42. }
  43. }