/
firewall.go
48 lines (41 loc) · 1.07 KB
/
firewall.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package middleware
// github.com/pilinux/gorestlib
// The MIT License (MIT)
// Copyright (c) 2022 pilinux
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// Firewall - whitelist/blacklist IPs
func Firewall(listType string, ipList string) gin.HandlerFunc {
return func(c *gin.Context) {
// Get IP address by reading off the forwarded-for
// header (for proxies) and falls back to use the remote address
ipAddress := c.Request.RemoteAddr
forwardedAddress := c.Request.Header.Get("X-Forwarded-For")
if forwardedAddress != "" {
//X-Forwarded-For
ipAddress = forwardedAddress //Single IP
//Array of IPs
ip := strings.Split(forwardedAddress, ", ")
if len(ip) > 1 {
ipAddress = ip[0] //First IP
}
}
if !strings.Contains(ipList, "*") {
if listType == "whitelist" {
if !strings.Contains(ipList, ipAddress) {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
}
if listType == "blacklist" {
if strings.Contains(ipList, ipAddress) {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
}
}
}
}