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