add frontend auth middleware, embed user data in frontend html

This commit is contained in:
sam 2023-09-04 17:32:45 +02:00
parent d8cb8c8fa8
commit 0fa769a248
Signed by: sam
GPG key ID: B4EF20DDE721CAA1
12 changed files with 265 additions and 42 deletions

View file

@ -2,6 +2,7 @@ package frontend
import (
"embed"
"encoding/json"
"html/template"
"net/http"
"os"
@ -9,6 +10,7 @@ import (
"git.sleepycat.moe/sam/mercury/frontend"
"git.sleepycat.moe/sam/mercury/internal/database"
"git.sleepycat.moe/sam/mercury/web/api"
"git.sleepycat.moe/sam/mercury/web/app"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog/log"
@ -89,10 +91,65 @@ func (app *Frontend) ServeAssets(w http.ResponseWriter, r *http.Request) {
}
func (app *Frontend) ServeFrontend(w http.ResponseWriter, r *http.Request) {
_, ok := app.TokenFromContext(r.Context())
if !ok {
http.Redirect(w, r, "/auth/login", http.StatusSeeOther)
return
}
app.serveFrontend(w, r)
}
func (app *Frontend) ServeUser(w http.ResponseWriter, r *http.Request) {
_, ok := app.TokenFromContext(r.Context())
if !ok {
username := chi.URLParam(r, "username")
http.Redirect(w, r, "/@"+username, http.StatusSeeOther)
return
}
app.serveFrontend(w, r)
}
func (app *Frontend) ServeStatus(w http.ResponseWriter, r *http.Request) {
_, ok := app.TokenFromContext(r.Context())
if !ok {
username := chi.URLParam(r, "username")
postID := chi.URLParam(r, "postID")
http.Redirect(w, r, "/@"+username+"/posts/"+postID, http.StatusSeeOther)
return
}
app.serveFrontend(w, r)
}
func (app *Frontend) serveFrontend(w http.ResponseWriter, r *http.Request) {
token, ok := app.TokenFromContext(r.Context())
if !ok {
log.Error().Msg("app.serveFrontend was called without a token being set")
http.Redirect(w, r, "/auth/login", http.StatusSeeOther)
return
}
acct, err := app.Account().ByID(r.Context(), token.UserID)
if err != nil {
log.Err(err).Msg("fetching account")
app.ErrorTemplate(w, r, "Internal server error", "An internal server error occurred. Please try again later.")
return
}
b, err := json.Marshal(api.DBAccountToSelfAccount(acct))
if err != nil {
log.Err(err).Msg("marshaling account json")
app.ErrorTemplate(w, r, "Internal server error", "An internal server error occurred. Please try again later.")
return
}
w.Header().Set("Content-Type", "text/html")
err := app.tmpl.Execute(w, map[string]any{
"Config": database.DefaultConfig,
"Vue": app.glue,
err = app.tmpl.Execute(w, map[string]any{
"Config": database.DefaultConfig,
"Vue": app.glue,
"AccountData": template.HTML(b),
})
if err != nil {
log.Err(err).Msg("executing frontend template")