implemented post management dashboard and started work on projects

This commit is contained in:
2024-06-02 00:58:11 +02:00
parent 8c56a9421e
commit a0a938021d
29 changed files with 969 additions and 595 deletions
+92
View File
@@ -0,0 +1,92 @@
'use server'
import { APIError, attemptAPIAction } from "@/util/api/error";
import { Auth, Post, PostTag, Tag, User } from "@/model/Models";
import { cookies } from "next/headers";
async function tryCreateAttachment(request: Request) {
// Make sure the DB is ready
await PostTag.sync();
await Tag.sync();
await Post.sync();
// Prepare data
const requestBody = await request.json();
const authCkie = await cookies().get("auth");
// Sanity check auth cookie
if ( !authCkie || !authCkie.value) throw new APIError({ status: 500, responseText: "missing auth cookie" });
// Get JSON from the Cookie
const cookieJSON = authCkie.value;
const authObject = JSON.parse(cookieJSON);
// Fetch User Auth from the database
const auth = await Auth.findOne({
include: [
{
model: User.withScope(['withPerms']),
attributes: {
exclude: ['username', 'password', 'updatedAt', 'createdAt']
}
}
],
where: { token: authObject.token }
});
// Sanity check the auth and associated user
if (!auth || !auth.user) throw new APIError({ status: 401, responseText: "Authentication Error" });
// Handle incomplete data or other problems
if (!requestBody) throw new APIError({ status: 500, responseText: "Empty request body" });
if (!requestBody.title) throw new APIError({ status: 500, responseText: "Missing post title" });
if (!requestBody.content) throw new APIError({ status: 500, responseText: "Missing post content" });
if (!auth.user.id) throw new APIError({ status: 500, responseText: "Missing user id" });
if (!auth.user.perms || !auth.user.perms.isAdmin) throw new APIError({ status: 401, responseText: `Unauthorized ${JSON.stringify(auth.user)}` });
// Create a new Post in the database
const post = await Post.create(
{
content: requestBody.content,
user_id: auth.user.id,
title: requestBody.title,
},{
include: {
association: Post.associations.user
}
}).then(post=>post.reload())
// Return the response
return new Response(JSON.stringify(post), { status: 200 });
}
export async function tryFetchAttachments(request: Request) {
await Post.sync();
const foundPosts = await Post.findAll({
include: [
{
association: Post.associations.user,
attributes: { exclude: ['password', 'createdAt', 'updatedAt'] }
},{
association: Post.associations.postTags
}]
});
return new Response(JSON.stringify(foundPosts), { status: 200 });
}
export async function GET(request: Request) {
return await attemptAPIAction(tryFetchAttachments,request);
}
export async function POST(request: Request) {
return await attemptAPIAction(tryCreateAttachment,request);
}