Code Monkey home page Code Monkey logo

ngx-turnstile's Introduction

Cloudflare Turnstile Component for Angular

ngx-turnstile

An easy to use component for implementing Cloudflare Turnstile in Angular.

Installation

Add this library to your Angular project using npm or yarn.

yarn add ngx-turnstile
npm install ngx-turnstile --save

Quickstart

To start, import the NgxTurnstileModule in your app module.

// app.module.ts
import { NgxTurnstileModule } from "ngx-turnstile";
import { BrowserModule } from "@angular/platform-browser";
import { MyApp } from "./app.component.ts";

@NgModule({
  bootstrap: [MyApp],
  declarations: [MyApp],
  imports: [BrowserModule, NgxTurnstileModule],
})
export class MyAppModule {}

After that, you are free to use the component anywhere:

// app.component.ts
import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  template: `<ngx-turnstile [siteKey]="siteKey" (resolved)="sendCaptchaResponse($event)" theme="auto" [tabIndex]="0"></ngx-turnstile>`,
})
export class MyApp {
  sendCaptchaResponse(captchaResponse: string) {
    console.log(`Resolved captcha with response: ${captchaResponse}`);
  }
}

Usage with @angular/forms

Import both NgxTurnstileModule and NgxTurnstileFormsModule modules in your app module.

import { NgxTurnstileModule, NgxTurnstileFormsModule } from "ngx-turnstile";

Then import either FormsModule or ReactiveFormsModule from @angular/forms depending on the type of form you want to use.

You can then use the ngModel, formControl or formControlName directives on the component depending on which module you imported from @angular/forms.

Reactive Form Example

<ngx-turnstile [siteKey]="siteKey" theme="auto" [formControl]="tokenControl"></ngx-turnstile>

Template Driven Form Example

<ngx-turnstile [siteKey]="siteKey" theme="light" [(ngModel)]="token"></ngx-turnstile>

The component is read-only, meaning that you should not update the control with a custom value. Updating the control value will reset the component

API

The component supports these options as input:

  • siteKey
  • action
  • cData
  • theme
  • tabIndex

These options are well documented in the Cloudflare Docs. The letter cases are adapted to camelCase to facilitate easy migration from ng-recaptcha.

Events

  • resolved(response: string). Occurs when the CAPTCHA resolution value changed.
  • errored(errorCode: string). Occurs when the CAPTCHA widget returned an error code.

Example

For those who prefer examples over documentation, simply clone the repository and run

$ yarn install
$ ng build ngx-turnstile
$ ng serve ngx-turnstile-demo

ngx-turnstile's People

Contributors

aleksanderbodurri avatar cherylchen2 avatar choyiny avatar emilychangg avatar guillaume-ro-fr avatar natereprogle avatar piprees avatar rbalet avatar shameerrehman avatar wilson-ascenda avatar yuskhan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

ngx-turnstile's Issues

Reset in Component

Is there any way to use a reset method within a component?
At the moment I'm using it in an insecure way: eval("turnstile.reset()");

Could not resolve dependency

Hi, having problem with dependency:

@angular/common@"~16.2.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/common@"^14.2.0" from [email protected]
npm ERR! node_modules/ngx-turnstile
npm ERR! ngx-turnstile@"^0.0.7" from the root project

Angular v16 NX v17

can't use command with --force or --legacy-peer-deps because of deploy on Cloudflare.

Thanks

Getting the following error after installing ngx-trunstile, could you help us on this issue.

Error: node_modules/ngx-turnstile/lib/ngx-turnstile.component.d.ts:34:103 - error TS2344: Type '{ siteKey: { alias: "siteKey"; required: false; }; action: { alias: "action"; required: false; }; cData: { alias: "cData"; 
required: false; }; theme: { alias: "theme"; required: false; }; version: { alias: "version"; required: false; }; tabIndex: { ...; }; appearance: { ...; }; }' does not satisfy the constraint '{ [key: string]: string; }'.
  Property '"siteKey"' is incompatible with index signature.
    Type '{ alias: "siteKey"; required: false; }' is not assignable to type 'string'.

34     static ɵcmp: i0.ɵɵComponentDeclaration<NgxTurnstileComponent, "ngx-turnstile", ["ngx-turnstile"], { "siteKey": { "alias": "siteKey"; "required": false; }; "action": { "alias": "action"; "required": false; }; "cData": { "alias": "cData"; "required": false; }; "theme": { "alias": "theme"; "required": false; }; "version": { "alias": "version"; "required": false; }; "tabIndex": { "alias": "tabIndex"; "required": false; }; "appearance": { "alias": "appearance"; "required": false; }; }, { "resolved": "resolved"; }, never, never, false, never>;
                                                                                                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Error: src/app/app.component.ts:5:29 - error NG8002: Can't bind to 'siteKey' since it isn't a known property of 'ngx-turnstile'.
1. If 'ngx-turnstile' is an Angular component and it has 'siteKey' input, then verify that it is part of this module.
2. If 'ngx-turnstile' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.

5   template: `<ngx-turnstile [siteKey]="siteKey" theme="auto" [tabIndex]="0"></ngx-turnstile>`,
                              ~~~~~~~~~~~~~~~~~~~


Error: Can't resolve 'https://challenges.cloudflare.com/turnstile/v0/api.js' in 'C:\Babu_HP_Laptop\POC\cloudflare\cloudflare'

Type Error: Cannot read properties of null (reading 'writeValue')

Hello,
First, thanks for this nice contribution !

Second, I am trying to use the component in version 0.2.1 with Angular 17.2.0 and Angular Material 17.2.1, I get an error on page rendering.

At network level, I see that call to Cloudflare's Turnstile succeeded and the input created by component and named "cf-turnstile-response" is correctly filled with a value, but when I access tokenControl value it is null.
I think issue happens when callback tries to fill the formControl.

Here is the code:

<div class="login-page">
	<section class="mat-typography">
  		<h1 class="title"> {{ 'login.title' | translate }} </h1>
	</section>
	
    <div class="form">
        <form [formGroup]="form" class="login-form">
            <mat-form-field class="field">
                <label for="username">{{ 'login.username' | translate }}</label>
                <input matInput type="text" formControlName="username" id="username">
                @if (form.controls["username"].errors) {
                    <mat-error [innerHTML]="'login.username-required' | translate">
                    </mat-error>
                }
            </mat-form-field>
            <mat-form-field class="field">
                <label for="password">{{ 'login.password' | translate }}</label>
                <input matInput type="password" formControlName="password" id="password">
                @if (form.controls["password"].errors) {
                    <mat-error [innerHTML]="'login.password-required' | translate">
                    </mat-error>
                }
            </mat-form-field>
            <ngx-turnstile [siteKey]="siteKey" theme="auto" [formControl]="tokenControl"></ngx-turnstile>
    
            <div  class="col btn-login">
                <button [disabled]="isLoading | async" mat-raised-button color="primary" (click)="onLogin()">
                    {{ 'login.login' | translate }}
                </button>
            </div>
        </form>
    </div>
</div>

HTML component is:


import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { Subject, take } from 'rxjs';
import { User } from '../../api/common/models';
import { SecurityService } from '../../api/common/services';
import { LoaderService } from '../../services/loader/loader.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  form: FormGroup = this.formBuilder.group({
    username: ['', Validators.required],
    password: ['', Validators.required]
  });

  isLoading: Subject<boolean> = this.loaderService.isLoading; 
  tokenControl: FormControl = new FormControl('');
   // CHanged value here
  siteKey : string = "XXXX";

  constructor(
      private formBuilder: FormBuilder,
      private router: Router,
      private securityService: SecurityService,
      private errorService: ErrorService,
      private loaderService:  LoaderService
  ) { 
  }

  ngOnInit(): void {
    this.tokenControl = new FormControl();
  }

  onLogin() {
    if (this.form.invalid) {
      return;
    }
    const tokenValue = this.tokenControl.value;
    this.securityService.login({body : {
      username: this.form.controls["username"].value,
      password: this.form.controls["password"].value,
      captchaResponse: tokenValue
    }}).pipe(take(1)).subscribe({
      complete: () => {
        ...
      },  
      error: (error: any) => {
       console.log(error)
      }
    });
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.