Modul IONIC Framework Auth Guard
Modul IONIC Framework Auth Guard
Auth Guards
@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
}
4. Coding di bagian auth.guard.ts
@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
@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
@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
@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>
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');
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']));
echo json_encode($pesan);
echo mysqli_error($con);
?>