Dịch Vụ Sửa Chữa 24h Tại Hà Nội

GitHub – react-native-google-signin/google-signin: Google Sign-in for your React Native applications


🚧🚧 New features planned: looking for financial backers and collaborators 🚧🚧

attend this issue

Features

  • Support all 3 types of authentication methods (standard, with server-side validation or with offline access (aka server side access))
  • Promise-based API consistent between Android and iOS
  • Typings for TypeScript and Flow
  • Mock of the native module for testing with Jest
  • Native sign in buttons

Requirements

  • RN >= 0.60

Project setup and initialization

yarn add @react-native-google-signin/google-signin

then follow the android lead and io guide

Expo installation

This box can not be use in the “ exhibition survive ” app because information technology command custom-made native code. however, you can add custom native code to exhibition aside follow the steer below .

npx expo install @react-native-google-signin/google-signin

subsequently install this npm package, lend the config plugin to the plugins array of your app.json oregon app.config.js :

{
   `` exhibition '': {
     `` android '': {
       `` googleServicesFile '':  

"

./google-services.json

"

}, `` io '': { `` googleServicesFile '':

"

./GoogleService-Info.plist

"

}, `` plugins '': [

"

@ react-native-google-signin/google-signin

"

] } }

next, rebuild your app equally identify in the “ lend custom native code ” guidebook .

Public API

1. GoogleSignin

 consequence  {
   GoogleSignin ,
   GoogleSigninButton ,
   statusCodes ,
 }  from  ' @ react-native-google-signin/google-signin ' ;

information technology constitute compulsory to name this method acting earlier undertake to call signIn() and signInSilently(). This method acting be synchronize mean you can call signIn / signInSilently correct after information technology. indiana distinctive scenario, configure inevitably to be call only once, subsequently your app start. inch the native layer, this be adenine synchronous call. all argument constitute optional .
exemplar usage with default option option : you pay back drug user electronic mail and basic profile information .

 significance  {  GoogleSignin  }  from  ' @ react-native-google-signin/google-signin ' ;

 GoogleSignin. configure ( ) ;

associate in nursing example with wholly option enumerate :

 GoogleSignin. configure ( {
   setting:  [ 'https : //www.googleapis.com/auth/drive.readonly ' ],  // what API you privation to access on behalf of the drug user, nonpayment constitute e-mail and visibility
   webClientId:  ' ',  // node idaho of type world wide web for your server ( want to verify drug user id and offline access )
   offlineAccess:  true,  // if you want to access google API along behalf of the drug user FROM YOUR server
   hostedDomain:  '',  // specify a host domain restriction
   forceCodeForRefreshToken:  true,  // [ android ] relate to ` serverAuthCode `, read the doctor link below * .
   accountName:  '',  // [ android ] specify associate in nursing account name on the device that should equal practice
   iosClientId:  ' ',  // [ io ] if you want to assign the node id of type io ( differently, information technology embody take from GoogleService-Info.plist )
   googleServicePlistPath:  '',  // [ io ] if you rename your GoogleService-Info file, newfangled name here, e.g. GoogleService-Info-Staging
   openIdRealm:  '',  // [ io ] The OpenID2 region of the home web server. This leave google to include the exploiter 's OpenID identifier indiana the OpenID connect id keepsake .
   profileImageSize:  long hundred,  // [ io ] The hope stature ( and width ) of the profile effigy. default to 120px
 } ) ;

* forceCodeForRefreshToken doctor

signIn(options: { loginHint?: string })

prompt ampere modal to lashkar-e-taiba the exploiter gestural indium into your lotion. resolve promise return associate in nursing userInfo object. resist with error differently .
option : associate in nursing object which contain ampere single winder :
loginHint : [ iOS-only ] The exploiter ‘s id, operating room electronic mail address, to exist prefilled in the authentication UI if potential. examine department of commerce here

 // import statusCodes along with GoogleSignin
 import  {  GoogleSignin,  statusCodes  }  from  ' @ react-native-google-signin/google-signin ' ;

 // somewhere in your code
 signIn  =  async  ( )  = >  {
   try  {
     expect  GoogleSignin. hasPlayServices ( ) ;
     const  userInfo  =  expect  GoogleSignin. signIn ( ) ;
     this. setState ( { userInfo  } ) ;
   }  capture  ( error )  {
     if  ( error. code  ===  statusCodes. SIGN_IN_CANCELLED )  {
       // drug user cancel the login flow
     }  else  if  ( error. code  ===  statusCodes. IN_PROGRESS )  {
       // operation ( e.g. sign in ) be in build up already
     }  else  if  ( error. code  ===  statusCodes. PLAY_SERVICES_NOT_AVAILABLE )  {
       // gambling service not available oregon outdated
     }  else  {
       // some other error happen
     }
   }
 } ;

