From dfc3dd2065579f9c6483a1c63b350b3562c3b155 Mon Sep 17 00:00:00 2001 From: Ivan Rezchikov Date: Thu, 18 Jun 2026 22:52:49 +0300 Subject: [PATCH] feat: logout --- app/actions/login.tsx | 12 ++-- app/actions/logout.tsx | 9 +++ app/api/callback/route.ts | 93 ++++++++---------------------- components/header.tsx | 9 ++- lib/auth/pkce.ts | 11 ++++ lib/auth/session.ts | 42 ++++++++++++++ lib/{cookies.ts => auth/tokens.ts} | 4 +- lib/jwt.ts | 22 ------- lib/kotosoft/client.ts | 42 ++++++++++++++ lib/session.ts | 9 --- lib/user.ts | 19 ++---- lib/user/repository.ts | 26 +++++++++ lib/utils.ts | 2 +- 13 files changed, 172 insertions(+), 128 deletions(-) create mode 100644 app/actions/logout.tsx create mode 100644 lib/auth/pkce.ts create mode 100644 lib/auth/session.ts rename lib/{cookies.ts => auth/tokens.ts} (82%) delete mode 100644 lib/jwt.ts create mode 100644 lib/kotosoft/client.ts delete mode 100644 lib/session.ts create mode 100644 lib/user/repository.ts diff --git a/app/actions/login.tsx b/app/actions/login.tsx index 7f7a36f..cb2dc34 100644 --- a/app/actions/login.tsx +++ b/app/actions/login.tsx @@ -1,19 +1,17 @@ "use server" +import { generatePkce, generateState } from "@/lib/auth/pkce"; import { pkceConfig } from "@/lib/cookieConfig"; -import crypto from "crypto" import { cookies } from "next/headers"; import { redirect } from "next/navigation"; export default async function login() { - const verifier = crypto.randomBytes(32).toString("base64url"); - const challenge = crypto.createHash("sha256").update(verifier).digest("base64url"); - const state = crypto.randomBytes(16).toString("hex"); + const { verifier, challenge } = generatePkce(); + const state = generateState(); const store = await cookies(); - - store.set("pkce_verifier", verifier, pkceConfig) - store.set("oauth_state", state, { ...pkceConfig, path: "/" }) + store.set("pkce_verifier", verifier, pkceConfig); + store.set("oauth_state", state, { ...pkceConfig, path: "/" }); const params = new URLSearchParams({ client_id: process.env.KOTOSOFT_ID_CLIENT_ID!, diff --git a/app/actions/logout.tsx b/app/actions/logout.tsx new file mode 100644 index 0000000..be135a4 --- /dev/null +++ b/app/actions/logout.tsx @@ -0,0 +1,9 @@ +"use server" + +import { deleteSession } from "@/lib/auth/session"; +import { redirect } from "next/navigation"; + +export default async function logout() { + await deleteSession(); + redirect("/"); +} \ No newline at end of file diff --git a/app/api/callback/route.ts b/app/api/callback/route.ts index 2e7c4af..a93c8af 100644 --- a/app/api/callback/route.ts +++ b/app/api/callback/route.ts @@ -1,90 +1,47 @@ import { cookies } from "next/headers"; import { NextRequest, NextResponse } from "next/server"; -import { deleteOAuthCookies, setTokens } from "@/lib/cookies"; -import { prisma } from "@/lib/prisma"; -import { setSessionCookie } from "@/lib/session"; -import { signJwt } from "@/lib/jwt"; -import { v4 as uuidv4 } from "uuid"; +import { deleteOAuthCookies, setTokens } from "@/lib/auth/tokens"; +import { createSession } from "@/lib/auth/session"; +import { exchangeCode, fetchKotosoftUser } from "@/lib/kotosoft/client"; +import { findOrCreateUser } from "@/lib/user/repository"; export async function GET(request: NextRequest) { - const searchParams = request.nextUrl.searchParams; - + const { searchParams } = request.nextUrl; const code = searchParams.get("code"); const state = searchParams.get("state"); if (!code || !state) { - return NextResponse.json({ status: 409, message: "Incorrect request" }); + return NextResponse.json({ message: "Incorrect request" }, { status: 409 }); } const store = await cookies(); - const codeVerifier = store.get("pkce_verifier")?.value; const savedState = store.get("oauth_state")?.value; if (!codeVerifier || !savedState || savedState !== state) { - return NextResponse.json({ status: 403, message: "Access denied" }); + return NextResponse.json({ message: "Access denied" }, { status: 403 }); } - const body = new URLSearchParams({ - grant_type: "authorization_code", - code, - redirect_uri: `${process.env.PUBLIC_URL}/api/callback`, - code_verifier: codeVerifier, - }); + try { + const tokens = await exchangeCode(code, codeVerifier); + await setTokens(tokens.access_token, tokens.refresh_token, tokens.expires_in); - const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/oauth/token`, { - method: "POST", - headers: { - "Content-Type": "application/x-www-form-urlencoded", - Authorization: `Basic ${Buffer.from( - `${process.env.KOTOSOFT_ID_CLIENT_ID}:${process.env.KOTOSOFT_ID_CLIENT_SECRET}` - ).toString("base64")}`, - }, - body, - }); - - if (!response.ok) { - console.log(response) - return NextResponse.redirect(new URL("/callback/error", request.url)); - } - - const data = await response.json(); - - await setTokens(data.access_token, data.refresh_token, data.expires_in); - - const user = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/me`, { - headers: { - Authorization: `Bearer ${data.access_token}`, - }, - }); - const userData = await user.json(); - - var existingUser = await prisma.user.findUnique({ - where: { - kotosoftId: userData.id, - } - }); - - if (!existingUser) { - const createdUser = await prisma.user.create({ - data: { - id: uuidv4(), - kotosoftId: userData.id, - email: userData.email, - firstName: userData.first_name, - secondName: userData.second_name, - sex: userData.sex, - birthDate: userData.birth_date, - }, + const kotosoftUser = await fetchKotosoftUser(tokens.access_token); + const user = await findOrCreateUser({ + kotosoftId: kotosoftUser.id, + email: kotosoftUser.email, + firstName: kotosoftUser.first_name, + secondName: kotosoftUser.second_name, + sex: kotosoftUser.sex, + birthDate: kotosoftUser.birth_date, }); - existingUser = createdUser!; + await createSession(user.id); + await deleteOAuthCookies(); + + return NextResponse.redirect(new URL("/", request.url)); + } catch (e) { + console.error("OAuth callback error:", e); + return NextResponse.redirect(new URL("/callback/error", request.url)); } - - const token = await signJwt(existingUser.id); - - await setSessionCookie(token); - await deleteOAuthCookies(); - - return NextResponse.redirect(new URL("/", request.url)); } \ No newline at end of file diff --git a/components/header.tsx b/components/header.tsx index eeaa625..e63e91a 100644 --- a/components/header.tsx +++ b/components/header.tsx @@ -2,6 +2,7 @@ import Image from "next/image"; import { Button } from "./ui/button"; import login from "@/app/actions/login"; import { getCurrentUser } from "@/lib/user"; +import logout from "@/app/actions/logout"; export default async function Header() { const user = await getCurrentUser(); @@ -20,11 +21,9 @@ export default async function Header() { { user ? ( -
- - {user.firstName} {user.secondName} - -
+
+ +
) : (
diff --git a/lib/auth/pkce.ts b/lib/auth/pkce.ts new file mode 100644 index 0000000..628cd09 --- /dev/null +++ b/lib/auth/pkce.ts @@ -0,0 +1,11 @@ +import crypto from "crypto" + +export function generatePkce() { + const verifier = crypto.randomBytes(32).toString("base64url"); + const challenge = crypto.createHash("sha256").update(verifier).digest("base64url"); + return { verifier, challenge }; +} + +export function generateState() { + return crypto.randomBytes(16).toString("hex"); +} \ No newline at end of file diff --git a/lib/auth/session.ts b/lib/auth/session.ts new file mode 100644 index 0000000..f614eb5 --- /dev/null +++ b/lib/auth/session.ts @@ -0,0 +1,42 @@ +import { SignJWT, jwtVerify } from "jose"; +import { cookies } from "next/headers"; +import { cookieConfig } from "@/lib/cookieConfig"; + +const secret = new TextEncoder().encode(process.env.JWT_SECRET!); + +async function signJwt(userId: string) { + return await new SignJWT({}) + .setProtectedHeader({ alg: "HS256" }) + .setSubject(userId) + .setIssuedAt() + .setExpirationTime(`${process.env.SESSION_MAX_AGE}s`) + .sign(secret); +} + +export async function createSession(userId: string) { + const token = await signJwt(userId); + const store = await cookies(); + store.set("session", token, { + ...cookieConfig, + path: "/", + maxAge: parseInt(process.env.SESSION_MAX_AGE!), + }); +} + +export async function getSessionUserId(): Promise { + const store = await cookies(); + const token = store.get("session")?.value; + if (!token) return null; + + try { + const { payload } = await jwtVerify(token, secret); + return payload.sub ?? null; + } catch { + return null; + } +} + +export async function deleteSession() { + const store = await cookies(); + store.delete("session"); +} \ No newline at end of file diff --git a/lib/cookies.ts b/lib/auth/tokens.ts similarity index 82% rename from lib/cookies.ts rename to lib/auth/tokens.ts index a02b5e1..49aeb2c 100644 --- a/lib/cookies.ts +++ b/lib/auth/tokens.ts @@ -1,10 +1,10 @@ import { cookies } from "next/headers"; -import { cookieConfig } from "./cookieConfig"; +import { cookieConfig } from "@/lib/cookieConfig"; export async function setTokens(accessToken: string, refreshToken: string, ttl: number) { const store = await cookies(); store.set("access_token", accessToken, { ...cookieConfig, path: "/", maxAge: ttl }); - store.set("refresh_token", refreshToken, { ...cookieConfig, path: "/", maxAge: ttl * 7 }); + store.set("refresh_token", refreshToken, { ...cookieConfig, path: "/", maxAge: ttl * 7 * 24 * 60 * 60 }); } export async function deleteOAuthCookies() { diff --git a/lib/jwt.ts b/lib/jwt.ts deleted file mode 100644 index 51d2092..0000000 --- a/lib/jwt.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { SignJWT, jwtVerify } from "jose"; - -const secret = new TextEncoder().encode(process.env.JWT_SECRET!); - -export async function signJwt(userId: string) { - return await new SignJWT({}) - .setProtectedHeader({ alg: "HS256" }) - .setSubject(userId) - .setIssuedAt() - .setExpirationTime(`${process.env.SESSION_MAX_AGE}s`) - .sign(secret); -} - -export async function verifyJwt(token: string) { - try { - const { payload } = await jwtVerify(token, secret); - - return payload; - } catch { - return null; - } -} \ No newline at end of file diff --git a/lib/kotosoft/client.ts b/lib/kotosoft/client.ts new file mode 100644 index 0000000..045432c --- /dev/null +++ b/lib/kotosoft/client.ts @@ -0,0 +1,42 @@ +const API_URL = process.env.KOTOSOFT_ID_API_URL!; +const CLIENT_ID = process.env.KOTOSOFT_ID_CLIENT_ID!; +const CLIENT_SECRET = process.env.KOTOSOFT_ID_CLIENT_SECRET!; + +export async function exchangeCode(code: string, codeVerifier: string) { + const body = new URLSearchParams({ + grant_type: "authorization_code", + code, + redirect_uri: `${process.env.PUBLIC_URL}/api/callback`, + code_verifier: codeVerifier, + }); + + const response = await fetch(`${API_URL}/oauth/token`, { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + Authorization: `Basic ${Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64")}`, + }, + body, + }); + + if (!response.ok) throw new Error("Failed to exchange code"); + + return response.json() as Promise<{ access_token: string; refresh_token: string; expires_in: number }>; +} + +export async function fetchKotosoftUser(accessToken: string) { + const response = await fetch(`${API_URL}/api/v1/me`, { + headers: { Authorization: `Bearer ${accessToken}` }, + }); + + if (!response.ok) throw new Error("Failed to fetch user"); + + return response.json() as Promise<{ + id: string; + email: string; + first_name: string; + second_name: string; + sex: string; + birth_date: string; + }>; +} \ No newline at end of file diff --git a/lib/session.ts b/lib/session.ts deleted file mode 100644 index f7063c6..0000000 --- a/lib/session.ts +++ /dev/null @@ -1,9 +0,0 @@ -"use server"; - -import { cookies } from "next/headers"; -import { cookieConfig } from "./cookieConfig"; - -export async function setSessionCookie(token: string) { - const store = await cookies(); - store.set("session", token, { ...cookieConfig, path: "/", maxAge: parseInt(process.env.SESSION_MAX_AGE!) }); -} \ No newline at end of file diff --git a/lib/user.ts b/lib/user.ts index 4461228..c0431c7 100644 --- a/lib/user.ts +++ b/lib/user.ts @@ -1,17 +1,8 @@ -import { cookies } from "next/headers"; -import { prisma } from "@/lib/prisma"; -import { verifyJwt } from "@/lib/jwt"; +import { getSessionUserId } from "@/lib/auth/session"; +import { findUserById } from "@/lib/user/repository"; export async function getCurrentUser() { - const store = await cookies(); - const token = store.get("session")?.value; - - if (!token) return null; - - const payload = await verifyJwt(token); - if (!payload?.sub) return null; - - return prisma.user.findUnique({ - where: { id: payload.sub as string }, - }); + const userId = await getSessionUserId(); + if (!userId) return null; + return findUserById(userId); } \ No newline at end of file diff --git a/lib/user/repository.ts b/lib/user/repository.ts new file mode 100644 index 0000000..bc4f32f --- /dev/null +++ b/lib/user/repository.ts @@ -0,0 +1,26 @@ +import { prisma } from "@/lib/prisma"; +import { v4 as uuidv4 } from "uuid"; + +export async function findUserByKotosoftId(kotosoftId: string) { + return prisma.user.findUnique({ where: { kotosoftId } }); +} + +export async function findUserById(id: string) { + return prisma.user.findUnique({ where: { id } }); +} + +export async function findOrCreateUser(data: { + kotosoftId: string; + email: string; + firstName: string; + secondName: string; + sex: string; + birthDate: string; +}) { + const existing = await findUserByKotosoftId(data.kotosoftId); + if (existing) return existing; + + return prisma.user.create({ + data: { id: uuidv4(), ...data }, + }); +} \ No newline at end of file diff --git a/lib/utils.ts b/lib/utils.ts index bd0c391..a7dc3a1 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -3,4 +3,4 @@ import { twMerge } from "tailwind-merge" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) -} +} \ No newline at end of file