0% found this document useful (0 votes)
52 views

Modul IONIC Framework Auth Guard

This document provides instructions for implementing authentication guards in an Ionic application using Angular. It includes 10 steps to set up authentication services, login and dashboard pages, and canLoad guards to secure routes. Key aspects covered are initializing an authentication service, adding login and logout functionality, and using guards to check for authentication and redirect users accordingly.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

Modul IONIC Framework Auth Guard

This document provides instructions for implementing authentication guards in an Ionic application using Angular. It includes 10 steps to set up authentication services, login and dashboard pages, and canLoad guards to secure routes. Key aspects covered are initializing an authentication service, adding login and logout functionality, and using guards to check for authentication and redirect users accordingly.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Modul IONIC Framework (Angular Version)

Auth Guards

Modul dikembangkan oleh :


Mohammad Irham Akbar S.Kom.,M.Cs
1. Ikuti Langkah-langkah berikut ini

• ionic start cobalogin


• cd cobalogin
• ionic g service services/authentication
• ionic g page login
• ionic g page dashboard
• ionic g guard guards/auth --implements CanLoad
• ionic g guard guards/autoLogin --implements CanLoad
• npm install @capacitor-community/http
• npm install @ionic-native/network
• npm install @capacitor/preferences

2. Coding di bagian app.module.ts

import { NgModule } from '@angular/core';


import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';

import { AppComponent } from './app.component';


import { AppRoutingModule } from './app-routing.module';
import { HttpClientModule } from '@angular/common/http';
import { Network } from '@ionic-native/network/ngx';

@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, IonicModule.forRoot(),HttpClientModule,
AppRoutingModule],
providers: [Network,{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy
}],
bootstrap: [AppComponent],
})
export class AppModule {}
3. Coding di bagian authentication.service.ts

import { Injectable } from '@angular/core';


import { HttpClient } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
import { Preferences } from '@capacitor/preferences';
const TOKEN_KEY = 'token-saya';
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
// Inisialisasi is auth
isAuthenticated: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null);
token = '';
constructor(private http: HttpClient) {
this.loadToken();
}
async loadToken() {
const token = await Preferences.get({ key: TOKEN_KEY });
if (token && token.value) {
console.log('set token: ', token.value);
this.token = token.value;
this.isAuthenticated.next(true);
} else {
this.isAuthenticated.next(false);
}
}
apiURL() {
return "http://localhost/backend/";
}
logout(): Promise<void> {
this.isAuthenticated.next(false);
return Preferences.remove({ key: TOKEN_KEY });
}

}
4. Coding di bagian auth.guard.ts

import { AuthenticationService } from './../services/authentication.service';


import { Injectable } from '@angular/core';
import { CanLoad, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { filter, map, take } from 'rxjs/operators';

@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanLoad {
constructor(private authService: AuthenticationService, private router: Router)
{}

canLoad(): Observable<boolean> {
return this.authService.isAuthenticated.pipe(
filter((val) => val !== null), // filter data auth
take(1), // mengambil data auth
map((isAuthenticated) => {
if (isAuthenticated) {
return true;
} else {
this.router.navigateByUrl('/');
console.log('anda harus login dulu');
return false;
}
})
);
}
}
5. Coding di bagian auto-login.guard.ts

import { Injectable } from '@angular/core';


import { CanLoad, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthenticationService } from '../services/authentication.service';
import { filter, map, take } from 'rxjs/operators';

@Injectable({
providedIn: 'root'
})
export class AutoLoginGuard implements CanLoad {
constructor(private authService: AuthenticationService, private router: Router) {
}
canLoad(): Observable<boolean> {
console.log('cek sesi login');
return this.authService.isAuthenticated.pipe(
filter((val) => val !== null), // Filter out initial Behaviour subject value
take(1), // Otherwise the Observable doesn't complete!
map((isAuthenticated) => {
if (isAuthenticated) {
console.log('Ada sesi login, redirect ke dashboard');
// Jika ada sesi login
this.router.navigateByUrl('/dashboard', { replaceUrl: true });
} else {
console.log('tidak ada sesi login');
return true;
}
})
);
}
}
6. Coding di bagian app-routing.module.ts

import { NgModule } from '@angular/core';


import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { AutoLoginGuard } from './guards/auto-login.guard';
import { AuthGuard } from './guards/auth.guard';

const routes: Routes = [


{
path: 'home',
loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)
},
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
},
{
path: 'login',
loadChildren: () => import('./login/login.module').then( m =>
m.LoginPageModule),
canLoad: [AutoLoginGuard]
},
{
path: 'dashboard',
loadChildren: () => import('./dashboard/dashboard.module').then( m =>
m.DashboardPageModule),
canLoad: [AuthGuard] // Secure all child pages
},
];

@NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
7. Coding di bagian login.page.html

<ion-header>
<ion-toolbar>
<ion-title>login</ion-title>
</ion-toolbar>
</ion-header>

