package routes import ( "bytes" "fmt" "log" "time" "git.phc.dm.unipi.it/phc/storage/config" "git.phc.dm.unipi.it/phc/storage/database" "git.phc.dm.unipi.it/phc/storage/utils" "github.com/gofiber/fiber/v2" ) func (r *Router) Api(api fiber.Router) { sessions := map[string]struct{}{} api.Post("/login", func(c *fiber.Ctx) error { var form struct { Password string `form:"password"` } if err := c.BodyParser(&form); err != nil { return err } if form.Password == config.AdminPassword { token := utils.GenerateRandomString(32) sessions[token] = struct{}{} c.Cookie(&fiber.Cookie{ Name: "sid", Value: token, Path: "/", Expires: time.Now().Add(3 * 24 * time.Hour), }) } return c.JSON("ok") }) api.Get("/status", func(c *fiber.Ctx) error { return c.JSON("ok") }) api.Get("/current-user", func(c *fiber.Ctx) error { if _, found := sessions[c.Cookies("sid")]; !found { return c.JSON("anonymous") } return c.JSON("admin") }) api.Get("/dashboard-state", func(c *fiber.Ctx) error { state, err := r.Database.GetDashboardState() if err != nil { return err } return c.JSON(state) }) api.Post("/dashboard-state", func(c *fiber.Ctx) error { if _, found := sessions[c.Cookies("sid")]; !found { return fmt.Errorf("invalid session token") } var state database.DashboardState if err := c.BodyParser(&state); err != nil { return err } if err := r.Database.SetDashboardState(state); err != nil { return err } return c.JSON("ok") }) api.Get("/buckets", func(c *fiber.Ctx) error { buckets, err := r.Database.AllBuckets() if err != nil { return err } return c.JSON(buckets) }) api.Post("/buckets", func(c *fiber.Ctx) error { var req struct { Bucket string `json:"bucket"` Path string `json:"path"` } log.Printf("%v", string(c.Body())) if err := c.BodyParser(&req); err != nil { return err } opts := []any{} if req.Path != "" { opts = append(opts, req.Path) } if err := r.Database.CreateBucket(req.Bucket, opts...); err != nil { return err } return c.JSON("ok") }) api.Get("/buckets/:bucket", func(c *fiber.Ctx) error { bucket := c.Params("bucket") objects, err := r.Database.AllBucketObjects(bucket) if err != nil { return err } return c.JSON(objects) }) api.Post("/buckets/:bucket", func(c *fiber.Ctx) error { bucket := c.Params("bucket") ff, err := c.FormFile("file") if err != nil { return err } mf, err := ff.Open() if err != nil { return err } id, err := r.Database.CreateBucketObject(bucket, mf) if err != nil { return err } return c.JSON(fiber.Map{ "bucket": bucket, "id": id, }) }) api.Get("/buckets/:bucket/:id", func(c *fiber.Ctx) error { bucket := c.Params("bucket") id := c.Params("id") buf := &bytes.Buffer{} if err := r.Database.GetBucketObject(bucket, id, buf); err != nil { return err } return c.SendStream(buf) }) }