cacert-boardvoting/cmd/boardvoting/helpers.go
Jan Dittberner 335ce16547 Add tests for handlers and middleware
- drop migration 2022052601_drop_unused_decisions_colums because it was implicitly part of an earlier migration
- add /health endpoint for database health check
- add tests for the health check endpoint
- add tests for middleware secureHeaders, logRequest and tryAuthenticate
- add models.UserModel.CreateUser method
2022-05-26 19:22:56 +02:00

169 lines
4.1 KiB
Go

/*
Copyright 2017-2022 CAcert Inc.
SPDX-License-Identifier: Apache-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"errors"
"fmt"
"html/template"
"io/fs"
"net/http"
"path/filepath"
"runtime/debug"
"strings"
"github.com/Masterminds/sprig/v3"
"github.com/go-playground/form/v4"
"github.com/justinas/nosurf"
"git.cacert.org/cacert-boardvoting/internal/models"
"git.cacert.org/cacert-boardvoting/ui"
)
func (app *application) serverError(w http.ResponseWriter, err error) {
trace := fmt.Sprintf("%s\n%s", err.Error(), debug.Stack())
_ = app.errorLog.Output(2, trace)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
func (app *application) clientError(w http.ResponseWriter, status int) {
http.Error(w, http.StatusText(status), status)
}
func (app *application) notFound(w http.ResponseWriter) {
app.clientError(w, http.StatusNotFound)
}
func (app *application) decodePostForm(r *http.Request, dst any) error {
err := r.ParseForm()
if err != nil {
return fmt.Errorf("could not parse HTML form: %w", err)
}
err = app.formDecoder.Decode(dst, r.PostForm)
if err != nil {
var invalidDecoderError *form.InvalidDecoderError
if errors.As(err, &invalidDecoderError) {
panic(err)
}
return fmt.Errorf("could not decode form: %w", err)
}
return nil
}
func newTemplateCache() (map[string]*template.Template, error) {
cache := map[string]*template.Template{}
pages, err := fs.Glob(ui.Files, "html/pages/*.html")
if err != nil {
return nil, fmt.Errorf("could not find page templates: %w", err)
}
funcMaps := sprig.FuncMap()
funcMaps["nl2br"] = func(text string) template.HTML {
// #nosec G203 input is sanitized
return template.HTML(strings.ReplaceAll(template.HTMLEscapeString(text), "\n", "<br>"))
}
funcMaps["canManageUsers"] = func(v *models.User) (bool, error) {
return checkRole(v, []string{models.RoleSecretary, models.RoleAdmin})
}
funcMaps["canVote"] = func(v *models.User) (bool, error) {
return checkRole(v, []string{models.RoleVoter})
}
funcMaps["canStartVote"] = func(v *models.User) (bool, error) {
return checkRole(v, []string{models.RoleVoter})
}
for _, page := range pages {
name := filepath.Base(page)
ts, err := template.New("").Funcs(funcMaps).ParseFS(
ui.Files,
"html/base.html",
"html/partials/*.html",
page,
)
if err != nil {
return nil, fmt.Errorf("could not parse base template: %w", err)
}
cache[name] = ts
}
return cache, nil
}
type templateData struct {
PrevPage string
NextPage string
Motion *models.MotionForDisplay
Motions []*models.MotionForDisplay
User *models.User
Users []*models.User
Request *http.Request
Flash string
Form any
ActiveNav topLevelNavItem
ActiveSubNav subLevelNavItem
CSRFToken string
}
func (app *application) newTemplateData(
r *http.Request,
nav topLevelNavItem,
subNav subLevelNavItem,
) *templateData {
user, _ := app.GetUser(r)
return &templateData{
Request: r,
User: user,
ActiveNav: nav,
ActiveSubNav: subNav,
Flash: app.sessionManager.PopString(r.Context(), "flash"),
CSRFToken: nosurf.Token(r),
}
}
func (app *application) render(w http.ResponseWriter, status int, page string, data *templateData) {
ts, ok := app.templateCache[page]
if !ok {
app.serverError(w, fmt.Errorf("the template %s does not exist", page))
return
}
buf := new(bytes.Buffer)
err := ts.ExecuteTemplate(buf, "base", data)
if err != nil {
app.serverError(w, err)
return
}
w.WriteHeader(status)
_, _ = buf.WriteTo(w)
}