problem with getting a user in google oauth2

I’m developing authorization using google oAuth2 in node.js and react. The plan was as follows:

  1. receive a link to select a google account,
  2. receive data from the account (directly the user), generate a token and put it in cookies, redirect back to the application to the home page
  3. on the first render of the home page I receive from Cookie token and using it I get the user..

But the request remains pending and from the cookie I get [Object: null prototype] {}, and as a result I cannot get the user data.
In the developer tools in the cookie storage there is!

Here is my code, maybe someone will find the error and help me

CONTROLLER:
1. 
getGoogleOAuthUrl() {
    const oAuthServerEndpoint="https://accounts.google.com/o/oauth2/v2/auth";
    const queryParams = {
      client_id: process.env.GOOGLE_CLIENT_ID,
      redirect_uri: `${process.env.API_URL}/api/user/auth/google`,
      response_type: 'code',
      access_type: 'offline',
      scope: [
        'https://www.googleapis.com/auth/userinfo.profile',
        'https://www.googleapis.com/auth/userinfo.email',
      ].join(' '),
      prompt: 'consent',
    };
    const qs = new URLSearchParams(queryParams);
    return `${oAuthServerEndpoint}?${qs.toString()}`;
  }

2. 
async getGoogleUser(req, res, next) {
    try {
      const { code } = req.query;

      const { id_token, access_token } =
        await googleOAuthService.getGoogleTokens({
          code,
          clientId: process.env.GOOGLE_CLIENT_ID,
          clientSecret: process.env.GOOGLE_CLIENT_SECRET,
          redirectUri: `${process.env.API_URL}/api/user/auth/google`,
        });
      const googleUser = await axios
        .get(
          `https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=${access_token}`,
          {
            headers: {
              Authorization: `Bearer ${id_token}`,
            },
          }
        )
        .then((res) => res.data);
      const tokens = tokenService.generateTokens(googleUser);
      res.cookie('refreshToken', tokens.refreshToken, {
        maxAge: 30 * 24 * 60 * 60 * 1000,
        httpOnly: true,
        secure: false,
      });
      await res.redirect(process.env.CLIENT_URL);
    } catch (error) {
      console.log(`Не вдалося отримати данні користувача`);
      next(error);
    }
  }

3. 
async getCurentGoogleUser(req, res, next) {
    try {
      const refreshToken = await req.cookies['refreshToken'];
      console.log(req.cookies)//[Object: null prototype] {}
      if (refreshToken) {
        const userData = tokenService.validateRefreshToken(refreshToken);
        const email = await userData.email;
        const name = await userData.name;
        const user = await googleOAuthService.registration(
          email,
          name,
          refreshToken
        );
       return await res.json(user);
      }
    } catch (error) {
      next(error);
    }
  }


ROUTER: 
router.get('/auth/google/url', (req, res) => {
  return res.send(googleAuthController.getGoogleOAuthUrl());
})
router.get('/auth/google',googleAuthController.getGoogleUser)
router.get("/auth/me", googleAuthController.getCurentGoogleUser)
SERVICES:
async getGoogleRedirectUrl() {
    return $api.get('/api/user/auth/google/url');
  }
async getGoogleUser() {
    return $api.get('/api/user/auth/me');
  }

AUTHSLICE:
...

export const fetchGetGoogleUser = createAsyncThunk(
  'auth/fetchGetGoogleUser',
  async () => await AuthServices.getGoogleUser()
);
...
.addCase(fetchGetGoogleUser.pending, (state) => {
        state.status="loading";
        state.error = null;
      })
      .addCase(fetchGetGoogleUser.fulfilled, (state, { payload }) => {
        state.isAuth = true;
        state.user = payload.data.user;
        localStorage.setItem('token', payload.data.accessToken)
      })
      .addCase(fetchGetGoogleUser.rejected, (state, { payload }) => {
        state.status="error";
      })


COMPONENT HOME:
...
  useEffect(() => {
   dispatch(fetchGetGoogleUser());
  }, [dispatch]);
...

It confuses me that this appeared during deployment to the hosting. Everything works fine on localhost

Leave a Comment