Files
tinyauth/internal/middleware/ui_middleware.go
T
Stavros 4f7335ed73 refactor: rework app logging, dependency injection and cancellation (#844)
* feat: add new logger

* refactor: use one struct for context handling and cancellation

* refactor: rework logging and config in controllers

* refactor: rework logging and config in middlewares

* refactor: rework logging and cancellation in services

* refactor: rework cli logging

* fix: improve logging in routines

* feat: use sync groups for better cancellation

* refactor: simplify middleware, controller and service init

* tests: fix controller tests

* tests: use require instead of assert where previous step is required

* tests: fix middleware tests

* tests: fix service tests

* tests: fix context tests

* fix: fix typos

* feat: add option to enable or disable concurrent listeners

* fix: assign public key correctly in oidc server

* tests: fix don't try to test logger with char size

* fix: coderabbit comments

* tests: use filepath join instead of path join

* fix: ensure unix socket shutdown doesn't run twice

* chore: remove temp lint file
2026-05-10 16:10:36 +03:00

69 lines
1.4 KiB
Go

package middleware
import (
"fmt"
"io/fs"
"net/http"
"os"
"strings"
"time"
"github.com/tinyauthapp/tinyauth/internal/assets"
"github.com/gin-gonic/gin"
)
type UIMiddleware struct {
uiFs fs.FS
uiFileServer http.Handler
}
func NewUIMiddleware() (*UIMiddleware, error) {
m := &UIMiddleware{}
ui, err := fs.Sub(assets.FrontendAssets, "dist")
if err != nil {
return nil, fmt.Errorf("failed to load ui assets: %w", err)
}
m.uiFs = ui
m.uiFileServer = http.FileServerFS(ui)
return m, nil
}
func (m *UIMiddleware) Middleware() gin.HandlerFunc {
return func(c *gin.Context) {
path := strings.TrimPrefix(c.Request.URL.Path, "/")
switch strings.SplitN(path, "/", 2)[0] {
case "api", "resources", ".well-known":
c.Next()
return
case "robots.txt":
c.Writer.Header().Set("Content-Type", "text/plain")
c.Writer.WriteHeader(http.StatusOK)
c.Writer.Write([]byte("User-agent: *\nDisallow: /\n"))
return
default:
_, err := fs.Stat(m.uiFs, path)
// Enough for one authentication flow
maxAge := 15 * time.Minute
if os.IsNotExist(err) {
c.Request.URL.Path = "/"
} else if strings.HasPrefix(path, "assets/") {
// assets are named with a hash and can be cached for a long time
maxAge = 30 * 24 * time.Hour
}
c.Writer.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", int(maxAge.Seconds())))
m.uiFileServer.ServeHTTP(c.Writer, c.Request)
c.Abort()
return
}
}
}