Skip to content

Commit

Permalink
Set Content-Type on HTTP JSON responses (fix #16)
Browse files Browse the repository at this point in the history
  • Loading branch information
retrixe committed Aug 7, 2023
1 parent 2df5b08 commit 1b107cd
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 22 deletions.
2 changes: 2 additions & 0 deletions auth/memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func (a *MemoryAuthenticator) Validate(w http.ResponseWriter, r *http.Request) s

token := GetTokenFromRequest(r)
if !isValidToken(token) {
w.Header().Set("content-type", "application/json")
http.Error(w, "{\"error\": \"You are not authenticated to access this resource!\"}",
http.StatusUnauthorized)
return ""
Expand All @@ -43,6 +44,7 @@ func (a *MemoryAuthenticator) Validate(w http.ResponseWriter, r *http.Request) s
}
a.Logout(token)
}
w.Header().Set("content-type", "application/json")
http.Error(w, "{\"error\": \"You are not authenticated to access this resource!\"}",
http.StatusUnauthorized)
return ""
Expand Down
3 changes: 3 additions & 0 deletions auth/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ func (a *RedisAuthenticator) Validate(w http.ResponseWriter, r *http.Request) st

token := GetTokenFromRequest(r)
if !isValidToken(token) {
w.Header().Set("content-type", "application/json")
http.Error(w, "{\"error\": \"You are not authenticated to access this resource!\"}",
http.StatusUnauthorized)
return ""
Expand All @@ -59,10 +60,12 @@ func (a *RedisAuthenticator) Validate(w http.ResponseWriter, r *http.Request) st
if !exists {
a.Logout(token)
}
w.Header().Set("content-type", "application/json")
http.Error(w, "{\"error\": \"You are not authenticated to access this resource!\"}",
http.StatusUnauthorized)
} else if err != nil {
log.Println("An error occurred while making a request to Redis!", err) // skipcq: GO-S0904
w.Header().Set("content-type", "application/json")
http.Error(w, "{\"error\": \"Internal Server Error!\"}", http.StatusInternalServerError)
return ""
}
Expand Down
28 changes: 20 additions & 8 deletions connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ func (connector *Connector) AddProcess(proc *Process) {
}

func httpError(w http.ResponseWriter, error string, code int) {
w.Header().Set("content-type", "application/json")
errorJson, err := json.Marshal(struct {
Error string `json:"error"`
}{Error: error})
Expand All @@ -199,10 +200,21 @@ func httpError(w http.ResponseWriter, error string, code int) {
}
}

func writeJsonStringRes(w http.ResponseWriter, resp string) error {
w.Header().Set("content-type", "application/json")
_, err := fmt.Fprintln(w, resp)
return err
}

func writeJsonStructRes(w http.ResponseWriter, resp interface{}) error {
w.Header().Set("content-type", "application/json")
return json.NewEncoder(w).Encode(resp)
}

func (connector *Connector) registerMiscRoutes() {
// GET /
connector.Router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "{\"version\": \""+OctyneVersion+"\"}")
writeJsonStringRes(w, "{\"version\": \""+OctyneVersion+"\"}")
})

// GET /config
Expand All @@ -223,7 +235,7 @@ func (connector *Connector) registerMiscRoutes() {
return
}
connector.Info("config.view", "ip", GetIP(r), "user", user)
fmt.Fprintln(w, string(contents))
writeJsonStringRes(w, string(contents))
} else if r.Method == "PATCH" {
var buffer bytes.Buffer
_, err := buffer.ReadFrom(r.Body)
Expand Down Expand Up @@ -257,7 +269,7 @@ func (connector *Connector) registerMiscRoutes() {
}
connector.UpdateConfig(&config)
connector.Info("config.edit", "ip", GetIP(r), "user", user, "newConfig", config)
fmt.Fprintln(w, "{\"success\":true}")
writeJsonStringRes(w, "{\"success\":true}")
info.Println("Config updated remotely by user over HTTP API (see action logs for info)!")
}
})
Expand Down Expand Up @@ -293,7 +305,7 @@ func (connector *Connector) registerMiscRoutes() {
connector.UpdateConfig(&config)
// Send the response.
connector.Info("config.reload", "ip", GetIP(r), "user", user)
fmt.Fprintln(w, "{\"success\":true}")
writeJsonStringRes(w, "{\"success\":true}")
info.Println("Config reloaded successfully!")
})

