Menambahkan Recaptcha di aplikasi Ionic 4 - Mari Belajar Coding

16 Februari 2020

Menambahkan Recaptcha di aplikasi Ionic 4

Menambahkan Recaptcha di aplikasi Ionic 4

Captcha merupakan sebuah tes turing untuk membedakan manusia dengan komputer. Hal ini bertujuan untuk melindungi situs atau aplikasi dari spamming dan penyalahgunaan. Mudah bagi manusia untuk menyelesaikannya tetapi sulit bagi bot atau software. reCAPTCHA sendiri merupakan sebuah layanan captcha gratis yang disediakan oleh google. 

Tutorial kali ini kita akan belajar menambahkan recaptcha dalam aplikasi yang di bangun menggunakan framework Ionic 4. Pertama-tama kita daftar recaptcha untuk mendapatkan api key nya. www.google.com/recaptcha.  

Pilih tambah plus di samping kanan atas untuk create situs baru.
kemudian isi seperti dibawah ini. Isikan label dan pilih recaptcha v2. isikan domain dengan localhost dan 127.0.0.1.

Menambahkan Recaptcha di aplikasi Ionic 4

Tekan submit untuk menyelesaikannya. Teman-teman akan mendapatkan site key dan secret key. site key ini yang akan kita gunakan dalam aplikasi.

Menambahkan Recaptcha di aplikasi Ionic 4

Buat aplikasi Ionic baru memalui terminal. Ketikkan perintah berikut ini.

ionic start MyAppIonic4 blank --type=angular

Setelah aplikasi ionic selesai di install, buka directory MyAppIonic4. Kemudian Install plugin recaptcha ionic melalui terminal. Pastikan install dalam directory MyAppIonic4.

npm install ngx-captcha

Kita akan menggunakan halaman home yang sudah ada. Buka file home.module.ts, tambahkan import module reactive form dan ngx captcha seperti dibawah ini.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';

import { HomePage } from './home.page';

import { ReactiveFormsModule } from '@angular/forms';
import { NgxCaptchaModule } from 'ngx-captcha';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    ReactiveFormsModule,
    NgxCaptchaModule,
    RouterModule.forChild([
      {
        path: '',
        component: HomePage
      }
    ])
  ],
  declarations: [HomePage]
})
export class HomePageModule {}

Buka file home.page.html untuk membuat tampilan form dan tempat recaptcha.

<ion-header translucent>
  <ion-toolbar color="primary">
    <ion-title>
      reCAPTCHA
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <form [formGroup]="FormSubmit"> 
    
    <!--Tempat menampilkan recaptcha-->
    <ngx-recaptcha2 #captchaElem
      [siteKey]="siteKey"
      (reset)="handleReset()"
      (expire)="handleExpire()"
      (load)="handleLoad()"
      (success)="handleSuccess($event)"
      [useGlobalDomain]="false"
      [size]="size"
      [hl]="lang"
      [theme]="theme"
      [type]="type"
      formControlName="recaptcha">
    </ngx-recaptcha2>

    <br>
      <ion-button expand="full" color="primary" (click)="Submit()"  [disabled]="!FormSubmit.valid">Submit</ion-button>
  </form>
</ion-content>

Terakhir kita akan setting beberapa pengaturan recaptcaha seperti menangani proses reset, expire, succcess, dan sebagainya di home.page.ts

import { 
  Component,
  AfterViewInit,
  ElementRef, OnInit,
  ViewChild,
  ChangeDetectorRef,
  ChangeDetectionStrategy
 } from '@angular/core';

import { FormControl, 
  FormGroupDirective, 
  FormBuilder, 
  FormGroup, 
  NgForm, 
  Validators, 
  AbstractControl } from '@angular/forms';
import { ReCaptcha2Component } from 'ngx-captcha';

declare var hljs: any;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage  {

  @ViewChild('captchaElem', { static: false }) captchaElem: ReCaptcha2Component;
  @ViewChild('langInput', { static: false }) langInput: ElementRef;

  //site key yang harus di ganti
  public readonly siteKey = '6LfpNdkUAAAAAc6';

  public captchaIsLoaded = false;
  public captchaSuccess = false;
  public captchaIsExpired = false;
  public captchaResponse?: string;
  public theme: 'light' | 'dark' = 'light';
  public size: 'compact' | 'normal' = 'normal';
  public lang = 'en';
  public type: 'image' | 'audio';
  public useGlobalDomain: boolean = false;

  FormSubmit: FormGroup;

  constructor(
    private FormGroup: FormBuilder,
    private cdr: ChangeDetectorRef
  ) {
    this.FormSubmit = this.FormGroup.group({
      recaptcha: ['', Validators.required]
    });
  }

  ngAfterViewInit(): void {
    this.highlight();
  }

  handleReset(): void {
    this.captchaSuccess = false;
    this.captchaResponse = undefined;
    this.captchaIsExpired = false;
    this.cdr.detectChanges();
  }

  handleSuccess(captchaResponse: string): void {
    this.captchaSuccess = true;
    this.captchaResponse = captchaResponse;
    this.captchaIsExpired = false;
    this.cdr.detectChanges();
  }

  handleLoad(): void {
    this.captchaIsLoaded = true;
    this.captchaIsExpired = false;
    this.cdr.detectChanges();
  }

  handleExpire(): void {
    this.captchaSuccess = false;
    this.captchaIsExpired = true;
    this.cdr.detectChanges();
  }

  changeTheme(theme: 'light' | 'dark'): void {
    this.theme = theme;
  }

  changeSize(size: 'compact' | 'normal'): void {
    this.size = size;
  }

  changeType(type: 'image' | 'audio'): void {
    this.type = type;
  }
  
  setLanguage(): void {
    this.lang = this.langInput.nativeElement.value;
  }

  setUseGlobalDomain(use: boolean): void {
    this.useGlobalDomain = use;
  }

  getCurrentResponse(): void {
    const currentResponse = this.captchaElem.getCurrentResponse();
    // if (!currentResponse) {
    //   alert('There is no current response - have you submitted captcha?');
    // } else {
    //   alert(currentResponse);
    // }
  }

  getResponse(): void {
    const response = this.captchaElem.getResponse();
    // if (!response) {
    //   alert('There is no response - have you submitted captcha?');
    // } else {
    //   alert(response);
    // }
  }

  reload(): void {
    this.captchaElem.reloadCaptcha();
  }

  getCaptchaId(): void {
   // alert(this.captchaElem.getCaptchaId());
  }

  reset(): void {
    this.captchaElem.resetCaptcha();
  }

  private highlight(): void {
    const highlightBlocks = document.getElementsByTagName('code');
    for (let i = 0; i < highlightBlocks.length; i++) {
      const block = highlightBlocks[i];
      hljs.highlightBlock(block);
    }
  }

}

Tampilan Aplikasi.
Menambahkan Recaptcha di aplikasi Ionic 4

Related Posts

Load comments