wasmcloud/cmd/wasmcloudd/html.go

81 lines
1.6 KiB
Go
Raw Normal View History

2019-11-19 17:07:56 +00:00
package main
import (
2019-11-19 17:25:17 +00:00
"html/template"
2019-11-19 17:07:56 +00:00
"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)
}
2019-11-19 17:25:17 +00:00
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)
})
}