minor bugfixes and cleanup

This commit is contained in:
ston1th 2018-09-19 00:10:16 +02:00
commit 97d914bce4
26 changed files with 198 additions and 221 deletions

View file

@ -25,7 +25,7 @@ func newContext(w http.ResponseWriter, r *http.Request, s *HTTPServer) (ctx *Con
h.Set("X-Frame-Options", "DENY")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-XSS-Protection", "1; mode=block")
h.Set("Content-Security-Policy", "default-src 'none';style-src 'self' 'unsafe-inline';frame-ancestors 'none'")
h.Set("Content-Security-Policy", "default-src 'none';style-src 'self';frame-ancestors 'none'")
ctx = &Context{
Request: r,
Response: w,
@ -101,6 +101,10 @@ func (c *Context) Exec() {
c.Data.Login = c.LoggedOn()
c.Data.Time = time.Since(c.Time).Nanoseconds() / 1e5
if c.Data.Msg != "" {
c.Status = http.StatusBadRequest
}
c.Err = c.T.Execute(c.Response, c.Data)
if c.Err != nil {
c.Status = http.StatusInternalServerError
@ -118,6 +122,16 @@ func (c *Context) log() {
log.Printf("%s %s %s %d\n", c.Request.RemoteAddr, c.Request.Method, c.Request.URL, c.Status)
}
func (c *Context) Error(i interface{}) {
switch v := i.(type) {
case string:
c.Data.Msg = v
case error:
c.Data.Msg = v.Error()
}
c.Exec()
}
func (c *Context) NotFound() {
c.Template("notFoundHandler")
c.Data = webData{Title: "404"}
@ -170,17 +184,11 @@ func (c *Context) Var(name string) (ret string) {
return
}
// TODO remove f
// CheckToken validates the xsrf token
func (c *Context) CheckXsrf(f func()) (ok bool) {
// CheckXsrf validates the xsrf token
func (c *Context) CheckXsrf() (ok bool) {
ok = checkXsrf(c.Form("token"), c.Token.RawSig()[:keySize])
if !ok {
if f != nil {
f()
return
}
c.Data.Msg = "wrong csrf token"
c.Exec()
c.Error("wrong csrf token")
}
return
}
@ -190,26 +198,6 @@ func (c *Context) LoggedOn() (ok bool) {
return
}
func newCookie(value string, maxAge int) (cookie *http.Cookie) {
cookie = &http.Cookie{
Name: cookieName,
Value: value,
Path: "/",
MaxAge: maxAge,
//TODO make secure configurable
Secure: false,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
}
if maxAge > 0 {
d := time.Duration(maxAge) * time.Second
cookie.Expires = time.Now().Add(d)
} else if maxAge < 0 {
cookie.Expires = time.Unix(1, 0)
}
return
}
func (c *Context) SetCookie(claims map[string]interface{}) {
t := jwt.NewToken(claims, nil)
if err := c.Srv.JWT.Sign(t); err != nil {
@ -217,7 +205,22 @@ func (c *Context) SetCookie(claims map[string]interface{}) {
return
}
c.Token = *t
http.SetCookie(c.Response, newCookie(c.Token.String(), int(jwt.DefaultExpiry.Seconds())))
cookie := &http.Cookie{
Name: cookieName,
Value: c.Token.String(),
Path: "/",
MaxAge: int(jwt.DefaultExpiry.Seconds()),
Secure: c.Srv.Secure,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
}
if cookie.MaxAge > 0 {
d := time.Duration(cookie.MaxAge) * time.Second
cookie.Expires = time.Now().Add(d)
} else if cookie.MaxAge < 0 {
cookie.Expires = time.Unix(1, 0)
}
http.SetCookie(c.Response, cookie)
}
func (c *Context) User() string {