From 95b138f29e2fe7b0ce301cf9988165bf5fc8700f Mon Sep 17 00:00:00 2001
From: Archie
Date: Fri, 6 Nov 2026 10:02:29 +0000
Subject: [PATCH] committing summative
---
.env.example | 6 +
.gitignore | 12 +
README.md | 25 +
app/(auth)/layout.tsx | 11 +
app/(auth)/login/AuthLoginForm.tsx | 95 +
app/(auth)/login/SigninButton.tsx | 24 +
app/(auth)/login/page.tsx | 60 +
app/(auth)/register/page.tsx | 124 +
app/actions/GoogleAction.ts | 19 +
app/actions/NewsletterActions.ts | 276 ++
app/actions/UserAction.ts | 72 +
app/api/auth/[...nextauth]/route.ts | 2 +
app/api/auth/register/route.ts | 59 +
app/components/ExternalNewsletters.tsx | 62 +
app/components/NavBar.tsx | 69 +
app/components/Providers.tsx | 12 +
app/components/navbarData.tsx | 28 +
app/dashboard/CreateNewsletterFrom.tsx | 119 +
app/dashboard/[id]/EditNewsletterForm.tsx | 124 +
app/dashboard/[id]/loading.tsx | 7 +
app/dashboard/[id]/page.tsx | 29 +
app/dashboard/loading.tsx | 7 +
app/dashboard/page.tsx | 165 +
app/globals.css | 3 +-
app/layout.tsx | 21 +-
app/lib/auth.ts | 14 +
app/lib/client/register.ts | 39 +
app/lib/prisma.ts | 20 +
app/newsletters/[id]/loading.tsx | 7 +
app/newsletters/[id]/page.tsx | 37 +
app/newsletters/loading.tsx | 7 +
app/newsletters/page.tsx | 68 +
app/page.tsx | 76 +-
app/users/loading.tsx | 6 +
app/users/page.tsx | 108 +
auth.ts | 106 +
next.config.ts | 2 +-
package-lock.json | 3958 +++++++++++++++++----
package.json | 22 +-
prisma/schema.prisma | 54 +
prisma/seed.ts | 61 +
prisma7.config.ts | 14 +
proxy.ts | 42 +
tsconfig.json | 2 +-
44 files changed, 5319 insertions(+), 755 deletions(-)
create mode 100644 .env.example
create mode 100644 app/(auth)/layout.tsx
create mode 100644 app/(auth)/login/AuthLoginForm.tsx
create mode 100644 app/(auth)/login/SigninButton.tsx
create mode 100644 app/(auth)/login/page.tsx
create mode 100644 app/(auth)/register/page.tsx
create mode 100644 app/actions/GoogleAction.ts
create mode 100644 app/actions/NewsletterActions.ts
create mode 100644 app/actions/UserAction.ts
create mode 100644 app/api/auth/[...nextauth]/route.ts
create mode 100644 app/api/auth/register/route.ts
create mode 100644 app/components/ExternalNewsletters.tsx
create mode 100644 app/components/NavBar.tsx
create mode 100644 app/components/Providers.tsx
create mode 100644 app/components/navbarData.tsx
create mode 100644 app/dashboard/CreateNewsletterFrom.tsx
create mode 100644 app/dashboard/[id]/EditNewsletterForm.tsx
create mode 100644 app/dashboard/[id]/loading.tsx
create mode 100644 app/dashboard/[id]/page.tsx
create mode 100644 app/dashboard/loading.tsx
create mode 100644 app/dashboard/page.tsx
create mode 100644 app/lib/auth.ts
create mode 100644 app/lib/client/register.ts
create mode 100644 app/lib/prisma.ts
create mode 100644 app/newsletters/[id]/loading.tsx
create mode 100644 app/newsletters/[id]/page.tsx
create mode 100644 app/newsletters/loading.tsx
create mode 100644 app/newsletters/page.tsx
create mode 100644 app/users/loading.tsx
create mode 100644 app/users/page.tsx
create mode 100644 auth.ts
create mode 100644 prisma/schema.prisma
create mode 100644 prisma/seed.ts
create mode 100644 prisma7.config.ts
create mode 100644 proxy.ts
diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..fc4f842
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,6 @@
+DATABASE_URL=
+AUTH_SECRET=
+AUTH_GOOGLE_ID=
+AUTH_GOOGLE_SECRET=
+ENFORCEADMIN=
+SEED_ACCOUNT_PASSWORD=
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index 5ef6a52..4077f37 100644
--- a/.gitignore
+++ b/.gitignore
@@ -32,6 +32,18 @@ yarn-error.log*
# env files (can opt-in for committing if needed)
.env*
+!.env.example
+
+# ai stuff
+/.agents/
+/.claude/
+/.windsurf/
+/skills-lock.json
+
+
+# regenerated by setup commands
+/lib/generated/prisma/
+/generated/prisma
# vercel
.vercel
diff --git a/README.md b/README.md
index e215bc4..3f31f63 100644
--- a/README.md
+++ b/README.md
@@ -34,3 +34,28 @@ You can check out [the Next.js GitHub repository](https://github.com/vercel/next
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
+
+# CMS README - Archie McCulloch
+
+### Setup Instructions
+- copy `.env.example` to `.env` and fill in values
+- ENFORCEADMIN is checked against "true" to determine whether to expose /users
+
+- `npm install`
+- `npx prisma validate --config ./prisma7.config.ts`
+- `npx prisma migrate dev --name init --config prisma7.config.ts`
+- `npx prisma generate --config prisma7.config.ts`
+- `npx tsx prisma/seed.ts`
+- `npm run dev`
+- seeded login details: "seededTest@test.test" + password defined in .env
+-
+
+### Authentication Approach
+- Registation is done by a custom registration endpoint that creates uses in the database with hashed passwords using bcrypt
+- Email and passwod login is done with Auth.js Credentials provider which check against stored user and password hash
+- Google login is done with Auth.js Google provider, a database account is created if not already existing linked to their Google account by their Google ID
+- Routes access control is controlled by the proxy
+- Newsletter actions check for ownership using logged in user's ID
+- Auth.js signOut() endpoint clears the session and redirects to login page
+- Front end uses SessionProvider to gain access to session data which is fed by Auth.js
+- Auth.js uses JWT to store session information with http only cookies, a callback is used to append user.id to session
diff --git a/app/(auth)/layout.tsx b/app/(auth)/layout.tsx
new file mode 100644
index 0000000..b410880
--- /dev/null
+++ b/app/(auth)/layout.tsx
@@ -0,0 +1,11 @@
+export default function AuthLayout({ children }: { children: React.ReactNode }) {
+ return (
+
+ )
+ }
\ No newline at end of file
diff --git a/app/(auth)/login/AuthLoginForm.tsx b/app/(auth)/login/AuthLoginForm.tsx
new file mode 100644
index 0000000..21ca08e
--- /dev/null
+++ b/app/(auth)/login/AuthLoginForm.tsx
@@ -0,0 +1,95 @@
+"use client"
+
+import { signIn } from "next-auth/react"; // client function
+import { useState } from "react";
+import { useRouter } from "next/navigation";
+import Link from "next/link";
+
+export default function AuthLoginForm() {
+ const [email, setEmail] = useState("");
+ const [password, setPassword] = useState("");
+ const [error, setError] = useState("");
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const router = useRouter();
+
+ const handleSubmit = async (e: React.SubmitEvent) => { // event object from form element
+ e.preventDefault(); // stops default submission to send through the js instead
+ setError(""); // clear state
+ setIsSubmitting(true);
+
+ try {
+ const res = await signIn("credentials", { // sends to auth.js server endpoint selecting credentials provider and supplies obj argument which it passes into authorize function, returns the user
+ email,
+ password,
+ redirect: false, // prevents auto redirect
+ });
+
+ if (res.error || !res) {
+ setError("Sign in failed");
+ } else {
+ router.push("/"); // if signin function doesnt error
+ }
+ } catch {
+ setError("Unable to sign in. Please try again.")
+ } finally {
+ setIsSubmitting(false);
+ }
+
+ }
+
+ return (
+ <>
+
+ OR
+
+ Don't have an account?{" "}
+
+ Sign Up
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/app/(auth)/login/SigninButton.tsx b/app/(auth)/login/SigninButton.tsx
new file mode 100644
index 0000000..a010cba
--- /dev/null
+++ b/app/(auth)/login/SigninButton.tsx
@@ -0,0 +1,24 @@
+export default function SigninButton({
+ text,
+ style,
+ callback,
+ formAction
+}: {
+ text: string;
+ style: string;
+ callback?: () => void;
+ formAction?: any;
+}) {
+ return (
+
+
+ {text}
+
+
+ );
+};
\ No newline at end of file
diff --git a/app/(auth)/login/page.tsx b/app/(auth)/login/page.tsx
new file mode 100644
index 0000000..a33a36e
--- /dev/null
+++ b/app/(auth)/login/page.tsx
@@ -0,0 +1,60 @@
+"use client";
+
+import { Suspense, useState, useEffect } from "react";
+import AuthLoginForm from "./AuthLoginForm"
+import SigninButton from "./SigninButton";
+import { handleGoogleLogin } from "@/app/actions/GoogleAction";
+import { useSearchParams } from "next/navigation";
+
+function LoginContent() {
+ const [elogin, setElogin] = useState(false);
+ const showEmailLogin = () => { // lets you toggle on and off showEmailLogin which is used to decide if the authloginform is shown
+ setElogin(!elogin);
+ };
+
+ const searchParams = useSearchParams();
+ const isJustRegisted = searchParams.get("registered") === "true"; // if redirected with reigstered = true
+
+ useEffect(() => {
+ if (isJustRegisted) {
+ setElogin(true);
+ }
+ }, [isJustRegisted]);
+
+ return (
+ <>
+ Please Sign In
+
+
+
+
+
+ >
+ )
+}
+
+export default function LoginPage() { // displays fallback while url dependent content loads (searchparams), errors if it tries to prepare page in advance
+ return (
+ <>
+ Loading login..
}>
+
+
+ >
+
+ );
+}
\ No newline at end of file
diff --git a/app/(auth)/register/page.tsx b/app/(auth)/register/page.tsx
new file mode 100644
index 0000000..af7fab0
--- /dev/null
+++ b/app/(auth)/register/page.tsx
@@ -0,0 +1,124 @@
+'use client';
+
+import Link from "next/link";
+import { useState, useEffect } from "react";
+import { register } from "../../lib/client/register";
+import { useRouter } from "next/navigation"
+
+export default function RegisterPage() {
+ const [name, setName] = useState(""); // creating state objects and getting setters
+ const [email, setEmail] = useState("");
+ const [password, setPassword] = useState("");
+ const [confirmPassword, setConfirmPassword] = useState("");
+ const [error, setError] = useState("");
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const router = useRouter();
+
+ const handleSubmit = async (e: React.SubmitEvent) => { // event object from form element
+ e.preventDefault(); // stops default submission to send through the js instead
+ setError(""); // clear state
+
+ if (password !== confirmPassword) {
+ setError("Passwords do not match")
+ return;
+ }
+
+ if (password.length < 16 || password === password.toLowerCase() || password === password.toUpperCase()) { // rejects password if its not 16+ characters or if its all in the same case
+ setError("Password must be at least 16 characters and a mix of lower and upper case. To keep your account secure also include special characters and dont use predictable phrases.")
+ return;
+ }
+
+ setIsSubmitting(true); // once password is valid
+
+ try {
+ await register({ email, password, name })
+ router.push("/login?registered=true")
+ } catch (error) {
+ setError(error instanceof Error ? error.message : "Registration failed")
+ } finally {
+ setIsSubmitting(false);
+ }
+ }
+
+ // useEffect(() => { // on page load
+ // if (!isLoading && isAuthenticated) {
+ // router.push("/")
+ // }
+ // },[isLoading, isAuthenticated, router])
+
+ return (
+ <>
+
+ Create Account
+
+ >
+ )
+};
diff --git a/app/actions/GoogleAction.ts b/app/actions/GoogleAction.ts
new file mode 100644
index 0000000..01b6429
--- /dev/null
+++ b/app/actions/GoogleAction.ts
@@ -0,0 +1,19 @@
+"use server";
+
+import { auth, signIn, signOut } from "@/auth";
+
+export async function handleGoogleLogin() {
+ await signIn("google", {redirectTo: "/"})
+
+}
+
+export async function checkGoogleSession() {
+ const session = await auth();
+ return session;
+}
+
+export async function handleGoogleLogout() {
+ await signOut({redirectTo: "/login"})
+}
+
+// creates our functions to check session, login, logout using functions we exported from auth's nextauth functions
\ No newline at end of file
diff --git a/app/actions/NewsletterActions.ts b/app/actions/NewsletterActions.ts
new file mode 100644
index 0000000..bc9e036
--- /dev/null
+++ b/app/actions/NewsletterActions.ts
@@ -0,0 +1,276 @@
+"use server";
+
+import { prisma } from "../lib/prisma";
+import { revalidatePath } from "next/cache";
+import { auth } from "@/auth";
+import { NewsletterStatus } from "@/lib/generated/prisma/enums";
+
+async function getAuthorId() {
+ const session = await auth(); // returns valid session object
+
+ if (!session?.user?.id) { // if no session, user, or id
+ throw new Error("You must be logged in");
+ }
+
+ return session.user.id;
+}
+
+export async function getPubNewsletters() {
+ return await prisma.newsletters.findMany({
+ where: {
+ status: "Sent",
+ },
+ orderBy: {
+ createdAt: "desc",
+ },
+ include: { // includes author
+ author: {
+ select: {
+ name: true, // only takes authors name not private info
+ },
+ },
+ },
+ });
+}
+
+export async function getPubNewsletter(id: string) { // single pub newsletter
+ return await prisma.newsletters.findUnique({
+ where: {
+ id,
+ status: "Sent",
+ },
+ include: {
+ author: {
+ select: {
+ name: true,
+ },
+ },
+ },
+ });
+}
+
+export async function getUserNewsletters() {
+
+ const authorID = await getAuthorId();
+
+ return await prisma.newsletters.findMany({
+ where: {
+ authorID,
+ },
+ orderBy: {
+ createdAt: "desc", // newest first
+ },
+ include: { // includes author
+ author: {
+ select: {
+ name: true, // only takes authors name not private info
+ },
+ },
+ },
+ });
+}
+
+export async function getUserNewsletter(id: string) {
+ const authorID = await getAuthorId();
+
+ return await prisma.newsletters.findUnique({
+ where: {
+ id,
+ authorID,
+ },
+ });
+}
+
+export async function publishNewsletter(id: string) {
+ try {
+ const authorID = await getAuthorId();
+
+ const newsletter = await prisma.newsletters.update({
+ where: {
+ id,
+ authorID, // if it was called with a post id that doesnt belong to that author it wont be found
+ },
+ data: {
+ status: "Sent",
+ },
+ });
+
+ revalidatePath("/dashboard");
+ revalidatePath("/newsletters");
+ revalidatePath(`/newsletters/${id}`);
+ revalidatePath(`/dashboard/${id}`);
+
+ return { success: true, newsletter };
+ } catch (error) {
+ console.error("Error publishing newsletter:", error);
+ return { success: false, error: "Failed to publish newsletter" };
+ }
+}
+
+export async function unPublishNewsletter(id: string) {
+ try {
+ const authorID = await getAuthorId();
+
+ const newsletter = await prisma.newsletters.update({
+ where: {
+ id,
+ authorID, // if it was called with a post id that doesnt belong to that author it wont be found
+ },
+ data: {
+ status: "Draft",
+ },
+ });
+
+ revalidatePath("/dashboard");
+ revalidatePath("/newsletters");
+ revalidatePath(`/newsletters/${id}`);
+ revalidatePath(`/dashboard/${id}`);
+
+ return { success: true, newsletter };
+ } catch (error) {
+ console.error("Error unpublishing newsletter:", error);
+ return { success: false, error: "Failed to unpublish newsletter" };
+ }
+}
+
+export async function scheduleNewsletter(id: string) {
+ try {
+ const authorID = await getAuthorId();
+
+ const newsletter = await prisma.newsletters.update({
+ where: {
+ id,
+ authorID, // if it was called with a post id that doesnt belong to that author it wont be found
+ },
+ data: {
+ status: "Schedule",
+ },
+ });
+
+ revalidatePath("/dashboard");
+ revalidatePath("/newsletters");
+ revalidatePath(`/newsletters/${id}`);
+ revalidatePath(`/dashboard/${id}`);
+
+ return { success: true, newsletter };
+ } catch (error) {
+ console.error("Error publishing newsletter:", error);
+ return { success: false, error: "Failed to publish newsletter" };
+ }
+}
+
+// export async function likeNewsletter(id: string) {
+// try {
+// const authorID = await getAuthorId();
+
+// const newsletter = await prisma.newsletters.update({
+// where: {
+// id,
+// authorID, // if it was called with a post id that doesnt belong to that author it wont be found
+// },
+// data: {
+// status: "Sent",
+// },
+// });
+
+// revalidatePath("/dashboard");
+// revalidatePath("/newsletters");
+// revalidatePath(`/newsletters/${id}`);
+// revalidatePath(`/dashboard/${id}`);
+
+// return { success: true, newsletter };
+// } catch (error) {
+// console.error("Error publishing newsletter:", error);
+// return { success: false, error: "Failed to publish newsletter" };
+// }
+// }
+
+export async function addNewsletter(data: {
+ title: string;
+ imageUrl: string;
+ content: string;
+}
+) {
+ try {
+ const authorID = await getAuthorId();
+
+ const newNewsletter = await prisma.newsletters.create({
+ data: {
+ title: data.title.trim(),
+ imageUrl: data.imageUrl.trim(),
+ content: data.content, // keep spaces
+ authorID,
+ }
+ })
+
+ revalidatePath("/newsletters");
+ revalidatePath("/dashboard");
+
+ return { success: true, newsletter: newNewsletter };
+ } catch (error) {
+ console.error("Error adding newsletter:", error);
+ return { success: false, error: "Failed to add newsletter" };
+ }
+
+}
+
+export async function editNewsletter(
+ id: string,
+ data: {
+ title: string;
+ imageUrl: string;
+ content: string;
+ },
+) {
+ try {
+ const authorID = await getAuthorId();
+
+ const updatedNewsletter = await prisma.newsletters.update({
+ where: {
+ id, // find target newsletter
+ authorID, // thats also owned by current session owner
+ status: {
+ not: "Sent"
+ }
+ },
+ data: {
+ title: data.title.trim(),
+ imageUrl: data.imageUrl.trim(),
+ content: data.content,
+ },
+ });
+
+ revalidatePath("/newsletters");
+ revalidatePath("/dashboard");
+ revalidatePath(`/newsletters/${id}`);
+ revalidatePath(`/dashboard/${id}`);
+
+ return { success: true, newsletter: updatedNewsletter };
+ } catch (error) {
+ console.error("Error editing newsletter:", error);
+ return { success: false, error: "Failed to edit newsletter" };
+ }
+}
+
+export async function removeNewsletter(id: string) {
+ try {
+ const authorID = await getAuthorId();
+
+ const deletedNewsletter = await prisma.newsletters.delete({
+ where: {
+ id,
+ authorID,
+ },
+ });
+
+ revalidatePath("/newsletters");
+ revalidatePath("/dashboard");
+ revalidatePath(`/newsletters/${id}`);
+ revalidatePath(`/dashboard/${id}`);
+
+ return { success: true, newsletter: deletedNewsletter };
+ } catch (error) {
+ console.error("Error deleting newsletter:", error);
+ return { success: false, error: "Failed to delete newsletter" };
+ }
+}
\ No newline at end of file
diff --git a/app/actions/UserAction.ts b/app/actions/UserAction.ts
new file mode 100644
index 0000000..4c16045
--- /dev/null
+++ b/app/actions/UserAction.ts
@@ -0,0 +1,72 @@
+"use server";
+
+import { prisma } from "../lib/prisma";
+import { revalidatePath } from "next/cache";
+
+export async function addUser(data: {
+ name?: string;
+ email: string;
+ pass: string;
+}) {
+ try {
+ const newUser = await prisma.users.create({ // creates a new user from parameter object data
+ data: {
+ name: data.name,
+ email: data.email,
+ passwordHash: data.pass,
+ },
+ });
+ revalidatePath("/users"); // next function informs changes made to page so refreshes cached data
+ return { success: true, user: newUser }; // returns object containing status and object returned from prisma.users.create
+ } catch (error) { // if it fails return error
+ console.error("Error adding user:", error);
+ return { success: false, error: "Failed to add user" };
+ }
+}
+
+export async function editUser(
+ id: string,
+ data: {
+ name?: string;
+ email?: string;
+ pass?: string;
+ },
+) {
+ try {
+ const updatedUser = await prisma.users.update({
+ where: { id }, // shorthand for where: { id: id } - finds user by id in table matching id parameter
+ data: {
+ ...(data.name && { name: data.name }), // if data.name exists then update name to data.name
+ ...(data.email && { email: data.email }), // likely as prisma cant update a field with an object it must be a property value of data object
+ ...(data.pass && { passwordHash: data.pass }), //. if data.name is empty (false) the expression is false and spread will crteate an empty object which will not update the name field in the database
+ },
+ });
+
+ revalidatePath("/users");
+ return { success: true, user: updatedUser };
+ } catch (error) {
+ console.error("Error editing user:", error);
+ return { success: false, error: "Failed to edit user" };
+ }
+}
+
+export async function removeUser(id: string) { // this should be clear from the above explanations
+ try {
+ const deletedUser = await prisma.users.delete({
+ where: { id },
+ });
+ revalidatePath("/users");
+ revalidatePath("/newsletters");
+ revalidatePath("/dashboard");
+ return { success: true, user: deletedUser };
+ } catch (error) {
+ console.error("Error deleting user:", error);
+ return { success: false, error: "Failed to delete user" };
+ }
+}
+
+export async function getUsers() {
+ return await prisma.users.findMany({
+ orderBy: { createdAt: "desc" } // changed from lab code as my id's are string - newest first
+ }); // returns all users in the table in descending order of id
+}
diff --git a/app/api/auth/[...nextauth]/route.ts b/app/api/auth/[...nextauth]/route.ts
new file mode 100644
index 0000000..0eebb94
--- /dev/null
+++ b/app/api/auth/[...nextauth]/route.ts
@@ -0,0 +1,2 @@
+import { handlers } from "@/auth"
+export const { GET, POST } = handlers
\ No newline at end of file
diff --git a/app/api/auth/register/route.ts b/app/api/auth/register/route.ts
new file mode 100644
index 0000000..96d8e7e
--- /dev/null
+++ b/app/api/auth/register/route.ts
@@ -0,0 +1,59 @@
+import { NextRequest, NextResponse } from "next/server";
+import { prisma } from "../../../lib/prisma";
+import { hashPassword } from "../../../lib/auth";
+
+export async function POST(request: NextRequest) { // handles post request to /api/auth/register endpoint
+ try {
+ const body = await request.json(); // converts json req to obj, request.json reads only the req body
+ const { email, password, name } = body; // breaks down the body obj into variables
+
+ if (!email || !password) { // checks required variables
+ return NextResponse.json(
+ { error: "Email and password are required" },
+ { status: 400 }
+ )
+ };
+
+ const existingUser = await prisma.users.findUnique({ // checks whether that email is already registered
+ where: { email }
+ });
+
+ if (existingUser) {
+ return NextResponse.json(
+ { error: "User with this email already exists" },
+ { status: 409 }
+ )
+ }
+
+ const hashedPassword = await hashPassword(password);
+ const user = await prisma.users.create({ // creates new user with hashed password
+ data: {
+ email,
+ passwordHash: hashedPassword,
+ name
+ }
+ });
+
+ const response = NextResponse.json( // crafts the response with a message and user obj thats just been added
+ {
+ message: "User reigseted successfully",
+ user: {
+ id: user.id,
+ email: user.email,
+ name: user.name
+ }
+ },
+ { status: 201}
+ );
+
+ return response; // returns the crafted response
+
+ } catch (error) {
+ console.error("Registration error:", error);
+ return NextResponse.json(
+ { error: "Internal server error" },
+ { status: 500 }
+ );
+ }
+
+}
diff --git a/app/components/ExternalNewsletters.tsx b/app/components/ExternalNewsletters.tsx
new file mode 100644
index 0000000..a8ec8b9
--- /dev/null
+++ b/app/components/ExternalNewsletters.tsx
@@ -0,0 +1,62 @@
+type ExternalNewsletter = {
+ title: string;
+ description: string;
+ url: string;
+};
+
+export default async function ExternalNewsletters() {
+ try {
+ const response = await fetch(
+ "https://us-rse.org/api/newsletters.json", // can go to url to see the response body
+ {
+ signal: AbortSignal.timeout(5000), // errors after 5s to stop loading and go to catch
+ }
+ );
+
+ const numNewsletters = 5; // probably dont want a massively page I also dk how many newsletters the api is gonna return
+
+ if (!response.ok) { // display status if not succeeded
+ throw new Error(`Feed request failed: ${response.status}`);
+ }
+
+ const newsletters: ExternalNewsletter[] = await response.json(); // converts api response body into a list of objects of our type
+ return (
+
+
+ {/* I am assuming when I pick the first five its the latest 5 */}
+ Latest from US-RSE
+
+
+
+
+ );
+ } catch (error) {
+ console.error("External newsletter feed failed:", error);
+
+ return (
+
+ This source is currently unavailable.
+
+ );
+ }
+}
\ No newline at end of file
diff --git a/app/components/NavBar.tsx b/app/components/NavBar.tsx
new file mode 100644
index 0000000..c84e837
--- /dev/null
+++ b/app/components/NavBar.tsx
@@ -0,0 +1,69 @@
+"use client";
+
+import {Links} from "./navbarData";
+import Link from "next/link";
+import { usePathname } from "next/navigation";
+import { useSession, signOut } from "next-auth/react";
+
+export default function NavBar( { enforceAdmin } : { enforceAdmin: boolean; } ) {
+ const pathname = usePathname();
+ const { data: session} = useSession();
+ const visibleLinks = Links.filter( // check each link
+ (link) => (link.url !== "/dashboard" || session?.user) && (link.url !== "/users" || !enforceAdmin)
+ // keep link if its not dashboard or if theres a session (logged in) (only keep dashboard if logged in)
+ // and keep link if its not users or if enforceadmin is false
+ );
+
+ return (
+
+
+
+
+
+ {visibleLinks.map((link) => ( // below highlights the active link
+
+ {link.text}
+
+ ))}
+
+
+
Secure CMS
+
+
+
+ {visibleLinks.map((link) => (
+
+ {link.text}
+
+ ))}
+
+
+
+ {session?.user ? (
+ <>
+ {session.user.name || session.user.email || "Account"}
+ signOut({ redirectTo: "/login" })}>
+ Logout
+
+ >
+ ) : (
+ <>
+
+ Login
+
+
+ Sign Up
+
+ >
+ )}
+
+
+
+
+ );
+}
+
diff --git a/app/components/Providers.tsx b/app/components/Providers.tsx
new file mode 100644
index 0000000..48bfc9f
--- /dev/null
+++ b/app/components/Providers.tsx
@@ -0,0 +1,12 @@
+"use client";
+
+import { SessionProvider } from "next-auth/react";
+
+export function Providers({ children }: { children: React.ReactNode }) {
+ return (
+ {children}
+
+ )
+}
+
+// surrounds page content to give children access to auth context and functions
\ No newline at end of file
diff --git a/app/components/navbarData.tsx b/app/components/navbarData.tsx
new file mode 100644
index 0000000..22e9e8b
--- /dev/null
+++ b/app/components/navbarData.tsx
@@ -0,0 +1,28 @@
+interface Link {
+ id: number;
+ url: string;
+ text: string;
+}
+
+export const Links: Link[] = [
+ {
+ id: 1,
+ url: "/",
+ text: "Home",
+ },
+ {
+ id: 2,
+ url: "/users",
+ text: "Users",
+ },
+ {
+ id: 3,
+ url: "/dashboard",
+ text: "Dashboard",
+ },
+ {
+ id: 4,
+ url: "/newsletters",
+ text: "Newsletters",
+ },
+]
\ No newline at end of file
diff --git a/app/dashboard/CreateNewsletterFrom.tsx b/app/dashboard/CreateNewsletterFrom.tsx
new file mode 100644
index 0000000..c7da254
--- /dev/null
+++ b/app/dashboard/CreateNewsletterFrom.tsx
@@ -0,0 +1,119 @@
+"use client"
+
+import { addNewsletter, } from "@/app/actions/NewsletterActions";
+import { useState } from "react";
+import { useRouter } from "next/navigation"
+
+export default function CreateNewsletterForm() {
+ const [title, setTitle] = useState("");
+ const [imageUrl, setImageUrl] = useState("");
+ const [content, setContent] = useState("");
+ const [error, setError] = useState("");
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const [isCreated, setIsCreated] = useState(false);
+
+ const router = useRouter();
+
+ const handleSubmit = async (e: React.SubmitEvent) => {
+ e.preventDefault(); // stops default submission to send through the js instead
+ setError(""); // clear state
+ setIsSubmitting(true);
+ setIsCreated(false)
+
+ try {
+ if (
+ typeof title !== "string" ||
+ typeof imageUrl !== "string" ||
+ typeof content !== "string" ||
+ !title.trim() ||
+ !content.trim()
+ ) {
+ throw new Error("Please provide a title and content");
+ }
+
+ const result = await addNewsletter({
+ title,
+ imageUrl,
+ content,
+ });
+
+ if (!result.success) {
+ throw new Error(result.error);
+ } else {
+ setTitle("");
+ setContent("");
+ setImageUrl("");
+ setIsCreated(true)
+
+ // if (result.newsletter) { router.push(`/dashboard/${result.newsletter.id}`); };
+ }
+ } catch {
+ setError("Unable to create newsletter. Please try again.")
+ } finally {
+ setIsSubmitting(false);
+ }
+
+ }
+
+ return (
+
+ )
+}
\ No newline at end of file
diff --git a/app/dashboard/[id]/EditNewsletterForm.tsx b/app/dashboard/[id]/EditNewsletterForm.tsx
new file mode 100644
index 0000000..e460e7e
--- /dev/null
+++ b/app/dashboard/[id]/EditNewsletterForm.tsx
@@ -0,0 +1,124 @@
+"use client";
+
+import { editNewsletter } from "@/app/actions/NewsletterActions";
+import { NewsletterStatus } from "@/lib/generated/prisma/enums";
+import { useState } from "react";
+import { useRouter } from "next/navigation"
+
+type EditableNewsletter = {
+ id: string;
+ title: string;
+ imageUrl: string;
+ content: string;
+};
+
+export default function EditNewsletterForm({ newsletter } : { newsletter: EditableNewsletter }) {
+ const [title, setTitle] = useState(newsletter.title);
+ const [imageUrl, setImageUrl] = useState(newsletter.imageUrl);
+ const [content, setContent] = useState(newsletter.content);
+
+ const [error, setError] = useState("");
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const [isSaved, setIsSaved] = useState(false);
+
+ const router = useRouter();
+
+ const handleSubmit = async (e: React.SubmitEvent) => {
+ e.preventDefault(); // stops default submission to send through the js instead
+ setError(""); // clear state
+ setIsSubmitting(true);
+ setIsSaved(false)
+
+ try {
+ if (
+ typeof title !== "string" ||
+ typeof imageUrl !== "string" ||
+ typeof content !== "string" ||
+ !title.trim() ||
+ !content.trim()
+ ) {
+ throw new Error("Please provide a title and content");
+ }
+
+ const result = await editNewsletter(newsletter.id, {
+ title,
+ imageUrl,
+ content,
+ });
+
+ if (!result.success) {
+ throw new Error(result.error);
+ }
+
+ setIsSaved(true);
+
+ } catch {
+ setError("Unable to update newsletter. Please try again.")
+ } finally {
+ setIsSubmitting(false);
+ }
+
+ }
+
+ return (
+
+ {error && (
+
+ {error}
+
+ )}
+ {isSaved && ( // display if redirect with search param
+
+ Newsletter sucessfully saved
+
+ )}
+ {" "}
+
+
+ Title
+
+ setTitle(e.target.value)}
+ required
+ />
+
+
+
+ Image URL
+
+ setImageUrl(e.target.value)}
+ />
+
+
+
+ Content
+
+ setContent(e.target.value)}
+ required
+ />
+
+
+
+ {isSubmitting ? (
+
+ ) : (
+ "Update Newsletter"
+ )}
+
+
+
+ )
+}
\ No newline at end of file
diff --git a/app/dashboard/[id]/loading.tsx b/app/dashboard/[id]/loading.tsx
new file mode 100644
index 0000000..bcb183e
--- /dev/null
+++ b/app/dashboard/[id]/loading.tsx
@@ -0,0 +1,7 @@
+export default function Loading() {
+ return (
+
+ Loading newsletter draft
+
+ );
+}
\ No newline at end of file
diff --git a/app/dashboard/[id]/page.tsx b/app/dashboard/[id]/page.tsx
new file mode 100644
index 0000000..5c434c2
--- /dev/null
+++ b/app/dashboard/[id]/page.tsx
@@ -0,0 +1,29 @@
+import { getUserNewsletter, editNewsletter } from "@/app/actions/NewsletterActions";
+import { notFound, redirect } from "next/navigation";
+import EditNewsletterForm from "./EditNewsletterForm";
+
+export default async function NewsletterPage({ params }: { params: Promise<{ id: string }>; }) { // next passes in params object when this comp is called
+ const { id } = await params; // [id] catches the value from the url and gives it a param value with the key of id
+ const newsletter = await getUserNewsletter(id);
+
+ if (!newsletter) { // otherwise tries to reference things that dont exist
+ notFound();
+ }
+
+ if (newsletter.status === "Sent") {
+ redirect(`/newsletters/${newsletter.id}`); // if sent dont let them access edit page
+ }
+
+ return (
+
+
+ Edit newsletter
+
+
+
+
+ );
+}
\ No newline at end of file
diff --git a/app/dashboard/loading.tsx b/app/dashboard/loading.tsx
new file mode 100644
index 0000000..e219981
--- /dev/null
+++ b/app/dashboard/loading.tsx
@@ -0,0 +1,7 @@
+export default function Loading() {
+ return (
+
+ Loading dashboard...
+
+ );
+}
\ No newline at end of file
diff --git a/app/dashboard/page.tsx b/app/dashboard/page.tsx
new file mode 100644
index 0000000..5170c92
--- /dev/null
+++ b/app/dashboard/page.tsx
@@ -0,0 +1,165 @@
+import { getUserNewsletters, removeNewsletter, publishNewsletter, unPublishNewsletter, scheduleNewsletter} from "@/app/actions/NewsletterActions";
+import CreateNewsletterForm from "./CreateNewsletterFrom";
+import Link from "next/link";
+
+export default async function Dashboard() {
+
+ const newsletters = await getUserNewsletters();
+
+ return (
+
+
+ Dashboard
+
+
+
+ Create and manage your newsletters.
+
+
+
+
+
+
+ {newsletters.length === 0 ? (
+
No newsletters have been created yet.
+ ) : (
+
+ {newsletters.map((newsletter) => ( // maps each newsletter into a list item
+
+
+
+
+ {newsletter.title}
+
+
+
+
+ By {newsletter.author.name || "Unnamed author"}
+
+
+ {newsletter.imageUrl && ( // when this is an image it renders it
+
+
+
+ )}
+
+
Status: {newsletter.status}
+
+ {newsletter.status === "Sent" ? ( // if Sent render unpublish button
+
{
+ "use server";
+ const result = await unPublishNewsletter(newsletter.id);
+ if (!result.success) {
+ throw new Error(result.error);
+ }
+ }}
+ >
+
+ Unpublish
+
+
+ ) : (
+ {
+ "use server";
+ const result = await publishNewsletter(newsletter.id);
+ if (!result.success) {
+ throw new Error(result.error);
+ }
+ }}
+ >
+
+ Publish
+
+
+ ) }
+
+
+
+ {newsletter.status === "Sent" ? (
+
+ Schedule
+
+
+ ) : newsletter.status === "Schedule" ? (
+ {
+ "use server";
+ const result = await unPublishNewsletter(newsletter.id);
+ if (!result.success) {
+ throw new Error(result.error);
+ }
+ }}
+ >
+
+ Stop Schedule
+
+
+ ) : (
+ {
+ "use server";
+ const result = await scheduleNewsletter(newsletter.id);
+ if (!result.success) {
+ throw new Error(result.error);
+ }
+ }}
+ >
+
+ Schedule
+
+
+ ) }
+
+ {newsletter.status === "Sent" || newsletter.status === "Schedule" ? ( // render grey button with no link if Sent or Schedule
+
+ Edit
+
+ ) : (
+
+ Edit
+
+ )}
+ {
+ "use server";
+ const result = await removeNewsletter(newsletter.id);
+ if (!result.success) {
+ throw new Error(result.error);
+ }
+ }}
+ >
+
+ Remove
+
+
+
+
+
+
+ ))}
+
+ )}
+
+
+
+ );
+}
\ No newline at end of file
diff --git a/app/globals.css b/app/globals.css
index a2dc41e..b353fd8 100644
--- a/app/globals.css
+++ b/app/globals.css
@@ -1,4 +1,5 @@
@import "tailwindcss";
+@plugin "daisyui";
:root {
--background: #ffffff;
@@ -23,4 +24,4 @@ body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
-}
+}
\ No newline at end of file
diff --git a/app/layout.tsx b/app/layout.tsx
index 9852c15..7c4c421 100644
--- a/app/layout.tsx
+++ b/app/layout.tsx
@@ -1,6 +1,10 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
+import Home from "./page";
+import NavBar from "./components/NavBar";
+import { Providers } from "./components/Providers";
+import { Suspense } from "react";
const geistSans = Geist({
variable: "--font-geist-sans",
@@ -13,8 +17,8 @@ const geistMono = Geist_Mono({
});
export const metadata: Metadata = {
- title: "Create Next App",
- description: "Generated by create next app",
+ title: "Secure CMS",
+ description: "A Secure Content Management System",
};
export default function RootLayout({ children }: LayoutProps<"/">) {
@@ -23,7 +27,18 @@ export default function RootLayout({ children }: LayoutProps<"/">) {
lang="en"
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
>
- {children}
+
+
+
+ }>
+ {/* reserve space while navbar loads ^^ */}
+
+ {children}
+
+
+