package templates import ( "encoding/json" "errors" "fmt" "net/http" "net/url" "strconv" "strings" "text/template" "ruben/inventory2/internal/domains/accounts" etsy_platform "ruben/inventory2/internal/domains/platforms/etsy" "ruben/inventory2/internal/domains/raw_events" "ruben/inventory2/internal/logging" "ruben/inventory2/internal/server/middleware" "ruben/inventory2/internal/server/response" "github.com/angelbeltran/templater" "github.com/gin-gonic/gin" ) type ( webpageRouter struct { log *logging.Logger contentDir string templater *templater.Templater rawEvents *raw_events.Store accts *accounts.Store etsy *etsy_platform.Platform authMiddleware *middleware.Auth } // ErrTemplateNotFound is returned if the reason the template failed to compile // is due to the template not being found. ErrTemplateNotFound struct { err error } ) func SetupRoutes( logger *logging.Logger, r gin.IRouter, contentDir string, rawEvents *raw_events.Store, accts *accounts.Store, etsy *etsy_platform.Platform, authMiddleware *middleware.Auth, ) { s := &webpageRouter{ log: logger, contentDir: contentDir, // TODO: clean up the references to the templates dir throughout as well (should only be referred to in the 'main' package templater: new(templater.Templater).With(templater.Config{ Funcs: func(name string, props map[string]any) template.FuncMap { return template.FuncMap{ // parsing "parseInt": func(s string) (int, error) { return strconv.Atoi(s) }, "parseInt64": func(s string) (int64, error) { return strconv.ParseInt(s, 10, 64) }, "parsePlatform": func(s string) (accounts.Platform, error) { return accounts.NewPlatform(s) }, // arithmetic "addInt": func(a, b int) int { return a + b }, "subInt": func(a, b int) int { return a - b }, "multInt": func(a, b int) int { return a * b }, // json "prettyPrintJSON": func(j json.RawMessage) string { b, err := json.MarshalIndent(j, " ", "") if err != nil { return string(j) } return string(b) }, "marshalJSON": json.Marshal, } }, }), rawEvents: rawEvents, accts: accts, etsy: etsy, authMiddleware: authMiddleware, } authAndServeTemplate := s.authMiddleware.AuthenticateAndAddIdentity(s.serveTemplate) r.GET("/*rest", response.Handler(func(c *gin.Context) (response.Response, error) { c.Request.URL.Path = c.Request.URL.Path[3:] defer func() { c.Request.URL.Path = "/ui" + c.Request.URL.Path }() p := c.Request.URL.Path if p == "/" || p == "" { c, err := s.authMiddleware.AddIdentityToRequest(c) if err != nil { return nil, err } return s.serveTemplate(c) } return authAndServeTemplate(c) })) } // GET / // compiles the page template or component template matching the url func (s *webpageRouter) serveTemplate(c *gin.Context) (response.Response, error) { r := c.Request ctx := r.Context() args := []any{ "Request", r, // add services and data here "RawEvents", s.rawEvents.WithContext(ctx), "URLCalc", newURLCalculator(r.URL), "Accounts", s.accts.WithContext(ctx), "Etsy", s.etsy.WithContext(ctx), // auth tooling "Identity", middleware.GetIdentity(ctx), "Auth", newTemplateAuthenticator(r), } b, err := s.templater.Execute(strings.Trim(r.URL.Path, "/"), args...) if err != nil { if isFileNotFoundError(err) || isInvalidWildcardValue(err) { werr := response.NotFound(). Wrap(ErrTemplateNotFound{ err: err, }). Msg("resource not found") nfb, nferr := s.templater.Execute("not-found", args...) if nferr != nil { s.log.Error("failed to render not-found page: %v", nferr) return nil, werr } return nil, werr. HTML(nfb) } return nil, err } return response.HTML(b), nil } func isInvalidWildcardValue(err error) bool { var te *templater.ErrInvalidWildcardValue return errors.As(err, &te) } func isFileNotFoundError(err error) bool { var te *templater.ErrNotTemplateFileFound return errors.As(err, &te) } // template tooling type URLCalculator struct { url *url.URL } func newURLCalculator(u *url.URL) URLCalculator { cpy := *u return URLCalculator{ url: &cpy, } } func (c URLCalculator) SetQueryParam(k string, v any) string { u := *c.url q := u.Query() q.Set(k, fmt.Sprint(v)) u.RawQuery = q.Encode() 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) } func authorizeByMatchingAccountID(r *http.Request, acctIDPathPosition int) error { pathParts := strings.Split(strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/"), "/"), "/") if len(pathParts) < acctIDPathPosition { return fmt.Errorf("authorization failed due to unexpected path: %s", r.URL.Path) } part := pathParts[acctIDPathPosition-1] acctID, err := strconv.ParseInt(part, 10, 64) if err != nil { return response.NotFound(). Msgf("account does not exist: %s", part) } id := middleware.GetIdentity(r.Context()) if id.Account == nil || id.Account.AccountID != acctID { return response.Unauthorized(). Msgf("user does not have access to account %d", acctID) } return nil } func (e ErrTemplateNotFound) Error() string { if e.err != nil { return fmt.Sprintf("template not found: %v", e.err) } return fmt.Sprintf("template not found") } func (e ErrTemplateNotFound) Unwrap() error { return e.err }