Update to add Login Link
function LoginLink(user: UserData | null) {
return !user?.id && html`<a href="/.well-known/authenticate" id="login">Login</a>`;
}
Inject the link into the Page component
`${LoginLink(user)}`
Move to edge auth
Add middleware code
const url = new URL(request.url);
if (
request.method === "GET" &&
url.pathname === "/.well-known/authenticate"
) {
return startDiscordAuth(url, env.DISCORD_CLIENT_ID);
}
if (
request.method === "GET" &&
url.pathname === "/.well-known/callback/discord"
) {
const discordUser = await handleDiscordCallback(
url,
env.DISCORD_CLIENT_ID,
env.DISCORD_CLIENT_SECRET
);
const user = await updateUserData(env.Users, discordUser);
url.pathname = "/";
return new Response(null, {
status: 302,
headers: {
Location: url.href,
"Set-Cookie": `auth:token=${user.signature}; Path=/; Secure; HttpOnly=true`
}
});
}
if (request.method === "GET" && url.pathname === "/.well-known/logout") {
url.pathname = "/";
return new Response(null, {
status: 302,
headers: {
Location: url.href,
"Set-Cookie": `auth:token=; Path=/; Secure; HttpOnly=true; expires=Thu, 01 Jan 1970 00:00:00 GMT`
}
});
}
const authCookie = cookieParser(request.headers.get("Cookie") ?? "");
if (authCookie["auth:token"]) {
const existingUser = await getUserData(
env.Users,
authCookie["auth:token"],
env.KEY
);
const headers = new Headers(request.headers);
headers.set("X-User", JSON.stringify(existingUser));
const req = new Request(request, { headers });
return fetch(maskUpstreamForDev(req, env));
} else {
return fetch(maskUpstreamForDev(request, env));
}