|
| 1 | +package authx |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + |
| 6 | + "github.com/projectdiscovery/retryablehttp-go" |
| 7 | +) |
| 8 | + |
| 9 | +var ( |
| 10 | + _ AuthStrategy = &CookiesAuthStrategy{} |
| 11 | +) |
| 12 | + |
| 13 | +// CookiesAuthStrategy is a strategy for cookies auth |
| 14 | +type CookiesAuthStrategy struct { |
| 15 | + Data *Secret |
| 16 | +} |
| 17 | + |
| 18 | +// NewCookiesAuthStrategy creates a new cookies auth strategy |
| 19 | +func NewCookiesAuthStrategy(data *Secret) *CookiesAuthStrategy { |
| 20 | + return &CookiesAuthStrategy{Data: data} |
| 21 | +} |
| 22 | + |
| 23 | +// Apply applies the cookies auth strategy to the request |
| 24 | +func (s *CookiesAuthStrategy) Apply(req *http.Request) { |
| 25 | + for _, cookie := range s.Data.Cookies { |
| 26 | + req.AddCookie(&http.Cookie{ |
| 27 | + Name: cookie.Key, |
| 28 | + Value: cookie.Value, |
| 29 | + }) |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +// ApplyOnRR applies the cookies auth strategy to the retryable request |
| 34 | +func (s *CookiesAuthStrategy) ApplyOnRR(req *retryablehttp.Request) { |
| 35 | + // Build a set of cookie names to replace |
| 36 | + newCookieNames := make(map[string]struct{}, len(s.Data.Cookies)) |
| 37 | + for _, cookie := range s.Data.Cookies { |
| 38 | + newCookieNames[cookie.Key] = struct{}{} |
| 39 | + } |
| 40 | + |
| 41 | + // Filter existing cookies, keeping only those not being replaced |
| 42 | + existingCookies := req.Cookies() |
| 43 | + filteredCookies := make([]*http.Cookie, 0, len(existingCookies)) |
| 44 | + for _, cookie := range existingCookies { |
| 45 | + if _, shouldReplace := newCookieNames[cookie.Name]; !shouldReplace { |
| 46 | + filteredCookies = append(filteredCookies, cookie) |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + // Clear and reset cookies |
| 51 | + req.Header.Del("Cookie") |
| 52 | + for _, cookie := range filteredCookies { |
| 53 | + req.AddCookie(cookie) |
| 54 | + } |
| 55 | + // Add new cookies |
| 56 | + for _, cookie := range s.Data.Cookies { |
| 57 | + req.AddCookie(&http.Cookie{ |
| 58 | + Name: cookie.Key, |
| 59 | + Value: cookie.Value, |
| 60 | + }) |
| 61 | + } |
| 62 | +} |
0 commit comments