Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ AUTH_GOOGLE_ID=
AUTH_GOOGLE_SECRET=
# GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET are also accepted as aliases.

# Comma-separated email addresses allowed to access the admin dashboard.
ADMIN_EMAILS=

# Password reset email delivery (Resend)
RESEND_API_KEY=
AUTH_EMAIL_FROM=

# Optional AI answers
OPENAI_API_KEY=

Expand Down
17 changes: 13 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,13 @@ Signed-in users get recommended questions based on their interaction history and
### 🔐 Authentication
Sign in with Google, GitHub, or email via NextAuth.

Password reset links are delivered through Resend. Configure `RESEND_API_KEY` and
`AUTH_EMAIL_FROM` with a verified sender, and set `NEXT_PUBLIC_SITE_URL` to the
public origin used in reset links.

Set `ADMIN_EMAILS` to a comma-separated list of administrator email addresses
to enable the protected user-management dashboard.

### 🌓 Dark / Light Theme
Seamless theme switching for comfortable viewing.

Expand Down Expand Up @@ -215,7 +222,8 @@ accepts `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` as aliases.
|----------|---------|--------|
| `LOG_LEVEL` | `debug` (dev) / `info` (prod) | `debug`, `info`, `warn`, `error` |
| `NEXTAUTH_URL` | Auto-detected (`trustHost`) | Your site URL, e.g. `http://localhost:3000` |
| `NEXT_PUBLIC_API_BASE_URL` | `https://$VERCEL_URL` on Vercel, otherwise localhost | Base URL used by the API client in `lib/api.ts` |
| `NEXT_PUBLIC_API_BASE_URL` | `https://dev-flow-kappa-seven.vercel.app/` on Vercel, otherwise localhost | Base URL used by the API client in `lib/api.ts` |
| `ADMIN_EMAILS` | Empty | Comma-separated email addresses allowed to access `/admin/users` |

---

Expand Down Expand Up @@ -332,15 +340,15 @@ MONGODB_URI="..." npm run db:cleanup-test-questions -- --apply # Delete them and
- [x] Profile ownership checks for question and answer actions
- [x] Profile question tags and Top Tags fallback support
- [x] Legacy question tag backfill migration
- [x] Admin user search, profile editing, and account suspension controls
- [x] Protected admin dashboard for user management
- [x] Live demo deployment

### 🚧 In Progress
- [ ] Final polish and edge-case validation for remaining UI flows
- [ ] Securing the users and accounts REST endpoints

### 📋 Planned
- [ ] User management actions
- [ ] Live demo deployment
- [ ] Admin dashboard
- [ ] Real-time notifications
- [ ] Advanced analytics and reporting
- [ ] Community features (comments, discussions)
Expand Down Expand Up @@ -369,6 +377,7 @@ DevFlow/
│ │ ├── layout.tsx # Navbar, left sidebar, right sidebar
│ │ ├── loading.tsx # Shared Loader fallback
│ │ ├── page.tsx # Home: questions feed
│ │ ├── admin/users/ # Admin-only user management
│ │ ├── ask-question/page.tsx
│ │ ├── questions/[id]/ # Question details, answers
│ │ │ └── edit/ # Edit a question
Expand Down
5 changes: 5 additions & 0 deletions app/(auth)/forgot-password/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { PasswordResetRequestScreen } from "@/features/auth/components/PasswordResetScreens"

export default function ForgotPasswordPage() {
return <PasswordResetRequestScreen />
}
26 changes: 2 additions & 24 deletions app/(auth)/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,9 @@
import Image from "next/image";
import { ReactNode } from "react";

import { SocialAuthForm } from "@/features/auth/components"


const AuthLayout = ({ children }: { children: ReactNode }) => {
return (
<main className=" min-h-screen flex-center bg-auth-light bg-cover bg-center bg-no-repeat px-4 py-10 dark:bg-auth-dark">
<section className="light-border background-light800_dark200 shadow-light-100_dark100 min-w-full sm:min-w-[520px] rounded-[10px] border px-4 py-10 shadow-md sm: sm:px-8">
<div className="flex items-center justify-between gap-2">
<div className="space-y-2.5">
<h1 className="h2-bold text-dark-100_light900">Join DevFlow</h1>
<p className="paragraph-regular text-dark500_light400">
To get Your Questions answered
</p>
</div>
<Image
src={"/images/site-logo.svg"}
alt="site logo"
width={50}
height={50}
className="object-contain"
/>
</div>
{children}
<SocialAuthForm />
</section>
<main className="min-h-screen flex-center bg-auth-light bg-cover bg-center bg-no-repeat px-4 py-10 dark:bg-auth-dark">
{children}
</main>
);
};
Expand Down
30 changes: 30 additions & 0 deletions app/(auth)/reset-password/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Suspense } from "react"