<ion-content>
<ion-item lines="full">
<ion-label position="floating">Username</ion-label>
<ion-input type="text" [(ngModel)]="username" required="required"></ion-input>
</ion-item>
<ion-item lines="full">
<ion-label position="floating">Password</ion-label>
<ion-input type="password" [(ngModel)]="password" required="required"></ion-
input>
</ion-item>
<ion-row>
<ion-col>
<ion-button type="submit" color="primary" expand="block"
(click)="login()">Login</ion-button>
</ion-col>
</ion-row>

</ion-content>
8. Coding dibagian login.page.ts

import { AuthenticationService } from '../services/authentication.service';


import { Component, OnInit } from '@angular/core';
import { AlertController } from '@ionic/angular';
import { Http } from '@capacitor-community/http';
import { Preferences } from '@capacitor/preferences';

const TOKEN_KEY = 'token-saya';


const USERNAME = 'namasaya';

@Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
username: any;
password: any;

constructor(
private authService: AuthenticationService,
private alertController: AlertController,
) { }

ngOnInit() {

login() {
if (this.username != null && this.password != null) {
let url = this.authService.apiURL() + "proses_login.php";
Http.request({
method: "POST",
url: url,
headers: { "Content-Type": "application/json" },
data: {
username: this.username,
password: this.password
},
}).then((data) => {
console.log(data);
if (data['data']['status_login'] == 'berhasil') {
this.username = '';
this.password = '';
Preferences.set({ key: TOKEN_KEY, value: data['data']['token'] });
Preferences.set({ key: USERNAME, value: data['data']['username'] });
location.reload();
} else {
this.alertController.create({
header: 'Notifikasi',
message: 'Username dan Password salah',
buttons: ['OK']
}).then(res => {
res.present();
});
}
}, (err) => {
this.alertController.create({
header: 'Notifikasi',
message: 'Gagal Login, Periksa Koneksi Internet' + err,
buttons: ['OK']
}).then(res => {
res.present();
});
})
} else {
this.alertController.create({
header: 'Notifikasi',
message: 'Username dan Password Tidak Boleh Kosong',
buttons: ['OK']
}).then(res => {
res.present();
});
}

}
9. Coding di dashboard.page.html

<ion-header>
<ion-toolbar>
<ion-title>dashboard</ion-title>
</ion-toolbar>
</ion-header>

<ion-content>
<ion-item (click)="logout()">
<ion-icon slot="start" ios="exit-outline" md="exit-sharp"></ion-icon>
<ion-label>Logout</ion-label>
</ion-item>
<hr>
<center> Selamat datang {{ nama }}</center>
</ion-content>

10. Coding di dashboard.page.ts

import { Component, OnInit } from '@angular/core';


import { Preferences } from '@capacitor/preferences';
import { AuthenticationService } from '../services/authentication.service';
import { AlertController } from '@ionic/angular';
import { Router } from '@angular/router';
const USERNAME = 'namasaya';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.page.html',
styleUrls: ['./dashboard.page.scss'],
})
export class DashboardPage implements OnInit {
public nama= '';
constructor(private authService: AuthenticationService, private alertController :
AlertController, private router : Router) { }

ngOnInit() {
this.cekSesi();
console.log(this.nama);
}

async cekSesi() {
const ambilNama = await Preferences.get({ key: USERNAME });
if (ambilNama && ambilNama.value) {
let namauser = ambilNama.value;
this.nama = namauser;
} else {

}
}
logout() {
this.alertController.create({
header: 'Perhatian',
subHeader: 'Yakin Logout aplikasi ?',
buttons: [
{
text: 'Batal',
handler: (data: any) => {
console.log('Canceled', data);
}
},
{
text: 'Yakin',
handler: (data: any) => {
//jika tekan yakin
this.authService.logout();
this.router.navigateByUrl('/', { replaceUrl: true });
}
}
]
}).then(res => {
res.present();
});
}

}
11. Coding php api di direktori backend (atau bebas sesuai inisialisasi api_url di auth)

File koneksi.php

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: PUT, GET, HEAD, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Content-Type: application/json; charset=utf-8');

$con = mysqli_connect('localhost','root','','belajarcrud') or die("koneksi gagal");


?>

12. Lalu membuat api untuk proses login dengan post method

File proses_login.php
<?php

require 'koneksi.php';

$input = file_get_contents('php://input');
$data = json_decode($input,true);

$pesan = [];
$username = trim($data['username']);
$password = md5(trim($data['password']));

$query = mysqli_query($con,"select * from user where username='$username' and


password='$password'");
$jumlah = mysqli_num_rows($query);
if ($jumlah != 0) {
$value = mysqli_fetch_object($query);
$pesan['username'] = $value->username;
$pesan['token'] = time().'_'.$value->password;
$pesan['status_login'] = 'berhasil';
}else{
$pesan['status_login'] = 'gagal';
}

echo json_encode($pesan);
echo mysqli_error($con);
?>

You might also like