5.2.1 • Published 4 years ago

nhut-google-login v5.2.1

Weekly downloads
2
License
MIT
Repository
github
Last release
4 years ago

React Google Login

A Google oAUth Sign-in / Log-in Component for React

Storybook

Demo Link

Install

npm install react-google-login

How to use

import React from 'react';
import ReactDOM from 'react-dom';
import GoogleLogin from 'react-google-login';
// or
import { GoogleLogin } from 'react-google-login';


const responseGoogle = (response) => {
  console.log(response);
}

ReactDOM.render(
  <GoogleLogin
    clientId="658977310896-knrl3gka66fldh83dao2rhgbblmd4un9.apps.googleusercontent.com"
    buttonText="Login"
    onSuccess={responseGoogle}
    onFailure={responseGoogle}
    cookiePolicy={'single_host_origin'}
  />,
  document.getElementById('googleButton')
);

Google button without styling or custom button

ReactDOM.render(
  <GoogleLogin
    clientId="658977310896-knrl3gka66fldh83dao2rhgbblmd4un9.apps.googleusercontent.com"
    render={renderProps => (
      <button onClick={renderProps.onClick} disabled={renderProps.disabled}>This is my custom Google button</button>
    )}
    buttonText="Login"
    onSuccess={responseGoogle}
    onFailure={responseGoogle}
    cookiePolicy={'single_host_origin'}
  />,
  document.getElementById('googleButton')
);

Stay Logged in

isSignedIn={true} attribute will call onSuccess callback on load to keep the user signed in.

<GoogleLogin
  clientId="658977310896-knrl3gka66fldh83dao2rhgbblmd4un9.apps.googleusercontent.com"
  onSuccess={responseGoogle}
  isSignedIn={true}
/>

Login Hook

import { useGoogleLogin } from 'react-google-login'

const { signIn, loaded } = useGoogleLogin({
    onSuccess,
    onAutoLoadFinished,
    clientId,
    cookiePolicy,
    loginHint,
    hostedDomain,
    autoLoad,
    isSignedIn,
    fetchBasicProfile,
    redirectUri,
    discoveryDocs,
    onFailure,
    uxMode,
    scope,
    accessType,
    responseType,
    jsSrc,
    onRequest,
    prompt
  })

Logout Hook

import { useGoogleLogout } from 'react-google-login'

const { signOut, loaded } = useGoogleLogout({
    jsSrc,
    onFailure,
    clientId,
    cookiePolicy,
    loginHint,
    hostedDomain,
    fetchBasicProfile,
    discoveryDocs,
    uxMode,
    redirectUri,
    scope,
    accessType,
    onLogoutSuccess
  })

onSuccess callback

If responseType is not 'code', callback will return the GoogleAuth object.

If responseType is 'code', callback will return the authorization code that can be used to retrieve a refresh token from the server.

If you use the hostedDomain param, make sure to validate the id_token (a JSON web token) returned by Google on your backend server: 1. In the responseGoogle(response) {...} callback function, you should get back a standard JWT located at response.tokenId or res.getAuthResponse().id_token 2. Send this token to your server (preferably as an Authorization header) 3. Have your server decode the id_token by using a common JWT library such as jwt-simple or by sending a GET request to https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=YOUR_TOKEN_HERE 4. The returned decoded token should have an hd key equal to the hosted domain you'd like to restrict to.

Logout

Use GoogleLogout button to logout the user from google.

    import { GoogleLogout } from 'react-google-login';
    <GoogleLogout
      clientId="658977310896-knrl3gka66fldh83dao2rhgbblmd4un9.apps.googleusercontent.com"
      buttonText="Logout"
      onLogoutSuccess={logout}
    >
    </GoogleLogout>

Login Props

