feat: logout
This commit is contained in:
@@ -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!,
|
||||
|
||||
@@ -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("/");
|
||||
}
|
||||
+24
-67
@@ -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 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,
|
||||
});
|
||||
|
||||
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,
|
||||
},
|
||||
});
|
||||
|
||||
existingUser = createdUser!;
|
||||
}
|
||||
|
||||
const token = await signJwt(existingUser.id);
|
||||
|
||||
await setSessionCookie(token);
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -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() {
|
||||
</div>
|
||||
{
|
||||
user ? (
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="">
|
||||
{user.firstName} {user.secondName}
|
||||
</span>
|
||||
</div>
|
||||
<form action={logout}>
|
||||
<Button size="lg" type="submit">{`Logout from ${user.firstName} ${user.secondName}`}</Button>
|
||||
</form>
|
||||
) : (
|
||||
<form action={login}>
|
||||
<Button size="lg" type="submit">Sign in with Kotosoft ID</Button>
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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<string | null> {
|
||||
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");
|
||||
}
|
||||
@@ -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() {
|
||||
-22
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}>;
|
||||
}
|
||||
@@ -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!) });
|
||||
}
|
||||
+5
-14
@@ -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);
|
||||
}
|
||||
@@ -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 },
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user