polycule-connect/polyculeconnect/controller/ui/static.go
Melora Hugues ce8bd4ee7c
Some checks failed
ci/woodpecker/push/test Pipeline failed
ci/woodpecker/push/deploy unknown status
feat: start replacing dex with zitadel (#48)
Start the process of replacing dex with zitadel, this commit is
absolutely not prod-ready, basically we just added zitatel, and the
necessary elements to make it work to at least getting a client from the
DB

- replace logrus with zap
- start our own storage for the users
- instanciate zitaled on start
- allow getting client using the ID from the DB
2024-08-15 18:25:15 +02:00

82 lines
2.2 KiB
Go

package ui
import (
"bytes"
"fmt"
"html/template"
"io"
"net/http"
"path/filepath"
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/helpers"
"go.uber.org/zap"
)
const StaticRoute = "/static/"
type StaticController struct {
baseDir string
}
func NewStaticController(baseDir string) *StaticController {
return &StaticController{
baseDir: baseDir,
}
}
func (sc *StaticController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fs := http.FileServer(http.Dir(sc.baseDir + "/static"))
http.StripPrefix(StaticRoute, fs).ServeHTTP(w, r)
}
type IndexController struct {
l *zap.SugaredLogger
downstreamConstroller http.Handler
baseDir string
}
func NewIndexController(l *zap.SugaredLogger, downstream http.Handler, baseDir string) *IndexController {
return &IndexController{
l: l,
downstreamConstroller: downstream,
baseDir: baseDir,
}
}
func (ic IndexController) serveUI(w http.ResponseWriter, r *http.Request) (int, int, error) {
funcs := template.FuncMap{
"issuer": func() string { return "toto" },
}
lp := filepath.Join(ic.baseDir, "templates", "index.html")
hdrTpl := filepath.Join(ic.baseDir, "templates", "header.html")
footTpl := filepath.Join(ic.baseDir, "templates", "footer.html")
tmpl, err := template.New("index.html").Funcs(funcs).ParseFiles(hdrTpl, footTpl, lp)
if err != nil {
return http.StatusInternalServerError, -1, fmt.Errorf("failed to init template: %w", err)
}
buf := new(bytes.Buffer)
if err := tmpl.Execute(buf, nil); err != nil {
return http.StatusInternalServerError, -1, fmt.Errorf("failed to execute template: %w", err)
}
n, err := io.Copy(w, buf)
if err != nil {
return http.StatusInternalServerError, int(n), fmt.Errorf("failed to write response; %w", err)
}
return http.StatusOK, int(n), nil
}
func (ic *IndexController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.RequestURI != "/" {
ic.l.Debugf("Serving URI %q to dex handler", r.RequestURI)
ic.downstreamConstroller.ServeHTTP(w, r)
return
}
returncode, _, err := ic.serveUI(w, r)
if err != nil {
ic.l.Errorf("Error serving UI: %s", err.Error())
helpers.HandleResponse(w, r, returncode, nil, ic.l)
}
}