paramsvaluedefault valuedescription
clientIdstringREQUIREDYou can create a clientID by creating a new project on Google developers website.
jsSrcstringhttps://apis.google.com/js/api.jsURL of the Javascript file normally hosted by Google
hostedDomainstring-The G Suite domain to which users must belong to sign in
scopestringprofile email
responseTypestringpermissionCan be either space-delimited 'id_token', to retrieve an ID Token + 'permission' (or 'token'), to retrieve an Access Token, or 'code', to retrieve an Authorization Code.
accessTypestringonlineCan be either 'online' or 'offline'. Use offline with responseType 'code' to retrieve an authorization code for fetching a refresh token
onSuccessfunctionREQUIRED
onFailurefunctionREQUIRED
onRequestfunction-
onAutoLoadFinishedfunction-
buttonTextstringLogin with Google
classNamestring-
styleobject-
disabledStyleobject-
loginHintstring-
promptstring-Can be 'consent' to force google return refresh token.
tagstringbuttonsets element tag (div, a, span, etc
typestringbuttonsets button type (submitbutton)
autoLoadbooleanfalse
fetchBasicProfilebooleantrue
disabledbooleanfalse
discoveryDocs-https://developers.google.com/discovery/v1/using
uxModestringpopupThe UX mode to use for the sign-in flow. Valid values are popup and redirect.
themestringlightIf set to dark the button will follow the Google brand guidelines for dark. Otherwise it will default to light (https://developers.google.com/identity/branding-guidelines)
iconbooleantrueShow (true) or hide (false) the Google Icon
redirectUristring-If using ux_mode='redirect', this parameter allows you to override the default redirect_uri that will be used at the end of the consent flow. The default redirect_uri is the current URL stripped of query parameters and hash fragment.
isSignedInbooleanfalseIf true will return GoogleUser object on load, if user has given your app permission
renderfunction-Render prop to use a custom element, use renderProps.onClick

Google Scopes List: scopes

Logout Props

paramsvaluedefault valuedescription
clientIdstringREQUIREDYou can create a clientID by creating a new project on Google developers website.
jsSrcstringhttps://apis.google.com/js/api.jsURL of the Javascript file normally hosted by Google
hostedDomainstring-The G Suite domain to which users must belong to sign in
scopestringprofile email
accessTypestringonlineCan be either 'online' or 'offline'. Use offline with responseType 'code' to retrieve an authorization code for fetching a refresh token
onLogoutSuccessfunctionREQUIRED
onFailurefunctionREQUIRED
buttonTextstringLogin with Google
classNamestring-
disabledStyleobject-
loginHintstring-
tagstringbuttonsets element tag (div, a, span, etc
typestringbuttonsets button type (submitbutton)
fetchBasicProfilebooleantrue
disabledbooleanfalse
discoveryDocs-https://developers.google.com/discovery/v1/using
uxModestringpopupThe UX mode to use for the sign-in flow. Valid values are popup and redirect.
themestringlightIf set to dark the button will follow the Google brand guidelines for dark. Otherwise it will default to light (https://developers.google.com/identity/branding-guidelines)
iconbooleantrueShow (true) or hide (false) the Google Icon
redirectUristring-If using ux_mode='redirect', this parameter allows you to override the default redirect_uri that will be used at the end of the consent flow. The default redirect_uri is the current URL stripped of query parameters and hash fragment.
isSignedInbooleanfalseIf true will return GoogleUser object on load, if user has given your app permission
renderfunction-Render prop to use a custom element, use renderProps.onClick

Google Scopes List: scopes

onSuccess callback ( w/ offline false)

onSuccess callback returns a GoogleUser object which provides access to all of the GoogleUser methods listed here: https://developers.google.com/identity/sign-in/web/reference#users .

You can also access the returned values via the following properties on the returned object.

property namevaluedefinition
googleIdstringGoogle user ID
tokenIdstringToken Id
accessTokenstringAccess Token
tokenObjobjectToken details object
profileObjobjectProfile details object

onSuccess callback ( w/ offline true)

property namevaluedefinition
codeobjectoffline token

You can also pass child components such as icons into the button component.

  <GoogleLogin
    clientId={'658977310896-knrl3gka66fldh83dao2rhgbblmd4un9.apps.googleusercontent.com'}
    onSuccess={responseGoogle}
    onFailure={responseGoogle}
  >
    <FontAwesome
      name='google'
    />
    <span> Login with Google</span>
  </GoogleLogin>

onFailure callback

onFailure callback is called when either initialization or a signin attempt fails.

property namevaluedefinition
errorstringError code
detailsstringDetailed error description

Common error codes include:

error codedescription
idpiframe_initialization_failedinitialization of the Google Auth API failed (this will occur if a client doesn't have third party cookies enabled)
popup_closed_by_userThe user closed the popup before finishing the sign in flow.
access_deniedThe user denied the permission to the scopes required
immediate_failedNo user could be automatically selected without prompting the consent flow.

More details can be found in the official Google docs:

Dev Server

npm run start

Default dev server runs at localost:8080 in browser. You can set IP and PORT in webpack.config.dev.js

Run Tests

npm run test:watch

Production Bundle

npm run bundle

Deploy Storybook

npm run deploy-storybook
Checkout my other login: React Instagram Login
Checkout keppelen's React Facebook Login

Follow me on Twitter: @anthonyjgrove