import { AuthFlowCard } from "@/features/auth/components/AuthFlowCard"
import { PasswordResetFormScreen } from "@/features/auth/components/PasswordResetScreens"

type ResetPasswordPageProps = {
searchParams: Promise<{ token?: string | string[] }>
}

async function ResetPasswordContent({ searchParams }: ResetPasswordPageProps) {
const params = await searchParams
const token = typeof params.token === "string" ? params.token : undefined

return <PasswordResetFormScreen token={token} />
}

export default function ResetPasswordPage({ searchParams }: ResetPasswordPageProps) {
return (
<Suspense
fallback={
<AuthFlowCard>
<h1 className="h3-bold pr-9 text-dark-100_light900">Choose a new password</h1>
<div className="mt-5 min-h-48" />
</AuthFlowCard>
}
>
<ResetPasswordContent searchParams={searchParams} />
</Suspense>
)
}
45 changes: 28 additions & 17 deletions app/(auth)/sign-in/page.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,33 @@
"use client";
import { Suspense } from "react"

import { signInWithCredentials } from "@/features/auth/actions"
import { AuthForm } from "@/features/auth/components"
import { SignInSchema } from "@/shared/lib/validation";

const SignIn = () => {
return (
<AuthForm
schema={SignInSchema}
formType="SIGN_IN"
defaultValues={{ email: "", password: "" }}
onSubmitAction={(data) => signInWithCredentials(data)}
/>
)
};

export default SignIn;
import { AuthPanel } from "@/features/auth/components/AuthPanel"
import { SignInScreen } from "@/features/auth/components/SignInScreen"

type SignInPageProps = {
searchParams: Promise<{ accountLink?: string; provider?: string; passwordReset?: string }>
}

async function SignInContent({ searchParams }: SignInPageProps) {
const params = await searchParams
const provider =
params.accountLink === "1" &&
(params.provider === "google" || params.provider === "github")
? params.provider
: null

return <SignInScreen provider={provider} passwordReset={params.passwordReset === "1"} />
}

export default function SignInPage({ searchParams }: SignInPageProps) {
return (
<Suspense
fallback={
<AuthPanel title="Welcome Back" description="Sign in to continue to DevFlow">
<div className="min-h-72" />
</AuthPanel>
}
>
<SignInContent searchParams={searchParams} />
</Suspense>
)
}
20 changes: 13 additions & 7 deletions app/(auth)/sign-up/page.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
"use client";

import { signUpWithCredentials } from "@/features/auth/actions"
import { AuthForm } from "@/features/auth/components"
import { AuthForm, AuthPanel } from "@/features/auth/components"
import { SignUpSchema } from "@/shared/lib/validation";


const SignUp = () => {
return (
<AuthForm
schema={SignUpSchema}
formType="SIGN_UP"
defaultValues={{email:"",username:"",name:"",password:"" }}
onSubmitAction={(data) => signUpWithCredentials(data)}
/>
<AuthPanel
title="Join DevFlow"
description="Get your questions answered"
showSocialAuth
>
<AuthForm
schema={SignUpSchema}
formType="SIGN_UP"
defaultValues={{email:"",username:"",name:"",password:"" }}
onSubmitAction={(data) => signUpWithCredentials(data)}
/>
</AuthPanel>
);
};

Expand Down
35 changes: 35 additions & 0 deletions app/(root)/admin/users/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { redirect } from "next/navigation"
import { Suspense } from "react"

import { AdminUsersContent } from "@/features/users/components/AdminUsersContent"
import { isAdminEmail } from "@/server/admin-access"
import { auth } from "@/server/auth"
import Routes from "@/shared/constants/route"

type AdminUsersPageProps = {
searchParams: Promise<{ query?: string | string[] }>
}