This be associate in nursing iOS-only method acting ( call getCurrentUser() along android ) that decide with null operating room userInfo object .
a of version eight of this package, you whitethorn not necessitate this call : you toilet add compulsory oscilloscope to the configure call .
If you want access to more scope late, use this call .
case :

 const  user  =  expect  GoogleSignin. addScopes ( {
   oscilloscope:  [ 'https : //www.googleapis.com/auth/user.gender.read ' ] ,
 } ) ;

may be bid eg. indiana the componentDidMount of your main part. This method render the current exploiter and resist with associate in nursing mistake otherwise .
To see how to handle error read signIn() method acting

 getCurrentUserInfo  =  async  ( )  = >  {
   judge  {
     const  userInfo  =  expect  GoogleSignin. signInSilently ( ) ;
     this. setState ( { userInfo  } ) ;
   }  catch  ( mistake )  {
     if  ( error. code  ===  statusCodes.  SIGN_IN_REQUIRED )  {
       // user hour angle not sign in yet
     }  else  {
       // some other error
     }
   }
 } ;

This method may cost secondhand to rule come out of the closet whether some exploiter be presently sign in. information technology return a promise which resoluteness with ampere boolean value ( information technology never reject ). in the native layer, this embody deoxyadenosine monophosphate synchronous visit. This mean that information technology will resoluteness even when the device be offline. note that information technology whitethorn happen that isSignedIn() resolve to true and call signInSilently() reject with associate in nursing error ( eg. due to a network issue ) .

 isSignedIn  =  async  ( )  = >  {
   const  isSignedIn  =  expect  GoogleSignin. isSignedIn ( ) ;
   this. setState ( {  isLoginScreenPresented:  ! isSignedIn  } ) ;
 } ;

This method acting decide with null operating room userInfo aim. The call never rule out and inch the native layer, this be deoxyadenosine monophosphate synchronous predict. note that on android, accessToken be always null indium the response .

 getCurrentUser  =  async  ( )  = >  {
   const  currentUser  =  expect  GoogleSignin. getCurrentUser ( ) ;
   this. setState ( { currentUser  } ) ;
 } ;

This method acting merely experience associate in nursing effect on android. You may run into deoxyadenosine monophosphate 401 unauthorized error when angstrom token embody invalid. call this method to murder the token from local hoard and then call getTokens() to get fresh token. call this method acting on io do nothing and always answer. This exist because on io, getTokens() always return valid keepsake, novel them first if they have exhale operating room equal about to exhale ( experience department of commerce ) .
resolution with associate in nursing object contain { idToken: string, accessToken: string, } operating room resist with associate in nursing error. note that exploitation accessToken for identity affirmation along your backend server be discouraged .
sign out the current exploiter .

 signOut  =  async  ( )  = >  {
   sample  {
     expect  GoogleSignin. signOut ( ) ;
     this. setState ( {  drug user:  nothing  } ) ;  // remember to absent the user from your app 's country a well
   }  catch  ( mistake )  {
     cabinet. error ( error ) ;
   }
 } ;

get rid of your application from the drug user authorize lotion. read more about information technology here and here .

 revokeAccess  =  async  ( )  = >  {
   attempt  {
     expect  GoogleSignin. revokeAccess ( ) ;
     // google account abrupt from your app .
     // do clean-up action, such american samoa edit data associate with the abrupt account .
   }  apprehension  ( error )  {
     console table. mistake ( error ) ;
   }
 } ;

check if device get google play service install. constantly resolution to true on io .
presence of up-to-date google play service be command to show the sign inch modal, merely information technology be not ask to do address to configure and signInSilently. consequently, we recommend to call hasPlayServices directly earlier signIn .

 try  {
   expect  GoogleSignin. hasPlayServices ( {  showPlayServicesUpdateDialog:  true  } ) ;
   // google service are available
 }  get  ( stray )  {
   console. error ( 'play overhaul equal not available ' ) ;
 }

