handlers: clean up
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
leo 2023-04-19 04:45:49 +02:00
parent 773b10e60b
commit 608b0952b2
Signed by: wanderer
SSH Key Fingerprint: SHA256:Dp8+iwKHSlrMEHzE3bJnPng70I7LEsa3IJXRH/U+idQ

@ -3,7 +3,6 @@ package handlers
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"html/template" "html/template"
"io/fs" "io/fs"
"net/http" "net/http"
@ -38,8 +37,9 @@ func listAllTmpls() []string {
return files return files
} }
// TODO: mimic https://github.com/drone/funcmap/blob/master/funcmap.go
func setFuncMap(t *template.Template) { func setFuncMap(t *template.Template) {
t = t.Funcs(template.FuncMap{ t.Funcs(template.FuncMap{
"ifIE": func() template.HTML { return template.HTML("<!--[if IE]>") }, "ifIE": func() template.HTML { return template.HTML("<!--[if IE]>") },
"endifIE": func() template.HTML { return template.HTML("<![endif]>") }, "endifIE": func() template.HTML { return template.HTML("<![endif]>") },
"htmlSafe": func(html string) template.HTML { "htmlSafe": func(html string) template.HTML {
@ -51,30 +51,11 @@ func setFuncMap(t *template.Template) {
}) })
} }
func getFuncMap() []template.FuncMap {
return []template.FuncMap{
map[string]interface{}{
"ifIE": func() template.HTML { return template.HTML("<!--[if IE]>") },
"endifIE": func() template.HTML { return template.HTML("<![endif]>") },
"htmlSafe": func(html string) template.HTML {
return template.HTML(html)
},
"pageIs": func(want, got string) bool {
return want == got
},
},
}
}
func initTemplates(f fs.FS) { func initTemplates(f fs.FS) {
if f != nil || f != tmplFS { if f != nil || f != tmplFS {
tmplFS = f tmplFS = f
} }
// for _, funcs := range getFuncMap() {
// // log.Println(funcs)
// tmpls.Funcs(funcs)
// }
setFuncMap(tmpls) setFuncMap(tmpls)
allTmpls := listAllTmpls() allTmpls := listAllTmpls()
@ -86,7 +67,9 @@ func initTemplates(f fs.FS) {
func makeTplMap(tpl *template.Template) { func makeTplMap(tpl *template.Template) {
allTmpls := listAllTmpls() allTmpls := listAllTmpls()
var tp tplMap var tp tplMap
if templateMap == nil { if templateMap == nil {
tp = make(tplMap, len(allTmpls)) tp = make(tplMap, len(allTmpls))
} else { } else {
@ -105,9 +88,13 @@ func getTmpl(name string) *template.Template {
if liveMode { if liveMode {
log.Info("re-reading tmpls") log.Info("re-reading tmpls")
tpl := template.New("") tpl := template.New("")
setFuncMap(tpl) setFuncMap(tpl)
allTmpls := listAllTmpls() allTmpls := listAllTmpls()
// ensure this fails at compile time, if at all ("Must"). // ensure this fails at compile time, if at all ("Must").
tmpls = template.Must(tpl.ParseFS(tmplFS, allTmpls...)) tmpls = template.Must(tpl.ParseFS(tmplFS, allTmpls...))
} }
@ -123,19 +110,7 @@ func Admin() echo.HandlerFunc {
func Index() echo.HandlerFunc { func Index() echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {
// tpl, err := template.New("index").ParseFS(templates, "index.tmpl")
// tpl := template.New("index")
// tpl := theTmpls.New("index.tmpl")
// tpl := tmpls.Lookup("index.tmpl")
tpl := getTmpl("index.tmpl") tpl := getTmpl("index.tmpl")
// if conf.LiveMode {
// // reload tmpls.
// LoadTemplates(tmplFS)
// }
// tpl := templateMap["index.tmpl"]
csrf := c.Get("csrf").(string) csrf := c.Get("csrf").(string)
err := tpl.Execute(c.Response().Writer, err := tpl.Execute(c.Response().Writer,
@ -165,6 +140,7 @@ func Signin() echo.HandlerFunc {
log.Info("no session cookie found") log.Info("no session cookie found")
} }
} }
if session != nil { if session != nil {
log.Info("got session") log.Info("got session")
// if err := session.Valid(); err == nil && session.Expires.After(time.Now()) { // if err := session.Valid(); err == nil && session.Expires.After(time.Now()) {
@ -196,16 +172,15 @@ func Signin() echo.HandlerFunc {
func SigninPost(client *ent.Client) echo.HandlerFunc { func SigninPost(client *ent.Client) echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {
ct := c.Request().Header.Get("Content-Type")
fmt.Printf("signin(POST): content-type: %s\n", ct)
err := c.Request().ParseForm() err := c.Request().ParseForm()
if err != nil { if err != nil {
return err return err
} }
var username string var username string
var password string var password string
if uname := c.Request().FormValue("username"); uname != "" { if uname := c.Request().FormValue("username"); uname != "" {
username = uname username = uname
log.Infof("authenticating user '%s' at /signin", username) log.Infof("authenticating user '%s' at /signin", username)
@ -225,6 +200,7 @@ func SigninPost(client *ent.Client) echo.HandlerFunc {
ctx := context.WithValue(context.Background(), "logger", log) ctx := context.WithValue(context.Background(), "logger", log)
if usr, err := moduser.QueryUser(ctx, client, username); err == nil { if usr, err := moduser.QueryUser(ctx, client, username); err == nil {
log.Info("queried user:", &usr.ID) log.Info("queried user:", &usr.ID)
if usr.Password != password { if usr.Password != password {
log.Warn("wrong user credentials, redirecting to /signin") log.Warn("wrong user credentials, redirecting to /signin")
@ -262,19 +238,18 @@ func SigninPost(client *ent.Client) echo.HandlerFunc {
func Signup() echo.HandlerFunc { func Signup() echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {
session, err := c.Cookie("session") session, err := c.Cookie("session")
if err != nil { if err != nil && err == http.ErrNoCookie {
if err == http.ErrNoCookie { log.Info("no session cookie found")
log.Info("no session cookie found")
}
} }
if session != nil { if session != nil {
log.Info("got session") log.Info("got session")
// if err := session.Valid(); err == nil && session.Expires.After(time.Now()) { // if err := session.Valid(); err == nil && session.Expires.After(time.Now()) {
if err := session.Valid(); err == nil { if err := session.Valid(); err == nil {
return c.Redirect(302, "/home") return c.Redirect(302, "/home")
} else {
log.Warn("invalid (or expired) session", "error", err.Error())
} }
log.Warn("invalid (or expired) session", "error", err.Error())
} }
tpl := getTmpl("signup.tmpl") tpl := getTmpl("signup.tmpl")
@ -320,8 +295,10 @@ func SignupPost(client *ent.Client) echo.HandlerFunc {
} }
var username string var username string
if uname := c.Request().FormValue("username"); uname != "" { if uname := c.Request().FormValue("username"); uname != "" {
username = uname username = uname
if passwd := c.Request().FormValue("password"); passwd != "" { if passwd := c.Request().FormValue("password"); passwd != "" {
ctx := context.WithValue(context.Background(), "logger", log) ctx := context.WithValue(context.Background(), "logger", log)
@ -368,9 +345,9 @@ func Home() echo.HandlerFunc {
session, err := c.Cookie("session") session, err := c.Cookie("session")
if err != nil { if err != nil {
if err == http.ErrNoCookie { if err == http.ErrNoCookie {
// return err
log.Infof("error no cookie: %q", err) log.Infof("error no cookie: %q", err)
http.Error(c.Response().Writer, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) http.Error(c.Response().Writer, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return nil return nil
} }
@ -378,17 +355,18 @@ func Home() echo.HandlerFunc {
http.Error(c.Response().Writer, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) http.Error(c.Response().Writer, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return nil return nil
} }
if session != nil { if session != nil {
log.Info("got session") log.Info("got session")
// if err := session.Valid(); err == nil && session.Expires.After(time.Now()) {
if err := session.Valid(); err == nil { if err := session.Valid(); err != nil {
username = session.Value
} else {
log.Warn("invalid or expired session?") log.Warn("invalid or expired session?")
return echo.NewHTTPError(http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized)) return echo.NewHTTPError(http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
} }
username = session.Value
} }
// example denial. // example denial.
@ -408,8 +386,8 @@ func Home() echo.HandlerFunc {
}, },
) )
if err != nil { if err != nil {
// return err
log.Warnf("error: %q", err) log.Warnf("error: %q", err)
return echo.NewHTTPError(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)) return echo.NewHTTPError(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
} }
@ -429,6 +407,7 @@ func Logout() echo.HandlerFunc {
} }
log.Warnf("error: %q", err) log.Warnf("error: %q", err)
return nil return nil
} }
@ -464,6 +443,7 @@ func Logout() echo.HandlerFunc {
) )
if err != nil { if err != nil {
log.Warnf("error: %q", err) log.Warnf("error: %q", err)
return echo.NewHTTPError(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)) return echo.NewHTTPError(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
} }