async function AdminUsersResults({ searchParams }: AdminUsersPageProps) {
const params = await searchParams
const query = typeof params.query === "string" ? params.query : ""
return <AdminUsersContent query={query} />
}

export default async function AdminUsersPage({ searchParams }: AdminUsersPageProps) {
const session = await auth()
if (!isAdminEmail(session?.user?.email)) redirect(Routes.HOME)

return (
<Suspense
fallback={
<main className="w-full">
<h1 className="h1-bold text-dark100_light900">User Management</h1>
<div className="mt-8 h-64 animate-pulse rounded-xl bg-light-800 dark:bg-dark-300" />
</main>
}
>
<AdminUsersResults searchParams={searchParams} />
</Suspense>
)
}
80 changes: 80 additions & 0 deletions features/auth/account-link.actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
"use server"

import { createHash, randomBytes } from "node:crypto"

import bcrypt from "bcryptjs"
import { Types } from "mongoose"
import { cookies } from "next/headers"
import { z } from "zod"

import { Account, AccountLinkIntent, User } from "@/server/db"
import { dbConnect } from "@/server/db/connect"
import logger from "@/shared/lib/logger"
import { SignInSchema } from "@/shared/lib/validation"

const accountLinkSchema = SignInSchema.extend({
provider: z.enum(["google", "github"])
})

type FlowResult = { success: true } | { success: false; error: string }

const hashToken = (token: string) => createHash("sha256").update(token).digest("hex")
const ACCOUNT_LINK_COOKIE = "devflow-account-link"
const INTENT_LIFETIME_MS = 5 * 60 * 1000

export async function createAccountLinkIntent(
input: z.infer<typeof accountLinkSchema>
): Promise<FlowResult> {
const parsed = accountLinkSchema.safeParse(input)
if (!parsed.success) {
return { success: false, error: "Enter a valid email address and password." }
}

try {
await dbConnect()
const user = (await User.findOne({ email: parsed.data.email }).select("_id").lean()) as {
_id: Types.ObjectId
} | null
if (!user) {
return { success: false, error: "Email or password is incorrect." }
}

const account = (await Account.findOne({
userId: user._id,
provider: "credentials"
})
.select("password")
.lean()) as { password?: string } | null

if (!account?.password || !(await bcrypt.compare(parsed.data.password, account.password))) {
return { success: false, error: "Email or password is incorrect." }
}

const token = randomBytes(32).toString("hex")
const tokenHash = hashToken(token)
const expiresAt = new Date(Date.now() + INTENT_LIFETIME_MS)

await AccountLinkIntent.deleteMany({ userId: user._id, provider: parsed.data.provider })
await AccountLinkIntent.create({
tokenHash,
userId: user._id,
email: parsed.data.email,
provider: parsed.data.provider,
expiresAt
})

const cookieStore = await cookies()
cookieStore.set(ACCOUNT_LINK_COOKIE, token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/api/auth",
expires: expiresAt
})

return { success: true }
} catch (error) {
logger.error({ err: error }, "Failed to authorize an OAuth account link")
return { success: false, error: "Unable to verify your account. Please try again." }
}
}
20 changes: 13 additions & 7 deletions features/auth/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,20 +122,26 @@ export async function signInWithCredentials(
await dbConnect()

try {
const existingUser = (await User.findOne({ email }).lean()) as { _id: unknown } | null
if (!existingUser) {
return formatActionError(new NotFoundError({ user: ["User not found"] }))
}

const emailPattern = new RegExp(
`^${email.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`,
"i"
)
const existingAccount = (await Account.findOne({
provider: "credentials",
providerAccountId: email
}).lean()) as { password?: string } | null
providerAccountId: emailPattern
}).lean()) as { userId: string; password?: string } | null

if (!existingAccount || !existingAccount.password) {
return formatActionError(new NotFoundError({ account: ["Account not found"] }))
}

const existingUser = (await User.findById(existingAccount.userId)
.select("isSuspended")
.lean()) as { isSuspended?: boolean } | null
if (!existingUser || existingUser.isSuspended) {
return formatActionError(new RequestError("Authentication failed", 401))
}

const passwordMatch = await bcrypt.compare(password, existingAccount.password)
if (!passwordMatch) {
return formatActionError(new RequestError("Password does not match", 401))
Expand Down
Loading
Loading