เปิดมาครั้งแรกจะขึ้นว่า User is not logged in!
ถ้ากดปุ่ม login จะขึ้น User is logged in! และจะสามารถกดปุ่ม Next Page เพื่อไปหน้าถัดไปได้
พอกด logout ก็จะกลับมาขึ้นว่า User is not logged in!
จำการ login ของผู้ใช้ โดยกาาเก็บ token ผู้ใช้ลง localStorage
แล้วใช้ Auth Guard ตรวจสอบข้อมูลดังกล่าว
โดย concept แล้ว Auth Guard เราใช้
- ionViewCanEnter()
- ionViewCanLeave()
ดู IONIC PAGE LIFECYCLE EVENTS ทั้งหมด
Note: ห้ามเก็บ password ลง localStorage
เพราะไม่ปลอดภัย
แต่ให้เก็บเป็น token อะไรซักอย่างไว้ตรวจสอบพอ
ในตัวอย่างนี้เก็บ username
ซึ่งก็ไม่ปลอดภัย เพราะเดาค่าได้ง่าย
Note:
- รันบนมือถือ Android ถ้ายังไม่ login พอกด Next Page ไม่ขึ้น Error แจ้งเตือน
- รันด้วยคำสั่ง ionic serve -l ได้ผลเหมือนรันบนมือถือ
- รันบน browser เข้าหน้า Next Page ไม่ได้โดยขึ้น Error แจ้งเตือน
สร้างโปรเจ็กส์ เพิ่ม page และเพิ่ม provider
[code]
ionic start authGuardApp blank
cd authGuardApp
ionic g page Second
ionic g provider AuthService
[/code]
src/app/app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule } from '@angular/core'; import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'; import { SplashScreen } from '@ionic-native/splash-screen'; import { StatusBar } from '@ionic-native/status-bar'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; import { AuthServiceProvider } from '../providers/auth-service/auth-service'; import { SecondPage } from '../pages/second/second'; @NgModule({ declarations: [ MyApp, HomePage, SecondPage ], imports: [ BrowserModule, IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage, SecondPage ], providers: [ StatusBar, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler}, AuthServiceProvider ] }) export class AppModule {} |
src/providers/auth-service/auth-service.ts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
//import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable() export class AuthServiceProvider { constructor() { console.log('Hello AuthServiceProvider Provider'); } // Login a user // Normally make a server request and store // e.g. the auth token login(): void { localStorage.setItem('username', "jack"); //this.isLoggedIn = true; } // Logout a user, destroy token and remove // every information related to a user logout(): void { localStorage.removeItem('username'); //this.isLoggedIn = false; } // Returns whether the user is currently authenticated // Could check if current token is still valid authenticated(): boolean { let username = localStorage.getItem('username'); if (username == null) { //console.log("username is null"); return false; } else { //console.log("username is " + username); return true; } //return this.isLoggedIn; } } |
src/pages/home/home.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<ion-header> <ion-navbar> <ion-title> Ionic Blank </ion-title> </ion-navbar> </ion-header> <ion-content padding> <h2 *ngIf="isAuthenticated()" text-center>User is logged in!</h2> <h2 *ngIf="!isAuthenticated()" text-center>User is not logged in!</h2> <button full ion-button color="primary" (click)="loginUser()">Login</button> <button full ion-button color="danger" (click)="logoutUser()">Logout</button> <button full ion-button color="secondary" (click)="nextPage()">Next Page</button> </ion-content> |
src/pages/home/home.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import { Component } from '@angular/core'; import { NavController, AlertController } from 'ionic-angular'; import { AuthServiceProvider } from '../../providers/auth-service/auth-service'; import { SecondPage } from './../second/second'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { constructor(public navCtrl: NavController, public authService: AuthServiceProvider, public alertCtrl: AlertController) { } loginUser() { this.authService.login(); } logoutUser() { this.authService.logout(); } nextPage() { this.navCtrl.push(SecondPage).catch(err => { let alert = this.alertCtrl.create({ title: 'No entry!', subTitle: 'You shall not pass', buttons: ['Okay'] }); alert.present(); console.log("Error"); }); } isAuthenticated() { return this.authService.authenticated(); } } |
บรรทัดที่ 2: เพิ่ม AlertController
src/pages/second/second.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import { Component } from '@angular/core'; import { IonicPage, NavController } from 'ionic-angular'; import { AuthServiceProvider } from '../../providers/auth-service/auth-service'; @IonicPage() @Component({ selector: 'page-second', templateUrl: 'second.html', }) export class SecondPage { constructor(public navCtrl: NavController, public authService: AuthServiceProvider) { } ionViewCanEnter() { return this.authService.authenticated(); } ionViewDidLoad() { console.log('ionViewDidLoad SecondPage'); } } |
บรรทัดที่ 2: ลบ NavParams
Link