statping/web.go

529 lines
16 KiB
Go
Raw Normal View History

2018-06-10 01:31:13 +00:00
package main
import (
"fmt"
2018-06-19 04:48:25 +00:00
"github.com/fatih/structs"
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-23 04:17:57 +00:00
"github.com/hunterlong/statup/types"
2018-06-10 01:31:13 +00:00
"html/template"
"net/http"
2018-06-24 00:13:37 +00:00
"os"
2018-06-22 04:02:57 +00:00
"regexp"
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 (
2018-06-19 04:48:25 +00:00
cookieKey = "statup_auth"
2018-06-15 04:30:10 +00:00
)
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")
2018-06-19 04:48:25 +00:00
r.Handle("/service/{id}", http.HandlerFunc(ServicesViewHandler)).Methods("GET")
2018-06-11 03:41:02 +00:00
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))
2018-06-19 04:48:25 +00:00
r.Handle("/service/{id}/delete_failures", http.HandlerFunc(ServicesDeleteFailuresHandler)).Methods("GET")
2018-06-22 06:56:44 +00:00
r.Handle("/service/{id}/checkin", http.HandlerFunc(CheckinCreateUpdateHandler)).Methods("POST")
2018-06-15 04:30:10 +00:00
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-19 04:48:25 +00:00
r.Handle("/users/{id}/delete", http.HandlerFunc(UsersDeleteHandler)).Methods("GET")
2018-06-19 00:01:03 +00:00
r.Handle("/settings", http.HandlerFunc(PluginsHandler)).Methods("GET")
r.Handle("/settings", http.HandlerFunc(SaveSettingsHandler)).Methods("POST")
2018-06-23 04:17:57 +00:00
r.Handle("/settings/email", http.HandlerFunc(SaveEmailSettingsHandler)).Methods("POST")
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))
2018-06-22 06:56:44 +00:00
r.Handle("/api/checkin/{api}", http.HandlerFunc(ApiCheckinHandler))
2018-06-15 04:30:10 +00:00
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-23 08:42:50 +00:00
user, auth := AuthUser(username, password)
2018-06-10 01:31:13 +00:00
if auth {
session.Values["authenticated"] = true
2018-06-23 08:42:50 +00:00
session.Values["user_id"] = user.Id
2018-06-10 01:31:13 +00:00
session.Save(r, w)
http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
} else {
2018-06-24 00:13:37 +00:00
err := ErrorResponse{Error: "Incorrect login information submitted, try again."}
ExecuteResponse(w, r, "login.html", err)
2018-06-10 01:31:13 +00:00
}
}
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-22 04:02:57 +00:00
port, _ := strconv.Atoi(r.PostForm.Get("port"))
checkType := r.PostForm.Get("check_type")
2018-06-15 04:30:10 +00:00
2018-06-22 08:48:47 +00:00
service := &Service{
2018-06-10 03:44:47 +00:00
Name: name,
Domain: domain,
Method: method,
Expected: expected,
ExpectedStatus: status,
Interval: interval,
2018-06-22 04:02:57 +00:00
Type: checkType,
Port: port,
2018-06-10 03:44:47 +00:00
}
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-23 04:17:57 +00:00
if core != nil {
2018-06-23 00:10:37 +00:00
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
2018-06-24 00:13:37 +00:00
port := 5432
if os.Getenv("DB_CONN") == "mysql" {
port = 3306
}
var data interface{}
if os.Getenv("DB_CONN") != "" {
data = &DbConfig{
DbConn: os.Getenv("DB_CONN"),
DbHost: os.Getenv("DB_HOST"),
DbUser: os.Getenv("DB_USER"),
DbPass: os.Getenv("DB_PASS"),
DbData: os.Getenv("DB_DATABASE"),
DbPort: port,
Project: os.Getenv("NAME"),
Description: os.Getenv("DESCRIPTION"),
Email: "",
Username: "admin",
Password: "",
}
}
ExecuteResponse(w, r, "setup.html", data)
2018-06-10 01:31:13 +00:00
}
type index struct {
2018-06-19 04:48:25 +00:00
Core Core
2018-06-10 04:09:20 +00:00
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-19 04:48:25 +00:00
out := index{*core, services}
ExecuteResponse(w, r, "index.html", 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-24 00:13:37 +00:00
err := ErrorResponse{}
ExecuteResponse(w, r, "login.html", err)
2018-06-10 03:44:47 +00:00
} else {
2018-06-15 04:30:10 +00:00
fails, _ := CountFailures()
out := dashboard{services, core, CountOnline(), len(services), fails}
2018-06-19 04:48:25 +00:00
ExecuteResponse(w, r, "dashboard.html", 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-19 04:48:25 +00:00
auth := IsAuthenticated(r)
if !auth {
2018-06-10 01:31:13 +00:00
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
2018-06-19 04:48:25 +00:00
ExecuteResponse(w, r, "services.html", services)
2018-06-11 03:41:02 +00:00
}
func ServicesDeleteHandler(w http.ResponseWriter, r *http.Request) {
2018-06-19 04:48:25 +00:00
auth := IsAuthenticated(r)
if !auth {
2018-06-11 03:41:02 +00:00
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
vars := mux.Vars(r)
2018-06-23 00:10:37 +00:00
service := SelectService(StringInt(vars["id"]))
2018-06-11 03:41:02 +00:00
service.Delete()
http.Redirect(w, r, "/services", http.StatusSeeOther)
}
2018-06-19 04:48:25 +00:00
func ServicesDeleteFailuresHandler(w http.ResponseWriter, r *http.Request) {
auth := IsAuthenticated(r)
if !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
vars := mux.Vars(r)
2018-06-23 00:10:37 +00:00
service := SelectService(StringInt(vars["id"]))
2018-06-19 04:48:25 +00:00
service.DeleteFailures()
services, _ = SelectAllServices()
http.Redirect(w, r, "/services", http.StatusSeeOther)
}
2018-06-11 03:41:02 +00:00
func IsAuthenticated(r *http.Request) bool {
2018-06-19 04:48:25 +00:00
if store == nil {
return false
}
session, err := store.Get(r, cookieKey)
if err != nil {
return false
}
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-23 04:17:57 +00:00
func SaveEmailSettingsHandler(w http.ResponseWriter, r *http.Request) {
auth := IsAuthenticated(r)
if !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
emailer := SelectCommunication(1)
r.ParseForm()
emailer.Host = r.PostForm.Get("host")
emailer.Username = r.PostForm.Get("username")
emailer.Password = r.PostForm.Get("password")
emailer.Port = int(StringInt(r.PostForm.Get("port")))
emailer.Var1 = r.PostForm.Get("address")
Update(emailer)
sample := &types.Email{
2018-06-23 08:42:50 +00:00
To: SessionUser(r).Email,
2018-06-23 04:17:57 +00:00
Subject: "Sample Email",
2018-06-23 08:42:50 +00:00
Template: "error.html",
2018-06-23 04:17:57 +00:00
}
2018-06-23 08:42:50 +00:00
AddEmail(sample)
2018-06-23 04:17:57 +00:00
http.Redirect(w, r, "/settings", http.StatusSeeOther)
}
2018-06-19 00:01:03 +00:00
func SaveSettingsHandler(w http.ResponseWriter, r *http.Request) {
auth := IsAuthenticated(r)
if !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
r.ParseForm()
2018-06-19 04:48:25 +00:00
name := r.PostForm.Get("project")
if name != "" {
core.Name = name
}
2018-06-19 00:01:03 +00:00
description := r.PostForm.Get("description")
2018-06-19 04:48:25 +00:00
if description != core.Description {
core.Description = description
}
style := r.PostForm.Get("style")
if style != core.Style {
core.Style = style
}
footer := r.PostForm.Get("footer")
if footer != core.Footer {
core.Footer = footer
}
2018-06-19 00:01:03 +00:00
core.Update()
2018-06-19 04:48:25 +00:00
OnSettingsSaved(core)
2018-06-19 00:01:03 +00:00
http.Redirect(w, r, "/settings", http.StatusSeeOther)
}
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
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 {
2018-06-19 04:48:25 +00:00
fields := structs.Map(p.GetInfo())
2018-06-14 01:19:00 +00:00
2018-06-22 04:02:57 +00:00
pluginFields = append(pluginFields, PluginSelect{p.GetInfo().Name, p.GetForm(), fields})
2018-06-14 01:19:00 +00:00
}
2018-06-14 06:38:15 +00:00
core.PluginFields = pluginFields
2018-06-23 04:17:57 +00:00
fmt.Println(core.Communications)
2018-06-19 04:48:25 +00:00
ExecuteResponse(w, r, "plugins.html", core)
2018-06-11 03:41:02 +00:00
}
2018-06-14 06:38:15 +00:00
type PluginSelect struct {
Plugin string
2018-06-22 04:02:57 +00:00
Form string
2018-06-19 04:48:25 +00:00
Params map[string]interface{}
2018-06-14 06:38:15 +00:00
}
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-19 04:48:25 +00:00
plug.OnSave(structs.Map(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
}
2018-06-19 04:48:25 +00:00
ExecuteResponse(w, r, "help.html", nil)
2018-06-11 03:41:02 +00:00
}
2018-06-22 06:56:44 +00:00
func CheckinCreateUpdateHandler(w http.ResponseWriter, r *http.Request) {
auth := IsAuthenticated(r)
if !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
vars := mux.Vars(r)
interval := StringInt(r.PostForm.Get("interval"))
2018-06-23 00:10:37 +00:00
service := SelectService(StringInt(vars["id"]))
2018-06-22 06:56:44 +00:00
checkin := &Checkin{
Service: service.Id,
Interval: interval,
Api: NewSHA1Hash(18),
}
checkin.Create()
fmt.Println(checkin.Create())
ExecuteResponse(w, r, "service.html", service)
}
2018-06-11 03:41:02 +00:00
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)
2018-06-23 00:10:37 +00:00
service := SelectService(StringInt(vars["id"]))
2018-06-15 04:30:10 +00:00
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) {
vars := mux.Vars(r)
2018-06-23 00:10:37 +00:00
service := SelectService(StringInt(vars["id"]))
2018-06-19 04:48:25 +00:00
ExecuteResponse(w, r, "service.html", service)
2018-06-11 03:41:02 +00:00
}
2018-06-19 04:48:25 +00:00
func ExecuteResponse(w http.ResponseWriter, r *http.Request, file string, data interface{}) {
2018-06-11 03:41:02 +00:00
nav, _ := tmplBox.String("nav.html")
2018-06-22 04:02:57 +00:00
footer, _ := tmplBox.String("footer.html")
2018-06-11 03:41:02 +00:00
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-19 04:48:25 +00:00
"Auth": func() bool {
return IsAuthenticated(r)
2018-06-11 03:41:02 +00:00
},
2018-06-19 04:48:25 +00:00
"VERSION": func() string {
return VERSION
2018-06-11 09:58:41 +00:00
},
2018-06-19 06:00:56 +00:00
"underscore": func(html string) string {
return UnderScoreString(html)
},
2018-06-23 08:42:50 +00:00
"User": func() *User {
return SessionUser(r)
},
2018-06-11 03:41:02 +00:00
})
t, _ = t.Parse(nav)
2018-06-22 04:02:57 +00:00
t, _ = t.Parse(footer)
2018-06-11 03:41:02 +00:00
t.Parse(render)
2018-06-19 04:48:25 +00:00
t.Execute(w, data)
2018-06-10 01:31:13 +00:00
}
func UsersHandler(w http.ResponseWriter, r *http.Request) {
2018-06-19 04:48:25 +00:00
auth := IsAuthenticated(r)
if !auth {
2018-06-10 01:31:13 +00:00
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
2018-06-15 04:30:10 +00:00
users, _ := SelectAllUsers()
2018-06-19 04:48:25 +00:00
ExecuteResponse(w, r, "users.html", users)
}
func UsersDeleteHandler(w http.ResponseWriter, r *http.Request) {
auth := IsAuthenticated(r)
if !auth {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
vars := mux.Vars(r)
id, _ := strconv.Atoi(vars["id"])
user, _ := SelectUser(int64(id))
users, _ := SelectAllUsers()
if len(users) == 1 {
http.Redirect(w, r, "/users", http.StatusSeeOther)
return
}
user.Delete()
http.Redirect(w, r, "/users", http.StatusSeeOther)
2018-06-10 01:31:13 +00:00
}
2018-06-19 06:00:56 +00:00
func UnderScoreString(str string) string {
// convert every letter to lower case
newStr := strings.ToLower(str)
// convert all spaces/tab to underscore
regExp := regexp.MustCompile("[[:space:][:blank:]]")
newStrByte := regExp.ReplaceAll([]byte(newStr), []byte("_"))
regExp = regexp.MustCompile("`[^a-z0-9]`i")
newStrByte = regExp.ReplaceAll(newStrByte, []byte("_"))
regExp = regexp.MustCompile("[!/']")
newStrByte = regExp.ReplaceAll(newStrByte, []byte("_"))
// and remove underscore from beginning and ending
newStr = strings.TrimPrefix(string(newStrByte), "_")
newStr = strings.TrimSuffix(newStr, "_")
return newStr
2018-06-22 04:02:57 +00:00
}