Skip to content

Instantly share code, notes, and snippets.

@Vivek-abstract
Created February 25, 2019 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vivek-abstract/a29982baf3fcd2690df41f618aad5100 to your computer and use it in GitHub Desktop.
Save Vivek-abstract/a29982baf3fcd2690df41f618aad5100 to your computer and use it in GitHub Desktop.
Google Login in Ionic 4
constructor(private afAuth: AngularFireAuth, private http: HTTP) {
afAuth.authState.subscribe(user => {
this.user = user;
});
}
async signInWithGoogle(user) {
return await this.afAuth.auth.signInAndRetrieveDataWithCredential(
firebase.auth.GoogleAuthProvider.credential(user.idToken)
);
}
constructor(
private router: Router,
private formBuilder: FormBuilder,
public authService: AuthService,
private toastCtrl: ToastController,
private http: HTTP,
private httpAngular: Http,
private platform: Platform,
private gplus: GooglePlus,
public alertController: AlertController,
private facebook: Facebook,
private linkedinService: LinkedinService,
public loadingController: LoadingController
) {
}
googleLogin() {
this.presentLoading();
if (this.platform.is("cordova")) {
this.nativeGoogleLogin()
.then(userCredentials => {
if (userCredentials["additionalUserInfo"].isNewUser) {
let user = {
name: userCredentials["user"].displayName,
email: userCredentials["user"].email,
profile: userCredentials["user"].photoURL,
uid: userCredentials["user"].uid
};
this.sendDataToServer(user);
// Do something with data ex: create document
}
this.loading.dismiss();
this.router.navigateByUrl("home");
})
.catch(err => {
this.loading.dismiss();
this.showAlert("Error", "Something went wrong");
});
} else {
// When ionic serve is used
this.loginWithProvider("google");
}
}
async nativeGoogleLogin() {
try {
const user = await this.gplus.login({
webClientId: environment.webClientId,
offline: true,
scopes: "profile email"
});
return this.authService.signInWithGoogle(user);
} catch (err) {
return reject("Error");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment