Nuestro burocrata preferido: Sam Lowry https://lowry.sindominio.net
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

106 lines
2.5 KiB

package server
import (
"html/template"
"net/http"
"0xacab.org/sindominio/lowry/ldap"
"github.com/gorilla/mux"
)
var tmpl = template.Must(template.ParseFiles(
"tmpl/header.html",
"tmpl/footer.html",
"tmpl/navbar.html",
"tmpl/login.html",
"tmpl/index.html",
"tmpl/password.html",
))
type server struct {
ldap *ldap.Ldap
sess *sessionStore
}
// Serve lowry web site
func Serve(addr string, l *ldap.Ldap) error {
var s server
s.ldap = l
s.sess = initSessionStore()
r := mux.NewRouter()
r.HandleFunc("/", s.homeHandler)
r.HandleFunc("/login/", s.loginHandler)
r.HandleFunc("/logout/", s.logoutHandler).Methods("POST")
r.HandleFunc("/password/", s.passwordHandler)
r.HandleFunc("/bundle.js", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "dist/bundle.js") })
r.HandleFunc("/style.css", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "dist/style.css") })
r.Handle("/img/{img}", http.StripPrefix("/img/", http.FileServer(http.Dir("img"))))
return http.ListenAndServe(addr, r)
}
func (s *server) homeHandler(w http.ResponseWriter, r *http.Request) {
session := s.sess.get(w, r)
if session == nil {
tmpl.ExecuteTemplate(w, "login.html", false)
} else {
data := struct {
User string
Admin bool
}{session.user, s.isAdmin(session.user)}
tmpl.ExecuteTemplate(w, "index.html", data)
}
}
func (s *server) loginHandler(w http.ResponseWriter, r *http.Request) {
user := r.FormValue("user")
pass := r.FormValue("password")
err := s.ldap.ValidateUser(user, pass)
if err != nil {
tmpl.ExecuteTemplate(w, "login.html", true)
return
}
s.sess.set(user, w, r)
http.Redirect(w, r, "/", http.StatusFound)
}
func (s *server) logoutHandler(w http.ResponseWriter, r *http.Request) {
s.sess.del(w, r)
http.Redirect(w, r, "/", http.StatusFound)
}
func (s *server) passwordHandler(w http.ResponseWriter, r *http.Request) {
session := s.sess.get(w, r)
if session == nil {
http.Redirect(w, r, "/", http.StatusFound)
return
}
if r.Method != "POST" {
tmpl.ExecuteTemplate(w, "password.html", "")
return
}
oldpass := r.FormValue("oldpass")
pass := r.FormValue("password")
pass2 := r.FormValue("password2")
if pass != pass2 {
tmpl.ExecuteTemplate(w, "password.html", "WrongPass")
return
}
err := s.ldap.ChangePass(session.user, oldpass, pass)
if err != nil {
tmpl.ExecuteTemplate(w, "password.html", "WrongOldpass")
} else {
tmpl.ExecuteTemplate(w, "password.html", "PassChanged")
}
}
func (s *server) isAdmin(user string) bool {
return s.ldap.InGroup(user, "adm")
}