pass a struct with the info

pull/144/head
Henrique Dias 2017-06-27 09:57:11 +01:00
parent 3b3643be05
commit 1d26b8e95e
No known key found for this signature in database
GPG Key ID: 936F5EB68D786730
12 changed files with 79 additions and 70 deletions

View File

@ -12,9 +12,9 @@ import (
const assetsURL = "/_internal" const assetsURL = "/_internal"
// Serve provides the needed assets for the front-end // Serve provides the needed assets for the front-end
func serveAssets(w http.ResponseWriter, r *http.Request, m *FileManager) (int, error) { func serveAssets(ctx *requestContext, w http.ResponseWriter, r *http.Request) (int, error) {
// gets the filename to be used with Assets function // gets the filename to be used with Assets function
filename := strings.Replace(r.URL.Path, m.BaseURL+assetsURL, "", 1) filename := strings.Replace(r.URL.Path, ctx.FileManager.BaseURL+assetsURL, "", 1)
var file []byte var file []byte
var err error var err error
@ -22,10 +22,10 @@ func serveAssets(w http.ResponseWriter, r *http.Request, m *FileManager) (int, e
switch { switch {
case strings.HasPrefix(filename, "/css"): case strings.HasPrefix(filename, "/css"):
filename = strings.Replace(filename, "/css/", "", 1) filename = strings.Replace(filename, "/css/", "", 1)
file, err = m.assets.css.Bytes(filename) file, err = ctx.FileManager.assets.css.Bytes(filename)
case strings.HasPrefix(filename, "/js"): case strings.HasPrefix(filename, "/js"):
filename = strings.Replace(filename, "/js/", "", 1) filename = strings.Replace(filename, "/js/", "", 1)
file, err = m.assets.js.Bytes(filename) file, err = ctx.FileManager.assets.js.Bytes(filename)
default: default:
err = errors.New("not found") err = errors.New("not found")
} }

View File

@ -14,10 +14,10 @@ import (
) )
// checksum calculates the hash of a file. Supports MD5, SHA1, SHA256 and SHA512. // checksum calculates the hash of a file. Supports MD5, SHA1, SHA256 and SHA512.
func checksum(w http.ResponseWriter, r *http.Request, i *fileInfo) (int, error) { func checksum(ctx *requestContext, w http.ResponseWriter, r *http.Request) (int, error) {
query := r.URL.Query().Get("checksum") query := r.URL.Query().Get("checksum")
file, err := os.Open(i.Path) file, err := os.Open(ctx.Info.Path)
if err != nil { if err != nil {
return errorToHTTP(err, true), err return errorToHTTP(err, true), err
} }

View File

@ -22,7 +22,7 @@ var (
) )
// command handles the requests for VCS related commands: git, svn and mercurial // command handles the requests for VCS related commands: git, svn and mercurial
func command(w http.ResponseWriter, r *http.Request, c *FileManager, u *User) (int, error) { func command(ctx *requestContext, w http.ResponseWriter, r *http.Request) (int, error) {
// Upgrades the connection to a websocket and checks for errors. // Upgrades the connection to a websocket and checks for errors.
conn, err := upgrader.Upgrade(w, r, nil) conn, err := upgrader.Upgrade(w, r, nil)
if err != nil { if err != nil {
@ -51,7 +51,7 @@ func command(w http.ResponseWriter, r *http.Request, c *FileManager, u *User) (i
// Check if the command is allowed // Check if the command is allowed
allowed := false allowed := false
for _, cmd := range u.Commands { for _, cmd := range ctx.User.Commands {
if cmd == command[0] { if cmd == command[0] {
allowed = true allowed = true
} }
@ -77,7 +77,7 @@ func command(w http.ResponseWriter, r *http.Request, c *FileManager, u *User) (i
} }
// Gets the path and initializes a buffer. // Gets the path and initializes a buffer.
path := strings.Replace(r.URL.Path, c.BaseURL, c.scope, 1) path := strings.Replace(r.URL.Path, ctx.FileManager.BaseURL, ctx.User.scope, 1)
path = filepath.Clean(path) path = filepath.Clean(path)
buff := new(bytes.Buffer) buff := new(bytes.Buffer)

View File

@ -14,12 +14,12 @@ import (
// download creates an archive in one of the supported formats (zip, tar, // download creates an archive in one of the supported formats (zip, tar,
// tar.gz or tar.bz2) and sends it to be downloaded. // tar.gz or tar.bz2) and sends it to be downloaded.
func download(w http.ResponseWriter, r *http.Request, i *fileInfo) (int, error) { func download(ctx *requestContext, w http.ResponseWriter, r *http.Request) (int, error) {
query := r.URL.Query().Get("download") query := r.URL.Query().Get("download")
if !i.IsDir { if !ctx.Info.IsDir {
w.Header().Set("Content-Disposition", "attachment; filename="+i.Name) w.Header().Set("Content-Disposition", "attachment; filename="+ctx.Info.Name)
http.ServeFile(w, r, i.Path) http.ServeFile(w, r, ctx.Info.Path)
return 0, nil return 0, nil
} }
@ -34,11 +34,11 @@ func download(w http.ResponseWriter, r *http.Request, i *fileInfo) (int, error)
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
files = append(files, filepath.Join(i.Path, name)) files = append(files, filepath.Join(ctx.Info.Path, name))
} }
} else { } else {
files = append(files, i.Path) files = append(files, ctx.Info.Path)
} }
if query == "true" { if query == "true" {
@ -84,7 +84,7 @@ func download(w http.ResponseWriter, r *http.Request, i *fileInfo) (int, error)
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
name := i.Name name := ctx.Info.Name
if name == "." || name == "" { if name == "." || name == "" {
name = "download" name = "download"
} }

View File

@ -89,22 +89,22 @@ Error:
// serveSingle serves a single file in an editor (if it is editable), shows the // serveSingle serves a single file in an editor (if it is editable), shows the
// plain file, or downloads it if it can't be shown. // plain file, or downloads it if it can't be shown.
func serveSingle(w http.ResponseWriter, r *http.Request, c *FileManager, u *User, i *fileInfo) (int, error) { func serveSingle(ctx *requestContext, w http.ResponseWriter, r *http.Request) (int, error) {
var err error var err error
if err = i.RetrieveFileType(); err != nil { if err = ctx.Info.RetrieveFileType(); err != nil {
return errorToHTTP(err, true), err return errorToHTTP(err, true), err
} }
p := &page{ p := &page{
Name: i.Name, Name: ctx.Info.Name,
Path: i.VirtualPath, Path: ctx.Info.VirtualPath,
IsDir: false, IsDir: false,
Data: i, Data: ctx.Info,
User: u, User: ctx.User,
PrefixURL: c.PrefixURL, PrefixURL: ctx.FileManager.PrefixURL,
BaseURL: c.AbsoluteURL(), BaseURL: ctx.FileManager.AbsoluteURL(),
WebDavURL: c.AbsoluteWebDavURL(), WebDavURL: ctx.FileManager.AbsoluteWebDavURL(),
} }
// If the request accepts JSON, we send the file information. // If the request accepts JSON, we send the file information.
@ -112,23 +112,23 @@ func serveSingle(w http.ResponseWriter, r *http.Request, c *FileManager, u *User
return p.PrintAsJSON(w) return p.PrintAsJSON(w)
} }
if i.Type == "text" { if ctx.Info.Type == "text" {
if err = i.Read(); err != nil { if err = ctx.Info.Read(); err != nil {
return errorToHTTP(err, true), err return errorToHTTP(err, true), err
} }
} }
if i.CanBeEdited() && u.AllowEdit { if ctx.Info.CanBeEdited() && ctx.User.AllowEdit {
p.Data, err = getEditor(r, i) p.Data, err = getEditor(r, ctx.Info)
p.Editor = true p.Editor = true
if err != nil { if err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
return p.PrintAsHTML(w, c.assets.templates, "frontmatter", "editor") return p.PrintAsHTML(w, ctx.FileManager.assets.templates, "frontmatter", "editor")
} }
return p.PrintAsHTML(w, c.assets.templates, "single") return p.PrintAsHTML(w, ctx.FileManager.assets.templates, "single")
} }
func editorClass(mode string) string { func editorClass(mode string) string {

View File

@ -225,7 +225,11 @@ func (m *FileManager) NewUser(username string) error {
// ServeHTTP determines if the request is for this plugin, and if all prerequisites are met. // ServeHTTP determines if the request is for this plugin, and if all prerequisites are met.
func (m *FileManager) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) { func (m *FileManager) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
var ( var (
u *User ctx = &requestContext{
FileManager: m,
User: nil,
Info: nil,
}
code int code int
err error err error
) )
@ -234,7 +238,7 @@ func (m *FileManager) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, er
// method is GET and Status Forbidden otherwise. // method is GET and Status Forbidden otherwise.
if matchURL(r.URL.Path, m.BaseURL+assetsURL) { if matchURL(r.URL.Path, m.BaseURL+assetsURL) {
if r.Method == http.MethodGet { if r.Method == http.MethodGet {
return serveAssets(w, r, m) return serveAssets(ctx, w, r)
} }
return http.StatusForbidden, nil return http.StatusForbidden, nil
@ -242,14 +246,14 @@ func (m *FileManager) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, er
username, _, _ := r.BasicAuth() username, _, _ := r.BasicAuth()
if _, ok := m.Users[username]; ok { if _, ok := m.Users[username]; ok {
u = m.Users[username] ctx.User = m.Users[username]
} else { } else {
u = m.User ctx.User = m.User
} }
// Checks if the request URL is for the WebDav server // Checks if the request URL is for the WebDav server
if matchURL(r.URL.Path, m.WebDavURL) { if matchURL(r.URL.Path, m.WebDavURL) {
return serveWebDAV(w, r, m, u) return serveWebDAV(ctx, w, r)
} }
w.Header().Set("x-frame-options", "SAMEORIGIN") w.Header().Set("x-frame-options", "SAMEORIGIN")
@ -257,7 +261,7 @@ func (m *FileManager) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, er
w.Header().Set("x-xss-protection", "1; mode=block") w.Header().Set("x-xss-protection", "1; mode=block")
// Checks if the User is allowed to access this file // Checks if the User is allowed to access this file
if !u.Allowed(strings.TrimPrefix(r.URL.Path, m.BaseURL)) { if !ctx.User.Allowed(strings.TrimPrefix(r.URL.Path, m.BaseURL)) {
if r.Method == http.MethodGet { if r.Method == http.MethodGet {
return htmlError( return htmlError(
w, http.StatusForbidden, w, http.StatusForbidden,
@ -269,18 +273,18 @@ func (m *FileManager) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, er
} }
if r.URL.Query().Get("search") != "" { if r.URL.Query().Get("search") != "" {
return search(w, r, m, u) return search(ctx, w, r)
} }
if r.URL.Query().Get("command") != "" { if r.URL.Query().Get("command") != "" {
return command(w, r, m, u) return command(ctx, w, r)
} }
if r.Method == http.MethodGet { if r.Method == http.MethodGet {
var f *fileInfo var f *fileInfo
// Obtains the information of the directory/file. // Obtains the information of the directory/file.
f, err = getInfo(r.URL, m, u) f, err = getInfo(r.URL, m, ctx.User)
if err != nil { if err != nil {
if r.Method == http.MethodGet { if r.Method == http.MethodGet {
return htmlError(w, code, err) return htmlError(w, code, err)
@ -299,16 +303,16 @@ func (m *FileManager) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, er
switch { switch {
case r.URL.Query().Get("download") != "": case r.URL.Query().Get("download") != "":
code, err = download(w, r, f) code, err = download(ctx, w, r)
case !f.IsDir && r.URL.Query().Get("checksum") != "": case !f.IsDir && r.URL.Query().Get("checksum") != "":
code, err = checksum(w, r, f) code, err = checksum(ctx, w, r)
case r.URL.Query().Get("raw") == "true" && !f.IsDir: case r.URL.Query().Get("raw") == "true" && !f.IsDir:
http.ServeFile(w, r, f.Path) http.ServeFile(w, r, f.Path)
code, err = 0, nil code, err = 0, nil
case f.IsDir: case f.IsDir:
code, err = serveListing(w, r, m, u, f) code, err = serveListing(ctx, w, r)
default: default:
code, err = serveSingle(w, r, m, u, f) code, err = serveSingle(ctx, w, r)
} }
if err != nil { if err != nil {

View File

@ -6,6 +6,12 @@ import (
"strings" "strings"
) )
type requestContext struct {
User *User
FileManager *FileManager
Info *fileInfo
}
// responseWriterNoBody is a wrapper used to suprress the body of the response // responseWriterNoBody is a wrapper used to suprress the body of the response
// to a request. Mainly used for HEAD requests. // to a request. Mainly used for HEAD requests.
type responseWriterNoBody struct { type responseWriterNoBody struct {

View File

@ -10,22 +10,22 @@ import (
) )
// serveListing presents the user with a listage of a directory folder. // serveListing presents the user with a listage of a directory folder.
func serveListing(w http.ResponseWriter, r *http.Request, c *FileManager, u *User, i *fileInfo) (int, error) { func serveListing(ctx *requestContext, w http.ResponseWriter, r *http.Request) (int, error) {
var err error var err error
// Loads the content of the directory // Loads the content of the directory
listing, err := getListing(u, i.VirtualPath, c.PrefixURL+r.URL.Path) listing, err := getListing(ctx.User, ctx.Info.VirtualPath, ctx.FileManager.PrefixURL+r.URL.Path)
if err != nil { if err != nil {
return errorToHTTP(err, true), err return errorToHTTP(err, true), err
} }
listing.Context = httpserver.Context{ listing.Context = httpserver.Context{
Root: http.Dir(u.scope), Root: http.Dir(ctx.User.scope),
Req: r, Req: r,
URL: r.URL, URL: r.URL,
} }
cookieScope := c.BaseURL cookieScope := ctx.FileManager.BaseURL
if cookieScope == "" { if cookieScope == "" {
cookieScope = "/" cookieScope = "/"
} }
@ -80,17 +80,17 @@ func serveListing(w http.ResponseWriter, r *http.Request, c *FileManager, u *Use
p := &page{ p := &page{
minimal: r.Header.Get("Minimal") == "true", minimal: r.Header.Get("Minimal") == "true",
Name: listing.Name, Name: listing.Name,
Path: i.VirtualPath, Path: ctx.Info.VirtualPath,
IsDir: true, IsDir: true,
User: u, User: ctx.User,
PrefixURL: c.PrefixURL, PrefixURL: ctx.FileManager.PrefixURL,
BaseURL: c.AbsoluteURL(), BaseURL: ctx.FileManager.AbsoluteURL(),
WebDavURL: c.AbsoluteWebDavURL(), WebDavURL: ctx.FileManager.AbsoluteWebDavURL(),
Display: displayMode, Display: displayMode,
Data: listing, Data: listing,
} }
return p.PrintAsHTML(w, c.assets.templates, "listing") return p.PrintAsHTML(w, ctx.FileManager.assets.templates, "listing")
} }
// handleSortOrder gets and stores for a Listing the 'sort' and 'order', // handleSortOrder gets and stores for a Listing the 'sort' and 'order',

View File

@ -14,7 +14,7 @@ import (
) )
// put is used to update a file that was edited // put is used to update a file that was edited
func put(w http.ResponseWriter, r *http.Request, c *FileManager, u *User) (err error) { func put(ctx *requestContext, w http.ResponseWriter, r *http.Request) (err error) {
var ( var (
data = map[string]interface{}{} data = map[string]interface{}{}
file []byte file []byte

View File

@ -1 +0,0 @@
package filemanager

View File

@ -43,7 +43,7 @@ func parseSearch(value string) *searchOptions {
} }
// search searches for a file or directory. // search searches for a file or directory.
func search(w http.ResponseWriter, r *http.Request, m *FileManager, u *User) (int, error) { func search(ctx *requestContext, w http.ResponseWriter, r *http.Request) (int, error) {
// Upgrades the connection to a websocket and checks for errors. // Upgrades the connection to a websocket and checks for errors.
conn, err := upgrader.Upgrade(w, r, nil) conn, err := upgrader.Upgrade(w, r, nil)
if err != nil { if err != nil {
@ -71,10 +71,10 @@ func search(w http.ResponseWriter, r *http.Request, m *FileManager, u *User) (in
} }
search = parseSearch(value) search = parseSearch(value)
scope := strings.Replace(r.URL.Path, m.BaseURL, "", 1) scope := strings.Replace(r.URL.Path, ctx.FileManager.BaseURL, "", 1)
scope = strings.TrimPrefix(scope, "/") scope = strings.TrimPrefix(scope, "/")
scope = "/" + scope scope = "/" + scope
scope = u.scope + scope scope = ctx.User.scope + scope
scope = strings.Replace(scope, "\\", "/", -1) scope = strings.Replace(scope, "\\", "/", -1)
scope = filepath.Clean(scope) scope = filepath.Clean(scope)
@ -92,7 +92,7 @@ func search(w http.ResponseWriter, r *http.Request, m *FileManager, u *User) (in
} }
if strings.Contains(path, term) { if strings.Contains(path, term) {
if !u.Allowed(path) { if !ctx.User.Allowed(path) {
return nil return nil
} }

View File

@ -8,11 +8,11 @@ import (
) )
// serveWebDAV handles the webDAV route of the File Manager. // serveWebDAV handles the webDAV route of the File Manager.
func serveWebDAV(w http.ResponseWriter, r *http.Request, m *FileManager, u *User) (int, error) { func serveWebDAV(ctx *requestContext, w http.ResponseWriter, r *http.Request) (int, error) {
var err error var err error
// Checks for user permissions relatively to this path. // Checks for user permissions relatively to this path.
if !u.Allowed(strings.TrimPrefix(r.URL.Path, m.WebDavURL)) { if !ctx.User.Allowed(strings.TrimPrefix(r.URL.Path, ctx.FileManager.WebDavURL)) {
return http.StatusForbidden, nil return http.StatusForbidden, nil
} }
@ -26,8 +26,8 @@ func serveWebDAV(w http.ResponseWriter, r *http.Request, m *FileManager, u *User
// //
// It was decided on https://github.com/hacdias/caddy-filemanager/issues/85 // It was decided on https://github.com/hacdias/caddy-filemanager/issues/85
// that GET, for collections, will return the same as PROPFIND method. // that GET, for collections, will return the same as PROPFIND method.
path := strings.Replace(r.URL.Path, m.WebDavURL, "", 1) path := strings.Replace(r.URL.Path, ctx.FileManager.WebDavURL, "", 1)
path = u.scope + "/" + path path = ctx.User.scope + "/" + path
path = filepath.Clean(path) path = filepath.Clean(path)
var i os.FileInfo var i os.FileInfo
@ -45,28 +45,28 @@ func serveWebDAV(w http.ResponseWriter, r *http.Request, m *FileManager, u *User
} }
} }
case "PROPPATCH", "MOVE", "PATCH", "PUT", "DELETE": case "PROPPATCH", "MOVE", "PATCH", "PUT", "DELETE":
if !u.AllowEdit { if !ctx.User.AllowEdit {
return http.StatusForbidden, nil return http.StatusForbidden, nil
} }
case "MKCOL", "COPY": case "MKCOL", "COPY":
if !u.AllowNew { if !ctx.User.AllowNew {
return http.StatusForbidden, nil return http.StatusForbidden, nil
} }
} }
// Preprocess the PUT request if it's the case // Preprocess the PUT request if it's the case
if r.Method == http.MethodPut { if r.Method == http.MethodPut {
if err = m.BeforeSave(r, m, u); err != nil { if err = ctx.FileManager.BeforeSave(r, ctx.FileManager, ctx.User); err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
if put(w, r, m, u) != nil { if put(ctx, w, r) != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
} }
m.handler.ServeHTTP(w, r) ctx.FileManager.handler.ServeHTTP(w, r)
if err = m.AfterSave(r, m, u); err != nil { if err = ctx.FileManager.AfterSave(r, ctx.FileManager, ctx.User); err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }