Reference implementation of authentication in Ionic 2

So I’m trying to get started with ionic 2 from ionic 1 and need some guidance on how to set up authentication in my project. Specifically I’m using firebase and angularfire2.

As a general approach should I either:

a. Check for session/localStorage on app.ts and set the rootPage to login if unauthenticated? Using this method if I log the user out and set the nav rootpage back to the login, the tabs are displayed at the bottom.

b. Create the login page as a modal which removes the problem of the tabs appearing at the bottom, but I’m not sure if I should be firing the modal from app.ts since that doesn’t have a nav I don’t think.

Also, should I set up the auth login and logout as a service and refactor it out rather than having it in the login page and the logout button in the profile controllers?

Here’s my logic thus far using method A:

app.ts

export class MyApp {
  rootPage: any;
  local: Storage = new Storage(LocalStorage);
  constructor(platform: Platform) {
    this.local.get('user').then(user => { 
      if (user) {
        this.rootPage = TabsPage;
      } else {
        this.rootPage = LoginPage;
      }
    });
    
    platform.ready().then(() => {
      StatusBar.styleDefault();
    });
  }
}

And in myProfile.ts

  logout() {
    this.local.remove('user');
    this.user = null;
    let modal = Modal.create(LoginPage);
    this.nav.present(modal); //should I set the rootPage instead?  if so how do I remove the tabBar or set the rootpage of the containing app root page
  }

What I do is to have the root page of the app be a dispatch page with a blank template. The dispatch page subscribes to an observer provided by a service that provides notifications of login/logout and reacts thusly:

   let logsub = (loggedin) => {
      if (loggedin) {
        nav.setRoot(TabsPage);
      } else {
        nav.setRoot(LoginPage);
      }
    };

This way login and logout can happen through many different paths (switch user, explicit logout, inactivity timeout, &c) and the screen flow logic doesn’t have to know or care about it. All those things interact with the service that manages authentication status.

How would I create a subscrption using angular fire 2 for firebase. This is the example code they show but not sure how to subscribe to the event outside the template

https://angularfire2.com/api/

Type: class FirebaseAuth extends ReplaySubject

Usage:

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 have a working example here https://github.com/aaronksaunders/ionic2-angularfire-sample

ngOnInit() {

    // subscribe to the auth object to check for the login status
    // of the user, if logged in, save some user information and
    // execute the firebase query...
    // .. otherwise
    // show the login modal page
    this.auth.subscribe((data) => {
        console.log("in auth subscribe", data)
        if (data) {
            this.authInfo = data.password
            this.bookItems = this.af.list('/bookItems');
        } else {
            this.authInfo = null
            this.displayLoginModal()
        }
    })
}

Hi Aaron,
I tried an approach like yours, but the function passed to this.af.auth.subscribe() is not getting called despite successful login with angularfire2.

My sample project is here - https://github.com/cyberabis/momentu-ionic.

Any idea what’s going wrong?

After updating AngularFire2 to version beta 3, the issue got fixed.

So, in package.json, change as:

"angularfire2": "^2.0.0-beta.3-0930330"

And then, npm install and try running the application. npm install complained of unmet peer dependencies requiring Angular 2 RC 2, and I am using RC3. But it was just a warning, and the app runs fine after this change.