Best way to connect ionic 2 nativ facebook with firebase - ionic-framework

at the moment iam implementing a signIn into my ionic 2 app.
I want to use ionic 2 native facebook and somehow save the data to my firebase app.
Is there any way to archive that?
One way is to create a new firebase auth user with the facebook email adress and some password hash, but maybe there is a better solution.
Here is what i got so far (i know, not much) :)
import {NavController, Loading, Platform, Storage, LocalStorage} from "ionic-angular";
import {OnInit, Inject, Component} from "#angular/core";
import {ForgotPasswordPage} from "../forgot-password/forgot-password";
import {SignUpPage} from "../sign-up/sign-up";
import {HomePage} from "../../home/home";
import * as firebase from 'firebase';
import {Facebook} from 'ionic-native';
/*
Generated class for the LoginPage page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Component({
templateUrl: 'build/pages/auth/login/login.html',
})
export class LoginPage {
private local: any;
constructor(private navCtrl: NavController, private platform:Platform) {
this.local = new Storage(LocalStorage);
}
openForgotPasswordPage():void {
this.navCtrl.push(ForgotPasswordPage);
}
openSignUpPage():void {
this.navCtrl.push(SignUpPage);
}
login() {
firebase.auth().signInWithEmailAndPassword("test#test.com", "correcthorsebatterystaple").then(function (result) {
console.log("AUTH OK "+ result);
}, function (error) {
console.log("dawdaw");
});
}
facebookLogin() {
Facebook.login(['public_profile', 'user_birthday']).then(() => {
this.local.set('logged', true);
this.navCtrl.setRoot(HomePage);
}, (...args) => {
console.log(args);
})
} }

facebookLogin() {
Facebook.login(['public_profile', 'user_birthday']).then((result) => {
var creds = firebase.auth.FacebookAuthProvider.credential(result.access_token);
return firebase.auth().signInWithCredential(creds);
})
.then((_user) => {
console.log("_user:", _user);
})
.catch((_error) => {
console.error("Error:", _error);
});
}
see more info here - https://firebase.google.com/docs/auth/web/facebook-login#advanced-handle-the-sign-in-flow-manually

I have not tried this, so might not be 100% working, but try this Gist I found: https://gist.github.com/katowulf/de9ef6b04552091864fb807092764224

Related

Pause MyApp during modal.present()

Original Post:
I am coding an Ionic 2 Hybrid app and attempting to create a modal that logs into FB and gathers necessary information for the app to run properly.
While the modal is presented (and the user is logging in), I need the app to be paused in the background. In other words, it cannot be continuing with the subsequent processes until the modal is dismissed.
Here is the relevant portion of code as an example:
var user = firebase.auth().currentUser;
if (user) {
console.log("User is already signed in.");
} else {
console.log("No user is signed in.");
let profileModal = this.modalCtrl.create(ProfilePage);
profileModal.present();
}
console.log("test pause.")
While the modal is still being presented and before it is dismissed, "test pause." is being written to the console. I need it to NOT be written to the console until AFTER the modal is dismissed.
NOTE: I have everything working properly except this bit. I haven't figured out how to accomplish 'pausing' until the modal is dismissed.
Is there any way to do this?
Clarification:
I am presenting the modal in the ngOnInit() of the main app component. I am doing this because I need specific user information to be gathered before the main app component is loaded and any pages are set/added to the stack.
Otherwise, the rootpage will not be built properly.
Here is the updated code in its full context in the app.component.ts file:
import { Component, ViewChild, OnInit } from '#angular/core';
import { ModalController, Nav, Platform } from 'ionic-angular';
import { SettingsService } from './../services/settings';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { HomePage } from './../pages/home/home';
import { SignInPage } from './../pages/signin/signin';
import { CreatePage } from './../pages/create/create';
import { ProfilePage } from './../modals/profile/profile';
import firebase from 'firebase';
#Component({
templateUrl: 'app.html'
})
export class MyApp implements OnInit {
#ViewChild(Nav) nav: Nav;
rootPage: any = HomePage;
homePage: any = HomePage;
signInPage: any = SignInPage;
createPage: any = CreatePage;
photoURL: string;
constructor(private modalCtrl: ModalController,
private platform: Platform,
private statusBar: StatusBar,
private splashScreen: SplashScreen,
private settingsService: SettingsService) {
this.initializeApp();
}
ngOnInit() {
var config = {
apiKey: "AIzaSyDmTh_LZuMPnn7nJRquoW5xWwgQ4Ia3J9E",
authDomain: "thevault-ba308.firebaseapp.com",
databaseURL: "https://thevault-ba308.firebaseio.com",
projectId: "thevault-ba308",
storageBucket: "thevault-ba308.appspot.com",
messagingSenderId: "1024205108979"
};
firebase.initializeApp(config);
var user = firebase.auth().currentUser;
if (user) {
console.log("User is already signed in.");
}
else {
console.log("No user is signed in.");
let profileModal = this.modalCtrl.create(ProfilePage);
profileModal.present();
profileModal.onDidDismiss(() => {
console.log("test pause.")
this.photoURL = this.settingsService.getUserPhoto();
console.log(this.settingsService.getUserName());
})
}
}
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
openPage(page) {
this.nav.setRoot(page);
}
signOut() {
firebase.auth().signOut().then((result) => {
console.log("Sign out success.");
this.nav.setRoot(SignInPage);
}).catch((error) => {
console.log(error.message);
});
}
}
You should move all the code that was supposed to execute after modal is dismissed in this modal.onDismiss() part. Like this:
let profileModal = this.modalCtrl.create(ProfilePage);
profileModal.present();
profileModal.onDismiss((data) => {
console.log("Data from modalPage :",data);
console.log("test pause."); // Here you go. The code will be paused till the modal is dismissed.
});
Moreover, you can pass data to the modalPage via navParams and retrieve from the modalPage as well using this.viewCtrl.dismiss(data);.
For more reference, look at this and this ionic 2 documentation.
I was able to resolve my problem by using *ngIf in the app.html file.
<ion-content *ngIf="photoURL != null">

ionic 2 check if user already logged in with angularfire2

I did facebook login to my app and I'm trying to check if the user logged in then go to HomePage,if not go to loginPage.
I did it with firebase but I'm trying to do that with angularfire2
that's my code with firebase (I want it in angularfire2)
firebase.auth().onAuthStateChanged((user) => {
var that=this;
if (user) {
if(this.reg_boolean=="true"){
console.log("regCompleted");
this.nav.setRoot(TabsPage,{
dep:this.department,year:this.year,semester:this.semester
})
this.rootPage=TabsPage;
}
else{
this.rootPage = SignupPage;
}
console.log("I'm here! HomePage");
} else {
this.rootPage = LoginPage;
console.log("I'm here! LoginPage");
}
});
I got this to work in app.component.ts file.
import { ViewChild } from '#angular/core';
import { Nav } from 'ionic-angular';
import { AngularFire } from 'angularfire2'; // import this, duh
import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any;
pages: Array<{ title: string, component: any }>;
userName:string;
constructor(public platform: Platform,
public af: AngularFire,
public authService: AuthenticationService) { // used for logout
this.initializeApp();
// Listen for auth sub
af.auth.subscribe(user => {
this.rootPage = user ? HomePage : LoginPage;
});
....
So basically get listening on the subscribe and change the rootPage based on the value passed into the var user. You can do a console.log() on user if you want to be more specific with the redirection.

ionic 2: how to dismiss loader after data is ready?

In my Ionic 2 app, I have i have component that GET to fetch data.
i want to maker loader and dismiss it after data is ready.
i tried to look on other posts around the stack overflow but my issue is different.
i did something but the loader is forever and its not helps me.
It looks like following:
import { Component,ViewChild } from '#angular/core';
import { NavController,LoadingController,AlertController,ViewController} from 'ionic-angular';
import { Facebook } from 'ionic-native';
//import pages
import {LoginPage} from "../../pages/login/login";
import {User} from '../../models/user'
import { Storage} from '#ionic/storage';
//import provider
import { ProfileData } from '../../providers/profile-data';
import { NotesData } from '../../providers/notes-data';
import firebase from 'firebase'
import {AddNote} from "../add-note/add-note";
/*
Generated class for the NotesList page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Component({
selector: 'page-notes-list',
templateUrl: 'notes-list.html'
})
export class NotesList {
//facebook user
userProfile: any = null;
uid: any = null;
fireUid:any=null;
name:string=null;
photo: any =null;
user:User=null;
photos:any=null;
currentUser:any=null;
photonew:any=null;
//notes list
notes:any=null;
data:any;
pages: Array<{title: string, component: any}>;
constructor(public navCtrl: NavController,public profileData:ProfileData,private viewCtrl: ViewController,public notesData:NotesData,private loadingCtrl: LoadingController,private alertCtrl: AlertController,public storage:Storage) {
this.data={};
this.data.title="";
this.data.desc="";
}
ionViewDidLoad() {
//if i do that the loader is forever
/*
let loader = this.loadingCtrl.create({
dismissOnPageChange: true,
});
loader.present();
*/
// here i want the loader to be until the data is ready.
this.getNotesList(); //this functions not returns data so i can't do this.getNotesList().then(()=>
}
getNotesList(){
console.log("get event");
var that=this;
this.notesData.getNotesLIst().on('value', snapshot => {
let notesList= [];
snapshot.forEach( snap => {
console.log("id note"+snap.val().id);
notesList.push({
id: snap.val().id,
title: snap.val().title,
desc: snap.val().desc,
color:snap.val().color,
photo:snap.val().photo,
});
});
that.notes = notesList;
});
}
addNote(){
this.navCtrl.push(AddNote);
}
logOutFacebook(){
Facebook.logout().then((response)=>
{
this.navCtrl.push(LoginPage);
alert(JSON.stringify(response));
},(error)=>{
alert(error);
})
}
}
At first, you should show how do you implement your loading page. Is it a splash screen with cordorva? Or just as div displaying some image?
If it is a splash screen, you can add this code in your component after you get data, (it is from starter template, you can see the detail by creating a new project with ionic start):
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Splashscreen.hide();
});
And, if you use a div in your index page, it is similar, you can just get that element and remove it, with pure js.
okay it succeed to do that
this is my answer
ionViewDidLoad() {
let loader = this.loadingCtrl.create({});
loader.present();
this.getNotesList().then((x) => {
if (x) loader.dismiss();
});
}
getNotesList(){
return new Promise(resolve => {
var that=this;
this.notesData.getNotesLIst().on('value', snapshot => {
let notesList= [];
snapshot.forEach( snap => {
console.log("id note"+snap.val().id);
notesList.push({
id: snap.val().id,
title: snap.val().title,
desc: snap.val().desc,
color:snap.val().color,
photo:snap.val().photo,
});
});
that.notes = notesList;
resolve(true);
});
})
}

