package main
import (
"html/template"
"net/http"
)
func showRegisterForm(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("tmpl/register.html")
if err != nil {
panic(err)
}
t.Execute(w, nil)
}
func showLoginForm(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("tmpl/login.html")
if err != nil {
panic(err)
}
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)
})
}