how to subscribe to firebase login events with angularfire2 - firebase

I saw this example for how to subscribe to firebase auth events
this.firebase.onAuth((user) => {})
How can I do the same thing with angularfire2 and ionic2 and angular2 project?
constructor(nav:NavController, private auth: FirebaseAuth) {
auth.onAuth ... // I don't see any subscription events on the firbaseAuth object
}
I saw this syntax in the angularfire2 documentation but not sure what the | syntax means and how to do the same logic from the #Component declartion in the controller code:
import {FirebaseAuth} from 'angularfire2';
#Component({
selector: 'auth-status',
template: `
<div *ng-if="auth | async">You are logged in</div>
<div *ng-if="!(auth | async)">Please log in</div>
`
})
class App {
constructor (#Inject(FirebaseAuth) public auth: FirebaseAuth) {}
}

I don't know about Iconic, but using angularafire2 (2.0.0-beta.2). Here's how to do this. Assuming the project has been setup so that AngularFire is an injectable service. (I followed the instructions at Angularfire2 Github.)
#Component({
.. blah, blah, blah
})
export class MyComponent{
constructor(private AngularFire af){
af.subscribe.auth(auth => {
//the auth object contains the logged in user info
// if one exists.
console.log(auth)
});
}
In order to refer to the auth object from the html template (as in your example), just store the auth object returned by the call to subscribe as member variable. Your template code is just checking non-null to determine that there is a logged in user.

This has been updated in "angularfire2": "^4.0.0-rc.1"
The subscribe is now in authState from the import { AngularFireAuth } from 'angularfire2/auth';
So in your ngModule you need to add
import { AngularFireAuthModule } from 'angularfire2/auth';
And add it to your imports and then in your app.components.ts
this.af.authState.subscribe(auth => {
console.log(auth);
});

Related

User Authentication failed in angularFire2

//Login component.ts
import { Component } from '#angular/core';
import {AngularFireAuth} from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import {Router} from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
constructor(public afAuth: AngularFireAuth , public router: Router) { }
login() {
this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()).then((sucess) => {
this.router.navigate(['/option']);
});
}
angularFire2 version --5.0.0-rc.10
firebase version --4.13.1
I have imported the AngularFireAuthModule and AngularFireModule in my app.module.ts and enabled google authentication in firebase console but am still getting an error message as-this is the error message i get
Please Help !!
did you provided the correct Config for FireBase? With all you auth domain and api keys?
See step 4: AngularFire2 installation Guide
Please don't forget to not post the config here, or to change your values as it contains Secret keys.

FCMPlugin is not Defined in home.ts

I am trying to send a Push notification Using Firebase and Ionic 3. I have already imported the FCMPlugin in my project though my cmd. When I am creating a new message in firebase and try tos end, I don't receive anything, I run console log in my project and it gives me the following error "FCMPlugin is not defined".
I have declared the Plugin in my home.ts, but I am still getting this error, my home.ts is as follows:
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import {AlertController} from 'ionic-angular';
declare var FCMPlugin: any; // <---- this is the magic line
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(private alert:AlertController, private platform:Platform) {
this.onNotification();
}
async onNotification(){
try {
await this.platform.ready();
FCMPlugin.onNotification((data)=>{
this.alert.create({
message: data.message
}).present();
},(error) => console.error(error));
}
catch (e) {
console.error(e);
}
}
}
Can anyone provide me some guidance asIi am quite new to ionic?
Thanks in Regards
try using the FCM onNotification method inside an if block so that whenever you use it on a browser or whenever FCM is called before its initialisation it will not throw an error:
if (typeof FCMPlugin != 'undefined') {
FCMPlugin.onNotification((data)=>{})
}

how to determine if user is logged in "recently" in firebase

I'm trying to implement an angular guard to check if the user was signed in recently so they can change password, update email etc.
Using either angular fire 2 or angular I have a handle to the user (firebase.User). But how do I check if they qualify for "recently logged in" to perform sensitive operations?
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '#angular/router';
import { Observable } from 'rxjs/Rx';
import { Injectable, OnInit } from '#angular/core';
import { AuthService } from './auth.service';
import * as firebase from 'firebase/app';
#Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> {
return this.authService.user$.map((user) => {
if (user) {
// how to validate that this user is a recent login?
return true;
} else {
console.log('not authenticated');
this.router.navigateByUrl('/login');
return false;
}
}).first();
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.canActivate(route, state);
}
}
Why not just always re-authenticate before any sensitive information. It is common practice and Firebase provides APIs for re-authentication. You can check the auth_time in the Firebase ID token for the time of the last sign-in but Firebase Auth doesn't document the criteria for the recently logged in requirement and likely won't as they reserve the right to change it for security reasons. You are better off just requiring reauthentication, or you can try to updatePassword/updateEmail but if you get that specific error, reauthenticate and then try again.

How can i pass Data into my SQLite-Database

