statping/web.go

385 lines
11 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"
2018-06-10 01:31:13 +00:00
"html/template"
"net/http"
2018-06-10 03:44:47 +00:00
"strconv"
2018-06-14 01:19:00 +00:00
"strings"
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-15 04:30:10 +00:00
const (
cookieKey = "apizer_auth"
)
2018-06-14 06:38:15 +00:00
func Router() *mux.Router {
2018-06-11 03:41:02 +00:00
r := mux.NewRouter()
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())))
2018-06-15 04:30:10 +00:00
r.Handle("/setup", http.HandlerFunc(SetupHandler)).Methods("GET")
r.Handle("/setup", http.HandlerFunc(ProcessSetupHandler)).Methods("POST")
r.Handle("/dashboard", http.HandlerFunc(DashboardHandler)).Methods("GET")
r.Handle("/dashboard", http.HandlerFunc(LoginHandler)).Methods("POST")
2018-06-11 03:41:02 +00:00
r.Handle("/logout", http.HandlerFunc(LogoutHandler))
2018-06-15 04:30:10 +00:00
r.Handle("/services", http.HandlerFunc(ServicesHandler)).Methods("GET")
2018-06-11 03:41:02 +00:00
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))
2018-06-15 04:30:10 +00:00
r.Handle("/service/{id}/badge.svg", http.HandlerFunc(ServicesBadgeHandler))
r.Handle("/users", http.HandlerFunc(UsersHandler)).Methods("GET")
2018-06-11 03:41:02 +00:00
r.Handle("/users", http.HandlerFunc(CreateUserHandler)).Methods("POST")
2018-06-14 01:19:00 +00:00
r.Handle("/settings", http.HandlerFunc(PluginsHandler))
2018-06-12 07:21:16 +00:00
r.Handle("/plugins/download/{name}", http.HandlerFunc(PluginsDownloadHandler))
2018-06-14 01:19:00 +00:00
r.Handle("/plugins/{name}/save", http.HandlerFunc(PluginSavedHandler)).Methods("POST")
2018-06-11 03:41:02 +00:00
r.Handle("/help", http.HandlerFunc(HelpHandler))
2018-06-15 04:30:10 +00:00
r.Handle("/api", http.HandlerFunc(ApiIndexHandler))
r.Handle("/api/services", http.HandlerFunc(ApiAllServicesHandler))
r.Handle("/api/services/{id}", http.HandlerFunc(ApiServiceHandler)).Methods("GET")
r.Handle("/api/services/{id}", http.HandlerFunc(ApiServiceUpdateHandler)).Methods("POST")
r.Handle("/api/users", http.HandlerFunc(ApiAllUsersHandler))
r.Handle("/api/users/{id}", http.HandlerFunc(ApiUserHandler))
2018-06-14 06:38:15 +00:00
return r
}
2018-06-11 03:41:02 +00:00
2018-06-14 06:38:15 +00:00
func RunHTTPServer() {
fmt.Println("Statup HTTP Server running on http://localhost:8080")
r := Router()
2018-06-11 15:29:54 +00:00
for _, p := range allPlugins {
2018-06-14 01:19:00 +00:00
info := p.GetInfo()
for _, route := range p.Routes() {
2018-06-12 05:23:30 +00:00
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
}
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) {
2018-06-15 04:30:10 +00:00
session, _ := store.Get(r, cookieKey)
2018-06-10 01:31:13 +00:00
session.Values["authenticated"] = false
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func LoginHandler(w http.ResponseWriter, r *http.Request) {
2018-06-15 04:30:10 +00:00
session, _ := store.Get(r, cookieKey)
2018-06-10 01:31:13 +00:00
r.ParseForm()
username := r.PostForm.Get("username")
password := r.PostForm.Get("password")
2018-06-15 04:30:10 +00:00
_, auth := AuthUser(username, password)
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 CreateUserHandler(w http.ResponseWriter, r *http.Request) {
2018-06-15 04:30:10 +00:00
fmt.Println("creating user")
2018-06-10 01:31:13 +00:00
r.ParseForm()
username := r.PostForm.Get("username")
password := r.PostForm.Get("password")
user := &User{
Username: username,
Password: password,
}
2018-06-15 04:30:10 +00:00
_, err := user.Create()
if err != nil {
panic(err)
}
2018-06-10 01:31:13 +00:00
http.Redirect(w, r, "/users", http.StatusSeeOther)
}
func CreateServiceHandler(w http.ResponseWriter, r *http.Request) {
2018-06-15 04:30:10 +00:00
fmt.Println("service adding")
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"))
2018-06-15 04:30:10 +00:00
fmt.Println(r.PostForm)
service := Service{
2018-06-10 03:44:47 +00:00
Name: name,
Domain: domain,
Method: method,
Expected: expected,
ExpectedStatus: status,
Interval: interval,
}
fmt.Println(service)
2018-06-15 04:30:10 +00:00
_, err := service.Create()
if err != nil {
go service.CheckQueue()
}
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
2018-06-15 04:30:10 +00:00
Count24Failures uint64
2018-06-11 00:20:42 +00:00
}
2018-06-10 01:31:13 +00:00
func DashboardHandler(w http.ResponseWriter, r *http.Request) {
2018-06-15 04:30:10 +00:00
session, _ := store.Get(r, cookieKey)
2018-06-10 03:44:47 +00:00
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-15 04:30:10 +00:00
fails, _ := CountFailures()
out := dashboard{services, core, CountOnline(), len(services), fails}
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 {
2018-06-15 04:30:10 +00:00
Service Service
2018-06-11 03:41:02 +00:00
Auth bool
}
2018-06-10 01:31:13 +00:00
func ServicesHandler(w http.ResponseWriter, r *http.Request) {
2018-06-15 04:30:10 +00:00
session, _ := store.Get(r, cookieKey)
2018-06-10 01:31:13 +00:00
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) {
2018-06-15 04:30:10 +00:00
session, _ := store.Get(r, cookieKey)
2018-06-11 03:41:02 +00:00
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
vars := mux.Vars(r)
2018-06-15 04:30:10 +00:00
service, _ := SelectService(StringInt(vars["id"]))
2018-06-11 03:41:02 +00:00
service.Delete()
2018-06-15 04:30:10 +00:00
services, _ = SelectAllServices()
2018-06-11 03:41:02 +00:00
http.Redirect(w, r, "/services", http.StatusSeeOther)
}
func IsAuthenticated(r *http.Request) bool {
2018-06-15 04:30:10 +00:00
session, _ := store.Get(r, cookieKey)
2018-06-14 06:38:15 +00:00
if session.Values["authenticated"] == nil {
return false
}
2018-06-11 03:41:02 +00:00
return session.Values["authenticated"].(bool)
}
2018-06-14 01:19:00 +00:00
func PluginsHandler(w http.ResponseWriter, r *http.Request) {
2018-06-11 03:41:02 +00:00
auth := IsAuthenticated(r)
if !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
2018-06-14 01:19:00 +00:00
tmpl := ParsePlugins("plugins.html")
core.FetchPluginRepo()
2018-06-14 06:38:15 +00:00
var pluginFields []PluginSelect
2018-06-14 01:19:00 +00:00
2018-06-14 06:38:15 +00:00
for _, p := range allPlugins {
fields := SelectSettings(p.GetInfo())
2018-06-14 01:19:00 +00:00
2018-06-14 06:38:15 +00:00
pluginFields = append(pluginFields, PluginSelect{p.GetInfo().Name, fields})
2018-06-14 01:19:00 +00:00
}
2018-06-14 06:38:15 +00:00
core.PluginFields = pluginFields
fmt.Println(&core.PluginFields)
2018-06-11 03:41:02 +00:00
tmpl.Execute(w, core)
}
2018-06-14 06:38:15 +00:00
type PluginSelect struct {
Plugin string
Params map[string]string
}
2018-06-14 01:19:00 +00:00
func PluginSavedHandler(w http.ResponseWriter, r *http.Request) {
2018-06-11 03:41:02 +00:00
auth := IsAuthenticated(r)
if !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
2018-06-14 01:19:00 +00:00
r.ParseForm()
vars := mux.Vars(r)
2018-06-14 06:38:15 +00:00
plug := SelectPlugin(vars["name"])
2018-06-14 01:19:00 +00:00
data := make(map[string]string)
for k, v := range r.PostForm {
data[k] = strings.Join(v, "")
}
2018-06-14 06:38:15 +00:00
UpdateSettings(plug.GetInfo(), data)
plug.OnSave(data)
2018-06-14 01:19:00 +00:00
http.Redirect(w, r, "/settings", http.StatusSeeOther)
2018-06-12 07:21:16 +00:00
}
func PluginsDownloadHandler(w http.ResponseWriter, r *http.Request) {
auth := IsAuthenticated(r)
if !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
2018-06-14 01:19:00 +00:00
//vars := mux.Vars(r)
//name := vars["name"]
//DownloadPlugin(name)
2018-06-12 07:21:16 +00:00
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"])
}
2018-06-15 04:30:10 +00:00
func ServicesBadgeHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
service, _ := SelectService(StringInt(vars["id"]))
var badge []byte
if service.Online {
2018-06-18 09:53:18 +00:00
badge = []byte(`<svg xmlns="http://www.w3.org/2000/svg" width="104" height="20"><linearGradient id="b" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><mask id="a"><rect width="104" height="20" rx="3" fill="#fff"/></mask><g mask="url(#a)"><path fill="#555" d="M0 0h54v20H0z"/><path fill="#4c1" d="M54 0h50v20H54z"/><path fill="url(#b)" d="M0 0h104v20H0z"/></g><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11"><text x="28" y="15" fill="#010101" fill-opacity=".3">` + service.Name + `</text><text x="28" y="14">` + service.Name + `</text><text x="78" y="15" fill="#010101" fill-opacity=".3">online</text><text x="78" y="14">online</text></g></svg>`)
2018-06-15 04:30:10 +00:00
} else {
2018-06-18 09:53:18 +00:00
badge = []byte(`<svg xmlns="http://www.w3.org/2000/svg" width="99" height="20"><linearGradient id="b" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><mask id="a"><rect width="99" height="20" rx="3" fill="#fff"/></mask><g mask="url(#a)"><path fill="#555" d="M0 0h54v20H0z"/><path fill="#e05d44" d="M54 0h45v20H54z"/><path fill="url(#b)" d="M0 0h99v20H0z"/></g><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11"><text x="28" y="15" fill="#010101" fill-opacity=".3">` + service.Name + `</text><text x="28" y="14">` + service.Name + `</text><text x="75.5" y="15" fill="#010101" fill-opacity=".3">offline</text><text x="75.5" y="14">offline</text></g></svg>`)
2018-06-15 04:30:10 +00:00
}
w.Header().Set("Content-Type", "image/svg+xml")
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Write(badge)
}
2018-06-11 03:41:02 +00:00
func ServicesViewHandler(w http.ResponseWriter, r *http.Request) {
auth := IsAuthenticated(r)
vars := mux.Vars(r)
2018-06-15 04:30:10 +00:00
service, _ := SelectService(StringInt(vars["id"]))
2018-06-11 03:41:02 +00:00
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) {
2018-06-15 04:30:10 +00:00
fmt.Println("viewing user")
session, _ := store.Get(r, cookieKey)
2018-06-10 01:31:13 +00:00
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")
2018-06-15 04:30:10 +00:00
users, _ := SelectAllUsers()
tmpl.Execute(w, users)
2018-06-10 01:31:13 +00:00
}