2020-11-11 23:51:23 +00:00
|
|
|
package modweb
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/gofiber/fiber/v2"
|
2020-11-17 16:46:36 +00:00
|
|
|
"github.com/gofiber/fiber/v2/middleware/session"
|
2020-11-11 23:51:23 +00:00
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ModuleManager struct {
|
|
|
|
module Module
|
|
|
|
app *App
|
|
|
|
}
|
|
|
|
|
|
|
|
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-11-11 23:51:23 +00:00
|
|
|
return mm.app.fiber.Group("/" + mm.module.Name() + "/", handlers...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mm *ModuleManager) Render(ctx *fiber.Ctx, template string, data fiber.Map) error {
|
2020-11-16 20:19:37 +00:00
|
|
|
return ctx.Render(mm.module.Name() + "/" + template, mm.app.data(ctx, data), "layouts/main")
|
2020-11-11 23:51:23 +00:00
|
|
|
}
|
|
|
|
|
2020-11-17 16:46:36 +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 {
|
2020-11-17 16:46:36 +00:00
|
|
|
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-11-16 20:19:37 +00:00
|
|
|
func (mm *ModuleManager) SetHomepage(template string) {
|
|
|
|
mm.app.homepage = mm.module.Name() + "/" + template
|
|
|
|
}
|
2020-11-17 16:46:36 +00:00
|
|
|
|
|
|
|
func (mm *ModuleManager) SetSessionConfig(config session.Config) {
|
|
|
|
mm.app.sessions = session.New(config)
|
|
|
|
}
|