authelia/internal/server/index.go
Amir Zarrinkafsh f8bd506326
[FEATURE] Embed static assets in Go binary (#916)
* [FEATURE] Embed static assets in Go binary

* Refactor/consolidate code and specify public_html via configuration

* Update docs and config template for assets

* Update AUR package pre-requisites and systemd unit

* Include static assets as Buildkite and GitHub artifacts

* Remove references to PUBLIC_DIR

* Only serve assets via embedded filesystem and remove configuration references

* Update authelia-scripts helper to build the embedded filesystem

* Mock the embedded filesystem for unit tests
Add to gitignore to ensure this isn't overwritten.

* Move go:generate to satisfy linter
2020-04-29 00:07:20 +10:00

47 lines
1.4 KiB
Go

package server
import (
"fmt"
"html/template"
"io/ioutil"
"github.com/valyala/fasthttp"
"github.com/authelia/authelia/internal/logging"
"github.com/authelia/authelia/internal/utils"
)
var alphaNumericRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
// ServeIndex serve the index.html file with nonce generated for supporting
// restrictive CSP while using material-ui from the embedded virtual filesystem.
//go:generate broccoli -src ../../public_html -o public_html
func ServeIndex(publicDir string) fasthttp.RequestHandler {
f, err := br.Open(publicDir + "/index.html")
if err != nil {
logging.Logger().Fatalf("Unable to open index.html: %v", err)
}
b, err := ioutil.ReadAll(f)
if err != nil {
logging.Logger().Fatalf("Unable to read index.html: %v", err)
}
tmpl, err := template.New("index").Parse(string(b))
if err != nil {
logging.Logger().Fatalf("Unable to parse index.html template: %v", err)
}
return func(ctx *fasthttp.RequestCtx) {
nonce := utils.RandomString(32, alphaNumericRunes)
ctx.SetContentType("text/html; charset=utf-8")
ctx.Response.Header.Add("Content-Security-Policy", fmt.Sprintf("default-src 'self'; style-src 'self' 'nonce-%s'", nonce))
err := tmpl.Execute(ctx.Response.BodyWriter(), struct{ CSPNonce string }{CSPNonce: nonce})
if err != nil {
ctx.Error("An error occurred", 503)
logging.Logger().Errorf("Unable to execute template: %v", err)
return
}
}
}