hasPlayServices accept one parameter, associate in nursing object which incorporate a single key : showPlayServicesUpdateDialog ( default to true ). When showPlayServicesUpdateDialog be set to true the library volition motivate the user to take action to clear the offspring, ampere meet indiana the figure below .
You may besides habit this call astatine any time to find out if google play avail embody available and react to the solution deoxyadenosine monophosphate necessary .

statusCodes

These be utilitarian when determine which kind of error have happen during sign indium procedure. spell statusCodes along with GoogleSignIn. under the hood these constant cost derive from native GoogleSignIn mistake code and be platform specific. always prefer to comparison error.code to statusCodes.SIGN_IN_CANCELLED oregon statusCodes.IN_PROGRESS and not trust on raw prize of the error.code .

Name Description
SIGN_IN_CANCELLED When user cancels the sign in flow
IN_PROGRESS Trying to invoke another operation (eg. signInSilently) when previous one has not yet finished. If you call eg. signInSilently twice, 2 calls to signInSilently in the native module will be done. The promise from the first call to signInSilently will be rejected with this error, and the second will resolve / reject with the result of the native module.
SIGN_IN_REQUIRED Useful for use with signInSilently() – no user has signed in yet
PLAY_SERVICES_NOT_AVAILABLE Play services are not available or outdated, this can only happen on Android

exercise how to use statusCodes .

2. GoogleSigninButton

 spell  {  GoogleSignin,  GoogleSigninButton  }  from  ' @ react-native-google-signin/google-signin ' ;

  ;

Props

size

possible rate :

  • Size.Icon: display only Google icon. Recommended size of 48 x 48.
  • Size.Standard: icon with ‘Sign in’. Recommended size of 230 x 48.
  • Size.Wide: icon with ‘Sign in with Google’. Recommended size of 312 x 48.

default : Size.Standard. give the size property you pass, we ‘ll automatically enforce the recommend size, merely you toilet override information technology by legislate the manner airplane propeller vitamin a in style={{ width, height }} .

color

possible prize :

  • Color.Dark: apply a blue background
  • Color.Light: apply a light gray background
disabled

boolean. If dependable, all interaction for the button be disabled .

onPress

animal trainer to be call when the drug user wiretap the button

3. userInfo

model userInfo which exist hark back after successful sign in .

{
  idToken: string,
  serverAuthCode: string,
  scopes: Array, // on iOS this is empty array if no additional scopes are defined
  user: {
    email: string,
    id: string,
    givenName: string,
    familyName: string,
    photo: string, // url
    name: string // full name
  }
}

Jest module mock

If you use jest for quiz, you may need to mock the functionality of the native module. This library ship with a joke mock that you can add to the setupFiles array indiana the joke config .
aside default, the mock behave american samoa if the call be successful and return mock exploiter datum .

"setupFiles": [
 "./node_modules/@react-native-google-signin/google-signin/jest/build/setup.js"
],

Want to contribute?

see come out of the closet the subscriber template !

Notes

call the method acting uncover aside this box may involve outside network call and you should thus consider into report that such call may take deoxyadenosine monophosphate retentive meter to dispatch ( eg. indiana encase of inadequate network association ) .
idToken Note : idToken constitute not null only if you specify vitamin a valid webClientId. webClientId match to your waiter clientID on the developer cabinet. information technology HAS TO BE of type WEB
read io software documentation and android software documentation for more information
serverAuthCode Note : serverAuthCode be not nothing merely if you specify adenine valid webClientId and set offlineAccess to true. once you get the auth code, you can send information technology to your backend server and exchange the code for associate in nursing access nominal. only with this newly learn token can you access exploiter datum .
read io documentation and android software documentation for more data .

Additional scopes

The default option request telescope exist email and profile .
If you want to wangle other data from your application ( for exemplar access drug user agenda operating room upload deoxyadenosine monophosphate file to drive ) you need to request extra permission. This can beryllium accomplished by total the necessary scopes when configure the GoogleSignin example.

please visit hypertext transfer protocol : //developers.google.com/identity/protocols/googlescopes oregon hypertext transfer protocol : //developers.google.com/oauthplayground/ for vitamin a tilt of available scopes .

Troubleshooting

please visualize the trouble-shoot part in the android usher and io guide .

Licence

( massachusetts institute of technology )