Browse Source

Added PrivateWrite and PrivateRead settings to resource.

master
Gisle Aune 7 years ago
parent
commit
7f503ab37b
  1. 31
      resource.go
  2. 2
      resource_test.go

31
resource.go

@ -4,6 +4,8 @@ import (
"net/http"
"strings"
"git.aiterp.net/gisle/wrouter/response"
"git.aiterp.net/gisle/wrouter/auth"
)
@ -16,10 +18,13 @@ type Resource struct {
get IDFunc
update IDFunc
delete IDFunc
PrivateRead bool
PrivateWrite bool
}
func NewResource(list, create Func, get, update, delete IDFunc) *Resource {
return &Resource{list, create, get, update, delete}
return &Resource{list, create, get, update, delete, false, false}
}
func (resource *Resource) Handle(path string, w http.ResponseWriter, req *http.Request, user *auth.User) bool {
@ -41,6 +46,11 @@ func (resource *Resource) Handle(path string, w http.ResponseWriter, req *http.R
switch req.Method {
case "GET":
{
if resource.PrivateRead && user == nil {
response.Text(w, 401, "Not logged in")
return true
}
if subpath != "" {
resource.get(w, req, subpath, user)
} else {
@ -49,10 +59,13 @@ func (resource *Resource) Handle(path string, w http.ResponseWriter, req *http.R
}
case "POST":
{
if resource.PrivateWrite && user == nil {
response.Text(w, 401, "Not logged in")
return true
}
if subpath != "" {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(400)
w.Write([]byte("ID not allowed in POST"))
response.Text(w, 400, "ID not allowed in POST")
return true
}
@ -60,10 +73,20 @@ func (resource *Resource) Handle(path string, w http.ResponseWriter, req *http.R
}
case "PATCH", "PUT":
{
if resource.PrivateWrite && user == nil {
response.Text(w, 401, "Not logged in")
return true
}
resource.update(w, req, subpath, user)
}
case "DELETE":
{
if resource.PrivateWrite && user == nil {
response.Text(w, 401, "Not logged in")
return true
}
resource.delete(w, req, subpath, user)
}
}

2
resource_test.go

@ -109,7 +109,7 @@ func deletePage(w http.ResponseWriter, req *http.Request, id string, user *auth.
response.Text(w, 404, "Page not found")
}
var resource = Resource{listPage, createPage, getPage, updatePage, deletePage}
var resource = Resource{listPage, createPage, getPage, updatePage, deletePage, false, false}
type handlerStruct struct{}

Loading…
Cancel
Save