auth.go 2.13 KB
Newer Older
1 2 3
package middleware

import (
4
	"crypto/tls"
5 6 7
	"encoding/json"
	"io"
	"net/http"
8
	"time"
9 10

	"github.com/gin-gonic/gin"
11
	"github.com/rs/zerolog/log"
12 13 14 15 16 17 18 19 20 21 22
	"gitlab.com/tensorsecurity-rd/waf-console/internal/utils"
)

const (
	// Cookie name to check for the auth token
	AuthCookieName = "auth_token"
)

// AuthMiddleware validates the auth cookie with SSO service
func AuthMiddleware(ssoUrl string) gin.HandlerFunc {
	return func(c *gin.Context) {
23 24 25 26 27
		// skip ping
		if c.Request.URL.Path != "/ping" {
			c.Next()
			return
		}
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
		// Get auth cookie
		cookies := c.Request.Cookies()
		if len(cookies) == 0 {
			utils.AssembleResponse(c, nil, utils.ErrUnauthorized)
			c.Abort()
			return
		}

		// Create request to SSO service
		req, err := http.NewRequest(http.MethodPost, ssoUrl, nil)
		if err != nil {
			utils.AssembleResponse(c, nil, utils.ErrInternalServer)
			c.Abort()
			return
		}

		// Add auth cookie to request
		for _, cookie := range cookies {
			req.AddCookie(cookie)
		}

		// Make request to SSO service
50 51 52 53 54 55 56 57
		client := &http.Client{
			Timeout: 10 * time.Second,
			Transport: &http.Transport{
				TLSClientConfig: &tls.Config{
					InsecureSkipVerify: true,
				},
			},
		}
58 59
		resp, err := client.Do(req)
		if err != nil {
60
			log.Error().Err(err).Msg("failed to make sso request")
61 62 63 64 65 66 67 68 69
			utils.AssembleResponse(c, nil, utils.ErrInternalServer)
			c.Abort()
			return
		}
		defer resp.Body.Close()

		// Read response body
		body, err := io.ReadAll(resp.Body)
		if err != nil {
70
			log.Error().Err(err).Msg("failed to read sso response body")
71 72 73 74 75 76 77 78
			utils.AssembleResponse(c, nil, utils.ErrInternalServer)
			c.Abort()
			return
		}

		// Parse SSO response
		var ssoResp SSOResponse
		if err := json.Unmarshal(body, &ssoResp); err != nil {
79
			log.Error().Err(err).Msg("failed to unmarshal sso response")
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
			utils.AssembleResponse(c, nil, utils.ErrInternalServer)
			c.Abort()
			return
		}

		// Check if authentication was successful
		if ssoResp.Code != "OK" {
			utils.AssembleResponse(c, nil, utils.ErrUnauthorized)
			c.Abort()
			return
		}

		// Store user info in context for later use
		c.Set("userInfo", ssoResp.Data)

		// Authentication successful, continue
		c.Next()
	}
}