Skip to content

Instantly share code, notes, and snippets.

@penalosa
Last active June 9, 2023 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save penalosa/d014dd3d6be269bf460dece4a095f2cb to your computer and use it in GitHub Desktop.
Save penalosa/d014dd3d6be269bf460dece4a095f2cb to your computer and use it in GitHub Desktop.

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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment