initial commit
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { pkceConfig } from "@/lib/cookie-config";
|
||||
import crypto from "crypto";
|
||||
|
||||
export async function GET() {
|
||||
const verifier = crypto.randomBytes(32).toString("base64url");
|
||||
const challenge = crypto.createHash("sha256").update(verifier).digest("base64url");
|
||||
const state = crypto.randomBytes(16).toString("hex");
|
||||
|
||||
const store = await cookies();
|
||||
store.set("pkce_verifier", verifier, pkceConfig);
|
||||
store.set("oauth_state", state, { ...pkceConfig, path: "/api/callback" });
|
||||
|
||||
const params = new URLSearchParams({
|
||||
client_id: process.env.CLIENT_ID!,
|
||||
redirect_uri: `${process.env.PUBLIC_URL}/api/callback`,
|
||||
scope: "profile:read profile:edit profile:consent:read",
|
||||
response_type: "code",
|
||||
code_challenge: challenge,
|
||||
code_challenge_method: "S256",
|
||||
state,
|
||||
});
|
||||
|
||||
redirect(`${process.env.KOTOSOFT_ID_API_URL}/oauth/authorize?${params.toString()}`);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { setTokens, serverBasicAuth } from "@/actions/auth";
|
||||
import { type NextRequest } from "next/server";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const code = request.nextUrl.searchParams.get("code");
|
||||
const returnedState = request.nextUrl.searchParams.get("state");
|
||||
if (!code) redirect("/callback/error");
|
||||
|
||||
const store = await cookies();
|
||||
const codeVerifier = store.get("pkce_verifier")?.value;
|
||||
const savedState = store.get("oauth_state")?.value;
|
||||
|
||||
if (!codeVerifier || returnedState !== savedState) redirect("/callback/error");
|
||||
|
||||
store.delete("pkce_verifier");
|
||||
store.delete("oauth_state");
|
||||
|
||||
try {
|
||||
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/oauth/token`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
Authorization: await serverBasicAuth(),
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
grant_type: "authorization_code",
|
||||
code,
|
||||
redirect_uri: `${process.env.PUBLIC_URL}/api/callback`,
|
||||
code_verifier: codeVerifier,
|
||||
}).toString(),
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (!response.ok) redirect("/callback/error");
|
||||
|
||||
const data = await response.json();
|
||||
await setTokens(data.access_token, data.refresh_token, data.expires_in);
|
||||
} catch {
|
||||
redirect("/callback/error");
|
||||
}
|
||||
|
||||
redirect("/");
|
||||
}
|
||||
Reference in New Issue
Block a user