user2956577
user2956577

Reputation: 91

Ionic 3 unauthenticated user redirect

I am working with Ionic for the first time and I am trying to redirect unauthenticated users to my login page.

On login the user gets a json-web-token that is stored inside the local storage. I also have an authentication service that has a loggedIn() method that checks whether the token is valid.

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';
import { Storage } from '@ionic/storage';


@Injectable()
export class AuthServiceProvider {

constructor(
  public http: HttpClient,
  public store: Storage,
 ) { }

 ...

 public loggedIn(): boolean {
   return tokenNotExpired('__local/_ionickv/token');
 }

 ...

}

Inside my HomePage component I then check if the user is logged in, before the page is loaded, with ionViewCanEnter().

import { Storage } from '@ionic/storage';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { LoginPage } from './../login/login';
import { AuthServiceProvider } from './../../providers/auth-service/auth-service';

@IonicPage({
name: 'home',
})
@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
})
export class HomePage {

constructor(
  public navCtrl: NavController, 
  public navParams: NavParams,
  public auth: AuthServiceProvider,
  public store: Storage,
) { }

ionViewCanEnter(): boolean {
  if(!this.auth.loggedIn()){
    this.navCtrl.setRoot(LoginPage);
  }
  return this.auth.loggedIn();
}

public logout(): void {
  this.auth.logout();
  this.navCtrl.setRoot(LoginPage);
}

}

When I try to enter the member area without login, the page is not loaded, which is fine. Unfortunately I am not redirected, I am left on a blank page.

@ionic/cli-utils  : 1.19.0
ionic (Ionic CLI) : 3.19.0
@ionic/app-scripts : 3.1.0
Ionic Framework    : ionic-angular 3.9.2
Node : v8.9.1
npm  : 5.5.1 
OS   : Linux 4.10

Upvotes: 0

Views: 2141

Answers (1)

grigson
grigson

Reputation: 3786

It's kind of ionic issue

as workaround currently i have to wrap redirect in setTimeout

ionViewCanEnter(){
    if(!this.authService.authenticated){
      setTimeout(()=>this.navCtrl.setRoot('login'))
    }
    return this.authService.authenticated
  }

Upvotes: 8

Related Questions