google-auth.js

import { APP_CLIENT_ID } from '../constants/app';
import { writeUser } from '../LocalStorage';

export function initGoogle(callback) {
  window.gapi.load('auth2', function () {
    window.gapi.auth2
      .init({
        client_id: APP_CLIENT_ID
      })
      .then(() => {
        callback();
      });
  });
}

export function setCurrentUser() {
  const GoogleAuth = window.gapi.auth2.getAuthInstance();
  if (GoogleAuth.isSignedIn.get()) {
    const profile = GoogleAuth.currentUser.get().getBasicProfile();
    const result = {
      user: {
        uid: profile.getId(),
        email: profile.getEmail(),
        photoURL: profile.getImageUrl(),
        displayName: profile.getName()
      }
    };
    writeUser(result.user);
    return result;
  }
  return null;
}

export function getAuthToken() {
  const GoogleAuth = window.gapi.auth2.getAuthInstance();
  if (GoogleAuth.isSignedIn.get()) {
    const GoogleUser = GoogleAuth.currentUser.get();
    const authResponse = GoogleUser.getAuthResponse();
    const { id_token, token_type } = authResponse;
    return `${token_type} ${id_token}`;
  }
  return null;
}