Files
inventory-plus-plus/internal/server/ui/router.go
T

240 lines
5.4 KiB
Go

package ui
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
uiPath string
templater *templater.Templater
rawEvents *raw_events.Store
accts *accounts.Store
etsy *etsy_platform.Platform
}
// ErrTemplateNotFound is returned if the reason the template failed to compile
// is due to the template not being found.
ErrTemplateNotFound struct {
err error
}
)
func Routes(
logger *logging.Logger,
r gin.IRoutes,
uiPath string,
rawEvents *raw_events.Store,
accts *accounts.Store,
etsy *etsy_platform.Platform,
authenticate gin.HandlerFunc,
) {
s := &webpageRouter{
log: logger,
uiPath: uiPath,
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,
}
r.GET("", response.Handler(s.serveTemplate))
r.GET("/*rest", authenticate, response.Handler(s.serveTemplate))
}
// GET /
// compiles the page template or component template matching the url
func (s *webpageRouter) serveTemplate(c *gin.Context) (response.Response, error) {
// trim the url path prefix before loading the templates
c.Request.URL.Path = c.Request.URL.Path[len(s.uiPath):]
defer func() {
c.Request.URL.Path = s.uiPath + c.Request.URL.Path
}()
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.Errorf("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
}