diff options
Diffstat (limited to 'pages/api/v2/admin/broadcast/index.js')
| -rw-r--r-- | pages/api/v2/admin/broadcast/index.js | 54 |
1 files changed, 44 insertions, 10 deletions
diff --git a/pages/api/v2/admin/broadcast/index.js b/pages/api/v2/admin/broadcast/index.js index d3d3af0..470d61d 100644 --- a/pages/api/v2/admin/broadcast/index.js +++ b/pages/api/v2/admin/broadcast/index.js @@ -1,9 +1,17 @@ import { rateLimitStrict, redis } from "@/lib/redis"; -// import { getServerSession } from "next-auth"; -// import { authOptions } from "pages/api/auth/[...nextauth]"; +import { getServerSession } from "next-auth"; +import { authOptions } from "pages/api/auth/[...nextauth]"; export default async function handler(req, res) { // Check if the custom header "X-Your-Custom-Header" is present and has a specific value + const sessions = await getServerSession(req, res, authOptions); + + const admin = sessions?.user?.name === process.env.ADMIN_USERNAME; + // if req.method === POST and admin === false return 401 + if (!admin && req.method === "DELETE") { + return res.status(401).json({ message: "Unauthorized" }); + } + const customHeaderValue = req.headers["x-broadcast-key"]; if (customHeaderValue !== "get-broadcast") { @@ -21,14 +29,40 @@ export default async function handler(req, res) { }); } - const getId = await redis.get(`broadcast`); - if (getId) { - const broadcast = JSON.parse(getId); - return res - .status(200) - .json({ message: broadcast.message, startAt: broadcast.startAt }); - } else { - return res.status(200).json({ message: "No broadcast" }); + if (req.method === "POST") { + const { message, startAt = undefined, show = false } = req.body; + if (!message) { + return res.status(400).json({ message: "Message is required" }); + } + + const broadcastContent = { + message, + startAt, + show, + }; + await redis.set(`broadcasts`, JSON.stringify(broadcastContent)); + return res.status(200).json({ message: "Broadcast created" }); + } else if (req.method === "DELETE") { + const br = await redis.get(`broadcasts`); + // set broadcast show as false + if (br) { + const broadcast = JSON.parse(br); + broadcast.show = false; + await redis.set(`broadcasts`, JSON.stringify(broadcast)); + } + return res.status(200).json({ message: "Broadcast deleted" }); + } else if (req.method === "GET") { + const getId = await redis.get(`broadcasts`); + if (getId) { + const broadcast = JSON.parse(getId); + return res.status(200).json({ + message: broadcast.message, + startAt: broadcast.startAt, + show: broadcast.show, + }); + } else { + return res.status(200).json({ message: "No broadcast" }); + } } } |