statping/handlers/dashboard.go

234 lines
6.5 KiB
Go
Raw Normal View History

2018-12-04 05:57:11 +00:00
// Statping
2018-08-16 06:22:20 +00:00
// Copyright (C) 2018. Hunter Long and the project contributors
// Written by Hunter Long <info@socialeck.com> and the project contributors
//
2020-03-09 18:17:55 +00:00
// https://github.com/statping/statping
2018-08-16 06:22:20 +00:00
//
// The licenses for most software and other practical works are designed
// to take away your freedom to share and change the works. By contrast,
// the GNU General Public License is intended to guarantee your freedom to
// share and change all versions of a program--to make sure it remains free
// software for all its users.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
2018-06-30 00:57:05 +00:00
package handlers
import (
2020-02-06 05:00:12 +00:00
"encoding/json"
"fmt"
2020-01-16 09:29:49 +00:00
"github.com/dgrijalva/jwt-go"
2020-03-09 18:17:55 +00:00
"github.com/statping/statping/source"
"github.com/statping/statping/types/users"
"github.com/statping/statping/utils"
2018-06-30 00:57:05 +00:00
"net/http"
2020-02-06 05:00:12 +00:00
"os"
2020-01-16 09:29:49 +00:00
"time"
2018-06-30 00:57:05 +00:00
)
func logoutHandler(w http.ResponseWriter, r *http.Request) {
2020-01-16 09:29:49 +00:00
removeJwtToken(w)
2020-01-13 08:41:14 +00:00
http.Redirect(w, r, basePath, http.StatusSeeOther)
2018-06-30 00:57:05 +00:00
}
func helpHandler(w http.ResponseWriter, r *http.Request) {
if !IsUser(r) {
2020-01-13 08:41:14 +00:00
http.Redirect(w, r, basePath, http.StatusSeeOther)
2018-06-30 00:57:05 +00:00
return
}
help := source.HelpMarkdown()
2018-12-06 19:03:55 +00:00
ExecuteResponse(w, r, "help.gohtml", help, nil)
2018-06-30 00:57:05 +00:00
}
func logsHandler(w http.ResponseWriter, r *http.Request) {
utils.LockLines.Lock()
logs := make([]string, 0)
length := len(utils.LastLines)
// We need string log lines from end to start.
for i := length - 1; i >= 0; i-- {
logs = append(logs, utils.LastLines[i].FormatForHtml()+"\r\n")
}
utils.LockLines.Unlock()
2020-02-01 03:53:00 +00:00
returnJson(logs, w, r)
}
2020-02-06 05:00:12 +00:00
type themeApi struct {
Directory string `json:"directory,omitempty"`
Base string `json:"base"`
Variables string `json:"variables"`
Mobile string `json:"mobile"`
}
func apiThemeHandler(w http.ResponseWriter, r *http.Request) {
var base, variables, mobile, dir string
assets := utils.Directory + "/assets"
if _, err := os.Stat(assets); err == nil {
dir = assets
}
if dir != "" {
base, _ = utils.OpenFile(dir + "/scss/base.scss")
variables, _ = utils.OpenFile(dir + "/scss/variables.scss")
mobile, _ = utils.OpenFile(dir + "/scss/mobile.scss")
} else {
base, _ = source.TmplBox.String("scss/base.scss")
variables, _ = source.TmplBox.String("scss/variables.scss")
mobile, _ = source.TmplBox.String("scss/mobile.scss")
}
resp := &themeApi{
Directory: dir,
Base: base,
Variables: variables,
Mobile: mobile,
}
returnJson(resp, w, r)
}
func apiThemeSaveHandler(w http.ResponseWriter, r *http.Request) {
var themes themeApi
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&themes)
if err != nil {
sendErrorJson(err, w, r)
return
}
2020-02-19 04:07:22 +00:00
if err := source.SaveAsset([]byte(themes.Base), "scss/base.scss"); err != nil {
2020-02-06 05:00:12 +00:00
sendErrorJson(err, w, r)
return
}
2020-02-19 04:07:22 +00:00
if err := source.SaveAsset([]byte(themes.Variables), "scss/variables.scss"); err != nil {
2020-02-06 05:00:12 +00:00
sendErrorJson(err, w, r)
return
}
2020-02-19 04:07:22 +00:00
if err := source.SaveAsset([]byte(themes.Mobile), "scss/mobile.scss"); err != nil {
2020-02-06 05:00:12 +00:00
sendErrorJson(err, w, r)
return
}
2020-03-02 07:53:46 +00:00
if err := source.CompileSASS(source.DefaultScss...); err != nil {
2020-02-06 05:00:12 +00:00
sendErrorJson(err, w, r)
return
}
resetRouter()
sendJsonAction(themes, "saved", w, r)
}
func apiThemeCreateHandler(w http.ResponseWriter, r *http.Request) {
dir := utils.Directory
utils.Log.Infof("creating assets in folder: %s/%s", dir, "assets")
if err := source.CreateAllAssets(dir); err != nil {
log.Errorln(err)
sendErrorJson(err, w, r)
return
}
2020-03-02 07:53:46 +00:00
if err := source.CompileSASS(source.DefaultScss...); err != nil {
2020-03-19 04:55:32 +00:00
source.CopyToPublic(source.TmplBox, "css", "main.css")
2020-02-19 04:07:22 +00:00
source.CopyToPublic(source.TmplBox, "css", "base.css")
2020-02-06 05:00:12 +00:00
log.Errorln("Default 'base.css' was inserted because SASS did not work.")
}
resetRouter()
sendJsonAction(dir+"/assets", "created", w, r)
}
func apiThemeRemoveHandler(w http.ResponseWriter, r *http.Request) {
if err := source.DeleteAllAssets(utils.Directory); err != nil {
log.Errorln(fmt.Errorf("error deleting all assets %v", err))
}
sendJsonAction(utils.Directory+"/assets", "deleted", w, r)
}
func logsLineHandler(w http.ResponseWriter, r *http.Request) {
if lastLine := utils.GetLastLine(); lastLine != nil {
2018-11-30 11:12:17 +00:00
w.Header().Set("Content-Type", "text/plain")
2018-11-30 05:31:20 +00:00
w.WriteHeader(http.StatusOK)
w.Write([]byte(lastLine.FormatForHtml()))
2018-07-27 06:37:41 +00:00
}
}
2020-02-25 13:18:29 +00:00
//func exportHandler(w http.ResponseWriter, r *http.Request) {
// var notifiers []*notifier.Notification
// for _, v := range core.CoreApp.Notifications {
// notifier := v.(notifier.Notifier)
// notifiers = append(notifiers, notifier.Select())
// }
//
// export, _ := core.ExportSettings()
//
// mime := http.DetectContentType(export)
// fileSize := len(string(export))
//
// w.Header().Set("Content-Type", mime)
// w.Header().Set("Content-Disposition", "attachment; filename=export.json")
// w.Header().Set("Expires", "0")
// w.Header().Set("Content-Transfer-Encoding", "binary")
// w.Header().Set("Content-Length", strconv.Itoa(fileSize))
// w.Header().Set("Content-Control", "private, no-transform, no-store, must-revalidate")
//
// http.ServeContent(w, r, "export.json", utils.Now(), bytes.NewReader(export))
//
//}
2020-01-16 09:29:49 +00:00
type JwtClaim struct {
Username string `json:"username"`
Admin bool `json:"admin"`
jwt.StandardClaims
}
func removeJwtToken(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: cookieKey,
Value: "",
Expires: time.Now().UTC(),
})
}
2020-03-04 10:29:00 +00:00
func setJwtToken(user *users.User, w http.ResponseWriter) (JwtClaim, string) {
2020-01-20 05:02:15 +00:00
expirationTime := time.Now().Add(72 * time.Hour)
jwtClaim := JwtClaim{
Username: user.Username,
Admin: user.Admin.Bool,
StandardClaims: jwt.StandardClaims{
2020-01-16 09:29:49 +00:00
ExpiresAt: expirationTime.Unix(),
}}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwtClaim)
tokenString, err := token.SignedString([]byte(jwtKey))
if err != nil {
utils.Log.Errorln("error setting token: ", err)
}
http.SetCookie(w, &http.Cookie{
Name: cookieKey,
Value: tokenString,
Expires: expirationTime,
})
return jwtClaim, tokenString
}
func apiLoginHandler(w http.ResponseWriter, r *http.Request) {
form := parseForm(r)
username := form.Get("username")
password := form.Get("password")
2020-03-04 10:29:00 +00:00
user, auth := users.AuthUser(username, password)
2020-01-16 09:29:49 +00:00
if auth {
utils.Log.Infoln(fmt.Sprintf("User %v logged in from IP %v", user.Username, r.RemoteAddr))
claim, token := setJwtToken(user, w)
2020-01-16 09:29:49 +00:00
resp := struct {
Token string `json:"token"`
IsAdmin bool `json:"admin"`
2020-01-16 09:29:49 +00:00
}{
token,
claim.Admin,
2020-01-16 09:29:49 +00:00
}
returnJson(resp, w, r)
} else {
resp := struct {
Error string `json:"error"`
}{
"incorrect authentication",
}
returnJson(resp, w, r)
}
}