statping/web.go

371 lines
9.4 KiB
Go
Raw Normal View History

2018-06-10 01:31:13 +00:00
package main
import (
"fmt"
2018-06-11 03:41:02 +00:00
"github.com/gorilla/mux"
2018-06-12 05:23:30 +00:00
"github.com/gorilla/sessions"
"github.com/hunterlong/statup/plugin"
2018-06-10 01:31:13 +00:00
"html/template"
"net/http"
2018-06-10 03:44:47 +00:00
"strconv"
2018-06-11 03:41:02 +00:00
"time"
2018-06-10 01:31:13 +00:00
)
2018-06-11 07:49:41 +00:00
var (
session *sessions.CookieStore
)
2018-06-11 03:41:02 +00:00
2018-06-11 07:49:41 +00:00
func RunHTTPServer() {
2018-06-11 03:41:02 +00:00
r := mux.NewRouter()
fmt.Println("Statup HTTP Server running on http://localhost:8080")
r.Handle("/", http.HandlerFunc(IndexHandler))
r.PathPrefix("/css/").Handler(http.StripPrefix("/css/", http.FileServer(cssBox.HTTPBox())))
r.PathPrefix("/js/").Handler(http.StripPrefix("/js/", http.FileServer(jsBox.HTTPBox())))
r.Handle("/setup", http.HandlerFunc(SetupHandler))
r.Handle("/setup/save", http.HandlerFunc(ProcessSetupHandler))
r.Handle("/dashboard", http.HandlerFunc(DashboardHandler))
r.Handle("/login", http.HandlerFunc(LoginHandler))
r.Handle("/logout", http.HandlerFunc(LogoutHandler))
r.Handle("/services", http.HandlerFunc(ServicesHandler))
r.Handle("/services", http.HandlerFunc(CreateServiceHandler)).Methods("POST")
r.Handle("/service/{id}", http.HandlerFunc(ServicesViewHandler))
r.Handle("/service/{id}", http.HandlerFunc(ServicesUpdateHandler)).Methods("POST")
r.Handle("/service/{id}/edit", http.HandlerFunc(ServicesViewHandler))
r.Handle("/service/{id}/delete", http.HandlerFunc(ServicesDeleteHandler))
r.Handle("/users", http.HandlerFunc(UsersHandler))
r.Handle("/users", http.HandlerFunc(CreateUserHandler)).Methods("POST")
r.Handle("/settings", http.HandlerFunc(SettingsHandler))
r.Handle("/plugins", http.HandlerFunc(PluginsHandler))
2018-06-12 07:21:16 +00:00
r.Handle("/plugins/download/{name}", http.HandlerFunc(PluginsDownloadHandler))
2018-06-11 03:41:02 +00:00
r.Handle("/help", http.HandlerFunc(HelpHandler))
2018-06-11 15:29:54 +00:00
for _, p := range allPlugins {
symPlugin, _ := p.Lookup("Plugin")
2018-06-12 05:23:30 +00:00
var pluginObject plugin.PluginActions
pluginObject, ok := symPlugin.(plugin.PluginActions)
info := pluginObject.GetInfo()
2018-06-11 15:29:54 +00:00
if !ok {
2018-06-12 05:23:30 +00:00
fmt.Printf("Plugin '%v' could not load correctly, error: %v\n", info.Name, "unexpected type from module symbol")
2018-06-11 15:29:54 +00:00
continue
2018-06-11 07:49:41 +00:00
}
2018-06-12 05:23:30 +00:00
plugin.AllPlugins = append(plugin.AllPlugins, info)
for _, route := range pluginObject.Routes() {
path := fmt.Sprintf("/plugins/%v/%v", info.Name, route.URL)
r.Handle(path, http.HandlerFunc(route.Handler)).Methods(route.Method)
fmt.Printf("Added Route %v for plugin %v\n", path, info.Name)
}
2018-06-11 03:41:02 +00:00
}
2018-06-12 05:23:30 +00:00
core.Plugins = plugin.AllPlugins
2018-06-11 03:41:02 +00:00
srv := &http.Server{
Addr: "0.0.0.0:8080",
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: r,
}
srv.ListenAndServe()
2018-06-10 01:31:13 +00:00
}
func LogoutHandler(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "apizer_auth")
session.Values["authenticated"] = false
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func LoginHandler(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "apizer_auth")
r.ParseForm()
username := r.PostForm.Get("username")
password := r.PostForm.Get("password")
2018-06-10 03:44:47 +00:00
user, auth := AuthUser(username, password)
fmt.Println(user)
fmt.Println(auth)
2018-06-10 01:31:13 +00:00
if auth {
session.Values["authenticated"] = true
session.Save(r, w)
http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
} else {
w.WriteHeader(502)
w.Header().Set("Content-Type", "plain/text")
fmt.Fprintln(w, "bad")
}
}
//func AuthenticateHandler(w http.ResponseWriter, r *http.Request) {
// r.ParseForm()
// key := r.PostForm.Get("key")
// secret := r.PostForm.Get("secret")
// token := SelectToken(key, secret)
// if token.Id != 0 {
// go token.Hit(r)
// w.WriteHeader(200)
// w.Header().Set("Content-Type", "plain/text")
// fmt.Fprintln(w, token.Id)
// } else {
// w.WriteHeader(502)
// w.Header().Set("Content-Type", "plain/text")
// fmt.Fprintln(w, "bad")
// }
//}
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
username := r.PostForm.Get("username")
password := r.PostForm.Get("password")
user := &User{
Username: username,
Password: password,
}
user.Create()
http.Redirect(w, r, "/users", http.StatusSeeOther)
}
func CreateServiceHandler(w http.ResponseWriter, r *http.Request) {
2018-06-10 03:44:47 +00:00
r.ParseForm()
name := r.PostForm.Get("name")
domain := r.PostForm.Get("domain")
method := r.PostForm.Get("method")
expected := r.PostForm.Get("expected")
status, _ := strconv.Atoi(r.PostForm.Get("expected_status"))
interval, _ := strconv.Atoi(r.PostForm.Get("interval"))
service := &Service{
Name: name,
Domain: domain,
Method: method,
Expected: expected,
ExpectedStatus: status,
Interval: interval,
}
fmt.Println(service)
service.Create()
2018-06-10 01:31:13 +00:00
http.Redirect(w, r, "/services", http.StatusSeeOther)
}
func SetupHandler(w http.ResponseWriter, r *http.Request) {
2018-06-11 03:41:02 +00:00
tmpl := Parse("setup.html")
tmpl.Execute(w, nil)
2018-06-10 01:31:13 +00:00
}
type index struct {
2018-06-10 04:09:20 +00:00
Project string
Services []*Service
2018-06-10 01:31:13 +00:00
}
func IndexHandler(w http.ResponseWriter, r *http.Request) {
2018-06-10 01:47:57 +00:00
if core == nil {
2018-06-10 01:31:13 +00:00
http.Redirect(w, r, "/setup", http.StatusSeeOther)
return
}
2018-06-11 03:41:02 +00:00
tmpl := Parse("index.html")
2018-06-10 04:09:20 +00:00
out := index{core.Name, services}
2018-06-11 03:41:02 +00:00
tmpl.Execute(w, out)
2018-06-10 01:31:13 +00:00
}
2018-06-11 00:20:42 +00:00
type dashboard struct {
Services []*Service
Core *Core
CountOnline int
CountServices int
Count24Failures int
}
2018-06-10 01:31:13 +00:00
func DashboardHandler(w http.ResponseWriter, r *http.Request) {
2018-06-10 03:44:47 +00:00
session, _ := store.Get(r, "apizer_auth")
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
2018-06-11 03:41:02 +00:00
tmpl := Parse("login.html")
tmpl.Execute(w, nil)
2018-06-10 03:44:47 +00:00
} else {
2018-06-11 03:41:02 +00:00
tmpl := Parse("dashboard.html")
2018-06-11 00:20:42 +00:00
out := dashboard{services, core, CountOnline(), len(services), CountFailures()}
2018-06-11 03:41:02 +00:00
tmpl.Execute(w, out)
2018-06-10 01:31:13 +00:00
}
}
2018-06-11 03:41:02 +00:00
type serviceHandler struct {
Service *Service
Auth bool
}
2018-06-10 01:31:13 +00:00
func ServicesHandler(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "apizer_auth")
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
2018-06-11 03:41:02 +00:00
tmpl := Parse("services.html")
tmpl.Execute(w, services)
}
func ServicesDeleteHandler(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "apizer_auth")
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
vars := mux.Vars(r)
service := SelectService(vars["id"])
service.Delete()
services = SelectAllServices()
http.Redirect(w, r, "/services", http.StatusSeeOther)
}
func IsAuthenticated(r *http.Request) bool {
session, _ := store.Get(r, "apizer_auth")
return session.Values["authenticated"].(bool)
}
func SettingsHandler(w http.ResponseWriter, r *http.Request) {
auth := IsAuthenticated(r)
if !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
tmpl := Parse("settings.html")
tmpl.Execute(w, core)
}
func PluginsHandler(w http.ResponseWriter, r *http.Request) {
auth := IsAuthenticated(r)
if !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
tmpl := ParsePlugins("plugins.html")
2018-06-12 07:21:16 +00:00
core.FetchPluginRepo()
fmt.Println(core.FetchPluginRepo())
tmpl.Execute(w, &core)
}
func PluginsDownloadHandler(w http.ResponseWriter, r *http.Request) {
auth := IsAuthenticated(r)
if !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
vars := mux.Vars(r)
name := vars["name"]
DownloadPlugin(name)
LoadConfig()
http.Redirect(w, r, "/plugins", http.StatusSeeOther)
2018-06-11 03:41:02 +00:00
}
func HelpHandler(w http.ResponseWriter, r *http.Request) {
auth := IsAuthenticated(r)
if !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
tmpl := Parse("help.html")
tmpl.Execute(w, nil)
}
func ServicesUpdateHandler(w http.ResponseWriter, r *http.Request) {
//auth := IsAuthenticated(r)
//
//vars := mux.Vars(r)
//service := SelectService(vars["id"])
}
func ServicesViewHandler(w http.ResponseWriter, r *http.Request) {
auth := IsAuthenticated(r)
vars := mux.Vars(r)
service := SelectService(vars["id"])
tmpl := Parse("service.html")
serve := &serviceHandler{service, auth}
tmpl.Execute(w, serve)
}
func Parse(file string) *template.Template {
nav, _ := tmplBox.String("nav.html")
render, err := tmplBox.String(file)
2018-06-10 01:31:13 +00:00
if err != nil {
panic(err)
}
2018-06-11 03:41:02 +00:00
t := template.New("message")
t.Funcs(template.FuncMap{
"js": func(html string) template.JS {
return template.JS(html)
},
2018-06-11 09:58:41 +00:00
"safe": func(html string) template.HTML {
return template.HTML(html)
},
2018-06-11 03:41:02 +00:00
})
t, _ = t.Parse(nav)
t.Parse(render)
return t
}
func ParsePlugins(file string) *template.Template {
nav, _ := tmplBox.String("nav.html")
slack, _ := tmplBox.String("plugins/slack.html")
render, err := tmplBox.String(file)
2018-06-10 01:31:13 +00:00
if err != nil {
panic(err)
}
2018-06-11 03:41:02 +00:00
t := template.New("message")
t.Funcs(template.FuncMap{
"js": func(html string) template.JS {
return template.JS(html)
},
2018-06-11 09:58:41 +00:00
"safe": func(html string) template.HTML {
return template.HTML(html)
},
2018-06-11 03:41:02 +00:00
})
t, _ = t.Parse(nav)
t.Parse(slack)
t.Parse(render)
return t
2018-06-10 01:31:13 +00:00
}
func UsersHandler(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "apizer_auth")
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
2018-06-11 03:41:02 +00:00
tmpl := Parse("users.html")
tmpl.Execute(w, SelectAllUsers())
2018-06-10 01:31:13 +00:00
}
func PermissionsHandler(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "apizer_auth")
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
permsFile, err := tmplBox.String("permissions.html")
if err != nil {
panic(err)
}
permsTmpl, err := template.New("message").Parse(permsFile)
if err != nil {
panic(err)
}
permsTmpl.Execute(w, SelectAllUsers())
}