-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathip_restrict.go
More file actions
59 lines (52 loc) · 1.48 KB
/
Copy pathip_restrict.go
File metadata and controls
59 lines (52 loc) · 1.48 KB
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
49
50
51
52
53
54
55
56
57
58
59
package middlewares
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/humanjuan/golyn/globals"
"github.com/humanjuan/golyn/internal/utils"
"net/http"
"strings"
)
// RestrictAPIRequestMiddleware ensures requests only come from allowed domains
func RestrictAPIRequestMiddleware(dev bool) gin.HandlerFunc {
log := globals.GetAppLogger()
log.Debug("RestrictAPIRequestMiddleware() | dev: %v", dev)
return func(c *gin.Context) {
hostParts := strings.Split(c.Request.Host, ":")
host := hostParts[0]
log.Debug("RestrictAPIRequestMiddleware() | Request Host: %s", host)
config := globals.GetConfig()
allowed := false
for _, site := range config.Sites {
for _, domain := range site.Domains {
domain = strings.TrimSpace(domain)
if strings.ToLower(host) == strings.ToLower(domain) {
allowed = true
break
}
if dev {
// In dev mode, also allow .local version of the domains
devDomain := strings.Replace(domain, ".com", ".local", 1)
if !strings.HasSuffix(devDomain, ".local") {
devDomain = devDomain + ".local"
}
if strings.ToLower(host) == strings.ToLower(devDomain) {
allowed = true
break
}
}
}
if allowed {
break
}
}
if !allowed {
err := fmt.Errorf("access denied for host %s", host)
c.Error(utils.NewHTTPError(http.StatusForbidden, err.Error()))
c.Abort()
log.Warn("RestrictAPIRequestMiddleware() | Access denied | Host: %s | URL: %s", host, c.Request.URL)
return
}
c.Next()
}
}