modweb/manager.go

63 lines
1.5 KiB
Go
Raw Normal View History

2020-11-11 23:51:23 +00:00
package modweb
import (
2020-12-23 11:53:56 +00:00
"net/http"
2020-11-11 23:51:23 +00:00
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/session"
2020-11-11 23:51:23 +00:00
)
type ModuleManager struct {
module Module
2020-12-23 11:53:56 +00:00
app *App
2020-11-11 23:51:23 +00:00
}
func (mm *ModuleManager) RegisterViews(system http.FileSystem) {
2020-11-16 20:19:37 +00:00
mm.app.viewsFs.Register(mm.module.Name(), system)
2020-11-11 23:51:23 +00:00
}
func (mm *ModuleManager) Fiber(handlers ...fiber.Handler) fiber.Router {
2020-11-17 13:52:33 +00:00
handlers = append([]fiber.Handler{
func(ctx *fiber.Ctx) error {
min := mm.module.MinAccessLevel()
if min > 0 {
user := mm.User(ctx)
if user == nil || user.AccessLevel < min {
return ctx.Redirect("/")
}
}
return ctx.Next()
},
}, handlers...)
2020-12-23 11:53:56 +00:00
return mm.app.fiber.Group("/"+mm.module.Name()+"/", handlers...)
2020-11-11 23:51:23 +00:00
}
func (mm *ModuleManager) Render(ctx *fiber.Ctx, template string, data fiber.Map) error {
2020-12-23 11:53:56 +00:00
return ctx.Render(mm.module.Name()+"/"+template, mm.app.data(ctx, data), "layouts/main")
2020-11-11 23:51:23 +00:00
}
func (mm *ModuleManager) Session(ctx *fiber.Ctx) *session.Session {
sess, _ := mm.app.sessions.Get(ctx)
return sess
2020-11-11 23:51:23 +00:00
}
2020-11-16 20:19:37 +00:00
2020-11-17 13:52:33 +00:00
func (mm *ModuleManager) User(ctx *fiber.Ctx) *User {
sess := mm.Session(ctx)
2020-11-17 13:52:33 +00:00
if _, ok := sess.Get("user:id").(string); ok {
user := &User{}
user.Load(sess)
return user
}
return nil
}
2020-12-23 11:53:56 +00:00
func (mm *ModuleManager) SetHomepage(template string, handlers ...func(map[string]interface{})) {
2020-11-16 20:19:37 +00:00
mm.app.homepage = mm.module.Name() + "/" + template
2020-12-23 11:53:56 +00:00
mm.app.homepageHandlers = handlers
2020-11-16 20:19:37 +00:00
}
func (mm *ModuleManager) SetSessionConfig(config session.Config) {
mm.app.sessions = session.New(config)
}