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 {

View file

@ -88,21 +88,19 @@ func loginHandler(ctx *Context) {
case "POST":
user := ctx.Form("user")
password := ctx.Form("password")
if !ctx.CheckXsrf(nil) {
if !ctx.CheckXsrf() {
return
}
if user == "" || password == "" {
ctx.Data.Msg = "wrong inputs"
ctx.Exec()
ctx.Error("wrong inputs")
return
}
u, err := ctx.Srv.DB.Login(user, password)
if err != nil {
ctx.Data.Msg = err.Error()
ctx.Exec()
ctx.Error(err)
return
}
ctx.SetCookie(map[string]interface{}{userClaim: u.Username, adminClaim: u.Admin})
ctx.SetCookie(jwt.Claims{userClaim: u.Username, adminClaim: u.Admin})
ctx.Redirect(core.IndexURI, 302)
}
}
@ -118,18 +116,16 @@ func searchHandler(ctx *Context) {
ctx.Exec()
case "POST":
search := ctx.Form("search")
if !ctx.CheckXsrf(nil) {
if !ctx.CheckXsrf() {
return
}
//TODO
//res, err := ctx.Srv.DB.Index.Search(search)
//if err != nil {
// ctx.Data.Msg = err.Error()
// ctx.Exec()
// return
//}
//ctx.Data.Data = res
res, err := ctx.Srv.DB.Index.Search(search)
if err != nil {
ctx.Error(err)
return
}
ctx.Data.Data = res
ctx.Data.Search = search
ctx.Exec()
}
@ -164,7 +160,7 @@ func pageNewHandler(ctx *Context) {
Perm: perm,
}
ctx.Data.Data = p
if !ctx.CheckXsrf(nil) {
if !ctx.CheckXsrf() {
return
}
if section != core.WikiSection {
@ -172,8 +168,7 @@ func pageNewHandler(ctx *Context) {
}
page, err := ctx.Srv.DB.CreatePage(title, section, markdown, ctx.User(), perm)
if err != nil {
ctx.Data.Msg = err.Error()
ctx.Exec()
ctx.Error(err)
return
}
ctx.Redirect(page.StoreTitle, 302)
@ -242,6 +237,10 @@ func pageShareHandler(ctx *Context) {
ctx.NotFound()
return
}
if page.Perm != core.Private {
ctx.Error("only private pages can be shared")
return
}
ctx.Data.Data = st
ctx.Data.Title = page.Title
ctx.Data.BodyTitle = page.Title
@ -250,13 +249,12 @@ func pageShareHandler(ctx *Context) {
ctx.Exec()
case "POST":
duration := ctx.Form("duration")
if !ctx.CheckXsrf(nil) {
if !ctx.CheckXsrf() {
return
}
d, err := time.ParseDuration(duration)
if err != nil {
ctx.Data.Msg = err.Error()
ctx.Exec()
ctx.Error(err)
return
}
t := jwt.NewToken(map[string]interface{}{
@ -286,36 +284,31 @@ func pageBlacklistHandler(ctx *Context) {
case "GET":
ctx.Exec()
case "POST":
if !ctx.CheckXsrf(nil) {
if !ctx.CheckXsrf() {
return
}
t, err := jwt.DecodeToken(ctx.Form("share"))
if err != nil {
ctx.Data.Msg = err.Error()
ctx.Exec()
ctx.Error(err)
return
}
err = ctx.Srv.JWT.Verify(t)
if err != nil {
ctx.Data.Msg = err.Error()
ctx.Exec()
ctx.Error(err)
return
}
user := t.Claims.GetString(sharedClaim)
if user == "" {
ctx.Data.Msg = "blacklisting denied: no share token"
ctx.Exec()
ctx.Error("blacklisting denied: no share token")
return
}
if ctx.User() != user {
ctx.Data.Msg = "blacklisting denied: token was issued by " + user
ctx.Exec()
ctx.Error("blacklisting denied: token was issued by " + user)
return
}
err = ctx.Srv.JWT.Invalidate(t)
if err != nil {
ctx.Data.Msg = err.Error()
ctx.Exec()
ctx.Error(err)
return
}
ctx.Exec()
@ -342,13 +335,12 @@ func pageEditHandler(ctx *Context) {
page.Markdown = ctx.Form("markdown")
page.Perm = core.ParsePermString(ctx.Form("perm"))
ctx.Data.Data = page
if !ctx.CheckXsrf(nil) {
if !ctx.CheckXsrf() {
return
}
err = ctx.Srv.DB.UpdatePage(title, section, page.Markdown, ctx.User(), page.Perm)
if err != nil {
ctx.Data.Msg = err.Error()
ctx.Exec()
ctx.Error(err)
return
}
ctx.Redirect(page.StoreTitle, 302)
@ -367,12 +359,11 @@ func pageDelHandler(ctx *Context) {
case "GET":
ctx.Exec()
case "POST":
if !ctx.CheckXsrf(nil) {
if !ctx.CheckXsrf() {
return
}
if err := ctx.Srv.DB.DeletePage(title, section, ctx.User()); err != nil {
ctx.Data.Msg = err.Error()
ctx.Exec()
ctx.Error(err)
return
}
ctx.Redirect(core.IndexURI, 302)
@ -416,17 +407,15 @@ func userNewHandler(ctx *Context) {
if admin == "0" {
adm = true
}
if !ctx.CheckXsrf(nil) {
if !ctx.CheckXsrf() {
return
}
if user == "" || password == "" || password != repeat {
ctx.Data.Msg = "wrong inputs"
ctx.Exec()
ctx.Error("wrong inputs")
return
}
if err := ctx.Srv.DB.CreateUser(user, password, adm); err != nil {
ctx.Data.Msg = err.Error()
ctx.Exec()
ctx.Error(err)
return
}
ctx.Redirect("/user", 302)
@ -443,8 +432,7 @@ func userEditHandler(ctx *Context) {
case "GET":
u, err := ctx.Srv.DB.GetUserWithoutPassword(ctx.Var("user"))
if err != nil {
ctx.Data.Msg = err.Error()
ctx.Exec()
ctx.Error(err)
return
}
ctx.Data.Data = u
@ -458,25 +446,22 @@ func userEditHandler(ctx *Context) {
if admin == "0" {
adm = true
}
if !ctx.CheckXsrf(nil) {
if !ctx.CheckXsrf() {
return
}
if user == "" || password != repeat {
ctx.Data.Msg = "wrong inputs"
ctx.Exec()
ctx.Error("wrong inputs")
return
}
if ctx.Admin() {
if err := ctx.Srv.DB.AdminUpdateUser(user, password, adm); err != nil {
ctx.Data.Msg = err.Error()
ctx.Exec()
ctx.Error(err)
return
}
} else {
if user == ctx.User() {
if err := ctx.Srv.DB.UpdateUserPassword(user, password); err != nil {
ctx.Data.Msg = err.Error()
ctx.Exec()
ctx.Error(err)
return
}
ctx.Redirect(core.IndexURI, 302)
@ -505,8 +490,7 @@ func userDelHandler(ctx *Context) {
case "GET":
user, err := ctx.Srv.DB.GetUserWithoutPassword(ctx.Var("user"))
if err != nil {
ctx.Data.Msg = err.Error()
ctx.Exec()
ctx.Error(err)
return
}
ctx.Data.Data = user

View file

@ -1,3 +1,5 @@
// Copyright (C) 2018 Marius Schellenberger
package server
import (
@ -9,6 +11,7 @@ import (
"net/http"
"time"
"git.giftfish.de/ston1th/gowiki/pkg/core"
"git.giftfish.de/ston1th/gowiki/pkg/db"
"git.giftfish.de/ston1th/gowiki/pkg/log"
"git.giftfish.de/ston1th/jwt"
@ -19,10 +22,13 @@ const (
)
type HTTPServer struct {
Version string
indexPath string
listener net.Listener
srv *http.Server
Version string
Secure bool
Secret string
DataDir string
listener net.Listener
srv *http.Server
DB *db.DB
JWT *jwt.JWT
@ -31,9 +37,12 @@ type HTTPServer struct {
res map[string][]byte
}
func NewHTTPServer(l net.Listener, version, indexPath string, secCookie bool) (srv *HTTPServer) {
func NewHTTPServer(l net.Listener, conf core.Config) (srv *HTTPServer) {
srv = &HTTPServer{
Version: version,
Version: conf.Version,
Secure: conf.SecureCookie,
Secret: conf.Secret,
DataDir: conf.DataDir,
listener: l,
}
srv.loadTemplates()
@ -44,13 +53,15 @@ func NewHTTPServer(l net.Listener, version, indexPath string, secCookie bool) (s
}
func (s *HTTPServer) Start() (err error) {
//TODO make secret configurable
buf := bytes.NewBufferString("be688838ca8686e5c90689bf2ab585cef1137c999b48c70b92f67a5c34dc15697b5d11c982ed6d71be1e1e7f7b4e0733884aa97c3f7a339a8ed03577cf74be09")
var buf *bytes.Buffer
if s.Secret != "" {
buf = bytes.NewBufferString(s.Secret)
}
s.JWT, err = jwt.New(jwt.DefaultExpiry, jwt.NewMemBlacklist(), buf)
if err != nil {
return
}
s.DB, err = db.New(s.indexPath)
s.DB, err = db.New(s.DataDir)
if err != nil {
return
}

View file

@ -28,7 +28,7 @@ const (
<ul type="circle">
{{range $item := .Data}}
{{if ne $owner $item.Owner}}
{{$owner := $item.Owner}}
{{$owner = $item.Owner}}
</ul>
</div>
<div class="row">
@ -48,9 +48,9 @@ const (
<head>
<title>GoWiki | {{.Title}}</title>
<link rel="stylesheet" type="text/css" href="/bootstrap.css" media="screen" integrity="sha256-NeLmQ7cX66J4MdtgGlG3O/TgvsSyP1b9WbaQtxYZUbQ="></link>
<link rel="stylesheet" type="text/css" href="/custom.css" media="screen" integrity="sha256-4M0Ran7skk1gZoHDDh/mtuzwXN51uagML7tkWnhE0JI="></link>
<link rel="stylesheet" type="text/css" href="/custom.css" media="screen" integrity="sha256-1LNAeuiM/rtsY1jIgLovUZ7HbYnOCkj3ZyailNA3rFQ="></link>
</head>
<body style="padding-top:60px">
<body>
<div class="navbar navbar-expand fixed-top navbar-dark bg-primary">
<div class="container">
<a href="/" class="navbar-brand">GoWiki</a>
@ -62,7 +62,7 @@ const (
<div class="container">
<div id="back-to-top" class="proper-content">
{{if .Msg}}
<div class="alert alert-danger" style="margin-top:30px">
<div class="alert alert-danger msg">
<h4>Error!</h4>
<p>{{.Msg}}</p>
</div>
@ -256,7 +256,9 @@ const (
<a href="/{{.Data.StoreTitle}}/md" class="btn btn-sm btn-primary">Markdown</a>
{{if .Login}}
<a href="/{{.Data.StoreTitle}}/edit" class="btn btn-sm btn-primary">Edit</a>
{{if eq .Data.Perm 3}}
<a href="/{{.Data.StoreTitle}}/share" class="btn btn-sm btn-primary">Share</a>
{{end}}
{{if ne .Data.StoreTitle "wiki/Index"}}
<a href="/{{.Data.StoreTitle}}/del" class="btn btn-sm btn-primary">Delete</a>
{{end}}
@ -317,6 +319,7 @@ const (
</form>
{{end}}`
pageShare = `{{define "body"}}
{{if not .Msg}}
<div class="page-header">
<div class="row">
<div class="col-xs-4 offset-4">
@ -346,6 +349,7 @@ const (
</div>
</div>
</div>
{{end}}
{{end}}`
pageView = `{{define "body"}}
<div class="page-header">
@ -399,7 +403,7 @@ const (
<div class="col">
{{range $item := .Data}}
<a href="/{{$item.StoreTitle}}"><b>{{$item.Title}}</b></a>
<pre style="white-space:pre-wrap">{{$item.Text}}</pre><br>
<pre class="wrap">{{$item.HTML}}</pre><br>
{{end}}
</div>
</div>
@ -603,7 +607,12 @@ const (
float: left !important;
}
}
body {
padding-top: 60px;
}
.msg {
margin-top: 30px;
}
a.dark {
color: #222222;
}
@ -664,8 +673,11 @@ pre {
border: 1px solid #444444;
border-radius: 2px;
}
pre.wrap {
white-space: pre-wrap;
}
code {
padding: 3px 3px 1px 3px;
padding: 3px 3px 1px 0px;
font-size: 90%;
color: #0cdba6;
background-color: #444444;

View file

@ -1,3 +1,5 @@
// Copyright (C) 2018 Marius Schellenberger
package server
import (