84 lines
2.2 KiB
Go
84 lines
2.2 KiB
Go
|
package ui
|
||
|
|
||
|
import (
|
||
|
"html/template"
|
||
|
"log"
|
||
|
"net/http"
|
||
|
|
||
|
"streifling.com/jason/cpolis/cmd/data"
|
||
|
)
|
||
|
|
||
|
func HomePage(db *data.DB, s *data.CookieStore) http.HandlerFunc {
|
||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||
|
numRows, err := db.CountEntries()
|
||
|
if err != nil {
|
||
|
log.Fatalln(err)
|
||
|
}
|
||
|
|
||
|
files := []string{"web/templates/index.html"}
|
||
|
if numRows == 0 {
|
||
|
files = append(files, "web/templates/add-user.html")
|
||
|
tmpl, err := template.ParseFiles(files...)
|
||
|
template.Must(tmpl, err).Execute(w, nil)
|
||
|
} else {
|
||
|
session, _ := s.Get(r, "cookie")
|
||
|
if auth, ok := session.Values["authenticated"].(bool); auth && ok {
|
||
|
files = append(files, "web/templates/hub.html")
|
||
|
tmpl, err := template.ParseFiles(files...)
|
||
|
template.Must(tmpl, err).Execute(w, session.Values["role"])
|
||
|
} else {
|
||
|
files = append(files, "web/templates/login.html")
|
||
|
tmpl, err := template.ParseFiles(files...)
|
||
|
template.Must(tmpl, err).Execute(w, nil)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func Login(db *data.DB, s *data.CookieStore) http.HandlerFunc {
|
||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||
|
userName := r.PostFormValue("username")
|
||
|
password := r.PostFormValue("password")
|
||
|
|
||
|
id, err := db.GetID(userName)
|
||
|
if err != nil {
|
||
|
log.Println(err)
|
||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
if err := db.CheckPassword(id, password); err != nil {
|
||
|
log.Println(err)
|
||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
user, err := db.GetUser(id)
|
||
|
if err != nil {
|
||
|
log.Println(err)
|
||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
session, err := s.Get(r, "cookie")
|
||
|
if err != nil {
|
||
|
log.Println(err)
|
||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
session.Values["authenticated"] = true
|
||
|
session.Values["id"] = user.ID
|
||
|
session.Values["name"] = user.FirstName + user.LastName
|
||
|
session.Values["role"] = user.Role
|
||
|
if err := session.Save(r, w); err != nil {
|
||
|
log.Println(err)
|
||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
tmpl, err := template.ParseFiles("web/templates/hub.html")
|
||
|
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", user.Role)
|
||
|
}
|
||
|
}
|