Skip to content

Commit 645c555

Browse files
committed
refactor: move resource handling to a controller
1 parent 03af18f commit 645c555

13 files changed

Lines changed: 86 additions & 71 deletions

File tree

‎.gitignore‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,7 @@ secret*
2323
tmp
2424

2525
# version files
26-
internal/assets/version
26+
internal/assets/version
27+
28+
# data directory
29+
data

‎cmd/root.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ var rootCmd = &cobra.Command{
3333
conf.GoogleClientSecret = utils.GetSecret(conf.GoogleClientSecret, conf.GoogleClientSecretFile)
3434
conf.GenericClientSecret = utils.GetSecret(conf.GenericClientSecret, conf.GenericClientSecretFile)
3535

36+
// Validate config
3637
validator := validator.New()
3738

3839
err = validator.Struct(conf)

‎frontend/vite.config.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@ export default defineConfig({
1919
changeOrigin: true,
2020
rewrite: (path) => path.replace(/^\/api/, ""),
2121
},
22+
"/resources": {
23+
target: "http://tinyauth-backend:3000/resources",
24+
changeOrigin: true,
25+
rewrite: (path) => path.replace(/^\/resources/, ""),
26+
},
2227
},
2328
allowedHosts: true,
2429
},

‎internal/bootstrap/app_bootstrap.go‎

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ type Controller interface {
2020
type Middleware interface {
2121
Middleware() gin.HandlerFunc
2222
Init() error
23-
Name() string
2423
}
2524

2625
type Service interface {
@@ -103,6 +102,7 @@ func (app *BootstrapApp) Setup() error {
103102
err := ldapService.Init()
104103

105104
if err != nil {
105+
log.Warn().Err(err).Msg("Failed to initialize LDAP service, continuing without LDAP")
106106
ldapService = nil
107107
}
108108
}
@@ -120,6 +120,7 @@ func (app *BootstrapApp) Setup() error {
120120

121121
for _, svc := range services {
122122
if svc != nil {
123+
log.Debug().Str("service", fmt.Sprintf("%T", svc)).Msg("Initializing service")
123124
err := svc.Init()
124125
if err != nil {
125126
return err
@@ -142,7 +143,13 @@ func (app *BootstrapApp) Setup() error {
142143

143144
// Create engine
144145
engine := gin.New()
145-
router := engine.Group("/api")
146+
147+
if config.Version != "development" {
148+
gin.SetMode(gin.ReleaseMode)
149+
}
150+
151+
router := engine.Group("/")
152+
apiRouter := router.Group("/api")
146153

147154
// Create middlewares
148155
var middlewares []Middleware
@@ -151,18 +158,16 @@ func (app *BootstrapApp) Setup() error {
151158
Domain: domain,
152159
}, authService, oauthBrokerService)
153160

154-
uiMiddleware := middleware.NewUIMiddleware(middleware.UIMiddlewareConfig{
155-
ResourcesDir: app.Config.ResourcesDir,
156-
})
161+
uiMiddleware := middleware.NewUIMiddleware()
157162
zerologMiddleware := middleware.NewZerologMiddleware()
158163

159164
middlewares = append(middlewares, contextMiddleware, uiMiddleware, zerologMiddleware)
160165

161166
for _, middleware := range middlewares {
162-
log.Debug().Str("middleware", middleware.Name()).Msg("Initializing middleware")
167+
log.Debug().Str("middleware", fmt.Sprintf("%T", middleware)).Msg("Initializing middleware")
163168
err := middleware.Init()
164169
if err != nil {
165-
return fmt.Errorf("failed to initialize %s middleware: %w", middleware.Name(), err)
170+
return fmt.Errorf("failed to initialize %s middleware: %T", middleware, err)
166171
}
167172
router.Use(middleware.Middleware())
168173
}
@@ -177,24 +182,28 @@ func (app *BootstrapApp) Setup() error {
177182
ForgotPasswordMessage: app.Config.FogotPasswordMessage,
178183
BackgroundImage: app.Config.BackgroundImage,
179184
OAuthAutoRedirect: app.Config.OAuthAutoRedirect,
180-
}, router)
185+
}, apiRouter)
181186

182187
oauthController := controller.NewOAuthController(controller.OAuthControllerConfig{
183188
AppURL: app.Config.AppURL,
184189
SecureCookie: app.Config.SecureCookie,
185190
CSRFCookieName: csrfCookieName,
186191
RedirectCookieName: redirectCookieName,
187-
}, router, authService, oauthBrokerService)
192+
}, apiRouter, authService, oauthBrokerService)
188193

189194
proxyController := controller.NewProxyController(controller.ProxyControllerConfig{
190195
AppURL: app.Config.AppURL,
191-
}, router, dockerService, authService)
196+
}, apiRouter, dockerService, authService)
192197

