You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

143 lines
2.8 KiB
Go

3 years ago
package routes
import (
"encoding/json"
"log"
"time"
"github.com/aziis98/lupus-lite/handlers"
3 years ago
"github.com/gofiber/fiber/v2"
)
func ApiRoutes(r fiber.Router, h handlers.Handler) {
r.Get("/status", func(c *fiber.Ctx) error {
s, err := json.MarshalIndent(h.DebugDatabase(), "", " ")
3 years ago
if err != nil {
return err
}
log.Println(string(s))
return c.SendString("ok")
})
r.Post("/login", func(c *fiber.Ctx) error {
var form struct {
3 years ago
Username string `form:"username"`
Password string `form:"password"`
}
if err := c.BodyParser(&form); err != nil {
3 years ago
return err
}
token, err := h.Login(form.Username, form.Password)
3 years ago
if err != nil {
return err
}
c.Cookie(&fiber.Cookie{
Name: "sid",
Value: token,
Path: "/",
Expires: time.Now().Add(3 * 24 * time.Hour),
})
return c.Redirect("/")
})
r.Post("/logout",
func(c *fiber.Ctx) error {
c.Cookie(&fiber.Cookie{
Name: "sid",
Value: "",
Path: "/",
Expires: time.Now(),
})
return c.SendString("ok")
3 years ago
})
r.Post("/register",
func(c *fiber.Ctx) error {
var form struct {
Username string `form:"username"`
Password string `form:"password"`
Password2 string `form:"password2"`
}
3 years ago
if err := c.BodyParser(&form); err != nil {
return err
}
3 years ago
if err := h.Register(form.Username, form.Password, form.Password2); err != nil {
return err
}
3 years ago
return c.Redirect("/login")
})
3 years ago
r.Get("/user",
RequireLogged(h),
func(c *fiber.Ctx) error {
return c.JSON(requestUser(c).PublicUser())
})
3 years ago
r.Route("/partite", func(r fiber.Router) {
r.Use(RequireLogged(h))
3 years ago
ApiPartite(r, h.Partite())
3 years ago
})
}
func ApiPartite(r fiber.Router, p handlers.PartiteHandler) {
r.Get("/ws", BindWebsocketToEventBus(p.EventBus()))
3 years ago
r.Post("/", func(c *fiber.Ctx) error {
user := requestUser(c)
var form struct {
NumGiocatori int `form:"numero-giocatori"`
NumLupi int `form:"numero-lupi"`
NumFattucchiere int `form:"numero-fattucchiere"`
NumGuardie int `form:"numero-guardie"`
NumCacciatori int `form:"numero-cacciatori"`
NumMedium int `form:"numero-medium"`
NumVeggenti int `form:"numero-veggenti"`
}
if err := c.BodyParser(&form); err != nil {
return err
}
partita, err := p.Create(user.Username, handlers.PartitaConfig(form))
if err != nil {
return err
}
return c.JSON(partita)
})
r.Get("/:partita/players", func(c *fiber.Ctx) error {
partitaUid := c.Params("partita")
players, err := p.GetPlayers(partitaUid)
if err != nil {
return err
}
return c.JSON(players)
})
r.Get("/:partita/join", func(c *fiber.Ctx) error {
user := requestUser(c)
partitaUid := c.Params("partita")
if err := p.Join(partitaUid, user.Username); err != nil {
return err
}
return c.SendString("ok")
})
3 years ago
}