implement ban support

This commit is contained in:
mappu 2017-07-11 19:14:26 +12:00
parent 01b538aee2
commit 1bb94eae76
3 changed files with 27 additions and 6 deletions

View File

@ -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]
}

View File

@ -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

View File

@ -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