Assigning an import to a variable within a constructor

I am building an app in Ionic2. I want to implement Facebook within the app and so I am trying to use the ionic-native Facebook api. I imported it and then attempted to assign it to a variable so I could use the functions associated with it.
Here is my code.
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Facebook } from 'ionic-native';
#Component({
selector: 'page-news-feed',
templateUrl: 'news-feed.html',
})
export class NewsFeed {
fb: any;
constructor(public navCtrl: NavController, facebook: Facebook) {
this.fb = facebook;
}
doRefresh(refresher) {
console.log('Begin async operation', refresher);
setTimeout(() => {
console.log('Async operation has ended');
refresher.complete();
}, 2000);
}
this.fb.login([]);
ionViewDidLoad() {
console.log('Hello NewsFeed Page');
}
}
I thought an import works much like a class in that you can import it and assign it to a variable and then have access to its methods. Does it not work like that? How does it work?
You just have to import Facebook class like it is said in Ionic native docs :
https://ionicframework.com/docs/v2/native/
You don't need to inject it through the constructor. As method are static this will print an error.
Be sure to also call Facebook after platform.ready event. And don't forget to add the plugin. See your example modified accordingly.
import { Component } from '#angular/core';
import { NavController, Platform } from 'ionic-angular';
import { Facebook } from 'ionic-native';
#Component({
selector: 'page-news-feed',
templateUrl: 'news-feed.html',
})
export class NewsFeed {
constructor(public navCtrl: NavController, platform: Platform) {
platform.ready().then(() => {
console.log('Faceboook');
Facebook.login([]).then((response) => {
console.log(response);
}).catch((error) => {
console.error(error);
});
})
}
doRefresh(refresher) {
console.log('Begin async operation', refresher);
setTimeout(() => {
console.log('Async operation has ended');
refresher.complete();
}, 2000);
}
ionViewDidLoad() {
console.log('Hello NewsFeed Page');
}
}

