AuthMiddleware.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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?format=json", pyBackendIp, pyPort), nil)
  26. req.Header.Add("accessToken", accessToken)
  27. resp, err := client.Do(req)
  28. if err != nil {
  29. fmt.Println(err)
  30. fmt.Println(resp.StatusCode)
  31. response.Fail(c, nil, "无法连接Python_Backend权限认证服务器")
  32. c.Abort()
  33. return
  34. }
  35. defer resp.Body.Close()
  36. body, _ := ioutil.ReadAll(resp.Body)
  37. res := string(body)
  38. if strings.Contains(res, "username") {
  39. } else {
  40. response.Fail(c, nil, "权限不足")
  41. c.Abort()
  42. return
  43. }
  44. }
  45. }