Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# env files (can opt-in for committing if needed)
.env*

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
36 changes: 36 additions & 0 deletions app/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.

This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
63 changes: 63 additions & 0 deletions app/app/UserPanelClient.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"use client";

import { useEffect, useState } from "react";
import Image from "next/image";

type MeUnauthed = {
authenticated: false;
};

type MeAuthed = {
authenticated: true;
user: {
sub?: string;
email?: string;
name?: string;
picture?: string;
};
rawClaims: Record<string, unknown>;
};

type MeResponse = MeUnauthed | MeAuthed;

export default function UserPanelClient() {
const [data, setData] = useState<MeResponse | null>(null);
const [error, setError] = useState<string | null>(null);

useEffect(() => {
(async () => {
try {
const r = await fetch("/api/me");
if (!r.ok) throw new Error(`Request failed: ${r.status}`);
const json = (await r.json()) as MeResponse;
setData(json);
} catch (e) {
setError(e instanceof Error ? e.message : "Unknown error");
}
})();
}, []);

if (error) return <p>Error: {error}</p>;
if (!data) return <p>Loading…</p>;
if (!data.authenticated) return <p>Not signed in.</p>;

return (
<div style={{ marginTop: 16 }}>
<p>Signed in as: {data.user.email || data.user.name || "Unknown user"}</p>

{data.user.picture ? (
<Image
src={data.user.picture}
alt="avatar"
width={64}
height={64}
style={{ borderRadius: 999 }}
/>
) : null}

<pre style={{ marginTop: 12, background: "#f5f5f5", padding: 12, overflowX: "auto" }}>
{JSON.stringify(data.rawClaims, null, 2)}
</pre>
</div>
);
}
85 changes: 85 additions & 0 deletions app/app/api/auth/callback/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { NextResponse } from "next/server";

function readCookieValue(cookieHeader: string, name: string) {
const match = cookieHeader.match(new RegExp(`(?:^|; )${name}=([^;]+)`));
return match ? decodeURIComponent(match[1]) : null;
}

export async function GET(req: Request) {
const url = new URL(req.url);
const code = url.searchParams.get("code");
const state = url.searchParams.get("state");
const error = url.searchParams.get("error");
const errorDesc = url.searchParams.get("error_description");

if (error) {
return NextResponse.json({ error, error_description: errorDesc }, { status: 400 });
}
if (!code || !state) {
return NextResponse.json({ error: "Missing code/state" }, { status: 400 });
}

const domain = process.env.COGNITO_DOMAIN!;
const clientId = process.env.COGNITO_CLIENT_ID!;
const redirectUri = process.env.COGNITO_REDIRECT_URI!;

const cookieHeader = req.headers.get("cookie") ?? "";
const expectedState = readCookieValue(cookieHeader, "oauth_state");
const verifier = readCookieValue(cookieHeader, "pkce_verifier");

if (!expectedState || !verifier || state !== expectedState) {
return NextResponse.json({ error: "Invalid state" }, { status: 400 });
}

const body = new URLSearchParams({
grant_type: "authorization_code",
client_id: clientId,
redirect_uri: redirectUri,
code,
code_verifier: verifier,
});

const tokenResp = await fetch(`https://${domain}/oauth2/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body,
});

const tokenJson = await tokenResp.json();
if (!tokenResp.ok) {
return NextResponse.json(tokenJson, { status: tokenResp.status });
}

const secure = process.env.NODE_ENV === "production";

const res = NextResponse.redirect(new URL("/", url));

res.cookies.set("access_token", tokenJson.access_token, {
httpOnly: true,
sameSite: "lax",
secure,
path: "/",
maxAge: tokenJson.expires_in ?? 3600,
});
res.cookies.set("id_token", tokenJson.id_token, {
httpOnly: true,
sameSite: "lax",
secure,
path: "/",
maxAge: tokenJson.expires_in ?? 3600,
});

if (tokenJson.refresh_token) {
res.cookies.set("refresh_token", tokenJson.refresh_token, {
httpOnly: true,
sameSite: "lax",
secure,
path: "/",
});
}

res.cookies.set("oauth_state", "", { path: "/", maxAge: 0 });
res.cookies.set("pkce_verifier", "", { path: "/", maxAge: 0 });

return res;
}
56 changes: 56 additions & 0 deletions app/app/api/auth/login/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { NextResponse } from "next/server";
import crypto from "crypto";

function base64url(buf: Buffer) {
return buf
.toString("base64")
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/g, "");
}

function sha256(input: string) {
return crypto.createHash("sha256").update(input).digest();
}

export async function GET() {
const domain = process.env.COGNITO_DOMAIN!;
const clientId = process.env.COGNITO_CLIENT_ID!;
const redirectUri = process.env.COGNITO_REDIRECT_URI!;

const state = base64url(crypto.randomBytes(16));
const verifier = base64url(crypto.randomBytes(32));
const challenge = base64url(sha256(verifier));

const authorize =
`https://${domain}/oauth2/authorize` +
`?client_id=${encodeURIComponent(clientId)}` +
`&response_type=code` +
`&redirect_uri=${encodeURIComponent(redirectUri)}` +
`&scope=${encodeURIComponent("openid email profile")}` +
`&state=${encodeURIComponent(state)}` +
`&code_challenge=${encodeURIComponent(challenge)}` +
`&code_challenge_method=S256` +
`&identity_provider=Google`;

const res = NextResponse.redirect(authorize);

const secure = process.env.NODE_ENV === "production";

res.cookies.set("oauth_state", state, {
httpOnly: true,
sameSite: "lax",
secure,
path: "/",
maxAge: 10 * 60,
});
res.cookies.set("pkce_verifier", verifier, {
httpOnly: true,
sameSite: "lax",
secure,
path: "/",
maxAge: 10 * 60,
});

return res;
}
26 changes: 26 additions & 0 deletions app/app/api/auth/logout/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { NextResponse } from "next/server";

export async function GET(req: Request) {
const url = new URL(req.url);
const secure = process.env.NODE_ENV === "production";

const res = NextResponse.redirect(new URL("/", url));

for (const name of ["access_token", "id_token", "refresh_token"]) {
res.cookies.set(name, "", { path: "/", maxAge: 0, secure });
}

const domain = process.env.COGNITO_DOMAIN;
const clientId = process.env.COGNITO_CLIENT_ID;
const logoutUri = process.env.COGNITO_LOGOUT_URI;

if (domain && clientId && logoutUri) {
const cognitoLogout =
`https://${domain}/logout` +
`?client_id=${encodeURIComponent(clientId)}` +
`&logout_uri=${encodeURIComponent(logoutUri)}`;
return NextResponse.redirect(cognitoLogout);
}

return res;
}
Loading