authenticate.ts

import { OAuth2Client } from 'google-auth-library';
import { APP_CLIENT_ID } from '../../utility/constants/app';
import { getUserFromPayload } from '../../utility/auth/user';
import { AuthenticationError } from 'apollo-server-express';

// `Authorization: Bearer <Google ID Token>`.
// when decoded successfully, the ID Token content will be added as `req.user`.
export const authenticate = (req, res, next) => {
  const client = new OAuth2Client(APP_CLIENT_ID);
  if (!req.headers?.authorization?.startsWith('Bearer ')) {
    res.status(403).send('Unauthorized');
    return;
  }
  const idToken = req.headers.authorization.split('Bearer ')[1];
  client
    .verifyIdToken({
      idToken,
      audience: APP_CLIENT_ID
    })
    .then(ticket => {
      const payload = ticket.getPayload();
      req.user = getUserFromPayload(payload);
      // TODO upsert user into the db
      return next();
    })
    .catch(() => {
      res.status(403).send('Unauthorized');
    });
};

export const graphQlAuth = async req => {
  const client = new OAuth2Client(APP_CLIENT_ID);
  if (!req.headers?.authorization?.startsWith('Bearer ')) {
    //throw new AuthenticationError('you must be logged in');
    return null;
  }
  const idToken = req.headers.authorization.split('Bearer ')[1];
  const ticket = await client.verifyIdToken({
    idToken,
    audience: APP_CLIENT_ID
  });

  const payload = ticket.getPayload();
  const user = getUserFromPayload(payload);
  if (user) {
    return user;
  } else {
    return null;
  }
};