From 1bb94eae7630db5a4a0c294cdfd616e6a41af5fe Mon Sep 17 00:00:00 2001 From: mappu Date: Tue, 11 Jul 2017 19:14:26 +1200 Subject: [PATCH] implement ban support --- AuthorHash.go | 7 +++++-- TODO.txt | 4 ---- WikiServer.go | 22 ++++++++++++++++++++++ 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/AuthorHash.go b/AuthorHash.go index b894aba..ca06fc3 100644 --- a/AuthorHash.go +++ b/AuthorHash.go @@ -7,9 +7,12 @@ import ( "strings" ) +func RemoteAddrToIPAddress(remoteAddr string) string { + return strings.TrimRight(strings.TrimRight(remoteAddr, `0123456789`), `:`) // trim trailing port; IPv4 and IPv6-safe +} + func Author(r *http.Request) string { userAgentHash := md5.Sum([]byte(r.UserAgent())) - ipAddr := strings.TrimRight(strings.TrimRight(r.RemoteAddr, `0123456789`), `:`) // trim trailing port; IPv4 and IPv6-safe - return ipAddr + "-" + hex.EncodeToString(userAgentHash[:])[:6] + return RemoteAddrToIPAddress(r.RemoteAddr) + "-" + hex.EncodeToString(userAgentHash[:])[:6] } diff --git a/TODO.txt b/TODO.txt index 4ddd01a..2f2bf49 100644 --- a/TODO.txt +++ b/TODO.txt @@ -1,8 +1,4 @@ -RSS - -Ban support - Extend command-line tool to support remaining features (bans, ...) Command-line tool automatically open browser if ran with no arguments diff --git a/WikiServer.go b/WikiServer.go index 2b06431..d5130c0 100644 --- a/WikiServer.go +++ b/WikiServer.go @@ -19,6 +19,7 @@ type WikiServer struct { pageTmp *template.Template loc *time.Location rxDiff *regexp.Regexp + bans []*regexp.Regexp } func NewWikiServer(opts *ServerOptions) (*WikiServer, error) { @@ -43,7 +44,18 @@ func NewWikiServer(opts *ServerOptions) (*WikiServer, error) { pageTmp: tmpl, loc: loc, rxDiff: regexp.MustCompile(`diff/(\d+)/(\d+)`), + bans: make([]*regexp.Regexp, 0, len(opts.BannedUserIPRegexes)), } + + for _, banRx := range opts.BannedUserIPRegexes { + rx, err := regexp.Compile(banRx) + if err != nil { + return nil, err + } + + ws.bans = append(ws.bans, rx) + } + return &ws, nil } @@ -54,6 +66,16 @@ func (this *WikiServer) Close() { func (this *WikiServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Server", "YATWiki3") + if len(this.bans) > 0 { + remoteIP := RemoteAddrToIPAddress(r.RemoteAddr) + for _, ban := range this.bans { + if ban.MatchString(remoteIP) { + http.Error(w, "Unauthorised", 403) + return + } + } + } + if !strings.HasPrefix(r.URL.Path, this.opts.ExpectBaseURL) { http.Error(w, "Bad request", 400) return