denoland/deno_kv_oauth

Question: How can i get the email in Google

evilmonkey19 opened this issue · 2 comments

Hi!
I'm currently implementing an admin login using google as the login site because more secure than doing it myself. In order to check if the person logged in is an admin or not I want to check the email. How can i achieve that? I have been looking in the internet for a few days and, unfortunately, i didn't get lucky :(.

At this time, I can access and it logs in. The /protected works as expected so i guess the problem it's just getting the email. Also, I have the consent screen from the user, i guess.

This my current code:

// plugins/kv_oauth.ts
import { createGoogleOAuthConfig, createHelpers } from "jsr:@deno/kv-oauth";
import type { Plugin } from "$fresh/server.ts";


const { signIn, handleCallback, signOut, getSessionId } = createHelpers(
  createGoogleOAuthConfig({
  redirectUri: "http://localhost:8000/callback",
  scope: "https://www.googleapis.com/auth/userinfo.email",
  })
);

export default {
  name: "kv-oauth",
  routes: [
    {
      path: "/login",
      async handler(req) {
        return await signIn(req);
      },
    },
    {
      path: "/callback",
      async handler(req) {
        // Return object also includes `accessToken` and `sessionId` properties.
        const{ response } = await handleCallback(req);
        return response;
      },
    },
    {
      path: "/logout",
      async handler(req) {
        return await signOut(req);
      },
    },
    {
      path: "/protected",
      async handler(req) {
        return await getSessionId(req) === undefined
          ? new Response("Unauthorized", { status: 401 })
          : new Response("You are allowed");
      },
    },
  ],
} as Plugin;

handleCallback() returns an object which contains the tokens property. Use tokens.accessToken to make an API request to your given provider (Google, in this case) for the user's email. Please let me know if this helps.

I have already fixed the issue. It's my first time using the library, and i'm quite new to JS/TS, and it was extremely stupid the problem. For those who are in the same problem the solution is fairly easy. Just change the callback handler in the following way

{
  path: "/callback",
  async handler(req) {
    // Return object also includes `accessToken` and `sessionId` properties.
    const { response, sessionId, accessToken } = await handleCallback(req); // the sessionId it isn't used here, but just to let you know
    const emailReponse = await fetch("https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + tokens.accessToken);
    const emailData = await emailResponse.json();
    const email = emailData,.email;
    return response;
}

That's all! Thanks a lot @iuioiua !