authorization enforced on webpages

This commit is contained in:
2025-12-30 18:08:22 -07:00
parent c01d700482
commit 240d82344c
24 changed files with 509 additions and 123 deletions
+99 -44
View File
@@ -1,38 +1,28 @@
package site
import (
"bytes"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"ruben/inventory2/internal/site/response"
"strings"
"ruben/inventory2/internal/domains/accounts"
)
// GET /
func (s *Server) serveTemplates(w http.ResponseWriter, r *http.Request) {
func (s *Server) serveTemplates(r *http.Request) (response.Response, error) {
ctx := r.Context()
name, pathParams := getPageTemplateNameForURL(r.URL)
var (
acct accounts.Account
userID string
)
claims, ok := s.getAccessTokenClaims(r)
if ok {
userID = claims.Subject
acct, _ = s.accts.GetAccountByUserID(ctx, userID)
}
b, err := s.templater.ExecutePage(
name,
templateArgs := []any{
"Request",
r,
// add services here
// add services and data here
"RawEvents",
s.rawEvents.WithContext(ctx),
"URLCalc",
@@ -44,37 +34,26 @@ func (s *Server) serveTemplates(w http.ResponseWriter, r *http.Request) {
"Etsy",
s.etsy.WithContext(ctx),
// claims
"Claims",
claims,
"UserID",
userID,
"Account",
acct,
)
if err != nil {
// TODO: handle 401
// TODO: handle 403
// TODO: handle 404
if isFileNotFoundError(err) {
}
// TODO: handle 'not found' as a 404?
fmt.Println("[ERROR]: failed to load or parse layout template:", err)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
// TODO: apply auth to all templates needed!
// auth tooling
/*
AccessToken string
Claims authentication.AccessTokenClaims
User accounts.OAuthUser
Account *accounts.Account
*/
"Identity",
getIdentity(r.Context()),
"Auth",
newTemplateAuthenticator(r),
}
w.Write(b)
}
b, err := s.templater.ExecutePage(name, templateArgs...)
if err != nil {
return s.handleTemplateError(err, templateArgs...)
}
func isFileNotFoundError(err error) bool {
var pe *os.PathError
isPathErr := errors.As(err, &pe)
return isPathErr && pe.Err != nil && pe.Err.Error() == "no such file or directory"
return response.Body(io.NopCloser(bytes.NewBuffer(b))), nil
}
// TODO: clean this up...
@@ -142,6 +121,63 @@ func getMatchingGlobPatternsCapturingFilepathIncludingParametrizedFilepaths(file
}
}
func (s *Server) handleTemplateError(err error, templateArgs ...any) (response.Response, error) {
code := getHTTPStatusCode(err)
if code == http.StatusNotFound ||
code == http.StatusForbidden ||
code == http.StatusUnauthorized ||
isFileNotFoundError(err) {
b, err := s.templater.ExecutePage("not-found", templateArgs...)
if err != nil {
fmt.Println("failed to render not found page:", err)
return nil, response.NotFound().
Wrap(err).
Msg("resource not found")
}
return response.Body(io.NopCloser(bytes.NewBuffer(b))), nil
}
if code == http.StatusConflict {
b, err := s.templater.ExecutePage("conflict", templateArgs...)
if err != nil {
fmt.Println("failed to render conflict page:", err)
return nil, response.Conflict().
Wrap(err).
Msg("conflict")
}
return response.Body(io.NopCloser(bytes.NewBuffer(b))), nil
}
return nil, fmt.Errorf("failed to render page: %w", err)
}
func isFileNotFoundError(err error) bool {
var pe *os.PathError
isPathErr := errors.As(err, &pe)
return isPathErr && pe.Err != nil && pe.Err.Error() == "no such file or directory"
}
func getHTTPStatusCode(err error) int {
rerr, ok := response.GetError(err)
if !ok {
return http.StatusInternalServerError
}
code, ok := rerr.GetStatus()
if !ok {
return http.StatusInternalServerError
}
return code
}
// template tooling
type URLCalculator struct {
url *url.URL
}
@@ -161,3 +197,22 @@ func (c URLCalculator) SetQueryParam(k string, v any) string {
return u.String()
}
// template authenticator
type templateAuthenticator struct {
req *http.Request
}
func newTemplateAuthenticator(req *http.Request) *templateAuthenticator {
return &templateAuthenticator{
req: req,
}
}
// templateAuthorizationFunc these shouild always return an empty string
type templateAuthorizationFunc = func() (string, error)
func (a *templateAuthenticator) ByMatchingAccountID(acctIDPathPosition int) (string, error) {
return "", authorizeByMatchingAccountID(a.req, acctIDPathPosition)
}