Hello there :) I am pretty new to programming and I recently started an IONIC App. However I got stuck. I want to do something like a phone book where you can get random JSON contacts and save them to your sqlite database.
I got this:
import { Storage ] from '#ionic/storage';
#component({
selector: 'page-home'
templateUrl: 'home.html'
});
export class HomePage {
posts: any;
persons: any;
constructor(public navCtrl: NavController, public http: Http, public storage: Storage) {
this.http.get('https://jsonplaceholder.typicode.com/users').map(res=> res.json()).subscribe(data => {
this.posts = data;
});
}
//here i would like to recieve the data from the tapped Item
setData(){
console.log();
this.storage.set('myData', this.posts);
console.log(this.posts);
};
getData(){
this.storage.get('myData').then((data) => {
if (data !=null){
console.log(data);
}
})
};
}
Here is the View:
When i click / tap the save-button i would like to store the values in my sqlite-database and display them in my "local contacts".
<ion-content>
<ion-list>
<ion-item *ngFor="let post of posts">
<ion-list>
<ul><h1>{{post.name}}</h1></ul>
<ul><p>{{post.username}}, {{post.email}}</p></ul>
<ul><p>phone: {{post.phone}}</p></ul>
<button ion-button (click)="setData()">Set Data</button>
</ion-list>
</ion-item>
</ion-list>
</ion-content>
Maybe someone faced similar problems and can help me with this.
Thanks :)
The best way to handle persistent storage with Ionic is using ionic-storage.
Ionic Storage is a package created and maintained by the ionic team to abstract development from the specifics of each browser or platform and automatically use the best storage solution available.
1. Installing Dependencies
In your case for SQLite you need to first install the dependencies for both Angular and Cordova:
npm install #ionic/storage --save
and
cordova plugin add cordova-sqlite-storage --save
Then edit your NgModule declaration in src/app/app.module.ts to add IonicStorageModule as an import:
import { IonicStorageModule } from '#ionic/storage';
#NgModule({
declarations: [...],
imports: [
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot({
name: '__mydb',
driverOrder: ['indexeddb', 'sqlite', 'websql'],
})
],
bootstrap: [...],
entryComponents: [...],
providers: [...],
})
export class AppModule { }
2. Inject Storage into your component
import { Component } from '#angular/core';
import { Storage } from '#ionic/storage';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public storage: Storage) {}
}
3. Storing data in SQLite
Whenever you access storage, make sure to always wrap your code in the following:
storage.ready().then(() => { /* code here safely */});
3.1 Saving a key-value pair
storage.ready().then(() => {
storage.set('some key', 'some value');
});
3.2 Retrieving a value
storage.ready().then(() => {
storage.get('age').then((val: string) => {
console.log('Your age is', val);
});
});
3.3 Deleting a key-value pair
storage.ready().then(() => {
storage.remove('key').then((key: string) => { /* do something after deletion */})
});

How to get currently logged in auth state/user from angularfire2

I have an ionic2 app and am using Firebase and angularFire2. I'd like to get the current authentication state and current auth object/user from firebase using angularFire2.
Here's what's working so far - I can authenticate the user and subscribe to the FirebaseAuthState to get the facebook user object.
constructor(platform: Platform, private auth: FirebaseAuth) {
auth.subscribe((user: FirebaseAuthState) => {
if (user) {
// I could store user in localstorage, but I'd like to see an All Firebase solution
this.rootPage = TabsPage;
} else {
this.rootPage = LoginPage;
}
});
Now I can just set localstorage here and cache my user object to remember auth state. However, I am curious to see how I can use Firebase only without me implementing my own custom local storage key. I see that Firebase stores a localStorage key of it's own so knows that its logged in.
How can I get the auth object from code? Additionally, I tried the listed example in the AngularFire2 documentation to render the auth state in the template - but that gives me an error.
import {FirebaseAuth} from 'angularfire2';
#Component({
selector: 'auth-status',
template: `
<div *ng-if="auth | async">You are logged in</div>
<div *ng-if="!(auth | async)">Please log in</div>
`
})
class App {
constructor (#Inject(FirebaseAuth) public auth: FirebaseAuth) {}
}
Import: import { AngularFireAuth } from 'angularfire2/auth';
Inject: constructor(public afAuth: AngularFireAuth) { }
Check:
this.afAuth.authState.subscribe(res => {
if (res && res.uid) {
console.log('user is logged in');
} else {
console.log('user not logged in');
}
});
now in order to get the user info, you have to subscribe for getting the auth information. Ex
constructor(public af: AngularFire) {
this.af.auth.subscribe(auth => console.log(auth));// user info is inside auth object
}
auth object will be null if auth state does not exist
current authentication state is available from the injected FirebaseAuth. You can get the actual auth data auth.getAuth()
See: https://github.com/angular/angularfire2/blob/master/src/providers/auth.ts#L99
You can simply import AngularFireAuth and do this:
this.angularFireAuth.authState.subscribe(userResponse => {
if (userResponse) {
console.log('here is your user data');
localStorage.setItem('user', JSON.stringify(userResponse));
console.log(userResponse);
} else {
localStorage.setItem('user', null);
}
});
Here i am also using localStorage to save all data of my current user active on my app.

Resources