Update requestContext variable names

This commit is contained in:
Henrique Dias 2017-08-01 20:46:27 +01:00
parent 298a418e9b
commit ab419b0186
No known key found for this signature in database
GPG Key ID: 936F5EB68D786730
9 changed files with 59 additions and 59 deletions

View File

@ -27,7 +27,7 @@ func authHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int
} }
// Checks if the user exists. // Checks if the user exists.
u, ok := c.FM.Users[cred.Username] u, ok := c.Users[cred.Username]
if !ok { if !ok {
return http.StatusForbidden, nil return http.StatusForbidden, nil
} }
@ -78,7 +78,7 @@ func printToken(c *RequestContext, w http.ResponseWriter) (int, error) {
// Creates the token and signs it. // Creates the token and signs it.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
string, err := token.SignedString(c.FM.key) string, err := token.SignedString(c.key)
if err != nil { if err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
@ -114,7 +114,7 @@ func (e extractor) ExtractToken(r *http.Request) (string, error) {
// User if it is valid. // User if it is valid.
func validateAuth(c *RequestContext, r *http.Request) (bool, *User) { func validateAuth(c *RequestContext, r *http.Request) (bool, *User) {
keyFunc := func(token *jwt.Token) (interface{}, error) { keyFunc := func(token *jwt.Token) (interface{}, error) {
return c.FM.key, nil return c.key, nil
} }
var claims claims var claims claims
token, err := request.ParseFromRequestWithClaims(r, token, err := request.ParseFromRequestWithClaims(r,
@ -127,7 +127,7 @@ func validateAuth(c *RequestContext, r *http.Request) (bool, *User) {
return false, nil return false, nil
} }
u, ok := c.FM.Users[claims.User.Username] u, ok := c.Users[claims.User.Username]
if !ok { if !ok {
return false, nil return false, nil
} }

View File

@ -20,14 +20,14 @@ func downloadHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
// If the file isn't a directory, serve it using http.ServeFile. We display it // If the file isn't a directory, serve it using http.ServeFile. We display it
// inline if it is requested. // inline if it is requested.
if !c.FI.IsDir { if !c.File.IsDir {
if r.URL.Query().Get("inline") == "true" { if r.URL.Query().Get("inline") == "true" {
w.Header().Set("Content-Disposition", "inline") w.Header().Set("Content-Disposition", "inline")
} else { } else {
w.Header().Set("Content-Disposition", "attachment; filename="+c.FI.Name) w.Header().Set("Content-Disposition", "attachment; filename="+c.File.Name)
} }
http.ServeFile(w, r, c.FI.Path) http.ServeFile(w, r, c.File.Path)
return 0, nil return 0, nil
} }
@ -46,10 +46,10 @@ func downloadHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
// Clean the slashes. // Clean the slashes.
name = fileutils.SlashClean(name) name = fileutils.SlashClean(name)
files = append(files, filepath.Join(c.FI.Path, name)) files = append(files, filepath.Join(c.File.Path, name))
} }
} else { } else {
files = append(files, c.FI.Path) files = append(files, c.File.Path)
} }
// If the format is true, just set it to "zip". // If the format is true, just set it to "zip".
@ -93,7 +93,7 @@ func downloadHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
} }
// Defines the file name. // Defines the file name.
name := c.FI.Name name := c.File.Name
if name == "." || name == "" { if name == "." || name == "" {
name = "download" name = "download"
} }

View File

