added basic user auth flow
This commit is contained in:
parent
faa7372887
commit
5d2c668bad
7 changed files with 394 additions and 2 deletions
32
lib/auth-cookies.ts
Normal file
32
lib/auth-cookies.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
// app/lib/auth-cookies.ts
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export const ACCESS_COOKIE = "ma_at";
|
||||
export const REFRESH_COOKIE = "ma_rt";
|
||||
export const USER_COOKIE = "ma_user"; // tiny JSON: {id, username, email?}
|
||||
|
||||
export function setAuthCookies(
|
||||
res: NextResponse,
|
||||
tokens: { access_token: string; refresh_token: string; expires?: number },
|
||||
user: { id: string; username: string; email?: string | null },
|
||||
) {
|
||||
const maxAge = tokens.expires ? Math.max(0, Math.floor((tokens.expires - Date.now()) / 1000)) : 60 * 60; // default 1h
|
||||
res.cookies.set(ACCESS_COOKIE, tokens.access_token, {
|
||||
httpOnly: true, sameSite: "lax", secure: true, path: "/", maxAge,
|
||||
});
|
||||
// keep refresh longer (7d)
|
||||
res.cookies.set(REFRESH_COOKIE, tokens.refresh_token, {
|
||||
httpOnly: true, sameSite: "lax", secure: true, path: "/", maxAge: 60 * 60 * 24 * 7,
|
||||
});
|
||||
res.cookies.set(USER_COOKIE, JSON.stringify(user), {
|
||||
httpOnly: false, sameSite: "lax", secure: true, path: "/", maxAge,
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
export function clearAuthCookies(res: NextResponse) {
|
||||
res.cookies.set(ACCESS_COOKIE, "", { path: "/", maxAge: 0 });
|
||||
res.cookies.set(REFRESH_COOKIE, "", { path: "/", maxAge: 0 });
|
||||
res.cookies.set(USER_COOKIE, "", { path: "/", maxAge: 0 });
|
||||
return res;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue