refactor(auth): remove SessionProvider and sync user status on login/logout
This commit is contained in:
parent
0e6ee4dab2
commit
af10837072
7 changed files with 166 additions and 66 deletions
|
|
@ -4,20 +4,15 @@
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
|
import { db } from "@/db";
|
||||||
|
import { users } from "@/db/schema";
|
||||||
|
import { eq } from "drizzle-orm";
|
||||||
import { getUserServers } from "@/lib/services/server.service";
|
import { getUserServers } from "@/lib/services/server.service";
|
||||||
import { AppSidebar } from "@/components/layout/AppSidebar";
|
import { AppSidebar } from "@/components/layout/AppSidebar";
|
||||||
import { MemberSidebar } from "@/components/layout/MemberSidebar";
|
import { MemberSidebar } from "@/components/layout/MemberSidebar";
|
||||||
import { ServerProvider } from "@/lib/context/ServerContext";
|
import { ServerProvider } from "@/lib/context/ServerContext";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
/**
|
|
||||||
* Server component layout wrapper for authenticated application views.
|
|
||||||
* Handles session verification, fetches user servers, and renders global layout components.
|
|
||||||
*
|
|
||||||
* @param {Object} props - The component props.
|
|
||||||
* @param {React.ReactNode} props.children - The child page content to render inside the main viewport layout.
|
|
||||||
* @returns {Promise<JSX.Element>} The rendered application layout hierarchy with provider contexts.
|
|
||||||
*/
|
|
||||||
export default async function AppLayout({
|
export default async function AppLayout({
|
||||||
children,
|
children,
|
||||||
}: {
|
}: {
|
||||||
|
|
@ -29,12 +24,27 @@ export default async function AppLayout({
|
||||||
redirect("/login");
|
redirect("/login");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const [currentUser] = await db
|
||||||
|
.select({
|
||||||
|
id: users.id,
|
||||||
|
username: users.username,
|
||||||
|
color: users.color,
|
||||||
|
status: users.status,
|
||||||
|
})
|
||||||
|
.from(users)
|
||||||
|
.where(eq(users.id, session.user.id))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (!currentUser) {
|
||||||
|
redirect("/login");
|
||||||
|
}
|
||||||
|
|
||||||
const userServers = await getUserServers(session.user.id);
|
const userServers = await getUserServers(session.user.id);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ServerProvider>
|
<ServerProvider>
|
||||||
<div className="flex h-screen w-full overflow-hidden bg-background text-foreground">
|
<div className="flex h-screen w-full overflow-hidden bg-background text-foreground">
|
||||||
<AppSidebar servers={userServers} />
|
<AppSidebar servers={userServers} user={currentUser} />
|
||||||
<div className="flex-1 flex min-w-0">{children}</div>
|
<div className="flex-1 flex min-w-0">{children}</div>
|
||||||
<MemberSidebar />
|
<MemberSidebar />
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
41
app/api/auth/logout/route.ts
Normal file
41
app/api/auth/logout/route.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
||||||
|
/**
|
||||||
|
* @file app/api/auth/logout/route.ts
|
||||||
|
* @description API route handler for logging out authenticated users and updating their online presence.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { auth } from "@/auth";
|
||||||
|
import { db } from "@/db";
|
||||||
|
import { users } from "@/db/schema";
|
||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles POST requests to log out a user by updating their online status and last active timestamp.
|
||||||
|
*
|
||||||
|
* @returns {Promise<NextResponse>} JSON response indicating success or error status.
|
||||||
|
*/
|
||||||
|
export async function POST(): Promise<NextResponse> {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await db
|
||||||
|
.update(users)
|
||||||
|
.set({
|
||||||
|
status: "OFFLINE",
|
||||||
|
lastSeenAt: new Date(),
|
||||||
|
})
|
||||||
|
.where(eq(users.id, session.user.id));
|
||||||
|
|
||||||
|
return NextResponse.json({ success: true });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Logout error:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Internal Server Error" },
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,9 +1,8 @@
|
||||||
/**
|
/**
|
||||||
* @file app/layout.tsx
|
* @file app/layout.tsx
|
||||||
* @description Root layout component that wraps the entire application, providing global CSS styles, base HTML structure, and page metadata.
|
* @description Root layout component providing the global HTML structure and application metadata.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { SessionProvider } from "next-auth/react";
|
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -28,9 +27,7 @@ export default function RootLayout({
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<body className="min-h-screen flex flex-col">
|
<body className="min-h-screen flex flex-col">{children}</body>
|
||||||
<SessionProvider>{children}</SessionProvider>
|
|
||||||
</body>
|
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
60
auth.ts
60
auth.ts
|
|
@ -1,6 +1,6 @@
|
||||||
/**
|
/**
|
||||||
* @file auth.ts
|
* @file auth.ts
|
||||||
* @description NextAuth configuration defining authentication providers, credentials verification, JWT callbacks, and session handling.
|
* @description NextAuth configuration handling authentication and lightweight ID-only session management.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import NextAuth from "next-auth";
|
import NextAuth from "next-auth";
|
||||||
|
|
@ -21,10 +21,11 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||||
password: { label: "Password", type: "password" },
|
password: { label: "Password", type: "password" },
|
||||||
},
|
},
|
||||||
/**
|
/**
|
||||||
* Authorizes user credentials by checking against database records and verifying the password.
|
* Authorizes user credentials against database records.
|
||||||
*
|
*
|
||||||
|
* @function authorize
|
||||||
* @param {Record<string, unknown> | undefined} credentials - The incoming sign-in credentials containing email and password.
|
* @param {Record<string, unknown> | undefined} credentials - The incoming sign-in credentials containing email and password.
|
||||||
* @returns {Promise<Object | null>} The authenticated user object containing id, name, email, and color, or null if validation fails.
|
* @returns {Promise<{ id: string } | null>} The authenticated user object containing only the user ID, or null if validation fails.
|
||||||
*/
|
*/
|
||||||
authorize: async (credentials) => {
|
authorize: async (credentials) => {
|
||||||
const email = credentials?.email as string | undefined;
|
const email = credentials?.email as string | undefined;
|
||||||
|
|
@ -51,50 +52,63 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: user.id,
|
id: user.id,
|
||||||
username: user.username,
|
|
||||||
email: user.email,
|
|
||||||
color: user.color,
|
|
||||||
status: user.status,
|
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
callbacks: {
|
callbacks: {
|
||||||
/**
|
/**
|
||||||
* Callback triggered when a JSON Web Token is created or updated.
|
* Populates the JWT token with the user ID upon initial sign in.
|
||||||
*
|
*
|
||||||
* @param {Object} params - Callback parameters.
|
* @function jwt
|
||||||
* @param {Object} params.token - The current JWT token payload.
|
* @param {Object} params - The callback parameters.
|
||||||
* @param {Object} [params.user] - The authenticated user object available on initial sign in.
|
* @param {import("next-auth/jwt").JWT} params.token - The current JSON Web Token.
|
||||||
* @returns {Object} The updated JWT token containing custom user claims.
|
* @param {import("next-auth").User} [params.user] - The authenticated user object (available on first sign in).
|
||||||
|
* @returns {import("next-auth/jwt").JWT} The updated JWT token.
|
||||||
*/
|
*/
|
||||||
jwt({ token, user }) {
|
jwt({ token, user }) {
|
||||||
if (user) {
|
if (user) {
|
||||||
token.id = user.id;
|
token.id = user.id;
|
||||||
token.username = user.username;
|
|
||||||
token.color = user.color;
|
|
||||||
token.status = user.status;
|
|
||||||
}
|
}
|
||||||
return token;
|
return token;
|
||||||
},
|
},
|
||||||
/**
|
/**
|
||||||
* Callback triggered whenever a session is checked or accessed.
|
* Attaches the user ID from the JWT token to the active session.
|
||||||
*
|
*
|
||||||
* @param {Object} params - Callback parameters.
|
* @function session
|
||||||
* @param {Object} params.session - The current session object.
|
* @param {Object} params - The callback parameters.
|
||||||
* @param {Object} params.token - The decoded JWT token payload.
|
* @param {import("next-auth").Session} params.session - The current user session object.
|
||||||
* @returns {Object} The updated session object populated with custom token attributes.
|
* @param {import("next-auth/jwt").JWT} params.token - The active JSON Web Token.
|
||||||
|
* @returns {import("next-auth").Session} The updated session object.
|
||||||
*/
|
*/
|
||||||
session({ session, token }) {
|
session({ session, token }) {
|
||||||
if (token && session.user) {
|
if (token && session.user) {
|
||||||
session.user.id = token.id as string;
|
session.user.id = token.id as string;
|
||||||
session.user.username = token.username as string;
|
|
||||||
session.user.color = token.color as string;
|
|
||||||
session.user.status = token.status as any;
|
|
||||||
}
|
}
|
||||||
return session;
|
return session;
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
events: {
|
||||||
|
/**
|
||||||
|
* Updates the user's status to ONLINE and refreshes lastSeenAt upon successful sign in.
|
||||||
|
*
|
||||||
|
* @function signIn
|
||||||
|
* @param {Object} params - The event parameters.
|
||||||
|
* @param {import("next-auth").User} params.user - The signed-in user object.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async signIn({ user }) {
|
||||||
|
if (user?.id) {
|
||||||
|
await db
|
||||||
|
.update(users)
|
||||||
|
.set({
|
||||||
|
status: "ONLINE",
|
||||||
|
lastSeenAt: new Date(),
|
||||||
|
})
|
||||||
|
.where(eq(users.id, user.id));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
pages: {
|
pages: {
|
||||||
signIn: "/login",
|
signIn: "/login",
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -10,16 +10,42 @@ import { ServerSidebar } from "@/components/sidebar/ServerSidebar";
|
||||||
import { ChannelSidebar } from "@/components/sidebar/ChannelSidebar";
|
import { ChannelSidebar } from "@/components/sidebar/ChannelSidebar";
|
||||||
import { UserPanel } from "@/components/sidebar/UserPanel";
|
import { UserPanel } from "@/components/sidebar/UserPanel";
|
||||||
import type { ServerWithChannels } from "@/lib/context/ServerContext";
|
import type { ServerWithChannels } from "@/lib/context/ServerContext";
|
||||||
|
import type { UserStatus } from "@/db/schema";
|
||||||
import { clsx } from "clsx";
|
import { clsx } from "clsx";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Properties representing the user in the sidebar.
|
||||||
|
*
|
||||||
|
* @interface SidebarUser
|
||||||
|
* @property {string} username - The display name of the user.
|
||||||
|
* @property {string} color - The custom color assigned to the user's avatar or profile.
|
||||||
|
* @property {UserStatus} status - The current online status of the user.
|
||||||
|
*/
|
||||||
|
export interface SidebarUser {
|
||||||
|
username: string;
|
||||||
|
color: string;
|
||||||
|
status: UserStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Properties for the AppSidebar component.
|
||||||
|
*
|
||||||
|
* @interface AppSidebarProps
|
||||||
|
* @property {ServerWithChannels[]} servers - List of available servers including their channels.
|
||||||
|
* @property {SidebarUser} user - Information about the currently authenticated user.
|
||||||
|
*/
|
||||||
|
interface AppSidebarProps {
|
||||||
|
servers: ServerWithChannels[];
|
||||||
|
user: SidebarUser;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders the responsive application sidebar containing server navigation, channel lists, and user profile.
|
* Renders the responsive application sidebar containing server navigation, channel lists, and user profile.
|
||||||
*
|
*
|
||||||
* @param {Object} props - The component props.
|
* @param {AppSidebarProps} props - The component props.
|
||||||
* @param {ServerWithChannels[]} props.servers - Array of server objects with channels to display in the server navigation bar.
|
|
||||||
* @returns {JSX.Element} The rendered mobile overlay and responsive sidebar structure.
|
* @returns {JSX.Element} The rendered mobile overlay and responsive sidebar structure.
|
||||||
*/
|
*/
|
||||||
export function AppSidebar({ servers }: { servers: ServerWithChannels[] }) {
|
export function AppSidebar({ servers, user }: AppSidebarProps) {
|
||||||
const { isNavOpen, closeAll } = useSidebarStore();
|
const { isNavOpen, closeAll } = useSidebarStore();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
@ -36,7 +62,7 @@ export function AppSidebar({ servers }: { servers: ServerWithChannels[] }) {
|
||||||
<ChannelSidebar />
|
<ChannelSidebar />
|
||||||
</div>
|
</div>
|
||||||
<div className="w-78">
|
<div className="w-78">
|
||||||
<UserPanel />
|
<UserPanel user={user} />
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
|
|
@ -58,7 +84,7 @@ export function AppSidebar({ servers }: { servers: ServerWithChannels[] }) {
|
||||||
<ServerSidebar servers={servers} />
|
<ServerSidebar servers={servers} />
|
||||||
<ChannelSidebar />
|
<ChannelSidebar />
|
||||||
</div>
|
</div>
|
||||||
<UserPanel />
|
<UserPanel user={user} />
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -6,15 +6,36 @@
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { LogOut, Settings } from "lucide-react";
|
import { LogOut, Settings } from "lucide-react";
|
||||||
import { signOut, useSession } from "next-auth/react";
|
import { signOut } from "next-auth/react";
|
||||||
import { UserAvatar } from "@/components/ui/UserAvatar";
|
import { UserAvatar } from "@/components/ui/UserAvatar";
|
||||||
|
import { UserStatus } from "@/db/schema";
|
||||||
|
|
||||||
export function UserPanel() {
|
/**
|
||||||
const { data: session } = useSession();
|
* Props for the UserPanel component.
|
||||||
|
*/
|
||||||
|
interface UserPanelProps {
|
||||||
|
/** User details including username, avatar color, and online status. */
|
||||||
|
user: {
|
||||||
|
username: string;
|
||||||
|
color: string;
|
||||||
|
status: UserStatus;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
if (!session?.user) return null;
|
/**
|
||||||
|
* Renders the user panel footer containing the user's avatar, status, and action buttons.
|
||||||
const { user } = session;
|
*
|
||||||
|
* @param {UserPanelProps} props - Component properties.
|
||||||
|
* @returns {JSX.Element} The rendered user panel component.
|
||||||
|
*/
|
||||||
|
export function UserPanel({ user }: UserPanelProps) {
|
||||||
|
/**
|
||||||
|
* Handles user logout by invalidating the local session and redirecting to the login page.
|
||||||
|
*/
|
||||||
|
const handleLogout = async () => {
|
||||||
|
await fetch("/api/auth/logout", { method: "POST" });
|
||||||
|
await signOut({ callbackUrl: "/login" });
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-2 w-full bg-surface shrink-0">
|
<div className="p-2 w-full bg-surface shrink-0">
|
||||||
|
|
@ -47,7 +68,7 @@ export function UserPanel() {
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => signOut({ callbackUrl: "/login" })}
|
onClick={handleLogout}
|
||||||
className="p-1.5 text-muted hover:text-red-400 focus:outline-none cursor-pointer transition-colors"
|
className="p-1.5 text-muted hover:text-red-400 focus:outline-none cursor-pointer transition-colors"
|
||||||
aria-label="Log Out"
|
aria-label="Log Out"
|
||||||
>
|
>
|
||||||
|
|
|
||||||
25
lib/types/next-auth.d.ts
vendored
25
lib/types/next-auth.d.ts
vendored
|
|
@ -1,31 +1,22 @@
|
||||||
/**
|
/**
|
||||||
* @file lib/types/next-auth.d.ts
|
* Dynamic module declarations extending NextAuth types.
|
||||||
* @description TypeScript module augmentation for NextAuth types to add custom user and session attributes.
|
*
|
||||||
|
* @module next-auth
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { DefaultSession } from "next-auth";
|
import { DefaultSession } from "next-auth";
|
||||||
import type { UserStatus } from "@/db/schema";
|
|
||||||
|
|
||||||
declare module "next-auth" {
|
declare module "next-auth" {
|
||||||
/**
|
/**
|
||||||
* Extends the default NextAuth Session interface to include custom user properties.
|
* Extends the built-in session user interface to include custom properties.
|
||||||
|
*
|
||||||
|
* @interface Session
|
||||||
|
* @property {Object} user - The authenticated user's session details.
|
||||||
|
* @property {string} user.id - The unique database identifier of the user.
|
||||||
*/
|
*/
|
||||||
interface Session {
|
interface Session {
|
||||||
user: {
|
user: {
|
||||||
id: string;
|
id: string;
|
||||||
username: string;
|
|
||||||
color: string;
|
|
||||||
status: UserStatus;
|
|
||||||
} & DefaultSession["user"];
|
} & DefaultSession["user"];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Extends the default NextAuth User interface to include custom properties.
|
|
||||||
*/
|
|
||||||
interface User {
|
|
||||||
id?: string;
|
|
||||||
username?: string;
|
|
||||||
color?: string;
|
|
||||||
status?: UserStatus;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue