From ed7eab99f8a1f793c28a5c30918095390f1d3449 Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Tue, 19 Nov 2019 17:25:17 +0000 Subject: [PATCH] show pages --- html.go | 58 +++++++++++++++++++++++++++++++++++++++++- main.go | 4 +++ tmpl/base.html | 2 +- tmpl/controlindex.html | 2 ++ 4 files changed, 64 insertions(+), 2 deletions(-) diff --git a/html.go b/html.go index 7ee1951..6cdcf52 100644 --- a/html.go +++ b/html.go @@ -1,8 +1,8 @@ package main import ( + "html/template" "net/http" - "text/template" ) func showRegisterForm(w http.ResponseWriter, r *http.Request) { @@ -22,3 +22,59 @@ func showLoginForm(w http.ResponseWriter, r *http.Request) { t.Execute(w, nil) } + +func showPage(w http.ResponseWriter, tmpl string, loggedIn bool, data interface{}) error { + t, err := template.ParseFiles("tmpl/base.html", "tmpl/"+tmpl+".html") + if err != nil { + return err + } + + _ = t.Execute(w, struct { + LoggedIn bool + Data interface{} + }{ + LoggedIn: loggedIn, + Data: data, + }) + + return nil +} + +type wasmcloudHandler func(http.ResponseWriter, *http.Request, *User) + +func makeHandler(wantAuth bool, fn wasmcloudHandler) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + cookie, err := r.Cookie("wasmcloud-token") + if err != nil { + if wantAuth { + http.Redirect(w, r, "/login", http.StatusSeeOther) + return + } + + fn(w, r, nil) + return + } + + u, _, err := getUserAndToken(cookie.Value) + if err != nil { + http.Redirect(w, r, "/login", http.StatusSeeOther) + return + } + + fn(w, r, &u) + } +} + +func authenticatedShowAPage(name string) http.HandlerFunc { + return makeHandler(true, func(w http.ResponseWriter, r *http.Request, u *User) { + showPage(w, name, true, u) + }) +} + +func unauthenticatedShowAPage(name string) http.HandlerFunc { + return makeHandler(false, func(w http.ResponseWriter, r *http.Request, u *User) { + loggedIn := u != nil + + showPage(w, name, loggedIn, u) + }) +} diff --git a/main.go b/main.go index 159fec0..2d7abaa 100644 --- a/main.go +++ b/main.go @@ -43,6 +43,10 @@ func main() { rtr.HandleFunc("/login", loginUser).Methods("POST") rtr.HandleFunc("/logout", logoutUser) + // pages + rtr.HandleFunc("/", unauthenticatedShowAPage("index")) + rtr.HandleFunc("/control/", authenticatedShowAPage("controlindex")) + rtr.PathPrefix("/static/").Handler(http.FileServer(http.Dir("."))) log.Printf("listening on http://wasmcloud.kahless.cetacean.club:%s", *port) diff --git a/tmpl/base.html b/tmpl/base.html index 8ae3732..fe6fcf4 100644 --- a/tmpl/base.html +++ b/tmpl/base.html @@ -8,7 +8,7 @@
-

wasmcloud - Documentation - Support - {{ if .LoggedIn }} Control Panel {{ else }} Login {{ end }}

+

wasmcloud - Documentation - Support - {{ if .LoggedIn }} Control Panel {{ else }} Login {{ end }}

{{ template "content" . }}