dashboard: Can restrict access by IP

This commit is contained in:
nemunaire 2022-06-06 11:02:35 +02:00
parent 437ed4d393
commit 0e6a6893f1
2 changed files with 52 additions and 4 deletions

View file

@ -2,8 +2,12 @@ package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/gin-gonic/gin"
@ -13,9 +17,10 @@ type App struct {
router *gin.Engine
srv *http.Server
bind string
ips []string
}
func NewApp(htpasswd_file *string, baseURL string, bind string) App {
func NewApp(htpasswd_file *string, restrict_to_ips *string, baseURL string, bind string) App {
gin.ForceConsoleColor()
router := gin.Default()
@ -34,16 +39,58 @@ func NewApp(htpasswd_file *string, baseURL string, bind string) App {
baserouter.Use(Htpassword(*htpasswd_file))
}
declareStaticRoutes(baserouter, baseURL)
app := App{
router: router,
bind: bind,
}
if restrict_to_ips != nil && len(*restrict_to_ips) > 0 {
var err error
app.ips, err = loadIPs(*restrict_to_ips)
if err != nil {
log.Fatal("Unable to parse ip restricting file: ", err)
}
baserouter.Use(app.Restrict2IPs)
}
declareStaticRoutes(baserouter, baseURL)
return app
}
func loadIPs(file string) ([]string, error) {
fd, err := os.Open(file)
if err != nil {
return nil, err
}
defer fd.Close()
var ret []string
jdec := json.NewDecoder(fd)
if err := jdec.Decode(&ret); err != nil {
return ret, err
}
return ret, nil
}
func (app *App) Restrict2IPs(c *gin.Context) {
found := false
for _, ip := range app.ips {
if strings.HasPrefix(c.Request.RemoteAddr, ip) {
found = true
break
}
}
if found {
c.Next()
} else {
c.AbortWithError(http.StatusForbidden, fmt.Errorf("IP not authorized: %s", c.Request.RemoteAddr))
}
}
func (app *App) Start() {
app.srv = &http.Server{
Addr: app.bind,