114 lines
2.9 KiB
Go
Raw Normal View History

2018-01-26 12:38:19 +01:00
package app
import (
"fmt"
"log"
"path"
"strings"
"html/template"
"regexp"
"net/http"
)
type route struct {
pattern *regexp.Regexp
verb string
handler http.Handler
}
type RegexpHandler struct {
routes []*route
}
func (h *RegexpHandler) Handler(pattern *regexp.Regexp, verb string, handler http.Handler) {
h.routes = append(h.routes, &route{pattern, verb, handler})
}
func (h *RegexpHandler) HandleFunc(r string, v string, handler func(http.ResponseWriter, *http.Request)) {
re := regexp.MustCompile(r)
h.routes = append(h.routes, &route{re, v, http.HandlerFunc(handler)})
}
func (h *RegexpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for _, route := range h.routes {
if route.pattern.MatchString(r.URL.Path) && route.verb == r.Method {
route.handler.ServeHTTP(w, r)
return
}
}
http.NotFound(w, r)
}
type pageData struct {
Title string
Username string
Alerts map[string]string
}
// ServeAssets : Serves the static assets
func ServeAssets(w http.ResponseWriter, req *http.Request) {
http.ServeFile(w, req, path.Join("static", req.URL.Path[1:]))
}
// ServeIndex : Serves index page on GET request
func ServeIndex(w http.ResponseWriter, req *http.Request) {
p := &pageData{Title: getTitle()}
t, e := template.ParseFiles(path.Join("templates", "index.html"))
if e != nil {
log.Printf("Error parsing file %v\n", e)
} else {
t.Execute(w, p)
}
}
// ChangePassword : Serves index page on POST request - executes the change
func ChangePassword(w http.ResponseWriter, req *http.Request) {
req.ParseForm()
un := ""
username := req.Form["username"]
oldPassword := req.Form["old-password"]
newPassword := req.Form["new-password"]
confirmPassword := req.Form["confirm-password"]
alerts := map[string]string{}
if len(username) < 1 || username[0] == "" {
alerts["error"] = "Username not specified.<br/>"
} else {
un = username[0]
}
if len(oldPassword) < 1 || oldPassword[0] == "" {
alerts["error"] = alerts["error"] + "Old password not specified.<br/>"
}
if len(newPassword) < 1 || newPassword[0] == "" {
alerts["error"] = alerts["error"] + "New password not specified.<br/>"
}
if len(confirmPassword) < 1 || confirmPassword[0] == "" {
alerts["error"] = alerts["error"] + "Confirmation password not specified.<br/>"
}
if len(confirmPassword) >= 1 && len(newPassword) >= 1 && strings.Compare(newPassword[0], confirmPassword[0]) != 0 {
alerts["error"] = alerts["error"] + "New and confirmation passwords does not match.<br/>"
}
if len(alerts) == 0 {
client := NewLDAPClient()
if err := client.ModifyPassword(un, oldPassword[0], newPassword[0]); err != nil {
alerts["error"] = fmt.Sprintf("%v", err)
} else {
alerts["success"] = "Password successfuly changed"
}
}
p := &pageData{Title: getTitle(), Alerts: alerts, Username: un}
t, e := template.ParseFiles(path.Join("templates", "index.html"))
if e != nil {
log.Printf("Error parsing file %v\n", e)
} else {
t.Execute(w, p)
}
}