-
Notifications
You must be signed in to change notification settings - Fork 1
Implement Admin Page #133
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Shengle-Dai
wants to merge
4
commits into
main
Choose a base branch
from
admin-paeg
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Implement Admin Page #133
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| import { Request, Response } from "express-serve-static-core"; | ||
| import { | ||
| getAllOrganizations, | ||
| updateOrganizationAuthorized, | ||
| } from "./admin.services"; | ||
| import { | ||
| AdminOrganizationSchema, | ||
| UpdateOrganizationAuthorizedBody, | ||
| } from "common"; | ||
| import { z } from "zod"; | ||
|
|
||
| interface OrganizationParams { | ||
| id: string; | ||
| } | ||
|
|
||
| export const verifyAdminHandler = async (_req: Request, res: Response) => { | ||
| res.status(200).json({ message: "Admin verified", data: { isAdmin: true } }); | ||
| }; | ||
|
|
||
| export const getAllOrganizationsHandler = async ( | ||
| _req: Request, | ||
| res: Response, | ||
| ) => { | ||
| const organizations = await getAllOrganizations(); | ||
|
|
||
| const parsed = AdminOrganizationSchema.array().safeParse(organizations); | ||
| if (!parsed.success) { | ||
| res.status(500).json({ message: "Internal server error" }); | ||
| return; | ||
| } | ||
|
|
||
| res | ||
| .status(200) | ||
| .json({ message: "Organizations retrieved", data: parsed.data }); | ||
| }; | ||
|
|
||
| export const updateOrganizationAuthorizedHandler = async ( | ||
| req: Request< | ||
| OrganizationParams, | ||
| any, | ||
| z.infer<typeof UpdateOrganizationAuthorizedBody>, | ||
| {} | ||
| >, | ||
| res: Response, | ||
| ) => { | ||
| const organization = await updateOrganizationAuthorized( | ||
| req.params.id, | ||
| req.body.authorized, | ||
| ); | ||
|
|
||
| const parsed = AdminOrganizationSchema.safeParse(organization); | ||
| if (!parsed.success) { | ||
| res.status(500).json({ message: "Internal server error" }); | ||
| return; | ||
| } | ||
|
|
||
| res | ||
| .status(200) | ||
| .json({ message: "Organization authorization updated", data: parsed.data }); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| import { Router } from "express"; | ||
| import { authenticate } from "../../middleware/authenticate"; | ||
| import { authorizeAdmin } from "../../middleware/authorizeAdmin"; | ||
| import validate from "../../middleware/validate"; | ||
| import { UpdateOrganizationAuthorizedBody } from "common"; | ||
| import { | ||
| verifyAdminHandler, | ||
| getAllOrganizationsHandler, | ||
| updateOrganizationAuthorizedHandler, | ||
| } from "./admin.handlers"; | ||
| import { | ||
| asyncHandler, | ||
| handlePrismaErrors, | ||
| } from "../../middleware/handlePrismaErrors"; | ||
| import { z } from "zod"; | ||
|
|
||
| const adminRouter = Router(); | ||
|
|
||
| const OrganizationParams = z.object({ | ||
| id: z.string().uuid(), | ||
| }); | ||
|
|
||
| adminRouter.get( | ||
| "/verify", | ||
| authenticate, | ||
| authorizeAdmin, | ||
| asyncHandler(verifyAdminHandler), | ||
| ); | ||
|
|
||
| adminRouter.get( | ||
| "/organizations", | ||
| authenticate, | ||
| authorizeAdmin, | ||
| asyncHandler(getAllOrganizationsHandler), | ||
| ); | ||
|
|
||
| adminRouter.post( | ||
| "/organizations/:id/authorize", | ||
| validate({ params: OrganizationParams, body: UpdateOrganizationAuthorizedBody }), | ||
| authenticate, | ||
| authorizeAdmin, | ||
| asyncHandler(updateOrganizationAuthorizedHandler), | ||
| ); | ||
|
|
||
| adminRouter.use(handlePrismaErrors); | ||
|
|
||
| export default adminRouter; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| import { prisma } from "../../utils/prisma"; | ||
|
|
||
| export const getAllOrganizations = async () => { | ||
| const organizations = await prisma.organization.findMany({ | ||
| include: { | ||
| admins: true, | ||
| }, | ||
| orderBy: { | ||
| createdAt: "desc", | ||
| }, | ||
| }); | ||
|
|
||
| return organizations; | ||
| }; | ||
|
|
||
| export const updateOrganizationAuthorized = async ( | ||
| organizationId: string, | ||
| authorized: boolean, | ||
| ) => { | ||
| const organization = await prisma.organization.update({ | ||
| where: { id: organizationId }, | ||
| data: { authorized }, | ||
| include: { | ||
| admins: true, | ||
| }, | ||
| }); | ||
|
|
||
| return organization; | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export { default } from "./admin.router"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| import { NextFunction, Request, Response } from "express-serve-static-core"; | ||
|
|
||
| const getAdminEmails = (): string[] => { | ||
| const raw = process.env.ADMIN_EMAILS ?? ""; | ||
| return raw | ||
| .split(",") | ||
| .map((e) => e.trim().toLowerCase()) | ||
| .filter(Boolean); | ||
| }; | ||
|
|
||
| // Checks if the authenticated user's email is in the ADMIN_EMAILS env var. | ||
| // Must be used after the `authenticate` middleware. | ||
| export const authorizeAdmin = async <ParamsT, BodyT, QueryT>( | ||
| _req: Request<ParamsT, any, BodyT, QueryT>, | ||
| res: Response, | ||
| next: NextFunction, | ||
| ) => { | ||
| const user = res.locals.user; | ||
| if (!user?.email) { | ||
| res.status(403).json({ message: "Forbidden: admin access required" }); | ||
| return; | ||
| } | ||
|
|
||
| const adminEmails = getAdminEmails(); | ||
| if (!adminEmails.includes(user.email.toLowerCase())) { | ||
| res.status(403).json({ message: "Forbidden: admin access required" }); | ||
| return; | ||
| } | ||
|
|
||
| next(); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
159 changes: 159 additions & 0 deletions
159
frontend/src/app/admin/components/AdminOrganizationsTable.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,159 @@ | ||
| "use client"; | ||
|
|
||
| import { useState } from "react"; | ||
| import { useRouter } from "next/navigation"; | ||
| import { z } from "zod"; | ||
| import { AdminOrganizationSchema } from "common"; | ||
| import { createClient } from "@/utils/supabase/client"; | ||
| import { mutationFetch } from "@/lib/fetcher"; | ||
| import { toast } from "sonner"; | ||
| import { | ||
| Table, | ||
| TableBody, | ||
| TableCell, | ||
| TableHead, | ||
| TableHeader, | ||
| TableRow, | ||
| } from "@/components/ui/table"; | ||
| import { Badge } from "@/components/ui/badge"; | ||
| import { Button } from "@/components/ui/button"; | ||
| import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; | ||
| import { ShieldCheck, ShieldX } from "lucide-react"; | ||
|
|
||
| type Organization = z.infer<typeof AdminOrganizationSchema>; | ||
|
|
||
| interface AdminOrganizationsTableProps { | ||
| organizations: Organization[]; | ||
| } | ||
|
|
||
| export default function AdminOrganizationsTable({ | ||
| organizations, | ||
| }: AdminOrganizationsTableProps) { | ||
| const router = useRouter(); | ||
| const supabase = createClient(); | ||
| const [loadingId, setLoadingId] = useState<string | null>(null); | ||
|
|
||
| const handleAuthorize = async (orgId: string, authorized: boolean) => { | ||
| setLoadingId(orgId); | ||
| try { | ||
| const { | ||
| data: { session }, | ||
| } = await supabase.auth.getSession(); | ||
| if (!session?.access_token) { | ||
| toast.error("Session expired. Please sign in again."); | ||
| return; | ||
| } | ||
|
|
||
| await mutationFetch(`/admin/organizations/${orgId}/authorize`, { | ||
| method: "POST", | ||
| token: session.access_token, | ||
| body: { authorized }, | ||
| }); | ||
|
|
||
| toast.success( | ||
| authorized ? "Organization approved" : "Organization approval revoked", | ||
| ); | ||
| router.refresh(); | ||
| } catch (error) { | ||
| toast.error( | ||
| error instanceof Error ? error.message : "Failed to update organization", | ||
| ); | ||
| } finally { | ||
| setLoadingId(null); | ||
| } | ||
| }; | ||
|
|
||
| const pending = organizations.filter((org) => !org.authorized); | ||
| const approved = organizations.filter((org) => org.authorized); | ||
|
|
||
| const renderTable = (orgs: Organization[]) => { | ||
| if (orgs.length === 0) { | ||
| return ( | ||
| <p className="text-muted-foreground text-sm py-8 text-center"> | ||
| No organizations found. | ||
| </p> | ||
| ); | ||
| } | ||
|
|
||
| return ( | ||
| <div className="rounded-md border"> | ||
| <Table> | ||
| <TableHeader> | ||
| <TableRow> | ||
| <TableHead>Name</TableHead> | ||
| <TableHead>Admins</TableHead> | ||
| <TableHead>Status</TableHead> | ||
| <TableHead>Created</TableHead> | ||
| <TableHead className="text-right">Actions</TableHead> | ||
| </TableRow> | ||
| </TableHeader> | ||
| <TableBody> | ||
| {orgs.map((org) => ( | ||
| <TableRow key={org.id}> | ||
| <TableCell className="font-medium">{org.name}</TableCell> | ||
| <TableCell className="text-sm text-muted-foreground"> | ||
| {org.admins.map((a) => a.email).join(", ")} | ||
| </TableCell> | ||
| <TableCell> | ||
| {org.authorized ? ( | ||
| <Badge className="bg-green-100 text-green-800 hover:bg-green-100"> | ||
| Approved | ||
| </Badge> | ||
| ) : ( | ||
| <Badge variant="secondary">Pending</Badge> | ||
| )} | ||
| </TableCell> | ||
| <TableCell className="text-sm text-muted-foreground"> | ||
| {new Date(org.createdAt).toLocaleDateString()} | ||
| </TableCell> | ||
| <TableCell className="text-right"> | ||
| {org.authorized ? ( | ||
| <Button | ||
| variant="outline" | ||
| size="sm" | ||
| disabled={loadingId === org.id} | ||
| onClick={() => handleAuthorize(org.id, false)} | ||
| className="gap-1.5" | ||
| > | ||
| <ShieldX className="h-4 w-4" /> | ||
| Revoke | ||
| </Button> | ||
| ) : ( | ||
| <Button | ||
| size="sm" | ||
| disabled={loadingId === org.id} | ||
| onClick={() => handleAuthorize(org.id, true)} | ||
| className="gap-1.5" | ||
| > | ||
| <ShieldCheck className="h-4 w-4" /> | ||
| Approve | ||
| </Button> | ||
| )} | ||
| </TableCell> | ||
| </TableRow> | ||
| ))} | ||
| </TableBody> | ||
| </Table> | ||
| </div> | ||
| ); | ||
| }; | ||
|
|
||
| return ( | ||
| <Tabs defaultValue="pending"> | ||
| <TabsList> | ||
| <TabsTrigger value="pending"> | ||
| Pending ({pending.length}) | ||
| </TabsTrigger> | ||
| <TabsTrigger value="approved"> | ||
| Approved ({approved.length}) | ||
| </TabsTrigger> | ||
| <TabsTrigger value="all"> | ||
| All ({organizations.length}) | ||
| </TabsTrigger> | ||
| </TabsList> | ||
| <TabsContent value="pending">{renderTable(pending)}</TabsContent> | ||
| <TabsContent value="approved">{renderTable(approved)}</TabsContent> | ||
| <TabsContent value="all">{renderTable(organizations)}</TabsContent> | ||
| </Tabs> | ||
| ); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Reorder the middleware to
authenticate, authorizeAdmin, validateto match the other routes and prevent unauthenticated callers from inspecting the body schema.