2fas-server/internal/api/app.go

89 lines
2.5 KiB
Go
Raw Normal View History

2022-12-31 10:22:38 +01:00
package api
import (
"errors"
2022-12-31 10:22:38 +01:00
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
2023-01-30 19:59:42 +01:00
"github.com/twofas/2fas-server/config"
extension "github.com/twofas/2fas-server/internal/api/browser_extension/service"
health "github.com/twofas/2fas-server/internal/api/health/service"
icons "github.com/twofas/2fas-server/internal/api/icons/service"
mobile "github.com/twofas/2fas-server/internal/api/mobile/service"
support "github.com/twofas/2fas-server/internal/api/support/service"
"github.com/twofas/2fas-server/internal/common/api"
"github.com/twofas/2fas-server/internal/common/db"
"github.com/twofas/2fas-server/internal/common/redis"
2023-03-12 14:58:54 +01:00
"github.com/twofas/2fas-server/internal/common/validation"
2022-12-31 10:22:38 +01:00
)
var validate *validator.Validate
type Module interface {
RegisterRoutes(router *gin.Engine)
RegisterAdminRoutes(g *gin.RouterGroup)
2022-12-31 10:22:38 +01:00
}
type Application struct {
Addr string
Router *gin.Engine
Config config.Configuration
Modules []Module
HealthModule *health.HealthModule
2022-12-31 10:22:38 +01:00
}
func NewApplication(applicationName string, config config.Configuration) *Application {
2022-12-31 10:22:38 +01:00
validate = validator.New()
gorm := db.NewGormConnection(config)
database := db.NewDbConnection(config)
redisClient := redis.New(config.Redis.ServiceUrl, config.Redis.Port)
2023-03-12 14:58:54 +01:00
validate.RegisterValidation("not_blank", validation.NotBlank)
h := health.NewHealthModule(applicationName, config, redisClient)
2022-12-31 10:22:38 +01:00
modules := []Module{
h,
2022-12-31 10:22:38 +01:00
support.NewSupportModule(config, gorm, database, validate),
icons.NewIconsModule(config, gorm, database, validate),
2023-03-12 14:58:54 +01:00
extension.NewBrowserExtensionModule(config, gorm, database, redisClient, validate),
2022-12-31 10:22:38 +01:00
mobile.NewMobileModule(config, gorm, database, validate, redisClient),
}
app := &Application{
Addr: config.App.ListenAddr,
Config: config,
Modules: modules,
HealthModule: h,
2022-12-31 10:22:38 +01:00
}
return app
}
func (a *Application) RegisterRoutes(router *gin.Engine) {
router.NoRoute(func(c *gin.Context) {
c.JSON(404, api.NotFoundError(errors.New("URI not found")))
})
for _, module := range a.Modules {
module.RegisterRoutes(router)
}
}
func (a *Application) RegisterAdminRoutes(router *gin.Engine) {
router.NoRoute(func(c *gin.Context) {
c.JSON(404, api.NotFoundError(errors.New("URI not found")))
})
// The only route method is /health. Everything else
// is nested under /admin so that oAuth proxy can route to it.
a.HealthModule.RegisterHealth(router)
g := router.Group("/admin")
for _, module := range a.Modules {
module.RegisterAdminRoutes(g)
}
}