committing summative

This commit is contained in:
Archie committed 2026-11-06 10:02:29 +00:00
1 parent 73ac8e85be
commit 95b138f29e
44 files changed
+5313 -749

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
DATABASE_URL=
AUTH_SECRET=
AUTH_GOOGLE_ID=
AUTH_GOOGLE_SECRET=
ENFORCEADMIN=
SEED_ACCOUNT_PASSWORD=
+12
View File
@@ -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
+25
View File
@@ -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
+11
View File
@@ -0,0 +1,11 @@
export default function AuthLayout({ children }: { children: React.ReactNode }) {
return (
<div className="min-h[calc(100vh-4rem)] flex items-center justify-center p-4">
<div className="card w-full max-w-md bg-base-200 shadow-xl">
<div className="card-body">
{children}
</div>
</div>
</div>
)
}
+95
View File
@@ -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<HTMLFormElement>) => { // 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 (
<>
<form onSubmit={handleSubmit} className="mt-4">
{error && (
<div className="alert alert-error mb-4">
<span>{error}</span>
</div>
)}
{" "}
<div className="form-control">
<label className="label">
<span className="label-text">Email</span>
</label>
<input
type="email"
placeholder="Enter your email"
className="input input-bordered w-full"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div className="form-control mt-4">
<label className="label">
<span className="label-text">Password</span>
</label>
<input
type="password"
placeholder="Enter your password"
className="input input-bordered w-full"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
<div className="form-control mt-6">
<button type="submit" className="btn btn-primary w-full" disabled={isSubmitting}>
{isSubmitting ? (
<span className="loading loading-spinner loading-sm"></span>
) : (
"Sign In"
)}
</button>
</div>
</form>
<div className="divider">OR</div>
<p className="text-cent">
Don't have an account?{" "}
<Link href="/register" className="link link-primary">
Sign Up
</Link>
</p>
</>
);
}
+24
View File
@@ -0,0 +1,24 @@
export default function SigninButton({
text,
style,
callback,
formAction
}: {
text: string;
style: string;
callback?: () => void;
formAction?: any;
}) {
return (
<div className="form-control mt-6">
<button
type="submit"
formAction={formAction}
className={style}
onClick={callback}
>
{text}
</button>
</div>
);
};
+60
View File
@@ -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 (
<>
<h2 className="card-title text-2xl justify-center">Please Sign In</h2>
<form className="mt-4">
{isJustRegisted && ( // display if redirect with search param
<div className="p-10 bg-emerald-1001 text-emerald-700 mb-15 rounded-md">
Account created successfully. You can now sign in.
</div>
)}
<SigninButton
text="Google"
style="btn btn-primary w-full"
formAction={handleGoogleLogin}
/>
</form>
<div className="mt-4">
<SigninButton
text="Email"
style="btn btn-primary w-full"
callback={showEmailLogin}
/>
</div>
<div className="mt-4">{elogin ? <AuthLoginForm /> : ""}</div>
</>
)
}
export default function LoginPage() { // displays fallback while url dependent content loads (searchparams), errors if it tries to prepare page in advance
return (
<>
<Suspense fallback={<p>Loading login..</p>}>
<LoginContent />
</Suspense>
</>
);
}
+124
View File
@@ -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<HTMLFormElement>) => { // 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 (
<>
<h2 className="card-title text-2xl justify-center">Create Account</h2>
<form onSubmit={handleSubmit} className="mt-4">
{error && (
<div className="alert alert-error mb-4">
<span>{error}</span>
</div>
)}
{" "}
<div className="form-control mt-4">
<label className="label">
<span className="label-text">Name</span>
</label>
<input
type="text"
placeholder="Enter your name"
className="input input-bordered w-full"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="form-control mt-4">
<label className="label">
<span className="label-text">Email</span>
</label>
<input
type="email"
placeholder="Enter your email"
className="input input-bordered w-full"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div className="form-control mt-4">
<label className="label">
<span className="label-text">Password</span>
</label>
<input
type="password"
placeholder="Enter your password"
className="input input-bordered w-full"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
<div className="form-control mt-4">
<label className="label">
<span className="label-text">Confirm Password</span>
</label>
<input
type="password"
placeholder="Confirm your password"
className="input input-bordered w-full"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
/>
</div>
<div className="form-control mt-6">
<button type="submit" className="btn btn-primary w-full" disabled={isSubmitting}>
{isSubmitting ? (
<span className="loading loading-spinner loading-sm"></span>
) : (
"Create Account"
)}
</button>
</div>
</form>
</>
)
};
+19
View File
@@ -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
+276
View File
@@ -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" };
}
}
+72
View File
@@ -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
}
+2
View File
@@ -0,0 +1,2 @@
import { handlers } from "@/auth"
export const { GET, POST } = handlers
+59
View File
@@ -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 }
);
}
}
+62
View File
@@ -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 (
<section className="mt-12">
<h2 className="text-3xl font-bold">
{/* I am assuming when I pick the first five its the latest 5 */}
Latest from US-RSE
</h2>
<ul className="mt-6 space-y-6">
{newsletters.slice(0, numNewsletters).map((newsletter) => ( // slice out varnum from 0 and map them to list items
<li
key={newsletter.url}
className="border-b border-base-content/20 pb-6"
>
<h3 className="text-xl font-semibold">
<a
href={newsletter.url}
className="hover:underline"
>
{newsletter.title}
</a>
</h3>
<p className="mt-2 text-base-content/70">
{newsletter.description}
</p>
</li>
))}
</ul>
</section>
);
} catch (error) {
console.error("External newsletter feed failed:", error);
return (
<p className="mt-12">
This source is currently unavailable.
</p>
);
}
}
+69
View File
@@ -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 (
<div className="navbar bg-base-100 shadow-sm">
<div className="navbar-start">
<div className="dropdown">
<div tabIndex={0} role="button" className="btn btn-ghost lg:hidden">
<svg aria-label="Menu" xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 6h16M4 12h8m-8 6h16" /> </svg>
</div>
<ul
tabIndex={-1}
className="menu menu-sm dropdown-content bg-base-100 rounded-box z-1 mt-3 w-52 p-2 shadow">
{visibleLinks.map((link) => ( // below highlights the active link
<li className={pathname === link.url ? "menu-active" : ""} key={link.id}>
<Link href={link.url}>{link.text}</Link>
</li>
))}
</ul>
</div>
<a className="btn btn-ghost text-xl">Secure CMS</a>
</div>
<div className="navbar-center hidden lg:flex">
<ul className="menu menu-horizontal px-1">
{visibleLinks.map((link) => (
<li className={pathname === link.url ? "menu-active" : ""} key={link.id}>
<Link href={link.url}>{link.text}</Link>
</li>
))}
</ul>
</div>
<div className="navbar-end gap-2">
{session?.user ? (
<>
<span>{session.user.name || session.user.email || "Account"}</span>
<button type="button" className="btn btn-ghost" onClick={() => signOut({ redirectTo: "/login" })}>
Logout
</button>
</>
) : (
<>
<Link href="/login" className="btn btn-ghost">
Login
</Link>
<Link href="/register" className="btn btn-primary">
Sign Up
</Link>
</>
)}
</div>
</div>
);
}
+12
View File
@@ -0,0 +1,12 @@
"use client";
import { SessionProvider } from "next-auth/react";
export function Providers({ children }: { children: React.ReactNode }) {
return (
<SessionProvider>{children}</SessionProvider>
)
}
// surrounds page content to give children access to auth context and functions
+28
View File
@@ -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",
},
]
+119
View File
@@ -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<HTMLFormElement>) => {
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 (
<form onSubmit={handleSubmit} className="mt-4">
{error && (
<div className="alert alert-error mb-4">
<span>{error}</span>
</div>
)}
{isCreated && ( // display if redirect with search param
<div role="status" className="alert alert-success mb-4">
Newsletter sucessfully created
</div>
)}
{" "}
<div className="form-control">
<label className="label">
<span className="label-text">Title</span>
</label>
<input
type="text"
placeholder="Enter your title"
className="input input-bordered w-full"
value={title}
onChange={(e) => setTitle(e.target.value)}
required
/>
</div>
<div className="form-control mt-4">
<label className="label">
<span className="label-text">Image URL</span>
</label>
<input
type="url"
placeholder="Enter your image URL"
className="input input-bordered w-full"
value={imageUrl}
onChange={(e) => setImageUrl(e.target.value)}
/>
</div>
<div className="form-control mt-4">
<label className="label">
<span className="label-text">Content</span>
</label>
<textarea
placeholder="Enter your content"
className="textarea textarea-bordered w-full"
value={content}
onChange={(e) => setContent(e.target.value)}
required
/>
</div>
<div className="form-control mt-6">
<button type="submit" className="btn btn-primary w-full" disabled={isSubmitting}>
{isSubmitting ? (
<span className="loading loading-spinner loading-sm"></span>
) : (
"Create Newsletter"
)}
</button>
</div>
</form>
)
}
+124
View File
@@ -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<HTMLFormElement>) => {
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 (
<form onSubmit={handleSubmit} className="mt-4">
{error && (
<div className="alert alert-error mb-4">
<span>{error}</span>
</div>
)}
{isSaved && ( // display if redirect with search param
<div role="status" className="alert alert-success mb-4">
Newsletter sucessfully saved
</div>
)}
{" "}
<div className="form-control">
<label className="label">
<span className="label-text">Title</span>
</label>
<input
type="text"
placeholder="Enter your title"
className="input input-bordered w-full"
value={title}
onChange={(e) => setTitle(e.target.value)}
required
/>
</div>
<div className="form-control mt-4">
<label className="label">
<span className="label-text">Image URL</span>
</label>
<input
type="url"
placeholder="Enter your image URL"
className="input input-bordered w-full"
value={imageUrl}
onChange={(e) => setImageUrl(e.target.value)}
/>
</div>
<div className="form-control mt-4">
<label className="label">
<span className="label-text">Content</span>
</label>
<textarea
placeholder="Enter your content"
className="textarea textarea-bordered w-full"
value={content}
onChange={(e) => setContent(e.target.value)}
required
/>
</div>
<div className="form-control mt-6">
<button type="submit" className="btn btn-primary w-full" disabled={isSubmitting}>
{isSubmitting ? (
<span className="loading loading-spinner loading-sm"></span>
) : (
"Update Newsletter"
)}
</button>
</div>
</form>
)
}
+7
View File
@@ -0,0 +1,7 @@
export default function Loading() {
return (
<p className="mx-auto w-full max-w-3xl px-6 py-10">
Loading newsletter draft
</p>
);
}
+29
View File
@@ -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 (
<main className="mx-auto w-full max-w-3xl px-6 py-10">
<h1 className="text-4xl font-bold tracking-tight">
Edit newsletter
</h1>
<EditNewsletterForm
key={newsletter.id}
newsletter={newsletter}
/>
</main>
);
}
+7
View File
@@ -0,0 +1,7 @@
export default function Loading() {
return (
<p className="mx-auto w-full max-w-3xl px-6 py-10">
Loading dashboard...
</p>
);
}
+165
View File
@@ -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 (
<main className="mx-auto w-full max-w-5xl px-6 py-10">
<h1 className="text-4xl font-bold tracking-tight">
Dashboard
</h1>
<p className="mt-3 text-base-content/70">
Create and manage your newsletters.
</p>
<CreateNewsletterForm />
<div className="mt-8 overflow-x-auto">
<div className="mt-8">
{newsletters.length === 0 ? (
<p>No newsletters have been created yet.</p>
) : (
<ul className="space-y-10">
{newsletters.map((newsletter) => ( // maps each newsletter into a list item
<li
key={newsletter.id}
className="border-b border-base-content/20"
>
<article>
<h2 className="text-2xl font-semibold">
<Link
href={`/dashboard/${newsletter.id}`} // creates a custom link for the newsletter
className="hover:underline"
>
{newsletter.title}
</Link>
</h2>
<p className="mt-2 text-sm text-base-content/60">
By {newsletter.author.name || "Unnamed author"}
</p>
{newsletter.imageUrl && ( // when this is an image it renders it
<Link href={`/dashboard/${newsletter.id}`} className="mt-4 block">
<img
src={newsletter.imageUrl} // above also makes the image link to the custom link for specific newsletter
alt={newsletter.title}
className="mt-4 h-48 w-full rounded-lg object-cover"
/>
</Link>
)}
<div className="flex justify-between items-center gap-4 py-4">
<p className="text-sm text-base-content/60">Status: {newsletter.status}</p>
<div className="flex items-center gap-3">
{newsletter.status === "Sent" ? ( // if Sent render unpublish button
<form
action={async () => {
"use server";
const result = await unPublishNewsletter(newsletter.id);
if (!result.success) {
throw new Error(result.error);
}
}}
>
<button type="submit" className="btn btn-primary btn-sm">
Unpublish
</button>
</form>
) : (
<form
action={async () => {
"use server";
const result = await publishNewsletter(newsletter.id);
if (!result.success) {
throw new Error(result.error);
}
}}
>
<button type="submit" className="btn btn-primary btn-sm">
Publish
</button>
</form>
) }
{newsletter.status === "Sent" ? (
<button type="button" className="btn btn-outline btn-sm" disabled>
Schedule
</button>
) : newsletter.status === "Schedule" ? (
<form
action={async () => {
"use server";
const result = await unPublishNewsletter(newsletter.id);
if (!result.success) {
throw new Error(result.error);
}
}}
>
<button type="submit" className="btn btn-error btn-sm">
Stop Schedule
</button>
</form>
) : (
<form
action={async () => {
"use server";
const result = await scheduleNewsletter(newsletter.id);
if (!result.success) {
throw new Error(result.error);
}
}}
>
<button type="submit" className="btn btn-primary btn-sm">
Schedule
</button>
</form>
) }
{newsletter.status === "Sent" || newsletter.status === "Schedule" ? ( // render grey button with no link if Sent or Schedule
<button
type="button"
className="btn btn-outline btn-sm"
disabled
>
Edit
</button>
) : (
<Link
href={`/dashboard/${newsletter.id}`}
className="btn btn-secondary btn-sm"
>
Edit
</Link>
)}
<form
action = {async () => {
"use server";
const result = await removeNewsletter(newsletter.id);
if (!result.success) {
throw new Error(result.error);
}
}}
>
<button type="submit" className="btn btn-sm btn-outline btn-error">
Remove
</button>
</form>
</div>
</div>
</article>
</li>
))}
</ul>
)}
</div>
</div>
</main>
);
}
+1
View File
@@ -1,4 +1,5 @@
@import "tailwindcss";
@plugin "daisyui";
:root {
--background: #ffffff;
+18 -3
View File
@@ -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`}
>
<body className="min-h-full flex flex-col">{children}</body>
<body className="min-h-dvh flex flex-col">
<Providers>
<header className="font-sans">
<Suspense fallback={<div className="h-16" />}><NavBar enforceAdmin={process.env.ENFORCEADMIN === "true"} /></Suspense>
{/* reserve space while navbar loads ^^ */}
</header>
{children}
</Providers>
<footer className="mt-auto text-base-content/70 border-t border-base-content/10 text-sm text-right">
<p> 2026 Secure CMS created by Archie McCulloch </p>
</footer>
</body>
</html>
);
}
+14
View File
@@ -0,0 +1,14 @@
import bcrypt from "bcryptjs";
const SALT_ROUNDS = 10;
export async function hashPassword(password: string): Promise<string> { // hashes and salts password
return bcrypt.hash(password, SALT_ROUNDS)
}
export async function verifyPassword( // compares password to hash
password: string,
hash: string
): Promise<boolean> {
return bcrypt.compare(password, hash);
}
+39
View File
@@ -0,0 +1,39 @@
import { useCallback } from "react";
interface User {
id: string | null | undefined;
email: string | null | undefined;
name: string | null | undefined;
}
interface LoginCredentials {
email: string;
password: string;
}
interface RegisterCredentials extends LoginCredentials {
name?: string;
}
interface AuthResponse {
user: User;
message?: string;
error?: string;
}
export const register = async (credentials: RegisterCredentials): Promise<AuthResponse> => {
const response = await fetch("/api/auth/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(credentials), // turns credentials obj into json
credentials: "include"
});
const data: AuthResponse = await response.json(); // gets response data from promise and turns response into object
if (!response.ok) { // boolean value depending on success code
throw new Error(data.error || "Registration failed");
}
return data
}
+20
View File
@@ -0,0 +1,20 @@
import { PrismaClient } from '@/lib/generated/prisma/client';
import { PrismaPg } from "@prisma/adapter-pg";
import { Pool } from "pg";
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
function createPrismaClient() {
const pool = new Pool({ connectionString:
process.env.DATABASE_URL });
const adapter = new PrismaPg(pool);
return new PrismaClient({ adapter });
}
export const prisma = globalForPrisma.prisma ?? createPrismaClient();
if (process.env.NODE_ENV !== "production") {
globalForPrisma.prisma = prisma;
}
+7
View File
@@ -0,0 +1,7 @@
export default function Loading() {
return (
<p className="mx-auto w-full max-w-3xl px-6 py-10">
Loading newsletter…
</p>
);
}
+37
View File
@@ -0,0 +1,37 @@
import { getPubNewsletter } from "@/app/actions/NewsletterActions";
import { notFound } from "next/navigation";
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 getPubNewsletter(id);
if (!newsletter) { // otherwise tries to reference things that dont exist
notFound();
}
return (
<main className="mx-auto w-full max-w-3xl px-6 py-10">
<article>
<h1 className="text-4xl font-bold tracking-tight">
{newsletter.title}
</h1>
<p className="mt-3 text-sm text-base-content/60">
By {newsletter.author.name || "Unnamed author"}
</p>
{newsletter.imageUrl && (
<img
src={newsletter.imageUrl}
alt={newsletter.title}
className="mt-6 h-auto w-full rounded-lg"
/>
)}
<div className="mt-8 whitespace-pre-wrap leading-relaxed">
{newsletter.content}
</div>
</article>
</main>
);
}
+7
View File
@@ -0,0 +1,7 @@
export default function Loading() {
return (
<p className="mx-auto w-full max-w-6xl px-6 py-10">
Loading newsletters…
</p>
);
}
+68
View File
@@ -0,0 +1,68 @@
import { getPubNewsletters } from "../actions/NewsletterActions";
import Link from "next/link";
import { Suspense } from "react";
import ExternalNewsletters from "../components/ExternalNewsletters";
export default async function NewslettersPage() {
const newsletters = await getPubNewsletters();
return (
<main className="mx-auto w-full max-w-6xl px-6 py-10">
<h1 className="text-4xl font-bold tracking-tight">
Newsletters
</h1>
<p className="mt-3 text-base-content/70">
Read our latest published newsletters.
</p>
<div className="mt-8 overflow-x-auto">
<div className="mt-8">
{newsletters.length === 0 ? (
<p>No newsletters have been published yet.</p>
) : (
<ul className="space-y-10">
{newsletters.map((newsletter) => ( // maps each newsletter into a list item
<li
key={newsletter.id}
className="border-b border-base-content/20 pb-8"
>
<article>
<h2 className="text-2xl font-semibold">
<Link
href={`/newsletters/${newsletter.id}`} // creates a custom link for the newsletter
className="hover:underline"
>
{newsletter.title}
</Link>
</h2>
<p className="mt-2 text-sm text-base-content/60">
By {newsletter.author.name || "Unnamed author"}
</p>
{newsletter.imageUrl && ( // when this is an image it renders it
<Link href={`/newsletters/${newsletter.id}`} className="mt-4 block">
<img
src={newsletter.imageUrl} // above also makes the image link to the custom link for specific newsletter
alt={newsletter.title}
className="mt-4 h-48 w-full rounded-lg object-cover"
/>
</Link>
)}
</article>
</li>
))}
</ul>
)}
</div>
<div className="divider"> From other sources</div>
<div>
<Suspense fallback={<p className="mt-12">Loading external feed…</p>}>
<ExternalNewsletters />
</Suspense>
</div>
</div>
</main>
);
}
+9 -59
View File
@@ -2,68 +2,18 @@ import Image from "next/image";
export default function Home() {
return (
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:invert h-5 w-[100px]"
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the{" "}
<code className="rounded bg-black/[.06] px-1.5 py-0.5 font-mono text-[0.9em] dark:bg-white/[.08]">
page.tsx
</code>{" "}
file.
<main className="font-sans mx-auto flex flex-1 flex-col items-center justify-center">
<h1 className="font-bold tracking-tight text-4xl sm:text-5xl">
Welcome to my secure CMS
</h1>
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Learning
</a>{" "}
center.
<p className="mt-5 max-w-xl text-base-content/70">
A newsletter publishing and reading platform.
</p>
</div>
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
<a
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert h-[14px] w-4"
src="/vercel.svg"
alt="Vercel logomark"
width={16}
height={14}
/>
Deploy Now
<section className="mt-10 flex flex-col items-center gap-4 sm:flex-row">
<a href="/newsletters" className="btn btn-primary">
View Newsletters
</a>
<a
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Documentation
</a>
</div>
</section>
</main>
</div>
);
}
+6
View File
@@ -0,0 +1,6 @@
export default function Loading() {
return <p>Loading users...</p>;
}
// next expects uncached work such as db queries to have a loading boundary
// caching enabled in next.config.ts
+108
View File
@@ -0,0 +1,108 @@
import { JSX } from "react";
import { getUsers, addUser, editUser, removeUser } from "../actions/UserAction";
import { hashPassword } from "../lib/auth";
export default async function UsersPage(): Promise<JSX.Element> {
const users = await getUsers(); // fetches all users from database, returns array of records
return (
<div>
<form
action={async (formData: FormData) => { // during build time, next generates this func on the server
"use server"; /// when submit is pressed it sends formdata and func reference to server and next executes it
const name = formData.get("name") as string;
const email = formData.get("email") as string;
const pass = formData.get("pass") as string;
const hashedPass = await hashPassword(pass);
if (email && pass) { // if all required fields present then add user
const result = await addUser({ name, email, pass:hashedPass });
}
}}
className="grid grid-cols-1 md:grid-cols-4 gap-3 items-end mt-2">
<input
type="text"
name="name"
placeholder="Name"
className="input input-bordered input-sm w-full"
/>
<input
type="email"
name="email"
placeholder="Email"
className="input input-bordered input-sm w-full"
required
/>
<input
type="password"
name="pass"
placeholder="Password"
className="input input-bordered input-sm w-full"
required
/>
<button type="submit" className="btn btn-primary btn-sm">
Add User
</button>
</form>
<table className="table table-zebra w-full">
<thead>
<tr>
<th> ID</th>
<th> Name</th>
<th> Email</th>
<th className="text-right"> Actions</th>
</tr>
</thead>
<tbody>
{users.map((user) => ( // maps each record in user array to a table row, performs func on every obj/record where user refers to current obj
<tr key={user.id}>
<td className="font-mono">{user.id}</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td className="text-right flex justify-end gap-2">
{/* <form
action={async () => {
"use server";
await editUser(user.id, {
name: `${user.name} (Edited)`,
});
}}
>
<button
type="submit"
className="btn btn-xs btn-outline btn-warning"
>
Edit
</button>
</form> */}
<form
action = {async () => {
"use server";
await removeUser(user.id);
}}
>
<button
type="submit"
className="btn btn-xs btn-outline btn-error"
>
Remove
</button>
</form>
</td>
</tr>
))}
{users.length === 0 && ( // if length of array is 0 (no users in db)
<tr>
<td colSpan={4} className="text-center py-4 text-base-content/60">
No users found in database.
</td>
</tr>
)}
</tbody>
</table>
</div>
);
}
+106
View File
@@ -0,0 +1,106 @@
import NextAuth from "next-auth";
import Google from "next-auth/providers/google";
import Credentials from "next-auth/providers/credentials";
import { verifyPassword } from "@/app/lib/auth";
import { prisma } from "@/app/lib/prisma";
export const { handlers, signIn, signOut, auth } = NextAuth({ // serverside functions
providers: [
Google,
Credentials({ //
name: "Credentials",
credentials: {
email: { label: "Email", type: "email"},
password: { label: "Password", type: "password"},
},
async authorize(credentials) { // function to how to find the account and verify password
if (!credentials?.email || !credentials?.password) return null;
const user = await prisma.users.findUnique({ // finds user
where: { email: credentials.email as string},
});
if (!user || !user.passwordHash) return null; // checks it found a user with a password
const isValid = await verifyPassword(
credentials.password as string,
user.passwordHash,
);
if (!isValid) return null; // if input password doesnt match hashed password
return { id: user.id, email: user.email, name: user.name} // return obj containing user data, session stores data once authorize is succesful
},
}),
],
session: { strategy: "jwt"},
callbacks: {
authorized: async ({ auth }) => {
return !!auth
},
signIn: async ({ user, account, profile }) => { // when the above signIn function is called auth.js runs this function to determine if its an allowed signIn
// ^^ Auth.js passes in an object containing info about sign in attempt which we destructure
if (account?.provider !== "google"){ // only apply to google sign ins
return true;
}
if (!user.email || profile?.email_verified !== true) { // the object gives us access to information such as whether their google email is verified
return false;
}
try {
const existingGoogleUser = await prisma.users.findUnique({
where: {
googleId: account.providerAccountId, // also gives access to their unique google id which doesnt change - unlike an email which can
},
});
if (existingGoogleUser) {
return true;
}
const existingEmailUser = await prisma.users.findUnique({
where: {
email: user.email,
},
});
if (existingEmailUser) {
return false;
}
await prisma.users.create({
data: {
email: user.email,
name: user.name,
googleId: account.providerAccountId,
},
});
return true;
} catch (error) {
console.error("Google account creation failed:", error);
return false;
}
},
session: async ({ session }) => { // when session is access this function is called
if (!session.user?.email) return session; // if no email then no id
const user = await prisma.users.findUnique({
where: {
email: session.user.email,
},
});
if (user) { session.user.id = user.id;} // append user id and role to session
return session;
}
},
})
// exports functions from NextAuth to handle google login/out and check session
// you give next configs and it returns an object of functions we grab from it and export them for use
+1 -1
View File
@@ -6,7 +6,7 @@ const nextConfig: NextConfig = {
agentFeedback: true,
},
cacheComponents: true,
partialPrefetching: true,
partialPrefetching: false, // causing rendering freezes?
reactCompiler: true,
turbopack: {
rules: {
+3276 -680
View File
File diff suppressed because it is too large. Load diff
+17 -5
View File
@@ -9,19 +9,31 @@
"lint": "eslint"
},
"dependencies": {
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^3.0.3",
"dotenv": "^18.0.9",
"js-cookie": "^3.0.8",
"next": "16.4.3",
"react": "19.3.0",
"react-dom": "19.3.0"
"next-auth": "^5.0.0-beta.32",
"pg": "^8.23.1",
"react": "19.3.1",
"react-dom": "19.3.1"
},
"devDependencies": {
"@tailwindcss/turbopack": "^4",
"@types/node": "^20",
"@types/js-cookie": "^3.0.6",
"@types/node": "^26",
"@types/pg": "^8.23.1",
"@types/react": "^19",
"@types/react-dom": "^19",
"babel-plugin-react-compiler": "1.0.0",
"eslint": "^9",
"daisyui": "^5.7.50",
"eslint": "^10",
"eslint-config-next": "16.4.3",
"prisma": "^7.10.1",
"tailwindcss": "^4",
"typescript": "^5"
"tsx": "^4.23.15",
"typescript": "^7"
}
}
+54
View File
@@ -0,0 +1,54 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
// Get a free hosted Postgres database in seconds: `npx create-db`
generator client {
provider = "prisma-client"
output = "../lib/generated/prisma"
}
datasource db {
provider = "postgresql"
}
enum Role {
User
Moderator
Admin
}
enum NewsletterStatus {
Draft
Schedule
Sent
}
model Users {
id String @id @default(cuid()) // prsima generates cuid - generated text id
email String @unique
name String?
passwordHash String? // g-accounts dont have pword
googleId String? @unique // stable key for g-accounts
role Role @default(User)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
newsletters Newsletters[]
@@map("users")
}
model Newsletters {
id String @id @default(cuid())
title String
imageUrl String
content String
authorID String
author Users @relation(fields: [authorID], references: [id], onDelete: Cascade) // when the associated user is deleted so is the newsletter
status NewsletterStatus @default(Draft)
likes Int @default(0)
comments String[] @default([])
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
}
+61
View File
@@ -0,0 +1,61 @@
import bcrypt from "bcryptjs";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "../lib/generated/prisma/client"
import "dotenv/config"; // can access .env when run directly
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl) {
throw new Error("Database URL required in .env");
}
const prisma = new PrismaClient({
adapter: new PrismaPg({ connectionString:databaseUrl }),
});
async function main() {
const password = process.env.SEED_ACCOUNT_PASSWORD;
if (!password) {
throw new Error("A seed account password is required");
}
const passwordHash = await bcrypt.hash(password, 10);
const user = await prisma.users.upsert({
where: {
email: "seededTest@test.test",
},
update: {}, // if found do nothing
create: {
name: "seededTest",
email: "seededTest@test.test",
passwordHash,
},
});
await prisma.newsletters.upsert({
where: {
id: "seed-newsletter-1",
},
update: {},
create: {
id: "seed-newsletter-1",
title: "Example newsletter",
imageUrl: "https://images.unsplash.com/photo-1793645915308-bbb4be832480?q=80&w=1675&auto=format&fit=crop&ixlib=rb-4.1.0&ixid=NHwxMjA3fDA%3D",
content: "This is a sample newsletter for testing the CMS.",
authorID: user.id,
},
});
console.log("Seeded database with a user and newsletter");
}
main()
.catch((error) => { // needed to use .catch to handle error from promise which we cant await as outside async func
console.error("Seeding failed:", error);
process.exitCode = 1;
})
.finally(async () => {
await prisma.$disconnect();
});
+14
View File
@@ -0,0 +1,14 @@
// This file was generated by Prisma, and assumes you have installed the following:
// npm install --save-dev prisma dotenv
import "dotenv/config";
import { defineConfig } from "prisma/config";
export default defineConfig({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
},
datasource: {
url: process.env["DATABASE_URL"],
},
});
+42
View File
@@ -0,0 +1,42 @@
// export { auth as proxy } from "@/auth";
import { auth } from "@/auth";
import { cookies } from "next/headers"
import { NextResponse } from "next/server";
export const proxy = auth(async (req) => { // req is incoming request, auth from nextauth wraps the function
const isLoggedIn = !!req.auth // boolean based on if session info is present
const currentPath = req.nextUrl.pathname;
const isAuthRoute = currentPath === "/login" || currentPath === "/register"//
const isPublicRoute = isAuthRoute || currentPath === "/" || currentPath === "/newsletters" || currentPath.startsWith("/newsletters/") || currentPath ==="/users"; // checks individual newsletters
// is a public route if its an authroute, newsletter route, or root(homepage) route
const isAdminRoute = currentPath === "/users"
if (process.env.ENFORCEADMIN === "true" && isAdminRoute) {
return NextResponse.redirect(new URL("/login", req.nextUrl.origin))
}
if (!isLoggedIn && !isPublicRoute) { // if not logged in and not on public route
const newUrl = new URL("/login", req.nextUrl.origin);
return NextResponse.redirect(newUrl);
}
if (isLoggedIn && isAuthRoute) { // if logged in and trying to log in
const newUrl = new URL("/", req.nextUrl.origin);
return NextResponse.redirect(newUrl);
}
return NextResponse.next();
}
)
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
// runs proxy function on paths in matcher
+1 -1
View File
@@ -29,6 +29,6 @@
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
, "app/api/auth/logout/route.ts.old", "app/(auth)/login/CustomLoginForm.tsx.old" ],
"exclude": ["node_modules"]
}