-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathauth.go
More file actions
374 lines (316 loc) · 11.2 KB
/
auth.go
File metadata and controls
374 lines (316 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
package authula
import (
"context"
"fmt"
"net/http"
"sync"
"github.com/uptrace/bun"
"github.com/Authula/authula/internal"
"github.com/Authula/authula/internal/migrationmanager"
"github.com/Authula/authula/internal/plugins"
"github.com/Authula/authula/internal/util"
"github.com/Authula/authula/migrations"
"github.com/Authula/authula/models"
coreservices "github.com/Authula/authula/services"
)
type AuthConfig struct {
Config *models.Config
Plugins []models.Plugin
DB bun.IDB
}
// Auth is a composition root and entry point for the authentication framework.
type Auth struct {
config *models.Config
logger models.Logger
db bun.IDB
migrator *migrations.Migrator
migrationManager *migrationmanager.Manager
router *Router
ServiceRegistry models.ServiceRegistry
PluginRegistry models.PluginRegistry
handlerOnce sync.Once
coreServices *coreservices.CoreServices
systems []models.CoreSystem
Api internal.CoreAPI
}
// New creates a new Auth instance using the provided config and plugins.
// Handles plugin registration, migrations, and initialization in unified way.
// Works identically whether plugins are manually instantiated or built from config.
func New(authConfig *AuthConfig) *Auth {
if authConfig == nil || authConfig.Config == nil {
panic("auth config and auth config config must not be nil")
}
util.InitValidator()
logger := InitLogger(authConfig.Config)
db := authConfig.DB
if db == nil {
initializedDB, err := InitDatabase(authConfig.Config, logger, authConfig.Config.Logger.Level)
if err != nil {
panic(fmt.Errorf("failed to initialize database: %w", err))
}
db = initializedDB
}
migrator, err := migrations.NewMigrator(db, logger)
if err != nil {
panic(fmt.Errorf("failed to create migrator: %w", err))
}
migrationManager := migrationmanager.NewManager(migrator)
if err := migrationManager.RunCore(context.Background(), authConfig.Config.Database.Provider); err != nil {
panic(fmt.Errorf("failed to run core migrations: %w", err))
}
eventBus, err := InitEventBus(authConfig.Config)
if err != nil {
panic(fmt.Errorf("failed to initialize event bus: %w", err))
}
serviceRegistry := plugins.NewServiceRegistry()
coreServices := InitCoreServices(authConfig.Config, db, serviceRegistry)
pluginRegistry := plugins.NewPluginRegistry(
authConfig.Config,
logger,
db,
migrationManager,
serviceRegistry,
eventBus,
)
// Initialize PreParsedConfigs if not already done
if authConfig.Config.PreParsedConfigs == nil {
authConfig.Config.PreParsedConfigs = make(map[string]any)
}
// Initialize Plugins map if not already done
if authConfig.Config.Plugins == nil {
authConfig.Config.Plugins = make(models.PluginsConfig)
}
for _, plugin := range authConfig.Plugins {
pluginID := plugin.Metadata().ID
// Cache type-safe configs for all plugins
authConfig.Config.PreParsedConfigs[pluginID] = plugin.Config()
if !util.IsPluginEnabled(authConfig.Config, pluginID) {
continue
}
if err := pluginRegistry.Register(plugin); err != nil {
panic(fmt.Errorf("failed to register plugin: %w", err))
}
}
if err := pluginRegistry.RunMigrations(context.Background()); err != nil {
logger.Error("failed to run plugin migrations", "error", err)
panic(fmt.Errorf("failed to run plugin migrations: %w", err))
}
if err := pluginRegistry.InitAll(); err != nil {
logger.Error("failed to initialize plugins", "error", err)
panic(fmt.Errorf("failed to initialize plugins: %w", err))
}
api := internal.NewCoreAPI(logger, coreServices.UserService, coreServices.SessionService)
systems := InitCoreSystems(logger, authConfig.Config, coreServices)
for _, system := range systems {
if err := system.Init(context.Background()); err != nil {
logger.Error("failed to initialize core system", "system", system.Name(), "error", err)
panic(err)
}
}
router := NewRouter(authConfig.Config, logger, nil)
auth := &Auth{
config: authConfig.Config,
logger: logger,
db: db,
migrator: migrator,
migrationManager: migrationManager,
router: router,
ServiceRegistry: serviceRegistry,
PluginRegistry: pluginRegistry,
coreServices: coreServices,
systems: systems,
Api: api,
}
// Register middleware NOW (before any routes are registered)
// This ensures Chi's requirement that all middleware is defined before routes
auth.registerMiddleware()
return auth
}
func (auth *Auth) RunCoreMigrations(ctx context.Context) error {
if auth.migrationManager == nil {
return fmt.Errorf("migrator not initialized")
}
return auth.migrationManager.RunCore(ctx, auth.config.Database.Provider)
}
func (auth *Auth) DropCoreMigrations(ctx context.Context) error {
if auth.migrationManager == nil {
return fmt.Errorf("migrator not initialized")
}
return auth.migrationManager.DropCore(ctx, auth.config.Database.Provider)
}
// registerMiddleware registers all middleware from hooks and plugins
func (auth *Auth) registerMiddleware() {
currentConfig := auth.PluginRegistry.GetConfig()
// Register Plugin Global Middleware
for _, plugin := range auth.PluginRegistry.Plugins() {
pluginID := plugin.Metadata().ID
if !util.IsPluginEnabled(currentConfig, pluginID) {
auth.logger.Debug("skipping disabled plugin", "plugin", pluginID)
continue
}
if middlewareProvider, ok := plugin.(models.PluginWithMiddleware); ok {
middleware := middlewareProvider.Middleware()
if len(middleware) == 0 {
auth.logger.Debug("no middleware functions returned", "plugin", pluginID)
continue
}
auth.router.RegisterMiddleware(middleware...)
}
}
}
// RegisterMiddleware registers middleware to the chi router.
// Middleware should be registered before calling Handler().
func (auth *Auth) RegisterMiddleware(middleware ...func(http.Handler) http.Handler) {
auth.router.RegisterMiddleware(middleware...)
}
// RegisterRoute registers a single route with the basePath prefix
func (auth *Auth) RegisterRoute(route models.Route) {
auth.router.RegisterRoute(route)
}
// RegisterRoutes registers multiple routes with the basePath prefix
func (auth *Auth) RegisterRoutes(routes []models.Route) {
auth.router.RegisterRoutes(routes)
}
// RegisterCustomRoute registers a single custom route without the basePath prefix
// This is useful for application routes that should not be under the auth basePath
func (auth *Auth) RegisterCustomRoute(route models.Route) {
auth.router.RegisterCustomRoute(route)
}
// RegisterCustomRouteGroup registers a route group that can have a prefix path and metadata that applies to all routes
// This is useful if many routes should share paths and or metadata
func (auth *Auth) RegisterCustomRouteGroup(group models.RouteGroup) {
auth.router.RegisterCustomRouteGroup(group)
}
// RegisterCustomRoutes registers multiple custom routes without the basePath prefix
// This is useful for application routes that should not be under the auth basePath
func (auth *Auth) RegisterCustomRoutes(routes []models.Route) {
auth.router.RegisterCustomRoutes(routes)
}
// RegisterHook registers a single hook to the router.
// Hooks allow developers to intercept and modify requests/responses at various stages
// of the request lifecycle (OnRequest, Before, After, OnResponse).
func (auth *Auth) RegisterHook(hook models.Hook) {
auth.router.RegisterHook(hook)
}
// RegisterHooks registers multiple hooks to the router.
// Hooks allow developers to intercept and modify requests/responses at various stages
// of the request lifecycle (OnRequest, Before, After, OnResponse).
func (auth *Auth) RegisterHooks(hooks []models.Hook) {
auth.router.RegisterHooks(hooks)
}
// GetUserIDFromContext retrieves the user ID from a context.
// Returns the user ID and a boolean indicating whether it was found.
// This is a convenience wrapper around models.GetUserIDFromContext to avoid
// requiring application code to import the models package.
func (auth *Auth) GetUserIDFromContext(ctx context.Context) (string, bool) {
return models.GetUserIDFromContext(ctx)
}
// GetUserIDFromRequest retrieves the user ID from an HTTP request's context.
// Returns the user ID and a boolean indicating whether it was found.
// This is a convenience wrapper around models.GetUserIDFromRequest to avoid
// requiring application code to import the models package.
func (auth *Auth) GetUserIDFromRequest(req *http.Request) (string, bool) {
return models.GetUserIDFromRequest(req)
}
// Handler returns the HTTP handler that serves all authentication routes and hooks.
// It registers routes and hooks from all plugins with the router.
// This is the entry point for HTTP traffic.
func (auth *Auth) Handler() http.Handler {
auth.handlerOnce.Do(func() {
auth.router.RegisterRoutes(
internal.CoreRoutes(
auth.logger,
auth.coreServices.UserService,
auth.coreServices.SessionService,
),
)
currentConfig := auth.config
// Convert route mappings to metadata format for plugin routing
// This works identically whether RouteMappings come from config file or library mode
if len(currentConfig.RouteMappings) > 0 {
routeMetadata, err := util.ConvertRouteMetadata(currentConfig.RouteMappings)
if err != nil {
auth.logger.Error("failed to convert route metadata", "error", err)
} else {
adjustedMetadata := make(map[string]map[string]any)
for key, metadata := range routeMetadata {
adjustedKey := util.ApplyBasePathToMetadataKey(key, auth.router.basePath)
adjustedMetadata[adjustedKey] = metadata
}
auth.router.SetRouteMetadataFromConfig(adjustedMetadata)
}
}
// Register Plugin Routes
for _, plugin := range auth.PluginRegistry.Plugins() {
if !util.IsPluginEnabled(currentConfig, plugin.Metadata().ID) {
continue
}
if routeProvider, ok := plugin.(models.PluginWithRoutes); ok {
pluginRoutes := routeProvider.Routes()
if len(pluginRoutes) == 0 {
continue
}
auth.router.RegisterRoutes(pluginRoutes)
}
}
// Register Plugin Hooks
for _, plugin := range auth.PluginRegistry.Plugins() {
if !util.IsPluginEnabled(currentConfig, plugin.Metadata().ID) {
continue
}
if hookProvider, ok := plugin.(models.PluginWithHooks); ok {
hooks := hookProvider.Hooks()
if len(hooks) > 0 {
auth.router.RegisterHooks(hooks)
}
}
}
})
return auth.router.Handler()
}
// ClosePlugins calls Close for all registered plugins
func (auth *Auth) ClosePlugins() error {
if auth.PluginRegistry == nil {
return nil
}
auth.PluginRegistry.CloseAll()
return nil
}
func (auth *Auth) CloseSystems() error {
for _, system := range auth.systems {
if err := system.Close(); err != nil {
auth.logger.Error("failed to close core system", "system", system.Name(), "error", err)
}
}
return nil
}
func (auth *Auth) DB() bun.IDB {
if auth == nil {
return nil
}
return auth.db
}
func (auth *Auth) Router() *Router {
if auth == nil {
return nil
}
return auth.router
}
func (auth *Auth) Migrator() *migrations.Migrator {
if auth == nil {
return nil
}
return auth.migrator
}
func (auth *Auth) MigrationManager() *migrationmanager.Manager {
if auth == nil {
return nil
}
return auth.migrationManager
}
func (auth *Auth) CoreServices() *coreservices.CoreServices {
if auth == nil {
return nil
}
return auth.coreServices
}