Expand All @@ -320,7 +332,7 @@ func (connector *Connector) registerMiscRoutes() {
return true
})
// Send the list.
json.NewEncoder(w).Encode(serversResponse{Servers: processes}) // skipcq GSC-G104
writeJsonStructRes(w, serversResponse{Servers: processes}) // skipcq GSC-G104
})

// GET /server/{id}
Expand Down Expand Up @@ -368,7 +380,7 @@ func (connector *Connector) registerMiscRoutes() {
// Send a response.
res := make(map[string]bool)
res["success"] = err == nil
json.NewEncoder(w).Encode(res) // skipcq GSC-G104
writeJsonStructRes(w, res) // skipcq GSC-G104
} else if operation == "STOP" || operation == "KILL" || operation == "TERM" {
// Stop process if required.
if process.Online.Load() == 1 {
Expand All @@ -384,7 +396,7 @@ func (connector *Connector) registerMiscRoutes() {
// Send a response.
res := make(map[string]bool)
res["success"] = true
json.NewEncoder(w).Encode(res) // skipcq GSC-G104
writeJsonStructRes(w, res) // skipcq GSC-G104
} else {
httpError(w, "Invalid operation requested!", http.StatusBadRequest)
return
Expand Down Expand Up @@ -422,7 +434,7 @@ func (connector *Connector) registerMiscRoutes() {
TotalMemory: totalMemory,
ToDelete: process.ToDelete.Load(),
}
json.NewEncoder(w).Encode(res) // skipcq GSC-G104
writeJsonStructRes(w, res) // skipcq GSC-G104
} else {
httpError(w, "Only GET and POST is allowed!", http.StatusMethodNotAllowed)
}
Expand Down
12 changes: 6 additions & 6 deletions endpoints_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ func (connector *Connector) registerAuthRoutes() {
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
fmt.Fprintln(w, "{\"success\":true}")
writeJsonStringRes(w, "{\"success\":true}")
return
}
// Send the response.
json.NewEncoder(w).Encode(loginResponse{Token: token}) // skipcq GSC-G104
writeJsonStructRes(w, loginResponse{Token: token}) // skipcq GSC-G104
})

// GET /logout
Expand Down Expand Up @@ -95,7 +95,7 @@ func (connector *Connector) registerAuthRoutes() {
})
// Send the response.
connector.Info("auth.logout", "ip", GetIP(r), "user", user)
fmt.Fprintln(w, "{\"success\":true}")
writeJsonStringRes(w, "{\"success\":true}")
})

// GET /ott
Expand Down Expand Up @@ -126,7 +126,7 @@ func (connector *Connector) registerAuthRoutes() {
connector.Tickets.Delete(ticketString)
})()
// Send the response.
fmt.Fprintln(w, "{\"ticket\": \""+ticketString+"\"}")
writeJsonStringRes(w, "{\"ticket\": \""+ticketString+"\"}")
})

// GET /accounts
Expand Down Expand Up @@ -169,7 +169,7 @@ func (connector *Connector) registerAuthRoutes() {
httpError(w, "Internal Server Error!", http.StatusInternalServerError)
return
}
fmt.Fprintln(w, string(usernamesJson))
writeJsonStringRes(w, string(usernamesJson))
return
} else if r.Method == "POST" {
var buffer bytes.Buffer
Expand Down Expand Up @@ -264,6 +264,6 @@ func (connector *Connector) registerAuthRoutes() {
httpError(w, "Internal Server Error!", http.StatusInternalServerError)
return
}
fmt.Fprintln(w, "{\"success\":true}")
writeJsonStringRes(w, "{\"success\":true}")
})
}
16 changes: 8 additions & 8 deletions endpoints_files.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func (connector *Connector) registerFileRoutes() {
MimeType: mimeType,
})
}
json.NewEncoder(w).Encode(toSend) // skipcq GSC-G104
writeJsonStructRes(w, toSend) // skipcq GSC-G104
})

