Modul IONIC Framework (Angular Version)
Auth Guards
Modul dikembangkan oleh :
Mohammad Irham Akbar [Link].,[Link]
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 [Link]
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 './[Link]';
import { AppRoutingModule } from './[Link]';
import { HttpClientModule } from '@angular/common/http';
import { Network } from '@ionic-native/network/ngx';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, [Link](),HttpClientModule,
AppRoutingModule],
providers: [Network,{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy
}],
bootstrap: [AppComponent],
})
export class AppModule {}
3. Coding di bagian [Link]
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) {
[Link]();
}
async loadToken() {
const token = await [Link]({ key: TOKEN_KEY });
if (token && [Link]) {
[Link]('set token: ', [Link]);
[Link] = [Link];
[Link](true);
} else {
[Link](false);
}
}
apiURL() {
return "[Link]
}
logout(): Promise<void> {
[Link](false);
return [Link]({ key: TOKEN_KEY });
}
}
4. Coding di bagian [Link]
import { AuthenticationService } from './../services/[Link]';
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 [Link](
filter((val) => val !== null), // filter data auth
take(1), // mengambil data auth
map((isAuthenticated) => {
if (isAuthenticated) {
return true;
} else {
[Link]('/');
[Link]('anda harus login dulu');
return false;
}
})
);
}
}
5. Coding di bagian [Link]
import { Injectable } from '@angular/core';
import { CanLoad, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthenticationService } from '../services/[Link]';
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> {
[Link]('cek sesi login');
return [Link](
filter((val) => val !== null), // Filter out initial Behaviour subject value
take(1), // Otherwise the Observable doesn't complete!
map((isAuthenticated) => {
if (isAuthenticated) {
[Link]('Ada sesi login, redirect ke dashboard');
// Jika ada sesi login
[Link]('/dashboard', { replaceUrl: true });
} else {
[Link]('tidak ada sesi login');
return true;
}
})
);
}
}
6. Coding di bagian [Link]
import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { AutoLoginGuard } from './guards/[Link]';
import { AuthGuard } from './guards/[Link]';
const routes: Routes = [
{
path: 'home',
loadChildren: () => import('./home/[Link]').then( m => [Link])
},
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
},
{
path: 'login',
loadChildren: () => import('./login/[Link]').then( m =>
[Link]),
canLoad: [AutoLoginGuard]
},
{
path: 'dashboard',
loadChildren: () => import('./dashboard/[Link]').then( m =>
[Link]),
canLoad: [AuthGuard] // Secure all child pages
},
];
@NgModule({
imports: [
[Link](routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
7. Coding di bagian [Link]
<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 [Link]
import { AuthenticationService } from '../services/[Link]';
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: './[Link]',
styleUrls: ['./[Link]'],
})
export class LoginPage implements OnInit {
username: any;
password: any;
constructor(
private authService: AuthenticationService,
private alertController: AlertController,
) { }
ngOnInit() {
login() {
if ([Link] != null && [Link] != null) {
let url = [Link]() + "proses_login.php";
[Link]({
method: "POST",
url: url,
headers: { "Content-Type": "application/json" },
data: {
username: [Link],
password: [Link]
},
}).then((data) => {
[Link](data);
if (data['data']['status_login'] == 'berhasil') {
[Link] = '';
[Link] = '';
[Link]({ key: TOKEN_KEY, value: data['data']['token'] });
[Link]({ key: USERNAME, value: data['data']['username'] });
[Link]();
} else {
[Link]({
header: 'Notifikasi',
message: 'Username dan Password salah',
buttons: ['OK']
}).then(res => {
[Link]();
});
}
}, (err) => {
[Link]({
header: 'Notifikasi',
message: 'Gagal Login, Periksa Koneksi Internet' + err,
buttons: ['OK']
}).then(res => {
[Link]();
});
})
} else {
[Link]({
header: 'Notifikasi',
message: 'Username dan Password Tidak Boleh Kosong',
buttons: ['OK']
}).then(res => {
[Link]();
});
}
}
9. Coding di [Link]
<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 [Link]
import { Component, OnInit } from '@angular/core';
import { Preferences } from '@capacitor/preferences';
import { AuthenticationService } from '../services/[Link]';
import { AlertController } from '@ionic/angular';
import { Router } from '@angular/router';
const USERNAME = 'namasaya';
@Component({
selector: 'app-dashboard',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class DashboardPage implements OnInit {
public nama= '';
constructor(private authService: AuthenticationService, private alertController :
AlertController, private router : Router) { }
ngOnInit() {
[Link]();
[Link]([Link]);
}
async cekSesi() {
const ambilNama = await [Link]({ key: USERNAME });
if (ambilNama && [Link]) {
let namauser = [Link];
[Link] = namauser;
} else {
}
}
logout() {
[Link]({
header: 'Perhatian',
subHeader: 'Yakin Logout aplikasi ?',
buttons: [
{
text: 'Batal',
handler: (data: any) => {
[Link]('Canceled', data);
}
},
{
text: 'Yakin',
handler: (data: any) => {
//jika tekan yakin
[Link]();
[Link]('/', { replaceUrl: true });
}
}
]
}).then(res => {
[Link]();
});
}
}
11. Coding php api di direktori backend (atau bebas sesuai inisialisasi api_url di auth)
File [Link]
<?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 '[Link]';
$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);
?>