go-urlsh/internal/web/links.go

70 lines
1.8 KiB
Go
Raw Normal View History

package web
2023-04-28 18:24:09 +02:00
import (
"context"
"database/sql"
2023-04-28 18:24:09 +02:00
"fmt"
"log"
2024-05-04 17:06:01 +02:00
"code.lila.network/adoralaura/go-urlsh/internal/constants"
"code.lila.network/adoralaura/go-urlsh/internal/db"
"code.lila.network/adoralaura/go-urlsh/models"
"github.com/gofiber/fiber/v2"
2023-04-28 18:24:09 +02:00
)
2023-04-28 23:39:02 +02:00
func HandleAdminLinkNewGet(c *fiber.Ctx) error {
2024-05-04 17:06:01 +02:00
if !db.IsCookieValid(c.Cookies(constants.LoginCookieName, "")) {
2023-05-05 15:16:54 +02:00
c.Location("/admin/")
c.Status(fiber.StatusSeeOther)
return nil
}
return c.Render("add_link", nil)
}
2023-04-28 18:24:09 +02:00
func HandleAdminLinkEditGet(c *fiber.Ctx) error {
2024-05-04 17:06:01 +02:00
if !db.IsCookieValid(c.Cookies(constants.LoginCookieName, "")) {
c.Location("/admin/")
c.Status(fiber.StatusSeeOther)
return nil
}
var link = new(models.Link)
var id = c.Params("id", "")
if id == "" {
log.Println("[HandleAdminLinkEditGet] no id param given")
return fiber.NewError(fiber.StatusBadRequest, "400 Bad Request")
}
err := models.DB.NewSelect().Model(link).Where("id = ?", id).Scan(context.Background())
2023-04-28 18:24:09 +02:00
if err != nil {
if err == sql.ErrNoRows {
log.Printf("[HandleAdminLinkEditGet] Shortlink %v not found\n", id)
return fiber.NewError(fiber.StatusNotFound, "404 Not Found")
} else {
log.Printf("[HandleAdminLinkEditGet] Error querying Shortlink %v from database: %v\n", id, err)
return fiber.NewError(fiber.StatusInternalServerError, "500 Internal Server Error")
}
}
return c.Render("edit_link", link)
}
func HandleAdminLinkIndexGet(c *fiber.Ctx) error {
2024-05-04 17:06:01 +02:00
if !db.IsCookieValid(c.Cookies(constants.LoginCookieName, "")) {
c.Location("/admin/login")
c.Status(fiber.StatusSeeOther)
return nil
} else {
var links []models.Link
err := models.DB.NewSelect().Model(&links).Scan(context.Background())
if err != nil {
return fmt.Errorf("error querying links: %v", err.Error())
}
return c.Render("links", links)
2023-04-28 18:24:09 +02:00
}
}