// GET /server/{id}/file?path=path&ticket=ticket
Expand Down Expand Up @@ -177,7 +177,7 @@ func (connector *Connector) registerFileRoutes() {
}
connector.Info("server.files.delete", "ip", GetIP(r), "user", user, "server", id,
"path", clean(r.URL.Query().Get("path")))
fmt.Fprintln(w, "{\"success\":true}")
writeJsonStringRes(w, "{\"success\":true}")
} else if r.Method == "POST" {
// Parse our multipart form, 5120 << 20 specifies a maximum upload of a 5 GB file.
err := r.ParseMultipartForm(5120 << 20)
Expand Down Expand Up @@ -209,7 +209,7 @@ func (connector *Connector) registerFileRoutes() {
connector.Info("server.files.upload", "ip", GetIP(r), "user", user, "server", id,
"path", clean(r.URL.Query().Get("path")), "filename", meta.Filename)
io.Copy(toWrite, file)
fmt.Fprintln(w, "{\"success\":true}")
writeJsonStringRes(w, "{\"success\":true}")
} else if r.Method == "PATCH" {
// Get the request body to check the operation.
var body bytes.Buffer
Expand Down Expand Up @@ -286,7 +286,7 @@ func (connector *Connector) registerFileRoutes() {
}
connector.Info("server.files.move", "ip", GetIP(r), "user", user, "server", id,
"src", clean(req.Src), "dest", clean(req.Dest))
fmt.Fprintln(w, "{\"success\":true}")
writeJsonStringRes(w, "{\"success\":true}")
} else {
err := system.Copy(stat.Mode(), oldpath, newpath)
if err != nil {
Expand All @@ -296,7 +296,7 @@ func (connector *Connector) registerFileRoutes() {
}
connector.Info("server.files.copy", "ip", GetIP(r), "user", user, "server", id,
"src", clean(req.Src), "dest", clean(req.Dest))
fmt.Fprintln(w, "{\"success\":true}")
writeJsonStringRes(w, "{\"success\":true}")
}
} else {
httpError(w, "Invalid operation! Operations available: mv,cp", http.StatusMethodNotAllowed)
Expand Down Expand Up @@ -345,7 +345,7 @@ func (connector *Connector) registerFileRoutes() {
}
connector.Info("server.files.createFolder", "ip", GetIP(r), "user", user, "server", id,
"path", clean(r.URL.Query().Get("path")))
fmt.Fprintln(w, "{\"success\":true}")
writeJsonStringRes(w, "{\"success\":true}")
} else {
httpError(w, "Only POST is allowed!", http.StatusMethodNotAllowed)
}
Expand Down Expand Up @@ -434,7 +434,7 @@ func (connector *Connector) registerFileRoutes() {
}
connector.Info("server.files.compress", "ip", GetIP(r), "user", user, "server", id,
"zipFile", clean(r.URL.Query().Get("path")), "files", files, "compressed", compressed)
fmt.Fprintln(w, "{\"success\":true}")
writeJsonStringRes(w, "{\"success\":true}")
} else {
httpError(w, "Only POST is allowed!", http.StatusMethodNotAllowed)
}
Expand Down Expand Up @@ -513,7 +513,7 @@ func (connector *Connector) registerFileRoutes() {
}
connector.Info("server.files.decompress", "ip", GetIP(r), "user", user, "server", id,
"zipFile", clean(r.URL.Query().Get("path")), "destPath", body.String())
fmt.Fprintln(w, "{\"success\":true}")
writeJsonStringRes(w, "{\"success\":true}")
} else {
httpError(w, "Only POST is allowed!", http.StatusMethodNotAllowed)
}
Expand Down

0 comments on commit 1b107cd

Please sign in to comment.