From 6de8e80656e719b58719f8c802898d458b418b1c Mon Sep 17 00:00:00 2001 From: osamaayub Date: Thu, 22 Oct 2026 03:46:11 -0700 Subject: [PATCH 1/3] added user data in response format --- features/users/actions.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/users/actions.ts b/features/users/actions.ts index f66aa92..18874a3 100644 --- a/features/users/actions.ts +++ b/features/users/actions.ts @@ -599,7 +599,7 @@ export const updateUserProfile = async (params:UpdateUserProfileParams): Promise revalidatePath(`/profile/${userId}`) revalidatePath("/profile/edit") - return { success: true } + return { success: true,data:JSON.parse(JSON.stringify(user)) } } catch (error) { return handleActionError(error) } From 86afa7ad2f9891aab4664b18cecb50727409ffa3 Mon Sep 17 00:00:00 2001 From: osamaayub Date: Wed, 11 Nov 2026 13:17:54 +0500 Subject: [PATCH 2/3] chore: upgrade Next.js 16.4.0 to 16.4.6 Pin the patched same-major release to address the published security advisory and enable Next.js security-upgrade tracking. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- next.config.ts | 3 ++ package.json | 2 +- yarn.lock | 116 ++++++++++++++++++++++++------------------------- 3 files changed, 62 insertions(+), 59 deletions(-) diff --git a/next.config.ts b/next.config.ts index 896ff0f..407635e 100644 --- a/next.config.ts +++ b/next.config.ts @@ -2,6 +2,9 @@ import type { NextConfig } from "next" const nextConfig: NextConfig = { output: "standalone", + experimental: { + agentUpgrade: "security" + }, // Prerender a static shell for every route and stream request-time parts behind Suspense cacheComponents: true, partialPrefetching: true, diff --git a/package.json b/package.json index 679dad7..fa35233 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "dayjs": "^1.11.23", "lucide-react": "^0.523.0", "mongoose": "^8.18.0", - "next": "^16.4.0", + "next": "16.4.6", "next-auth": "^5.0.0-beta.32", "next-mdx-remote": "^6.0.0", "next-themes": "^0.4.6", diff --git a/yarn.lock b/yarn.lock index 2be9ade..3b00d30 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1293,10 +1293,10 @@ dependencies: "@tybys/wasm-util" "^0.10.3" -"@next/env@16.4.0": - version "16.4.0" - resolved "https://registry.yarnpkg.com/@next/env/-/env-16.4.0.tgz#ea67f893128c71a2900b1b6bf0702bc51d031ff3" - integrity sha512-pyLlT5oafGlX8X7xjgGNXz5dNIDSxREm+qD6i9VLSZiZFopA/XWl8NM/KPmLx/8EG/++c49iid3gNWSQW1+2dQ== +"@next/env@16.4.6": + version "16.4.6" + resolved "https://registry.yarnpkg.com/@next/env/-/env-16.4.6.tgz#a3417875856d1d28cd276a9b6581cc18e09410ff" + integrity sha512-SunBjJ6t+oBtecS3dTjdVuMhUogP5wD/vrGL5EVuQYM1iS4O5ilL51HkiJ3sPjMzRHiCChvr4dbaSJbR7F3lxA== "@next/eslint-plugin-next@15.5.18": version "15.5.18" @@ -1305,45 +1305,45 @@ dependencies: fast-glob "3.3.1" -"@next/swc-darwin-arm64@16.4.0": - version "16.4.0" - resolved "https://registry.yarnpkg.com/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.0.tgz#8674666b9e0b4eac61ef1bd4f6ffe25a63b6c0a3" - integrity sha512-yyZ+9MgViAKLLb5l1gPBGjRwnq3teNLb5Zx6JEw8LzNSTjlsnp+baUHFxTgl7PpjCmKf48VQfyipG1eBflb48Q== - -"@next/swc-darwin-x64@16.4.0": - version "16.4.0" - resolved "https://registry.yarnpkg.com/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.0.tgz#1c68aa4e69520993ad33f2b73a303ffbe40cdc77" - integrity sha512-RePEEejEj1Auf5s9qEcG0JbcDP3ceNUS/ofNX8AhxzgIjTVlZIHMatlp16YplcSMpsVo/ZMQHJTjbMYJznjGUg== - -"@next/swc-linux-arm64-gnu@16.4.0": - version "16.4.0" - resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.0.tgz#b3b7ee95395fc851d246138cfcf02a4f3865dca7" - integrity sha512-HhsyCqd+NpmvDDVY/LqkAN24f+QVvXh3ie+PfcwKinWL2Mu826JymQxJXGjAIfmJ4VlHjp4Pe/nZtXtUoEMAqw== - -"@next/swc-linux-arm64-musl@16.4.0": - version "16.4.0" - resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.0.tgz#78e04be5c10e551068873986d0d8ba160d60c9e7" - integrity sha512-sN9Pf+Zh+RpZAOmbR7d8KAA8T61CVhawtbEJ2Bk6QrRzx6Z/6haaF4UiwBzytM96GRRRWZh9/WALIEO3npMamA== - -"@next/swc-linux-x64-gnu@16.4.0": - version "16.4.0" - resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.0.tgz#ad39993dd78811ec876c5dd8418e24d120460a58" - integrity sha512-D5M5xLWQVd1CvR+L7BickM1weRfmM41x3L1NWcnKY/oyJJqr1qwaCgmu3dMAhLBOMdZwSuDCRV6DJRRpiUkbDQ== - -"@next/swc-linux-x64-musl@16.4.0": - version "16.4.0" - resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.0.tgz#ffb02c6636f0ed9d786cd072bf60b6d48390a1bd" - integrity sha512-8d5WLS6a9YalqpOgXdlbvonFu+sIgjA+CO6tGzetrpPVcUL56foa7B7664h41rAlbLi5fJwK4vWji3zf4QDy+w== - -"@next/swc-win32-arm64-msvc@16.4.0": - version "16.4.0" - resolved "https://registry.yarnpkg.com/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.0.tgz#16bc9ec0d095a4588e24975531fb53b04ca25019" - integrity sha512-sQuOIiW3snb48UwrBcDMvFA/u03qtw2LeuSIxFIQ9AJuW9UG/4Ddsfo+eV73PnZwBhyncMtsKVh7PrzMol2/fA== - -"@next/swc-win32-x64-msvc@16.4.0": - version "16.4.0" - resolved "https://registry.yarnpkg.com/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.0.tgz#426dfc826f07e2438ac4581d61c1accde388303c" - integrity sha512-6/33lCuxpdHUy27RegyGM/5uTpF7YZd3UR4D0gpkOA/tWY5YR7msbQjqPgCZmSmxrrTLGCXYA4A8vT2H5DPGTQ== +"@next/swc-darwin-arm64@16.4.6": + version "16.4.6" + resolved "https://registry.yarnpkg.com/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.6.tgz#12ef59eb2a31f4320d7b8d2b26d98c6442cd8cc9" + integrity sha512-kJ4VVZkley17xKaJx72QN2IBqjrj7zenCQZaUF0l9ShS/1Mt2kW4+Z5KGG6vgr3L/J562xTOizVyM1iA/u5nlg== + +"@next/swc-darwin-x64@16.4.6": + version "16.4.6" + resolved "https://registry.yarnpkg.com/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.6.tgz#659bef508bfa7bc644d6449904a20cbee690dbd3" + integrity sha512-eIPGZIqC+8JKaeZmvnCANJQF4xWkkHqSnAAajtFxgwDMAOnCgxNvP52SeWZ41PyVwoe+Le/NQuZSaQ8j7YshSA== + +"@next/swc-linux-arm64-gnu@16.4.6": + version "16.4.6" + resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.6.tgz#efec64c2f4ad4270416ddd3c1a30eb87b33db18a" + integrity sha512-9nI6O8vvczH2D9ZNdMGqb/3NuT15T9ksOZnAmx9/gjF2cOi74+xxyf1Hk96uIMfm14c9y6wHeBq6SH8g6udvcA== + +"@next/swc-linux-arm64-musl@16.4.6": + version "16.4.6" + resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.6.tgz#f7f663ebc7210dc360d44a3d85e0bb79af5931c5" + integrity sha512-7/qPhTxDp2ScluOJOhLuhWmlA17o1yZ0SIgpISBCpBxXgtnK4+KGywBpFkfLPiU1rnSM1faFGzYkH6i7JdTrqA== + +"@next/swc-linux-x64-gnu@16.4.6": + version "16.4.6" + resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.6.tgz#1bc1c10eb94808f526333e03950e11fb0cd83ae6" + integrity sha512-oOpbNa8XOW1qCGd9VvzC4fbkkRxEls7/WI6tz+YHC0xRA7KpV1U7DrAnCPjzVyOk/karzWEepCOcTIDmwK8FwQ== + +"@next/swc-linux-x64-musl@16.4.6": + version "16.4.6" + resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.6.tgz#15d014065483233623d1126f5e94fc599bdb5ec1" + integrity sha512-aM8CZ+OR2EwXaAYw7KGkW2GDmNDsLBIRe1MMRZCJPTdw/xhTD0IMUVO4sf3KqrzuRouGzwwLZn34+gFeVXiUQA== + +"@next/swc-win32-arm64-msvc@16.4.6": + version "16.4.6" + resolved "https://registry.yarnpkg.com/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.6.tgz#150f6424c2e7ee31b14be5937d5596ed60cd3278" + integrity sha512-U0p7/tEtqvHX2crhd841CDwKtp5CFkKXVjOhmfccR3Pvp64sj8KBwRqsvltqLOwVBbj0NtkxwXSDpEHYGbxeXQ== + +"@next/swc-win32-x64-msvc@16.4.6": + version "16.4.6" + resolved "https://registry.yarnpkg.com/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.6.tgz#78d5010d48e4d73073d62d4a085025ad59965595" + integrity sha512-3ZG15/5WIdlTQsIEvc9sPTTSL5XFrlLklIKmfF4fwsDnoAhu6NcBDXsk3mbGxNyo6aVLEGex+fHCv2MahY7a9g== "@nodelib/fs.scandir@2.1.5": version "2.1.5" @@ -5380,27 +5380,27 @@ next-tick@^1.1.0: resolved "https://registry.npmjs.org/next-tick/-/next-tick-1.1.0.tgz" integrity sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ== -next@^16.4.0: - version "16.4.0" - resolved "https://registry.yarnpkg.com/next/-/next-16.4.0.tgz#880d9da9d4b2a41bc0010d6f01d659aa24185ec7" - integrity sha512-N2C+9q89Z/oLrsepSRS4jRMtwmUZAoZuAHU0e9T6+sAB5DdhADmrnOW+zjYijlrYFmVfmQhGVGy9eMFoB7UgKg== +next@16.4.6: + version "16.4.6" + resolved "https://registry.yarnpkg.com/next/-/next-16.4.6.tgz#ce48f58e195a8eb224e58a2d136451f17c19d5cf" + integrity sha512-QZJiYhaZLJMo2KpkQGQIwvmd79WVsAWeYIU554a8d7zArS3si/IRy3lBNV/rtYhE70oLwdLYhPAXLPx8HwcwtA== dependencies: - "@next/env" "16.4.0" + "@next/env" "16.4.6" "@swc/helpers" "0.5.23" baseline-browser-mapping "^2.9.19" caniuse-lite "^1.0.30001579" postcss "8.5.23" styled-jsx "5.1.6" optionalDependencies: - "@next/swc-darwin-arm64" "16.4.0" - "@next/swc-darwin-x64" "16.4.0" - "@next/swc-linux-arm64-gnu" "16.4.0" - "@next/swc-linux-arm64-musl" "16.4.0" - "@next/swc-linux-x64-gnu" "16.4.0" - "@next/swc-linux-x64-musl" "16.4.0" - "@next/swc-win32-arm64-msvc" "16.4.0" - "@next/swc-win32-x64-msvc" "16.4.0" - sharp "^0.35.4" + "@next/swc-darwin-arm64" "16.4.6" + "@next/swc-darwin-x64" "16.4.6" + "@next/swc-linux-arm64-gnu" "16.4.6" + "@next/swc-linux-arm64-musl" "16.4.6" + "@next/swc-linux-x64-gnu" "16.4.6" + "@next/swc-linux-x64-musl" "16.4.6" + "@next/swc-win32-arm64-msvc" "16.4.6" + "@next/swc-win32-x64-msvc" "16.4.6" + sharp "^0.35.5" node-exports-info@^1.6.0: version "1.6.0" @@ -6181,7 +6181,7 @@ set-proto@^1.0.0: es-errors "^1.3.0" es-object-atoms "^1.0.0" -sharp@^0.35.4: +sharp@^0.35.5: version "0.35.5" resolved "https://registry.yarnpkg.com/sharp/-/sharp-0.35.5.tgz#43fb539872ec5f53cc7162eb850dbf6514692fbf" integrity sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g== From e021feee69f539f04c09d0f5a1b22c727705528d Mon Sep 17 00:00:00 2001 From: osamaayub Date: Wed, 11 Nov 2026 15:49:57 +0500 Subject: [PATCH 3/3] feat: add password reset and admin user management Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .env.example | 7 + README.md | 17 +- app/(auth)/forgot-password/page.tsx | 5 + app/(auth)/layout.tsx | 26 +-- app/(auth)/reset-password/page.tsx | 30 +++ app/(auth)/sign-in/page.tsx | 45 ++-- app/(auth)/sign-up/page.tsx | 20 +- app/(root)/admin/users/page.tsx | 35 +++ features/auth/account-link.actions.ts | 80 +++++++ features/auth/actions.ts | 20 +- .../auth/components/AccountLinkDialog.tsx | 147 ++++++++++++ features/auth/components/AuthFlowCard.tsx | 17 ++ features/auth/components/AuthForm.tsx | 11 + features/auth/components/AuthPanel.tsx | 38 ++++ .../auth/components/PasswordResetScreens.tsx | 203 +++++++++++++++++ features/auth/components/SignInScreen.tsx | 36 +++ features/auth/components/index.ts | 3 + features/auth/password-reset.actions.ts | 212 ++++++++++++++++++ features/users/admin-actions.ts | 185 +++++++++++++++ features/users/components/AdminUserRow.tsx | 148 ++++++++++++ .../users/components/AdminUsersContent.tsx | 69 ++++++ features/users/components/index.ts | 2 + server/admin-access.ts | 21 ++ server/auth.ts | 72 +++++- server/db/models/AuthToken/index.ts | 16 ++ server/db/models/index.ts | 1 + server/db/schemas/AuthToken.schema.ts | 41 ++++ server/db/schemas/User.schema.ts | 9 + server/db/schemas/index.ts | 1 + shared/components/navigation/LeftSidebar.tsx | 4 +- .../navigation/navbar/MobileNavigation.tsx | 4 +- .../components/navigation/navbar/NavLinks.tsx | 4 +- .../components/navigation/navbar/navbar.tsx | 3 +- shared/constants/index.ts | 6 + shared/constants/route.ts | 3 + shared/lib/validation.ts | 4 +- 36 files changed, 1474 insertions(+), 71 deletions(-) create mode 100644 app/(auth)/forgot-password/page.tsx create mode 100644 app/(auth)/reset-password/page.tsx create mode 100644 app/(root)/admin/users/page.tsx create mode 100644 features/auth/account-link.actions.ts create mode 100644 features/auth/components/AccountLinkDialog.tsx create mode 100644 features/auth/components/AuthFlowCard.tsx create mode 100644 features/auth/components/AuthPanel.tsx create mode 100644 features/auth/components/PasswordResetScreens.tsx create mode 100644 features/auth/components/SignInScreen.tsx create mode 100644 features/auth/password-reset.actions.ts create mode 100644 features/users/admin-actions.ts create mode 100644 features/users/components/AdminUserRow.tsx create mode 100644 features/users/components/AdminUsersContent.tsx create mode 100644 server/admin-access.ts create mode 100644 server/db/models/AuthToken/index.ts create mode 100644 server/db/schemas/AuthToken.schema.ts diff --git a/.env.example b/.env.example index a9d6f38..48207f1 100644 --- a/.env.example +++ b/.env.example @@ -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= diff --git a/README.md b/README.md index 24411b6..72e8b06 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,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. @@ -213,7 +220,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` | --- @@ -328,15 +336,15 @@ npm run db:backfill-question-tags # Restore tags for legacy questions - [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) @@ -365,6 +373,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 diff --git a/app/(auth)/forgot-password/page.tsx b/app/(auth)/forgot-password/page.tsx new file mode 100644 index 0000000..eda77f8 --- /dev/null +++ b/app/(auth)/forgot-password/page.tsx @@ -0,0 +1,5 @@ +import { PasswordResetRequestScreen } from "@/features/auth/components/PasswordResetScreens" + +export default function ForgotPasswordPage() { + return +} diff --git a/app/(auth)/layout.tsx b/app/(auth)/layout.tsx index bcfe733..15eba0e 100644 --- a/app/(auth)/layout.tsx +++ b/app/(auth)/layout.tsx @@ -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 ( -
-
-
-
-

Join DevFlow

-

- To get Your Questions answered -

-
- site logo -
- {children} - -
+
+ {children}
); }; diff --git a/app/(auth)/reset-password/page.tsx b/app/(auth)/reset-password/page.tsx new file mode 100644 index 0000000..bcbdc86 --- /dev/null +++ b/app/(auth)/reset-password/page.tsx @@ -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 +} + +export default function ResetPasswordPage({ searchParams }: ResetPasswordPageProps) { + return ( + +

Choose a new password

+
+ + } + > + + + ) +} diff --git a/app/(auth)/sign-in/page.tsx b/app/(auth)/sign-in/page.tsx index b6d43a6..d9349e8 100644 --- a/app/(auth)/sign-in/page.tsx +++ b/app/(auth)/sign-in/page.tsx @@ -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 ( - 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 +} +export default function SignInPage({ searchParams }: SignInPageProps) { + return ( + +
+ + } + > + + + ) +} diff --git a/app/(auth)/sign-up/page.tsx b/app/(auth)/sign-up/page.tsx index 7cd2313..0642aab 100644 --- a/app/(auth)/sign-up/page.tsx +++ b/app/(auth)/sign-up/page.tsx @@ -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 ( - signUpWithCredentials(data)} - /> + + signUpWithCredentials(data)} + /> + ); }; diff --git a/app/(root)/admin/users/page.tsx b/app/(root)/admin/users/page.tsx new file mode 100644 index 0000000..136b342 --- /dev/null +++ b/app/(root)/admin/users/page.tsx @@ -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 +} + +export default async function AdminUsersPage({ searchParams }: AdminUsersPageProps) { + const session = await auth() + if (!isAdminEmail(session?.user?.email)) redirect(Routes.HOME) + + return ( + +

User Management

+
+
+ } + > + + + ) +} diff --git a/features/auth/account-link.actions.ts b/features/auth/account-link.actions.ts new file mode 100644 index 0000000..086492e --- /dev/null +++ b/features/auth/account-link.actions.ts @@ -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 +): Promise { + 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." } + } +} diff --git a/features/auth/actions.ts b/features/auth/actions.ts index 455c01e..6cb5bb8 100644 --- a/features/auth/actions.ts +++ b/features/auth/actions.ts @@ -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)) diff --git a/features/auth/components/AccountLinkDialog.tsx b/features/auth/components/AccountLinkDialog.tsx new file mode 100644 index 0000000..75f902a --- /dev/null +++ b/features/auth/components/AccountLinkDialog.tsx @@ -0,0 +1,147 @@ +"use client" + +import { useRouter } from "next/navigation" +import { signIn } from "next-auth/react" +import { FormEvent, useState } from "react" +import { toast } from "sonner" + +import { createAccountLinkIntent } from "@/features/auth/account-link.actions" +import Routes from "@/shared/constants/route" + +type AccountLinkDialogProps = { + provider: "google" | "github" +} + +const providerName = { + google: "Google", + github: "GitHub" +} as const + +export function AccountLinkDialog({ provider }: AccountLinkDialogProps) { + const router = useRouter() + const [showCredentials, setShowCredentials] = useState(false) + const [email, setEmail] = useState("") + const [password, setPassword] = useState("") + const [isSubmitting, setIsSubmitting] = useState(false) + + const closeDialog = () => router.replace(Routes.SIGN_IN) + + const handleLink = async (event: FormEvent) => { + event.preventDefault() + setIsSubmitting(true) + + try { + const result = await createAccountLinkIntent({ email, password, provider }) + if (!result.success) { + toast.error(result.error || "Unable to verify your account.") + return + } + + const response = await signIn(provider, { + redirect: false, + redirectTo: Routes.HOME + }) + if (response?.url) { + window.location.assign(response.url) + } else { + toast.error("Unable to continue account linking. Please try again.") + } + } catch { + toast.error("Unable to continue account linking. Please try again.") + } finally { + setIsSubmitting(false) + } + } + + return ( +
+
+ {!showCredentials ? ( + <> + +

+ It seems you've previously created an account using your email and password. +

+

+ You can link your {providerName[provider]} login after confirming your existing account. +

+

+ Your existing account stays the same, and you can keep signing in with either method. +

+ + + + ) : ( + <> + +

+ Sign in with your DevFlow email and password to authorize linking your {providerName[provider]} account. +

+
+ + setEmail(event.target.value)} + className="background-light900_dark300 light-border-2 text-dark300_light700 min-h-10 w-full rounded-md border px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-orange-400" + /> + + setPassword(event.target.value)} + className="background-light900_dark300 light-border-2 text-dark300_light700 min-h-10 w-full rounded-md border px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-orange-400" + /> + + +
+ + )} +
+
+ ) +} diff --git a/features/auth/components/AuthFlowCard.tsx b/features/auth/components/AuthFlowCard.tsx new file mode 100644 index 0000000..868085c --- /dev/null +++ b/features/auth/components/AuthFlowCard.tsx @@ -0,0 +1,17 @@ +import Image from "next/image" +import { ReactNode } from "react" + +export function AuthFlowCard({ children }: { children: ReactNode }) { + return ( +
+ DevFlow + {children} +
+ ) +} diff --git a/features/auth/components/AuthForm.tsx b/features/auth/components/AuthForm.tsx index 0abb453..0cf7bfa 100644 --- a/features/auth/components/AuthForm.tsx +++ b/features/auth/components/AuthForm.tsx @@ -98,6 +98,17 @@ export function AuthForm({ /> ))} + {formType === "SIGN_IN" && ( +
+ + Forgot password? + +
+ )} + {form.formState.errors.root && (

{form.formState.errors.root.message}

)} diff --git a/features/auth/components/AuthPanel.tsx b/features/auth/components/AuthPanel.tsx new file mode 100644 index 0000000..84a13c4 --- /dev/null +++ b/features/auth/components/AuthPanel.tsx @@ -0,0 +1,38 @@ +import Image from "next/image" +import { ReactNode } from "react" + +import SocialAuthForm from "./SocialAuthForm" + +type AuthPanelProps = { + title: string + description: string + children: ReactNode + showSocialAuth?: boolean +} + +export function AuthPanel({ + title, + description, + children, + showSocialAuth = false +}: AuthPanelProps) { + return ( +
+
+
+

{title}

+

{description}

+
+ DevFlow +
+ {children} + {showSocialAuth && } +
+ ) +} diff --git a/features/auth/components/PasswordResetScreens.tsx b/features/auth/components/PasswordResetScreens.tsx new file mode 100644 index 0000000..60b2b44 --- /dev/null +++ b/features/auth/components/PasswordResetScreens.tsx @@ -0,0 +1,203 @@ +"use client" + +import Link from "next/link" +import { useRouter } from "next/navigation" +import { FormEvent, useState } from "react" + +import { AuthFlowCard } from "@/features/auth/components/AuthFlowCard" +import { requestPasswordReset, resetPassword } from "@/features/auth/password-reset.actions" +import Routes from "@/shared/constants/route" + +type PasswordResetScreensProps = { + token?: string +} + +export function PasswordResetRequestScreen() { + const [email, setEmail] = useState("") + const [sentTo, setSentTo] = useState(null) + const [error, setError] = useState("") + const [notice, setNotice] = useState("") + const [isSubmitting, setIsSubmitting] = useState(false) + + const sendLink = async (event?: FormEvent) => { + event?.preventDefault() + setError("") + setNotice("") + setIsSubmitting(true) + + try { + const result = await requestPasswordReset(email) + if (!result.success) { + setError(result.error || "Unable to send a reset link right now.") + return + } + + setSentTo(email.trim()) + setNotice("If an account exists for this address, a reset link is on its way.") + } finally { + setIsSubmitting(false) + } + } + + return ( + + {!sentTo ? ( + <> +

Forgot password?

+

+ No worries, we'll send you reset instructions. +

+
+ + setEmail(event.target.value)} + className="background-light900_dark300 light-border-2 text-dark300_light700 min-h-10 w-full rounded-md border px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-orange-400" + /> + {error &&

{error}

} + +
+ + ) : ( + <> +

Check your email

+

+ If an account exists for {sentTo}, we sent a password + reset link. +

+ + {notice &&

{notice}

} + {error &&

{error}

} + + )} + + โ†– Back to login + +
+ ) +} + +export function PasswordResetFormScreen({ token }: PasswordResetScreensProps) { + const router = useRouter() + const [password, setPassword] = useState("") + const [confirmPassword, setConfirmPassword] = useState("") + const [error, setError] = useState("") + const [isSubmitting, setIsSubmitting] = useState(false) + const [isComplete, setIsComplete] = useState(false) + + const handleSubmit = async (event: FormEvent) => { + event.preventDefault() + setError("") + + if (password !== confirmPassword) { + setError("Passwords do not match.") + return + } + if (!token) { + setError("This reset link is invalid or has expired. Request a new one.") + return + } + + setIsSubmitting(true) + try { + const result = await resetPassword(token, password) + if (!result.success) { + setError(result.error || "Unable to reset your password.") + return + } + setIsComplete(true) + router.replace(`${Routes.SIGN_IN}?passwordReset=1`) + } finally { + setIsSubmitting(false) + } + } + + return ( + + {isComplete ? ( + <> +

Password updated

+

+ Your password has been changed. You can now sign in with your new password. +

+ + Back to login + + + ) : ( + <> +

Choose a new password

+

+ Enter a new password for your DevFlow account. +

+
+ + setPassword(event.target.value)} + className="background-light900_dark300 light-border-2 text-dark300_light700 min-h-10 w-full rounded-md border px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-orange-400" + /> + + setConfirmPassword(event.target.value)} + className="background-light900_dark300 light-border-2 text-dark300_light700 min-h-10 w-full rounded-md border px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-orange-400" + /> + {error &&

{error}

} + +
+ + )} +
+ ) +} diff --git a/features/auth/components/SignInScreen.tsx b/features/auth/components/SignInScreen.tsx new file mode 100644 index 0000000..72074ff --- /dev/null +++ b/features/auth/components/SignInScreen.tsx @@ -0,0 +1,36 @@ +"use client" + +import { signInWithCredentials } from "@/features/auth/actions" +import { SignInSchema } from "@/shared/lib/validation" + +import { AccountLinkDialog } from "./AccountLinkDialog" +import { AuthForm } from "./AuthForm" +import { AuthPanel } from "./AuthPanel" + +type SignInScreenProps = { + provider: "google" | "github" | null + passwordReset: boolean +} + +export function SignInScreen({ provider, passwordReset }: SignInScreenProps) { + return ( + + {passwordReset && ( +

+ Your password has been updated. You can sign in now. +

+ )} + signInWithCredentials(data)} + /> + {provider && } +
+ ) +} diff --git a/features/auth/components/index.ts b/features/auth/components/index.ts index 97744ce..57b5f86 100644 --- a/features/auth/components/index.ts +++ b/features/auth/components/index.ts @@ -1,2 +1,5 @@ export { AuthForm } from "./AuthForm" export { default as SocialAuthForm } from "./SocialAuthForm" +export { AuthPanel } from "./AuthPanel" +export { AccountLinkDialog } from "./AccountLinkDialog" +export { SignInScreen } from "./SignInScreen" diff --git a/features/auth/password-reset.actions.ts b/features/auth/password-reset.actions.ts new file mode 100644 index 0000000..d2cef81 --- /dev/null +++ b/features/auth/password-reset.actions.ts @@ -0,0 +1,212 @@ +"use server" + +import { createHash, randomBytes } from "node:crypto" + +import bcrypt from "bcryptjs" +import mongoose, { Types } from "mongoose" +import { z } from "zod" + +import { Account, PasswordResetToken, User } from "@/server/db" +import { dbConnect } from "@/server/db/connect" +import logger from "@/shared/lib/logger" + +const emailSchema = z.string().trim().email() +const resetSchema = z.object({ + token: z.string().regex(/^[a-f0-9]{64}$/), + password: z.string().min(6).max(10) +}) + +type FlowResult = { success: true } | { success: false; error: string } + +const hashToken = (token: string) => createHash("sha256").update(token).digest("hex") + +function getEmailConfiguration() { + const apiKey = process.env.RESEND_API_KEY + const from = process.env.AUTH_EMAIL_FROM + const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || process.env.NEXTAUTH_URL + + if (!apiKey || !from || !siteUrl) { + throw new Error("Resend API key, sender address, and site URL must be configured.") + } + + return { apiKey, from, siteUrl: new URL(siteUrl).origin } +} + +async function deliverResetEmail(params: { + apiKey: string + from: string + siteUrl: string + email: string + name: string + token: string +}) { + const resetUrl = new URL("/reset-password", params.siteUrl) + resetUrl.searchParams.set("token", params.token) + const response = await fetch("https://api.resend.com/emails", { + method: "POST", + headers: { + Authorization: `Bearer ${params.apiKey}`, + "Content-Type": "application/json" + }, + body: JSON.stringify({ + from: params.from, + to: [params.email], + subject: "Reset your DevFlow password", + text: `Hi ${params.name},\n\nUse this link to reset your DevFlow password. It expires in one hour and can only be used once:\n${resetUrl.toString()}\n\nIf you did not request this, you can ignore this email.`, + html: `

Hi ${escapeHtml(params.name)},

Use this link to reset your DevFlow password. It expires in one hour and can only be used once.

Reset password

If you did not request this, you can ignore this email.

` + }) + }) + + if (!response.ok) { + const responseBody = await response.text() + logger.error( + { status: response.status, response: responseBody }, + "Resend rejected a password reset email" + ) + throw new Error("Email delivery failed.") + } +} + +function escapeHtml(value: string) { + return value.replace(/[&<>"']/g, (character) => { + const entities: Record = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'" + } + return entities[character] + }) +} + +export async function requestPasswordReset(value: string): Promise { + const parsedEmail = emailSchema.safeParse(value) + if (!parsedEmail.success) { + return { success: false, error: "Please enter a valid email address." } + } + + let emailConfig: ReturnType + try { + emailConfig = getEmailConfiguration() + await dbConnect() + const normalizedEmail = parsedEmail.data.toLowerCase() + const emailPattern = new RegExp( + `^${normalizedEmail.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`, + "i" + ) + const user = (await User.findOne({ email: emailPattern }) + .select("_id email name") + .lean()) as { _id: Types.ObjectId; email: string; name: string } | null + + if (!user) { + logger.info("Skipped password reset email because no matching user was found") + return { success: true } + } + + const token = randomBytes(32).toString("hex") + const tokenHash = hashToken(token) + const expiresAt = new Date(Date.now() + 60 * 60 * 1000) + await PasswordResetToken.deleteMany({ userId: user._id }) + await PasswordResetToken.create({ tokenHash, userId: user._id, expiresAt }) + + try { + await deliverResetEmail({ + ...emailConfig, + email: user.email, + name: user.name, + token + }) + logger.info("Resend accepted a password reset email") + } catch (error) { + await PasswordResetToken.deleteOne({ tokenHash }) + throw error + } + + return { success: true } + } catch (error) { + logger.error({ err: error }, "Failed to process a password reset request") + return { + success: false, + error: "Password reset email is unavailable right now. Please try again later." + } + } +} + +export async function resetPassword(token: string, password: string): Promise { + const parsed = resetSchema.safeParse({ token, password }) + if (!parsed.success) { + return { success: false, error: "The reset link or password is invalid." } + } + + let result: FlowResult = { + success: false, + error: "Unable to reset your password. Please try again." + } + const session = await mongoose.startSession() + + try { + await dbConnect() + await session.withTransaction(async () => { + const tokenHash = hashToken(parsed.data.token) + const resetRecord = (await PasswordResetToken.findOne({ + tokenHash, + expiresAt: { $gt: new Date() } + }) + .select("userId") + .session(session) + .lean()) as { userId: Types.ObjectId } | null + + if (!resetRecord) { + result = { success: false, error: "This reset link has expired or has already been used." } + return + } + + const user = (await User.findById(resetRecord.userId) + .select("email name") + .session(session) + .lean()) as { email: string; name: string } | null + if (!user) { + result = { success: false, error: "This account could not be found. Request a new link." } + return + } + + const passwordHash = await bcrypt.hash(parsed.data.password, 12) + const consumedToken = await PasswordResetToken.findOneAndDelete({ + tokenHash, + expiresAt: { $gt: new Date() } + }).session(session) + if (!consumedToken) { + result = { success: false, error: "This reset link has expired or has already been used." } + return + } + + const email = user.email.trim().toLowerCase() + const updateResult = await Account.updateOne( + { userId: resetRecord.userId, provider: "credentials" }, + { + $set: { name: user.name, password: passwordHash, providerAccountId: email }, + $setOnInsert: { + userId: resetRecord.userId, + provider: "credentials" + } + }, + { upsert: true, session } + ) + if (updateResult.matchedCount + updateResult.upsertedCount !== 1) { + logger.error({ userId: resetRecord.userId.toString() }, "Password reset account disappeared") + throw new Error("Password reset account update failed.") + } + + await PasswordResetToken.deleteMany({ userId: resetRecord.userId }).session(session) + result = { success: true } + }) + + return result + } catch (error) { + logger.error({ err: error }, "Failed to reset a DevFlow password") + return { success: false, error: "Unable to reset your password. Please try again." } + } finally { + await session.endSession() + } +} diff --git a/features/users/admin-actions.ts b/features/users/admin-actions.ts new file mode 100644 index 0000000..a6839e0 --- /dev/null +++ b/features/users/admin-actions.ts @@ -0,0 +1,185 @@ +"use server" + +import { Types } from "mongoose" +import { revalidatePath } from "next/cache" +import { z } from "zod" + +import { getAdminActorId, isAdminEmail } from "@/server/admin-access" +import { User } from "@/server/db" +import { dbConnect } from "@/server/db/connect" +import logger from "@/shared/lib/logger" + +const userIdSchema = z.string().regex(/^[0-9a-f]{24}$/i) +const searchSchema = z.string().trim().max(100) +const updateUserSchema = z.object({ + userId: userIdSchema, + name: z.string().trim().min(2).max(80), + username: z + .string() + .trim() + .toLowerCase() + .min(2) + .max(30) + .regex(/^[a-z0-9._-]+$/, "Username can only contain letters, numbers, dots, underscores, and hyphens."), + bio: z.string().trim().max(500), + location: z.string().trim().max(100), + portfolio: z.union([z.literal(""), z.string().trim().url()]) +}) + +export type ManagedUser = { + _id: string + name: string + username: string + email: string + bio: string + location: string + portfolio: string + isSuspended: boolean + isAdmin: boolean + createdAt: string +} + +type AdminActionResult = + | { success: true; data?: T } + | { success: false; error: string } + +export async function getManagedUsers(value: string): Promise> { + const actorId = await getAdminActorId() + if (!actorId) return { success: false, error: "You are not authorized to manage users." } + + const parsedQuery = searchSchema.safeParse(value) + if (!parsedQuery.success) { + return { success: false, error: "Search text must be 100 characters or fewer." } + } + + try { + await dbConnect() + const query = parsedQuery.data + const filter = query + ? { + $or: ["name", "username", "email"].map((field) => ({ + [field]: { $regex: escapeRegex(query), $options: "i" } + })) + } + : {} + const users = await User.find(filter) + .select("name username email bio location portfolio isSuspended createdAt") + .sort({ createdAt: -1 }) + .limit(100) + .lean() + + return { + success: true, + data: users.map((user) => ({ + _id: String(user._id), + name: user.name, + username: user.username, + email: user.email, + bio: user.bio ?? "", + location: user.location ?? "", + portfolio: user.portfolio ?? "", + isSuspended: user.isSuspended === true, + isAdmin: isAdminEmail(user.email), + createdAt: new Date(user.createdAt ?? Date.now()).toISOString() + })) + } + } catch (error) { + logger.error({ err: error }, "Failed to load managed users") + return { success: false, error: "Unable to load users right now." } + } +} + +export async function updateManagedUser(input: unknown): Promise { + const actorId = await getAdminActorId() + if (!actorId) return { success: false, error: "You are not authorized to manage users." } + + const parsed = updateUserSchema.safeParse(input) + if (!parsed.success) { + return { + success: false, + error: parsed.error.issues[0]?.message ?? "Please check the user details and try again." + } + } + + try { + await dbConnect() + const { userId, name, username, bio, location, portfolio } = parsed.data + const existingUser = await User.findById(userId).select("email").lean() + if (!existingUser) return { success: false, error: "User not found." } + + const duplicateUsername = await User.findOne({ + username: { $regex: `^${escapeRegex(username)}$`, $options: "i" }, + _id: { $ne: new Types.ObjectId(userId) } + }) + .select("_id") + .lean() + if (duplicateUsername) return { success: false, error: "That username is already in use." } + + await User.updateOne( + { _id: userId }, + { $set: { name, username, bio, location, portfolio } }, + { runValidators: true } + ) + + revalidatePath("/admin/users") + revalidatePath(`/profile/${userId}`) + revalidatePath("/community") + return { success: true } + } catch (error) { + logger.error({ err: error }, "Failed to update a managed user") + return { success: false, error: "Unable to update this user right now." } + } +} + +export async function setUserSuspension( + userId: string, + isSuspended: boolean +): Promise { + const actorId = await getAdminActorId() + if (!actorId) return { success: false, error: "You are not authorized to manage users." } + + const parsedId = userIdSchema.safeParse(userId) + if (!parsedId.success || typeof isSuspended !== "boolean") { + return { success: false, error: "Invalid user or suspension status." } + } + if (actorId === parsedId.data) { + return { success: false, error: "You cannot suspend your own account." } + } + + try { + await dbConnect() + const targetUser = await User.findById(parsedId.data) + .select("email") + .lean<{ email: string } | null>() + if (!targetUser) return { success: false, error: "User not found." } + if (isAdminEmail(targetUser.email)) { + return { success: false, error: "Administrator accounts cannot be suspended here." } + } + + await User.updateOne( + { _id: parsedId.data }, + { + $set: { + isSuspended, + suspendedAt: isSuspended ? new Date() : null + } + } + ) + + revalidatePath("/admin/users") + revalidatePath(`/profile/${parsedId.data}`) + revalidatePath("/community") + logger.info( + { actorId, targetUserId: parsedId.data, isSuspended }, + "Admin changed user suspension status" + ) + return { success: true } + } catch (error) { + logger.error({ err: error }, "Failed to change user suspension status") + return { success: false, error: "Unable to update this account right now." } + } +} + +function escapeRegex(value: string) { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") +} diff --git a/features/users/components/AdminUserRow.tsx b/features/users/components/AdminUserRow.tsx new file mode 100644 index 0000000..ef11f6f --- /dev/null +++ b/features/users/components/AdminUserRow.tsx @@ -0,0 +1,148 @@ +"use client" + +import { useRouter } from "next/navigation" +import { FormEvent, useState } from "react" +import { toast } from "sonner" + +import { + ManagedUser, + setUserSuspension, + updateManagedUser +} from "@/features/users/admin-actions" +import { Button, Input } from "@/shared/components/ui" + +export function AdminUserRow({ user }: { user: ManagedUser }) { + const router = useRouter() + const [isEditing, setIsEditing] = useState(false) + const [isSaving, setIsSaving] = useState(false) + const [isChangingStatus, setIsChangingStatus] = useState(false) + + const handleUpdate = async (event: FormEvent) => { + event.preventDefault() + setIsSaving(true) + + const formData = new FormData(event.currentTarget) + const result = await updateManagedUser({ + userId: user._id, + name: formData.get("name"), + username: formData.get("username"), + bio: formData.get("bio"), + location: formData.get("location"), + portfolio: formData.get("portfolio") + }) + + setIsSaving(false) + if (!result.success) { + toast.error(result.error) + return + } + + toast.success("User profile updated.") + setIsEditing(false) + router.refresh() + } + + const handleSuspension = async () => { + const action = user.isSuspended ? "restore" : "suspend" + if (!window.confirm(`Are you sure you want to ${action} ${user.name}'s account?`)) return + + setIsChangingStatus(true) + const result = await setUserSuspension(user._id, !user.isSuspended) + setIsChangingStatus(false) + + if (!result.success) { + toast.error(result.error) + return + } + + toast.success(user.isSuspended ? "Account restored." : "Account suspended.") + router.refresh() + } + + return ( +
+
+
+
+

{user.name}

+ {user.isAdmin && ( + + Admin + + )} + {user.isSuspended && ( + + Suspended + + )} +
+

+ @{user.username} ยท {user.email} +

+

+ Joined {new Date(user.createdAt).toLocaleDateString()} +

+
+
+ + {!user.isAdmin && ( + + )} +
+
+ + {isEditing && ( +
+ + + + +