feat: logout
This commit is contained in:
@@ -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 },
|
||||
});
|
||||
}
|
||||
+1
-1
@@ -3,4 +3,4 @@ import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user