@ -110,7 +110,7 @@ func getInfo(url *url.URL, c *FileManager, u *User) (*file, error) {
func (i *file) getListing(c *RequestContext, r *http.Request) error { func (i *file) getListing(c *RequestContext, r *http.Request) error {
// Gets the directory information using the Virtual File System of // Gets the directory information using the Virtual File System of
// the user configuration. // the user configuration.
f, err := c.User.FileSystem.OpenFile(c.FI.VirtualPath, os.O_RDONLY, 0) f, err := c.User.FileSystem.OpenFile(c.File.VirtualPath, os.O_RDONLY, 0)
if err != nil { if err != nil {
return err return err
} }

View File

@ -436,9 +436,9 @@ func (m *FileManager) registerPermission(name string, value bool) error {
// Compatible with http.Handler. // Compatible with http.Handler.
func (m *FileManager) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (m *FileManager) ServeHTTP(w http.ResponseWriter, r *http.Request) {
code, err := serveHTTP(&RequestContext{ code, err := serveHTTP(&RequestContext{
FM: m, FileManager: m,
User: nil, User: nil,
FI: nil, File: nil,
}, w, r) }, w, r)
if code >= 400 { if code >= 400 {

28
http.go
View File

@ -10,9 +10,9 @@ import (
// RequestContext contains the needed information to make handlers work. // RequestContext contains the needed information to make handlers work.
type RequestContext struct { type RequestContext struct {
*FileManager
User *User User *User
FM *FileManager File *file
FI *file
// On API handlers, Router is the APi handler we want. // On API handlers, Router is the APi handler we want.
Router string Router string
} }
@ -21,9 +21,9 @@ type RequestContext struct {
func serveHTTP(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) { func serveHTTP(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {
// Checks if the URL contains the baseURL and strips it. Otherwise, it just // Checks if the URL contains the baseURL and strips it. Otherwise, it just
// returns a 404 error because we're not supposed to be here! // returns a 404 error because we're not supposed to be here!
p := strings.TrimPrefix(r.URL.Path, c.FM.BaseURL) p := strings.TrimPrefix(r.URL.Path, c.BaseURL)
if len(p) >= len(r.URL.Path) && c.FM.BaseURL != "" { if len(p) >= len(r.URL.Path) && c.BaseURL != "" {
return http.StatusNotFound, nil return http.StatusNotFound, nil
} }
@ -34,7 +34,7 @@ func serveHTTP(c *RequestContext, w http.ResponseWriter, r *http.Request) (int,
if r.URL.Path == "/sw.js" { if r.URL.Path == "/sw.js" {
return renderFile( return renderFile(
w, w,
c.FM.assets.MustString("sw.js"), c.assets.MustString("sw.js"),
"application/javascript", "application/javascript",
c, c,
) )
@ -65,7 +65,7 @@ func serveHTTP(c *RequestContext, w http.ResponseWriter, r *http.Request) (int,
return renderFile( return renderFile(
w, w,
c.FM.assets.MustString("index.html"), c.assets.MustString("index.html"),
"text/html", "text/html",
c, c,
) )
@ -74,13 +74,13 @@ func serveHTTP(c *RequestContext, w http.ResponseWriter, r *http.Request) (int,
// staticHandler handles the static assets path. // staticHandler handles the static assets path.
func staticHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) { func staticHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {
if r.URL.Path != "/static/manifest.json" { if r.URL.Path != "/static/manifest.json" {
http.FileServer(c.FM.assets.HTTPBox()).ServeHTTP(w, r) http.FileServer(c.assets.HTTPBox()).ServeHTTP(w, r)
return 0, nil return 0, nil
} }
return renderFile( return renderFile(
w, w,
c.FM.assets.MustString("static/manifest.json"), c.assets.MustString("static/manifest.json"),
"application/json", "application/json",
c, c,
) )
@ -107,7 +107,7 @@ func apiHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int,
return http.StatusForbidden, nil return http.StatusForbidden, nil
} }
for p := range c.FM.Plugins { for p := range c.Plugins {
code, err := plugins[p].Handler.Before(c, w, r) code, err := plugins[p].Handler.Before(c, w, r)
if code != 0 || err != nil { if code != 0 || err != nil {
return code, err return code, err
@ -116,7 +116,7 @@ func apiHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int,
if c.Router == "checksum" || c.Router == "download" { if c.Router == "checksum" || c.Router == "download" {
var err error var err error
c.FI, err = getInfo(r.URL, c.FM, c.User) c.File, err = getInfo(r.URL, c.FileManager, c.User)
if err != nil { if err != nil {
return errorToHTTP(err, false), err return errorToHTTP(err, false), err
} }
@ -148,7 +148,7 @@ func apiHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int,
return code, err return code, err
} }
for p := range c.FM.Plugins { for p := range c.Plugins {
code, err := plugins[p].Handler.After(c, w, r) code, err := plugins[p].Handler.After(c, w, r)
if code != 0 || err != nil { if code != 0 || err != nil {
return code, err return code, err
@ -162,7 +162,7 @@ func apiHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int,
func checksumHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) { func checksumHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {
query := r.URL.Query().Get("algo") query := r.URL.Query().Get("algo")
val, err := c.FI.Checksum(query) val, err := c.File.Checksum(query)
if err == errInvalidOption { if err == errInvalidOption {
return http.StatusBadRequest, err return http.StatusBadRequest, err
} else if err != nil { } else if err != nil {
@ -196,12 +196,12 @@ func renderFile(w http.ResponseWriter, file string, contentType string, c *Reque
w.Header().Set("Content-Type", contentType+"; charset=utf-8") w.Header().Set("Content-Type", contentType+"; charset=utf-8")
var javascript = "" var javascript = ""
for name := range c.FM.Plugins { for name := range c.Plugins {
javascript += plugins[name].JavaScript + "\n" javascript += plugins[name].JavaScript + "\n"
} }
err := tpl.Execute(w, map[string]interface{}{ err := tpl.Execute(w, map[string]interface{}{
"BaseURL": c.FM.RootURL(), "BaseURL": c.RootURL(),
"JavaScript": template.JS(javascript), "JavaScript": template.JS(javascript),
}) })
if err != nil { if err != nil {

View File

@ -117,7 +117,7 @@ func (h Hugo) undraft(file string) error {
type hugo struct{} type hugo struct{}
func (h hugo) Before(c *filemanager.RequestContext, w http.ResponseWriter, r *http.Request) (int, error) { func (h hugo) Before(c *filemanager.RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {
o := c.FM.Plugins["hugo"].(*Hugo) o := c.Plugins["hugo"].(*Hugo)
// If we are using the 'magic url' for the settings, we should redirect the // If we are using the 'magic url' for the settings, we should redirect the
// request for the acutual path. // request for the acutual path.
@ -189,7 +189,7 @@ func (h hugo) Before(c *filemanager.RequestContext, w http.ResponseWriter, r *ht
filename := filepath.Join(string(c.User.FileSystem), r.URL.Path) filename := filepath.Join(string(c.User.FileSystem), r.URL.Path)
// Before save command handler. // Before save command handler.
if err := c.FM.Runner("before_publish", filename); err != nil { if err := c.Runner("before_publish", filename); err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
@ -205,7 +205,7 @@ func (h hugo) Before(c *filemanager.RequestContext, w http.ResponseWriter, r *ht
o.run(false) o.run(false)
// Executed the before publish command. // Executed the before publish command.
if err := c.FM.Runner("before_publish", filename); err != nil { if err := c.Runner("before_publish", filename); err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }

View File

@ -34,7 +34,7 @@ func resourceHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
case http.MethodPut: case http.MethodPut:
// Before save command handler. // Before save command handler.
path := filepath.Join(string(c.User.FileSystem), r.URL.Path) path := filepath.Join(string(c.User.FileSystem), r.URL.Path)
if err := c.FM.Runner("before_save", path); err != nil { if err := c.Runner("before_save", path); err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
@ -44,7 +44,7 @@ func resourceHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
} }
// After save command handler. // After save command handler.
if err := c.FM.Runner("after_save", path); err != nil { if err := c.Runner("after_save", path); err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
@ -60,7 +60,7 @@ func resourceHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
func resourceGetHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) { func resourceGetHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {
// Gets the information of the directory/file. // Gets the information of the directory/file.
f, err := getInfo(r.URL, c.FM, c.User) f, err := getInfo(r.URL, c.FileManager, c.User)
if err != nil { if err != nil {
return errorToHTTP(err, false), err return errorToHTTP(err, false), err
} }
@ -73,7 +73,7 @@ func resourceGetHandler(c *RequestContext, w http.ResponseWriter, r *http.Reques
// If it is a dir, go and serve the listing. // If it is a dir, go and serve the listing.
if f.IsDir { if f.IsDir {
c.FI = f c.File = f
return listingHandler(c, w, r) return listingHandler(c, w, r)
} }
@ -101,7 +101,7 @@ func resourceGetHandler(c *RequestContext, w http.ResponseWriter, r *http.Reques
} }
func listingHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) { func listingHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {
f := c.FI f := c.File
f.Kind = "listing" f.Kind = "listing"
// Tries to get the listing data. // Tries to get the listing data.
@ -112,7 +112,7 @@ func listingHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (
listing := f.listing listing := f.listing
// Defines the cookie scope. // Defines the cookie scope.
cookieScope := c.FM.RootURL() cookieScope := c.RootURL()
if cookieScope == "" { if cookieScope == "" {
cookieScope = "/" cookieScope = "/"
} }

View File

@ -69,11 +69,11 @@ func settingsGetHandler(c *RequestContext, w http.ResponseWriter, r *http.Reques
} }
result := &settingsGetRequest{ result := &settingsGetRequest{
Commands: c.FM.Commands, Commands: c.Commands,
Plugins: map[string][]pluginOption{}, Plugins: map[string][]pluginOption{},
} }
for name, p := range c.FM.Plugins { for name, p := range c.Plugins {
result.Plugins[name] = []pluginOption{} result.Plugins[name] = []pluginOption{}
t := reflect.TypeOf(p).Elem() t := reflect.TypeOf(p).Elem()
@ -100,23 +100,23 @@ func settingsPutHandler(c *RequestContext, w http.ResponseWriter, r *http.Reques
} }
// Update the commands. // Update the commands.
if mod.Which == "commands" { if mod.Which == "commands" {
if err := c.FM.db.Set("config", "commands", mod.Data.Commands); err != nil { if err := c.db.Set("config", "commands", mod.Data.Commands); err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
c.FM.Commands = mod.Data.Commands c.Commands = mod.Data.Commands
return http.StatusOK, nil return http.StatusOK, nil
} }
// Update the plugins. // Update the plugins.
if mod.Which == "plugins" { if mod.Which == "plugins" {
for name, plugin := range mod.Data.Plugins { for name, plugin := range mod.Data.Plugins {
err = mapstructure.Decode(plugin, c.FM.Plugins[name]) err = mapstructure.Decode(plugin, c.Plugins[name])
if err != nil { if err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
err = c.FM.db.Set("plugins", name, c.FM.Plugins[name]) err = c.db.Set("plugins", name, c.Plugins[name])
if err != nil { if err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }

View File

@ -87,14 +87,14 @@ func getUser(r *http.Request) (*User, string, error) {
func usersGetHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) { func usersGetHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {
// Request for the default user data. // Request for the default user data.
if r.URL.Path == "/base" { if r.URL.Path == "/base" {
return renderJSON(w, c.FM.DefaultUser) return renderJSON(w, c.DefaultUser)
} }
// Request for the listing of users. // Request for the listing of users.
if r.URL.Path == "/" { if r.URL.Path == "/" {
users := []User{} users := []User{}
for _, user := range c.FM.Users { for _, user := range c.Users {
// Copies the user info and removes its // Copies the user info and removes its
// password so it won't be sent to the // password so it won't be sent to the
// front-end. // front-end.
@ -116,7 +116,7 @@ func usersGetHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
} }
// Searches for the user and prints the one who matches. // Searches for the user and prints the one who matches.
for _, user := range c.FM.Users { for _, user := range c.Users {
if user.ID != id { if user.ID != id {
continue continue
} }
@ -184,7 +184,7 @@ func usersPostHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
u.Password = pw u.Password = pw
// Saves the user to the database. // Saves the user to the database.
err = c.FM.db.Save(u) err = c.db.Save(u)
if err == storm.ErrAlreadyExists { if err == storm.ErrAlreadyExists {
return http.StatusConflict, errUserExist return http.StatusConflict, errUserExist
} }
@ -194,7 +194,7 @@ func usersPostHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
} }
// Saves the user to the memory. // Saves the user to the memory.
c.FM.Users[u.Username] = u c.Users[u.Username] = u
// Set the Location header and return. // Set the Location header and return.
w.Header().Set("Location", "/users/"+strconv.Itoa(u.ID)) w.Header().Set("Location", "/users/"+strconv.Itoa(u.ID))
@ -213,7 +213,7 @@ func usersDeleteHandler(c *RequestContext, w http.ResponseWriter, r *http.Reques
} }
// Deletes the user from the database. // Deletes the user from the database.
err = c.FM.db.DeleteStruct(&User{ID: id}) err = c.db.DeleteStruct(&User{ID: id})
if err == storm.ErrNotFound { if err == storm.ErrNotFound {
return http.StatusNotFound, errUserNotExist return http.StatusNotFound, errUserNotExist
} }
@ -223,9 +223,9 @@ func usersDeleteHandler(c *RequestContext, w http.ResponseWriter, r *http.Reques
} }
// Delete the user from the in-memory users map. // Delete the user from the in-memory users map.
for _, user := range c.FM.Users { for _, user := range c.Users {
if user.ID == id { if user.ID == id {
delete(c.FM.Users, user.Username) delete(c.Users, user.Username)
break break
} }
} }
@ -260,12 +260,12 @@ func usersPutHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
if which == "partial" { if which == "partial" {
c.User.CSS = u.CSS c.User.CSS = u.CSS
c.User.Locale = u.Locale c.User.Locale = u.Locale
err = c.FM.db.UpdateField(&User{ID: c.User.ID}, "CSS", u.CSS) err = c.db.UpdateField(&User{ID: c.User.ID}, "CSS", u.CSS)
if err != nil { if err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
err = c.FM.db.UpdateField(&User{ID: c.User.ID}, "Locale", u.Locale) err = c.db.UpdateField(&User{ID: c.User.ID}, "Locale", u.Locale)
if err != nil { if err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
@ -285,7 +285,7 @@ func usersPutHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
} }
c.User.Password = pw c.User.Password = pw
err = c.FM.db.UpdateField(&User{ID: c.User.ID}, "Password", pw) err = c.db.UpdateField(&User{ID: c.User.ID}, "Password", pw)
if err != nil { if err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
@ -320,7 +320,7 @@ func usersPutHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
// Gets the current saved user from the in-memory map. // Gets the current saved user from the in-memory map.
var suser *User var suser *User
for _, user := range c.FM.Users { for _, user := range c.Users {
if user.ID == id { if user.ID == id {
suser = user suser = user
break break
@ -346,12 +346,12 @@ func usersPutHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
// Default permissions if current are nil. // Default permissions if current are nil.
if u.Permissions == nil { if u.Permissions == nil {
u.Permissions = c.FM.DefaultUser.Permissions u.Permissions = c.DefaultUser.Permissions
} }
// Updates the whole User struct because we always are supposed // Updates the whole User struct because we always are supposed
// to send a new entire object. // to send a new entire object.
err = c.FM.db.Save(u) err = c.db.Save(u)
if err != nil { if err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
@ -359,9 +359,9 @@ func usersPutHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
// If the user changed the username, delete the old user // If the user changed the username, delete the old user
// from the in-memory user map. // from the in-memory user map.
if suser.Username != u.Username { if suser.Username != u.Username {
delete(c.FM.Users, suser.Username) delete(c.Users, suser.Username)
} }
c.FM.Users[u.Username] = u c.Users[u.Username] = u
return http.StatusOK, nil return http.StatusOK, nil
} }