allowances/handlers.go

61 lines
1.5 KiB
Go
Raw Normal View History

package main
import (
2013-03-08 22:28:24 -08:00
"encoding/json"
"log"
"net/http"
2013-03-08 22:28:24 -08:00
"strconv"
"strings"
)
2013-02-21 00:19:38 -08:00
func homeHandler(w http.ResponseWriter, req *http.Request) {
session, _ := store.Get(req, "creds")
loggedIn := session.Values["logged in"]
if loggedIn == nil {
http.Redirect(w, req, "/login", http.StatusSeeOther)
2013-03-06 12:31:30 -08:00
return
2013-02-21 00:19:38 -08:00
}
2013-03-06 12:31:30 -08:00
children := loadChildren(*db_file)
2013-03-04 21:56:39 -08:00
T("index.html").Execute(w, map[string]interface{}{
2013-03-06 12:31:30 -08:00
"children": children})
}
2013-02-21 00:19:38 -08:00
func loginHandler(w http.ResponseWriter, req *http.Request) {
pwAttempt := req.FormValue("passwd")
2013-02-26 22:30:23 -08:00
if check_password(*passes_file, pwAttempt) {
session, _ := store.Get(req, "creds")
session.Values["logged in"] = true
session.Save(req, w)
2013-02-21 00:36:32 -08:00
http.Redirect(w, req, "/", http.StatusSeeOther)
2013-02-26 22:30:23 -08:00
return
}
2013-02-21 00:19:38 -08:00
T("login.html").Execute(w, map[string]interface{}{})
}
2013-02-26 22:39:26 -08:00
func logoutHandler(w http.ResponseWriter, req *http.Request) {
2013-02-26 23:19:21 -08:00
session, _ := store.Get(req, "creds")
delete(session.Values, "logged in")
session.Save(req, w)
http.Redirect(w, req, "/", http.StatusSeeOther)
return
2013-02-26 22:39:26 -08:00
}
2013-03-08 22:28:24 -08:00
func addHandler(w http.ResponseWriter, req *http.Request) {
path := req.URL.Path[len(addPath):]
bits := strings.Split(path, "/")
child := bits[0]
amount, err := strconv.Atoi(bits[1])
if err != nil {
log.Fatal("couldn't parse a dollar amount", err)
}
children := loadChildren(*db_file)
children[child] += amount
defer dumpChildren(*db_file, children)
w.Header().Set("Content-Type", "application/json")
b, err := json.Marshal(map[string]interface{}{
"amount": dollarize(children[child]),
"name": child,
})
w.Write(b)
}