modweb/app.go

94 lines
2.2 KiB
Go
Raw Normal View History

2020-11-16 22:48:58 +00:00
//go:generate go run github.com/UnnoTed/fileb0x b0x.yaml
2020-11-11 22:48:11 +00:00
package modweb
import (
2020-11-16 22:48:58 +00:00
"git.ddd.rip/ptrcnull/modweb/static"
2020-11-16 20:19:37 +00:00
"git.ddd.rip/ptrcnull/modweb/utils"
2020-11-11 22:48:11 +00:00
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/session"
2020-11-11 22:48:11 +00:00
"github.com/gofiber/template/html"
)
type App struct {
2020-12-23 11:53:56 +00:00
Config Config
modules map[string]Module
fiber *fiber.App
sessions *session.Store
authHandlers []AuthHandler
viewsFs *utils.JoinedFilesystem
homepage string
homepageHandlers []func(map[string]interface{})
2020-11-11 22:48:11 +00:00
}
2020-11-16 20:19:37 +00:00
func (app *App) data(ctx *fiber.Ctx, d fiber.Map) fiber.Map {
2020-11-11 22:48:11 +00:00
base := fiber.Map{
2020-11-16 20:19:37 +00:00
"app": app,
"modules": app.modules,
"auth": app.authHandlers,
2020-11-11 22:48:11 +00:00
}
for k, v := range d {
base[k] = v
}
sess, _ := app.sessions.Get(ctx)
2020-11-16 20:19:37 +00:00
if _, ok := sess.Get("user:id").(string); ok {
user := &User{}
user.Load(sess)
base["user"] = user
}
2020-11-11 22:48:11 +00:00
return base
}
func New(configs ...Config) *App {
2020-11-16 22:48:58 +00:00
viewsFs := utils.JoinedFS(static.HTTP)
2020-11-11 23:51:23 +00:00
views := html.NewFileSystem(viewsFs, ".html")
2020-11-16 20:19:37 +00:00
views.Reload(true)
2020-11-11 22:48:11 +00:00
app := &App{
2020-12-23 11:53:56 +00:00
fiber: fiber.New(fiber.Config{Views: views}),
sessions: session.New(),
modules: map[string]Module{},
viewsFs: viewsFs,
homepage: "homepage",
homepageHandlers: []func(map[string]interface{}){},
2020-11-11 22:48:11 +00:00
}
if len(configs) > 0 {
2020-11-16 20:19:37 +00:00
app.Config = configs[0]
2020-11-11 22:48:11 +00:00
}
app.fiber.Get("/", func(ctx *fiber.Ctx) error {
2020-12-23 11:53:56 +00:00
data := app.data(ctx, fiber.Map{
2020-11-11 22:48:11 +00:00
"title": "Homepage",
2020-12-23 11:53:56 +00:00
})
if app.homepageHandlers != nil && len(app.homepageHandlers) > 0 {
for _, fun := range app.homepageHandlers {
fun(data)
}
}
return ctx.Render(app.homepage, data, "layouts/main")
2020-11-11 22:48:11 +00:00
})
2020-11-16 20:19:37 +00:00
app.fiber.Get("/logout", func(ctx *fiber.Ctx) error {
store, _ := app.sessions.Get(ctx)
2020-11-16 20:19:37 +00:00
store.Destroy()
return ctx.Redirect("/")
})
2020-11-11 22:48:11 +00:00
return app
}
func (app *App) Register(module Module) {
app.modules[module.Name()] = module
2020-11-11 23:51:23 +00:00
module.Init(&ModuleManager{module, app})
2020-11-16 20:19:37 +00:00
if modAuth, ok := module.(AuthHandler); ok {
app.authHandlers = append(app.authHandlers, modAuth)
}
2020-11-11 22:48:11 +00:00
}
func (app *App) Run(addr string) error {
return app.fiber.Listen(addr)
}
2020-11-16 20:19:37 +00:00
func (app *App) AuthSupported() bool {
return len(app.authHandlers) > 0
}