193198
userController := controller.NewUserController(controller.UserControllerConfig{
194199
Domain: domain,
195-
}, router, authService)
200+
}, apiRouter, authService)
201+
202+
resourcesController := controller.NewResourcesController(controller.ResourcesControllerConfig{
203+
ResourcesDir: app.Config.ResourcesDir,
204+
}, router)
196205

197-
healthController := controller.NewHealthController(router)
206+
healthController := controller.NewHealthController(apiRouter)
198207

199208
// Setup routes
200209
controller := []Controller{
@@ -203,10 +212,11 @@ func (app *BootstrapApp) Setup() error {
203212
proxyController,
204213
userController,
205214
healthController,
215+
resourcesController,
206216
}
207217

208218
for _, ctrl := range controller {
209-
log.Debug().Msgf("Setting up %T routes", ctrl)
219+
log.Debug().Msgf("Setting up %T controller", ctrl)
210220
ctrl.SetupRoutes()
211221
}
212222

‎internal/controller/health_controller.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ func NewHealthController(router *gin.RouterGroup) *HealthController {
1414

1515
func (controller *HealthController) SetupRoutes() {
1616
controller.Router.GET("/health", controller.healthHandler)
17+
controller.Router.HEAD("/health", controller.healthHandler)
1718
}
1819

1920
func (controller *HealthController) healthHandler(c *gin.Context) {
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package controller
2+
3+
import (
4+
"net/http"
5+
6+
"github.com/gin-gonic/gin"
7+
)
8+
9+
type ResourcesControllerConfig struct {
10+
ResourcesDir string
11+
}
12+
13+
type ResourcesController struct {
14+
Config ResourcesControllerConfig
15+
Router *gin.RouterGroup
16+
}
17+
18+
func NewResourcesController(config ResourcesControllerConfig, router *gin.RouterGroup) *ResourcesController {
19+
return &ResourcesController{
20+
Config: config,
21+
Router: router,
22+
}
23+
}
24+
25+
func (controller *ResourcesController) SetupRoutes() {
26+
controller.Router.GET("/resources/*resource", controller.resourcesHandler)
27+
}
28+
29+
func (controller *ResourcesController) resourcesHandler(c *gin.Context) {
30+
fileServer := http.StripPrefix("/resources", http.FileServer(http.Dir(controller.Config.ResourcesDir)))
31+
fileServer.ServeHTTP(c.Writer, c.Request)
32+
}

‎internal/middleware/context_middleware.go‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,6 @@ func (m *ContextMiddleware) Init() error {
3232
return nil
3333
}
3434

35-
func (m *ContextMiddleware) Name() string {
36-
return "ContextMiddleware"
37-
}
38-
3935
func (m *ContextMiddleware) Middleware() gin.HandlerFunc {
4036
return func(c *gin.Context) {
4137
cookie, err := m.Auth.GetSessionCookie(c)

‎internal/middleware/ui_middleware.go‎

Lines changed: 5 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -4,28 +4,19 @@ import (
44
"io/fs"
55
"net/http"
66
"os"
7-
"path/filepath"
87
"strings"
98
"tinyauth/internal/assets"
109

1110
"github.com/gin-gonic/gin"
1211
)
1312

14-
type UIMiddlewareConfig struct {
15-
ResourcesDir string
16-
}
17-
1813
type UIMiddleware struct {
19-
Config UIMiddlewareConfig
20-
UIFS fs.FS
21-
UIFileServer http.Handler
22-
ResourcesFileServer http.Handler
14+
UIFS fs.FS
15+
UIFileServer http.Handler
2316
}
2417

25-
func NewUIMiddleware(config UIMiddlewareConfig) *UIMiddleware {
26-
return &UIMiddleware{
27-
Config: config,
28-
}
18+
func NewUIMiddleware() *UIMiddleware {
19+
return &UIMiddleware{}
2920
}
3021

3122
func (m *UIMiddleware) Init() error {
@@ -37,40 +28,18 @@ func (m *UIMiddleware) Init() error {
3728

3829
m.UIFS = ui
3930
m.UIFileServer = http.FileServer(http.FS(ui))
40-
m.ResourcesFileServer = http.FileServer(http.Dir(m.Config.ResourcesDir))
4131

4232
return nil
4333
}
4434

45-
func (m *UIMiddleware) Name() string {
46-
return "UIMiddleware"
47-
}
48-
4935
func (m *UIMiddleware) Middleware() gin.HandlerFunc {
5036
return func(c *gin.Context) {
5137
switch strings.Split(c.Request.URL.Path, "/")[1] {
5238
case "api":
5339
c.Next()
5440
return
5541
case "resources":
56-
requestFilePath := m.Config.ResourcesDir + strings.TrimPrefix(c.Request.URL.Path, "/resources/")
57-
58-
if !filepath.IsLocal(requestFilePath) {
59-
c.Status(404)
60-
c.Abort()
61-
return
62-
}
63-
64-
_, err := os.Stat(requestFilePath)
65-
66-
if os.IsNotExist(err) {
67-
c.Status(404)
68-
c.Abort()
69-
return
70-
}
71-
72-
m.ResourcesFileServer.ServeHTTP(c.Writer, c.Request)
73-
c.Abort()
42+
c.Next()
7443
return
7544
default:
7645
_, err := fs.Stat(m.UIFS, strings.TrimPrefix(c.Request.URL.Path, "/"))

‎internal/middleware/zerolog_middleware.go‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,6 @@ func (m *ZerologMiddleware) Init() error {
2626
return nil
2727
}
2828

29-
func (m *ZerologMiddleware) Name() string {
30-
return "ZerologMiddleware"
31-
}
32-
3329
func (m *ZerologMiddleware) logPath(path string) bool {
3430
for _, prefix := range loggerSkipPathsPrefix {
3531
if strings.HasPrefix(path, prefix) {
Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"tinyauth/internal/config"
88

99
"github.com/gin-gonic/gin"
10-
"github.com/traefik/paerser/parser"
1110

1211
"github.com/rs/zerolog"
1312
)
@@ -39,17 +38,6 @@ func ParseFileToLine(content string) string {
3938
return strings.Join(users, ",")
4039
}
4140

42-
func GetLabels(labels map[string]string) (config.Labels, error) {
43-
var labelsParsed config.Labels
44-
45-
err := parser.Decode(labels, &labelsParsed, "tinyauth", "tinyauth.users", "tinyauth.allowed", "tinyauth.headers", "tinyauth.domain", "tinyauth.basic", "tinyauth.oauth", "tinyauth.ip")
46-
if err != nil {
47-
return config.Labels{}, err
48-
}
49-
50-
return labelsParsed, nil
51-
}
52-
5341
func Filter[T any](slice []T, test func(T) bool) (res []T) {
5442
for _, value := range slice {
5543
if test(value) {

0 commit comments

Comments
 (0)