1
0
Fork 0
mirror of https://github.com/Eggbertx/gochan.git synced 2025-09-11 11:46:24 -07:00

Add config option to set max age for staff cookies

resolves  #41
This commit is contained in:
Eggbertx 2021-03-26 11:10:05 -07:00
parent 2382b30af1
commit c385a39bec
8 changed files with 64 additions and 23 deletions

View file

@ -5,10 +5,13 @@ import (
"io/ioutil"
"net"
"reflect"
"github.com/gochan-org/gochan/pkg/gcutil"
)
const (
randomStringSize = 16
cookieMaxAgeEx = ` (example: "1 year 2 months 3 days 4 hours", or "1y2mo3d4h"`
)
var (
@ -19,6 +22,7 @@ var (
"FirstPage": []string{"index.html", "board.html", "firstrun.html"},
"DocumentRoot": "html",
"TemplateDir": "templates",
"CookieMaxAge": "1y",
"LogDir": "log",
"SillyTags": []string{},
@ -75,12 +79,13 @@ type Style struct {
// If a field has a critical struct tag set to "true", a warning will be printed
// if it exists in the defaults map and an error will be printed if it doesn't.
type GochanConfig struct {
ListenIP string `critical:"true"`
Port int `critical:"true"`
FirstPage []string `critical:"true"`
Username string `critical:"true"`
UseFastCGI bool `critical:"true"`
DebugMode bool `description:"Disables several spam/browser checks that can cause problems when hosting an instance locally."`
ListenIP string `critical:"true"`
Port int `critical:"true"`
FirstPage []string `critical:"true"`
Username string `critical:"true"`
UseFastCGI bool `critical:"true"`
DebugMode bool `description:"Disables several spam/browser checks that can cause problems when hosting an instance locally."`
CookieMaxAge string `description:"The amount of time that session cookies will exist before they expire (ex: 1y2mo3d4h or 1 year 2 months 3 days 4 hours). Default is 1 year"`
DocumentRoot string `critical:"true"`
TemplateDir string `critical:"true"`
@ -179,6 +184,14 @@ func (cfg *GochanConfig) ValidateValues() error {
cfg.FirstPage = cfgDefaults["FirstPage"].([]string)
changed = true
}
_, err := gcutil.ParseDurationString(cfg.CookieMaxAge)
if err == gcutil.ErrInvalidDurationString {
return &ErrInvalidValue{Field: "CookieMaxAge", Value: cfg.CookieMaxAge, Details: err.Error() + cookieMaxAgeEx}
} else if err == gcutil.ErrEmptyDurationString {
return &ErrInvalidValue{Field: "CookieMaxAge", Details: err.Error() + cookieMaxAgeEx}
} else if err != nil {
return err
}
if cfg.DBtype != "mysql" && cfg.DBtype != "postgresql" {
return &ErrInvalidValue{Field: "DBtype", Value: cfg.DBtype, Details: "currently supported values: mysql, postgresql"}
}

View file

@ -239,7 +239,7 @@ var funcMap = template.FuncMap{
}
return loopArr
},
"generateConfigTable": func() string {
"generateConfigTable": func() template.HTML {
configType := reflect.TypeOf(*config.Config)
tableOut := `<table style="border-collapse: collapse;" id="config"><tr><th>Field name</th><th>Value</th><th>Type</th><th>Description</th></tr>`
numFields := configType.NumField()
@ -289,7 +289,7 @@ var funcMap = template.FuncMap{
tableOut += "</tr>"
}
tableOut += "</table>"
return tableOut
return template.HTML(tableOut)
},
"isStyleDefault": func(style string) bool {
return style == config.Config.DefaultStyle

View file

@ -46,7 +46,7 @@ func templateError(name string, err error) error {
if err == nil {
return nil
}
return fmt.Errorf("Failed loading template '%s/%s': %s",
return fmt.Errorf("failed loading template '%s/%s': %s",
config.Config.TemplateDir, name, err.Error())
}

View file

@ -22,11 +22,16 @@ import (
"golang.org/x/crypto/bcrypt"
)
const (
// DefaultMaxAge is used for cookies that have an invalid or unset max age (default is 1 year)
DefaultMaxAge = 60 * 60 * 24 * 31
)
var (
// ErrNotImplemented should be used for unimplemented functionality when necessary
ErrNotImplemented = errors.New("Not implemented")
ErrEmptyDurationString = errors.New("Empty Duration string")
ErrInvalidDurationString = errors.New("Invalid Duration string")
ErrNotImplemented = errors.New("not implemented")
ErrEmptyDurationString = errors.New("empty Duration string")
ErrInvalidDurationString = errors.New("invalid Duration string")
durationRegexp = regexp.MustCompile(`^((\d+)\s?ye?a?r?s?)?\s?((\d+)\s?mon?t?h?s?)?\s?((\d+)\s?we?e?k?s?)?\s?((\d+)\s?da?y?s?)?\s?((\d+)\s?ho?u?r?s?)?\s?((\d+)\s?mi?n?u?t?e?s?)?\s?((\d+)\s?s?e?c?o?n?d?s?)?$`)
)

View file

@ -95,6 +95,11 @@ var actions = map[string]Action{
status += gclog.Println(gclog.LErrorLog,
"Error backing up old gochan.json, cancelling save:", err.Error())
} else {
config.Config.CookieMaxAge = request.PostFormValue("CookieMaxAge")
if _, err = gcutil.ParseDurationString(config.Config.CookieMaxAge); err != nil {
status += err.Error()
config.Config.CookieMaxAge = "1y"
}
config.Config.Lockdown = (request.PostFormValue("Lockdown") == "on")
config.Config.LockdownMessage = request.PostFormValue("LockdownMessage")
SillytagsArr := strings.Split(request.PostFormValue("Sillytags"), "\n")
@ -556,13 +561,12 @@ var actions = map[string]Action{
do = ""
boardCreationStatus = gclog.Print(gclog.LErrorLog, "Error creating board: ", err.Error())
break
} else {
boardCreationStatus = "Board created successfully"
building.BuildBoards(false)
gcsql.ResetBoardSectionArrays()
gclog.Print(gclog.LStaffLog, "Boards rebuilt successfully")
done = true
}
boardCreationStatus = "Board created successfully"
building.BuildBoards(false)
gcsql.ResetBoardSectionArrays()
gclog.Print(gclog.LStaffLog, "Boards rebuilt successfully")
done = true
case do == "del":
// resetBoardSectionArrays()
case do == "edit":

View file

@ -4,8 +4,10 @@ import (
"net/http"
"time"
"github.com/gochan-org/gochan/pkg/config"
"github.com/gochan-org/gochan/pkg/gclog"
"github.com/gochan-org/gochan/pkg/gcsql"
"github.com/gochan-org/gochan/pkg/gcutil"
"github.com/gochan-org/gochan/pkg/serverutil"
"golang.org/x/crypto/bcrypt"
)
@ -40,12 +42,17 @@ func createSession(key, username, password string, request *http.Request, writer
}
// successful login, add cookie that expires in one month
maxAge, err := gcutil.ParseDurationString(config.Config.CookieMaxAge)
if err != nil {
maxAge = gcutil.DefaultMaxAge
}
http.SetCookie(writer, &http.Cookie{
Name: "sessiondata",
Value: key,
Path: "/",
Domain: domain,
MaxAge: 60 * 60 * 24 * 7,
MaxAge: int(maxAge),
})
if err = gcsql.CreateSession(key, username); err != nil {

View file

@ -60,7 +60,11 @@ func MakePost(writer http.ResponseWriter, request *http.Request) {
formEmail = request.FormValue("postemail")
http.SetCookie(writer, &http.Cookie{Name: "email", Value: formEmail, MaxAge: yearInSeconds})
http.SetCookie(writer, &http.Cookie{
Name: "email",
Value: formEmail,
MaxAge: yearInSeconds,
})
if !strings.Contains(formEmail, "noko") && !strings.Contains(formEmail, "sage") {
post.Email = formEmail
@ -98,8 +102,16 @@ func MakePost(writer http.ResponseWriter, request *http.Request) {
nameCookie = strings.Replace(url.QueryEscape(nameCookie), "+", "%20", -1)
// add name and email cookies that will expire in a year (31536000 seconds)
http.SetCookie(writer, &http.Cookie{Name: "name", Value: nameCookie, MaxAge: yearInSeconds})
http.SetCookie(writer, &http.Cookie{Name: "password", Value: password, MaxAge: yearInSeconds})
http.SetCookie(writer, &http.Cookie{
Name: "name",
Value: nameCookie,
MaxAge: yearInSeconds,
})
http.SetCookie(writer, &http.Cookie{
Name: "password",
Value: password,
MaxAge: yearInSeconds,
})
post.IP = gcutil.GetRealIP(request)
post.Timestamp = time.Now()

View file

@ -21,7 +21,7 @@
"Lockdown": false,
"LockdownMessage": "This imageboard has temporarily disabled posting. We apologize for the inconvenience",
"Sillytags": ["Admin","Mod","Janitor","Faget","Kick me","Derpy","Troll","worst pony"],
"Sillytags": ["Admin","Mod","Janitor","Dweeb","Kick me","Troll","worst pony"],
"UseSillytags": false,
"Modboard": "staff",