Firebase returns AUTHENTICATION_DISABLED [duplicate]

I am creating a simple sample auth app with Ionic 2 and angularfire 2 as backend, when i try to create new user it says:
EXCEPTION: Error: Uncaught (in promise): Error: The specified
authentication provider is not enabled for this Firebase.
But i already enabled firebase authentication in firebase console:
app.ts
import {App, Platform} from 'ionic-angular';
import {StatusBar} from 'ionic-native';
import {HomePage} from './pages/home/home';
import { FIREBASE_PROVIDERS, defaultFirebase, firebaseAuthConfig, AuthProviders, AuthMethods } from 'angularfire2';
#App({
template: '<ion-nav [root]="rootPage"></ion-nav>',
providers: [
FIREBASE_PROVIDERS,
defaultFirebase('https://samplequizapp-50eb5.firebaseio.com'),
firebaseAuthConfig({
provider: AuthProviders.Password,
method: AuthMethods.Password
})
],
config: {} // http://ionicframework.com/docs/v2/api/config/Config/
})
export class MyApp {
rootPage: any = HomePage;
constructor(platform: Platform) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
});
}
}
home.ts
import { Page } from 'ionic-angular';
import { AngularFire, FirebaseListObservable } from 'angularfire2';
import { OnInit } from '#angular/core'
#Page({
templateUrl: 'build/pages/home/home.html'
})
export class HomePage implements OnInit {
user: any = {};
data: FirebaseListObservable<any[]>;
constructor(private af: AngularFire) {
}
ngOnInit() {
this.data = this.af.database.list('/userId')
}
signUp(data) {
this.af.auth.createUser({
email: data.email,
password: data.password
})
}
}
I am pretty sure there is nothing wrong with my code:
Firebase2 in its current version (2.4.2) is not yet compatible with Firebase SDK v3, and all projects created with the new Firebase console are only accessible with calls comaptible with SDK v3.
You want to create your Firebase backend in the legacy console www.firebase.com first, and then migrate to the new console.
This is documented in this closed issue of the angularfire2 github: https://github.com/angular/angularfire2/issues/189