forked from fastschema/fastschema
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.go
More file actions
608 lines (503 loc) · 14.8 KB
/
init.go
File metadata and controls
608 lines (503 loc) · 14.8 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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
package fastschema
import (
"context"
"embed"
"encoding/json"
"fmt"
"net/http"
"path"
"runtime/debug"
"strings"
"github.com/fastschema/fastschema/db"
"github.com/fastschema/fastschema/fs"
"github.com/fastschema/fastschema/logger"
"github.com/fastschema/fastschema/pkg/auth"
"github.com/fastschema/fastschema/pkg/entdbadapter"
"github.com/fastschema/fastschema/pkg/errors"
"github.com/fastschema/fastschema/pkg/mailer"
"github.com/fastschema/fastschema/pkg/rclonefs"
"github.com/fastschema/fastschema/pkg/utils"
"github.com/fastschema/fastschema/pkg/zaplogger"
"github.com/fastschema/fastschema/plugins"
"github.com/fastschema/fastschema/schema"
ts "github.com/fastschema/fastschema/services/tool"
"github.com/joho/godotenv"
)
//go:embed all:dash/*
var embedDashStatic embed.FS
func init() {
fs.RegisterAuthProviderMaker(auth.ProviderLocal, auth.NewLocalAuthProvider)
fs.RegisterAuthProviderMaker(auth.ProviderGithub, auth.NewGithubAuthProvider)
fs.RegisterAuthProviderMaker(auth.ProviderGoogle, auth.NewGoogleAuthProvider)
}
func (a *App) init() (err error) {
var pluginsManager *plugins.Manager
if pluginsManager, err = plugins.NewManager(a, a.pluginsDir, nil); err != nil {
return err
}
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v\n%s", r, string(debug.Stack()))
}
if err == nil {
err = pluginsManager.Init()
}
}()
if err = pluginsManager.Config(); err != nil {
return err
}
if err = a.createDisks(); err != nil {
return err
}
if err = a.createLogger(); err != nil {
return err
}
if err := a.createAuthProviders(); err != nil {
return err
}
if err = a.createSchemaBuilder(); err != nil {
return err
}
a.createServices()
a.createResources()
if err = a.createDBClient(); err != nil {
return err
}
if err := a.createMailClients(); err != nil {
return err
}
// if a local disk has a public path, then add it to the statics
for _, disk := range a.disks {
publicPath := disk.LocalPublicPath()
if publicPath != "" {
a.startupMessages = append(
a.startupMessages,
fmt.Sprintf("Serving files from disk [%s:%s] at %s", disk.Name(), publicPath, disk.Root()),
)
a.statics = append(a.statics, &fs.StaticFs{
BasePath: publicPath,
RootDir: disk.Root(),
Config: &fs.StaticConfig{
Compress: true,
ByteRange: true,
Browse: false,
},
})
}
}
if err = a.createSetupPage(); err != nil {
return err
}
a.statics = append(a.statics, &fs.StaticFs{
BasePath: "/" + a.config.DashBaseName,
RootFS: http.FS(embedDashStatic),
FSPrefix: "dash",
})
return nil
}
func (a *App) prepareConfig() (err error) {
a.getAppDir()
a.dataDir = path.Join(a.dir, "data")
a.logDir = path.Join(a.dataDir, "logs")
a.publicDir = path.Join(a.dataDir, "public")
a.schemasDir = path.Join(a.dataDir, "schemas")
a.migrationDir = path.Join(a.dataDir, "migrations")
a.pluginsDir = path.Join(a.dataDir, "plugins")
envFile := path.Join(a.dataDir, ".env")
if err = utils.MkDirs(
a.logDir,
a.publicDir,
a.schemasDir,
a.migrationDir,
); err != nil {
return err
}
if utils.IsFileExists(envFile) {
a.envFile = envFile
if err := godotenv.Load(envFile); err != nil {
return err
}
}
if a.config.Hooks == nil {
a.config.Hooks = &fs.Hooks{
DBHooks: &db.Hooks{},
PreResolve: []fs.Middleware{},
PostResolve: []fs.Middleware{},
}
}
if a.config.AppKey == "" {
a.config.AppKey = utils.Env("APP_KEY")
}
if a.config.AppName == "" {
a.config.AppName = utils.Env("APP_NAME", "FastSchema")
}
if a.config.MaxRequestBodySize == 0 {
a.config.MaxRequestBodySize = utils.EnvInt("MAX_REQUEST_BODY_SIZE", 4*1024*1024) // 4MB
}
if a.config.Port == "" {
a.config.Port = utils.Env("APP_PORT", "8000")
}
if a.config.BaseURL == "" {
a.config.BaseURL = utils.Env("APP_BASE_URL")
}
if a.config.DashURL == "" {
a.config.DashURL = utils.Env("APP_DASH_URL")
}
if a.config.APIBaseName == "" {
a.config.APIBaseName = utils.Env("APP_API_BASE_NAME", "api")
}
if a.config.DashBaseName == "" {
a.config.DashBaseName = utils.Env("APP_DASH_BASE_NAME", "dash")
}
if a.config.BaseURL == "" {
a.config.BaseURL = "http://localhost:" + a.config.Port
}
if a.config.DashURL == "" {
a.config.DashURL = fmt.Sprintf("%s/%s", a.config.BaseURL, a.config.DashBaseName)
}
if a.config.AppKey == "" {
a.config.AppKey = utils.RandomString(32)
if err := utils.AppendFile(
envFile,
fmt.Sprintf("APP_KEY=%s\n", a.config.AppKey),
); err != nil {
return err
}
a.startupMessages = append(
a.startupMessages,
"APP_KEY is not set. A new key is generated and saved to "+envFile,
)
}
return nil
}
func (a *App) createSetupPage() error {
setupToken, err := a.GetSetupToken(context.Background())
if err != nil {
return err
}
if setupToken != "" {
type setupData struct {
Token string `json:"token"`
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
}
a.api.Add(fs.NewResource("setup", func(c fs.Context, setupData *setupData) (bool, error) {
if setupToken == "" {
return false, errors.BadRequest("Setup token is not available")
}
if setupData == nil || setupData.Token != setupToken {
return false, errors.Forbidden("Invalid setup data or token")
}
if err := ts.Setup(
c,
a.DB(),
a.Logger(),
setupData.Username, setupData.Email, setupData.Password,
); err != nil {
return false, err
}
if err := a.UpdateCache(c); err != nil {
return false, err
}
setupToken = ""
a.setupToken = ""
return true, nil
}, &fs.Meta{
Post: "/setup",
Public: true,
}))
setupURL := fmt.Sprintf(
"%s/setup/?token=%s\033[0m",
a.config.DashURL,
setupToken,
)
a.startupMessages = append(a.startupMessages, "Visit the following URL to setup the app: "+setupURL)
}
return nil
}
func (a *App) createDisks() (err error) {
storage := utils.Env("STORAGE")
if a.config.StorageConfig == nil {
if storage != "" {
if err := json.Unmarshal([]byte(storage), &a.config.StorageConfig); err != nil {
return err
}
} else {
a.config.StorageConfig = &fs.StorageConfig{}
}
}
defaultDiskName := a.config.StorageConfig.DefaultDisk
// if threre is no disk config, add a default disk
if a.config.StorageConfig.Disks == nil {
if defaultDiskName == "" {
defaultDiskName = "public"
}
a.config.StorageConfig.Disks = []*fs.DiskConfig{{
Name: "public",
Driver: "local",
PublicPath: "/",
BaseURL: a.config.BaseURL + "/",
Root: a.publicDir,
}}
}
if a.disks, err = rclonefs.NewFromConfig(a.config.StorageConfig.Disks, a.dataDir); err != nil {
return err
}
foundDefaultDisk := false
for _, disk := range a.disks {
if disk.Name() == defaultDiskName {
a.defaultDisk = disk
foundDefaultDisk = true
break
}
}
if defaultDiskName != "" && !foundDefaultDisk {
return fmt.Errorf("default disk [%s] not found", defaultDiskName)
}
if a.defaultDisk == nil && len(a.disks) > 0 {
a.defaultDisk = a.disks[0]
}
return nil
}
func (a *App) createLogger() (err error) {
if a.config.Logger != nil {
return nil
}
if a.config.LoggerConfig == nil {
a.config.LoggerConfig = &logger.Config{
Development: utils.Env("APP_ENV", "development") == "development",
LogFile: path.Join(a.logDir, "app.log"),
}
}
a.config.Logger, err = zaplogger.NewZapLogger(a.config.LoggerConfig)
return
}
func (a *App) createAuthProviders() (err error) {
if a.config.AuthConfig == nil {
if utils.Env("AUTH") != "" {
if err := json.Unmarshal([]byte(utils.Env("AUTH")), &a.config.AuthConfig); err != nil {
return err
}
} else {
a.config.AuthConfig = &fs.AuthConfig{}
}
}
// Override with individual environment variables if set
if envValue := utils.EnvInt("AUTH_ACCESS_TOKEN_LIFETIME"); envValue > 0 {
a.config.AuthConfig.AccessTokenLifetime = envValue
}
if envValue := utils.EnvInt("AUTH_REFRESH_TOKEN_LIFETIME"); envValue > 0 {
a.config.AuthConfig.RefreshTokenLifetime = envValue
}
if strings.ToLower(utils.Env("AUTH_ENABLE_REFRESH_TOKEN")) == "true" {
a.config.AuthConfig.EnableRefreshToken = true
}
if a.config.AuthConfig.EnabledProviders == nil {
a.config.AuthConfig.EnabledProviders = []string{}
}
if !utils.Contains(a.config.AuthConfig.EnabledProviders, auth.ProviderLocal) {
a.config.AuthConfig.EnabledProviders = append(
a.config.AuthConfig.EnabledProviders,
auth.ProviderLocal,
)
}
availableProviders := fs.AuthProviders()
for _, name := range a.config.AuthConfig.EnabledProviders {
if _, ok := a.authProviders[name]; ok {
return fmt.Errorf("auth provider %s is already registered", name)
}
if !utils.Contains(availableProviders, name) {
return fmt.Errorf("auth provider %s is not founud", name)
}
config := a.config.AuthConfig.Providers[name]
redirectURL := fmt.Sprintf("%s/%s/auth/%s/callback", a.config.BaseURL, a.config.APIBaseName, name)
provider, err := fs.CreateAuthProvider(name, config, redirectURL)
if err != nil {
return err
}
if la, ok := provider.(*auth.LocalProvider); ok {
la.Init(
a.DB,
a.Key,
a.Name,
func() string {
return a.config.BaseURL
},
a.Mailer,
a.JwtCustomClaimsFunc,
a.EmailTemplates,
)
}
a.authProviders[name] = provider
}
return nil
}
func (a *App) createSchemaBuilder() (err error) {
if a.schemaBuilder, err = schema.NewBuilderFromDir(
a.schemasDir,
a.SystemSchemas()...,
); err != nil {
return err
}
return nil
}
func (a *App) createDBClient() (err error) {
if a.DB() != nil {
return nil
}
if a.config.DBConfig == nil {
a.config.DBConfig = &db.Config{
Driver: utils.Env("DB_DRIVER", "sqlite"),
Name: utils.Env("DB_NAME"),
User: utils.Env("DB_USER"),
Pass: utils.Env("DB_PASS"),
Host: utils.Env("DB_HOST", "localhost"),
Port: utils.Env("DB_PORT"),
LogQueries: utils.Env("DB_LOGGING", "false") == "true",
DisableForeignKeys: utils.Env("DB_DISABLE_FOREIGN_KEYS", "false") == "true",
UseSoftDeletes: utils.Env("DB_USE_SOFT_DELETES", "false") == "true",
SSLMode: utils.Env("DB_SSLMODE"),
}
}
a.config.DBConfig.Hooks = func() *db.Hooks {
return a.config.Hooks.DBHooks
}
if a.config.DBConfig.Logger == nil {
a.config.DBConfig.Logger = a.Logger()
}
if a.config.DBConfig.MigrationDir == "" {
a.config.DBConfig.MigrationDir = a.migrationDir
}
if !utils.Contains(db.SupportDrivers, a.config.DBConfig.Driver) {
return fmt.Errorf("unsupported database driver: %s", a.config.DBConfig.Driver)
}
if a.config.DBConfig.MigrationDir == "" {
a.config.DBConfig.MigrationDir = a.migrationDir
}
pgxValidSSLModes := []string{"disable", "allow", "prefer", "require"}
if a.config.DBConfig.Driver == "pgx" && a.config.DBConfig.SSLMode != "" && !utils.Contains(pgxValidSSLModes, a.config.DBConfig.SSLMode) {
return fmt.Errorf("invalid ssl_mode %q: must be one of %v", a.config.DBConfig.SSLMode, pgxValidSSLModes)
}
// If driver is sqlite and the DB_NAME (file path) is not set,
// Set the DB_NAME to the default sqlite db file path.
if a.config.DBConfig.Driver == "sqlite" && a.config.DBConfig.Name == "" {
a.config.DBConfig.Name = path.Join(a.dataDir, "fastschema.db")
a.startupMessages = append(
a.startupMessages,
"Using default sqlite db file: "+a.config.DBConfig.Name,
)
}
if a.config.DB, err = entdbadapter.NewClient(a.config.DBConfig, a.schemaBuilder); err != nil {
return err
}
if err := a.UpdateCache(context.Background()); err != nil {
return err
}
return nil
}
func (a *App) createMailClients() (err error) {
if a.config.MailConfig == nil {
if utils.Env("MAIL") != "" {
if err := json.Unmarshal([]byte(utils.Env("MAIL")), &a.config.MailConfig); err != nil {
return err
}
} else {
a.config.MailConfig = &fs.MailConfig{}
}
}
if a.config.MailConfig == nil || len(a.config.MailConfig.Clients) == 0 {
return nil
}
// Ensure Templates struct exists and resolve from env vars
if a.config.MailConfig.Templates == nil {
a.config.MailConfig.Templates = &fs.EmailTemplates{}
}
if a.config.MailConfig.Templates.ActivationSubject == "" {
a.config.MailConfig.Templates.ActivationSubject = utils.Env("MAIL_ACTIVATION_SUBJECT")
}
if a.config.MailConfig.Templates.ActivationBody == "" {
a.config.MailConfig.Templates.ActivationBody = utils.Env("MAIL_ACTIVATION_BODY")
}
if a.config.MailConfig.Templates.RecoverySubject == "" {
a.config.MailConfig.Templates.RecoverySubject = utils.Env("MAIL_RECOVERY_SUBJECT")
}
if a.config.MailConfig.Templates.RecoveryBody == "" {
a.config.MailConfig.Templates.RecoveryBody = utils.Env("MAIL_RECOVERY_BODY")
}
if !utils.IsValidEmail(a.config.MailConfig.SenderMail) {
return fmt.Errorf("invalid sender mail: %s", a.config.MailConfig.SenderMail)
}
if a.config.MailConfig.SenderName == "" {
a.config.MailConfig.SenderName = a.config.AppName
}
defaultClientName := a.config.MailConfig.DefaultClientName
if a.mailClients, err = mailer.NewMailersFromConfig(a.config.MailConfig); err != nil {
return err
}
foundDefaultClient := false
for _, client := range a.mailClients {
if client.Name() == defaultClientName {
a.defaultMailClient = client
foundDefaultClient = true
break
}
}
if defaultClientName != "" && !foundDefaultClient {
return fmt.Errorf("default mail client [%s] not found", defaultClientName)
}
if a.defaultMailClient == nil && len(a.mailClients) > 0 {
a.defaultMailClient = a.mailClients[0]
}
return nil
}
func (a *App) getAppDir() {
defer func() {
a.startupMessages = append(a.startupMessages, "Using app directory: "+a.dir)
}()
if a.config.Dir == "" {
a.dir = a.wd
return
}
if strings.HasPrefix(a.config.Dir, "/") {
a.dir = a.config.Dir
return
}
a.dir = path.Join(a.wd, a.config.Dir)
}
func (a *App) GetSetupToken(ctx context.Context) (string, error) {
// If there is no roles and users, then the app is not setup
// we need to setup the app.
// Generate a random token and return it to enable the setup.
// If there are roles or users, then the app is already setup.
// Return an empty string to disable the setup.
needSetup, err := a.needSetup(ctx)
if err != nil {
return "", err
}
if !needSetup {
return "", nil
}
if a.setupToken == "" {
a.setupToken = utils.RandomString(32)
}
return a.setupToken, nil
}
func (a *App) needSetup(ctx context.Context) (bool, error) {
// If there is no roles and users, then the app is not setup
// we need to setup the app.
var err error
var userCount int
var roleCount int
countOption := &db.QueryOption{
Column: "id",
Unique: true,
}
if userCount, err = db.Builder[*fs.User](a.DB()).Count(ctx, countOption); err != nil {
return false, err
}
if roleCount, err = db.Builder[*fs.Role](a.DB()).Count(ctx, countOption); err != nil {
return false, err
}
return userCount == 0 && roleCount == 0, nil
}