36 lines
1.1 KiB
TypeScript
36 lines
1.1 KiB
TypeScript
if (process.env.NODE_ENV !== "test")
|
|
require("server-only");
|
|
import { cookies } from "next/headers";
|
|
import getPool from "@/lib/server/db";
|
|
import { getSessionCookieName, hashToken } from "@/lib/server/auth";
|
|
import { apiError } from "@/lib/server/errors";
|
|
import type { User } from "@/lib/shared/types";
|
|
|
|
export async function getSessionUser(): Promise<User | null> {
|
|
const cookieStore = await cookies();
|
|
const token = cookieStore.get(getSessionCookieName())?.value;
|
|
if (!token)
|
|
return null;
|
|
|
|
const pool = getPool();
|
|
const { rows } = await pool.query(
|
|
`select u.id, u.email, u.display_name
|
|
from sessions s
|
|
join users u on u.id = s.user_id
|
|
where s.token_hash = $1 and s.expires_at > now()`,
|
|
[hashToken(token)]
|
|
);
|
|
|
|
const user = rows[0];
|
|
if (!user)
|
|
return null;
|
|
|
|
return { id: user.id, email: user.email, displayName: user.display_name };
|
|
}
|
|
|
|
export async function requireSessionUser(): Promise<User> {
|
|
const user = await getSessionUser();
|
|
if (!user) apiError("UNAUTHORIZED");
|
|
return user;
|
|
}
|