@nestlab/google-recaptcha
Advanced tools
Comparing version 1.0.14 to 1.1.0
@@ -1,6 +0,6 @@ | ||
import { ForbiddenException } from '@nestjs/common'; | ||
import { BadRequestException } from '@nestjs/common'; | ||
import { ErrorCode } from '../enums/error-code'; | ||
export declare class GoogleRecaptchaException extends ForbiddenException { | ||
export declare class GoogleRecaptchaException extends BadRequestException { | ||
readonly errorCodes: ErrorCode[]; | ||
constructor(errorCodes: ErrorCode[]); | ||
} |
@@ -5,5 +5,5 @@ "use strict"; | ||
const common_1 = require("@nestjs/common"); | ||
class GoogleRecaptchaException extends common_1.ForbiddenException { | ||
class GoogleRecaptchaException extends common_1.BadRequestException { | ||
constructor(errorCodes) { | ||
super(); | ||
super(`Google recaptcha errors: ${errorCodes.join(', ')}.`); | ||
this.errorCodes = errorCodes; | ||
@@ -10,0 +10,0 @@ } |
@@ -6,1 +6,2 @@ export { Recaptcha } from './decorators/recaptcha'; | ||
export { ErrorCode } from './enums/error-code'; | ||
export { GoogleRecaptchaException } from './exceptions/google-recaptcha.exception'; |
@@ -11,2 +11,4 @@ "use strict"; | ||
Object.defineProperty(exports, "ErrorCode", { enumerable: true, get: function () { return error_code_1.ErrorCode; } }); | ||
var google_recaptcha_exception_1 = require("./exceptions/google-recaptcha.exception"); | ||
Object.defineProperty(exports, "GoogleRecaptchaException", { enumerable: true, get: function () { return google_recaptcha_exception_1.GoogleRecaptchaException; } }); | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@nestlab/google-recaptcha", | ||
"version": "1.0.14", | ||
"version": "1.1.0", | ||
"description": "Google recaptcha module for NestJS.", | ||
@@ -5,0 +5,0 @@ "keywords": [ |
128
README.md
# Google recaptcha module | ||
The [NestJS](https://docs.nestjs.com/) module to protect your endpoints via [google recaptcha](https://www.google.com/recaptcha/about/). | ||
- [Installation](#Installation) | ||
- [Configuration](#Configuration) | ||
- [Usage](#Usage) | ||
- [Error handling](#ErrorHandling) | ||
Usage example [here](https://github.com/chvarkov/google-recaptcha-example) | ||
### Install | ||
### Installation <a name="Installation"></a> | ||
``` | ||
@@ -10,3 +19,3 @@ $ npm i @nestlab/google-recaptcha | ||
### Configuration | ||
### Configuration <a name="Configuration"></a> | ||
@@ -27,4 +36,6 @@ ```typescript | ||
### Usage | ||
### Usage <a name="Usage"></a> | ||
Use `@Recaptcha` decorator to protect your endpoints. | ||
```typescript | ||
@@ -37,3 +48,3 @@ | ||
async send(): Promise<any> { | ||
// TODO: Implement it. | ||
// TODO: Your implementation. | ||
} | ||
@@ -44,35 +55,100 @@ } | ||
### Error handling | ||
If you want use google recaptcha guard in combination with another guards then you can use `@UseGuards` decorator. | ||
Example error customization. You can return or throw HttpException or return string. | ||
```typescript | ||
If you will return string, then response will have status code 400 (Bad request). | ||
@Controller('feedback') | ||
export class FeedbackController { | ||
@UseGuards(Guard1, GoogleRecaptchaGuard, Guard2) | ||
@Post('send') | ||
async send(): Promise<any> { | ||
// TODO: Your implementation. | ||
} | ||
} | ||
``` | ||
### Error handling <a name="ErrorHandling"></a> | ||
Google recaptcha guard will throw GoogleRecaptchaException on error. | ||
`GoogleRecaptchaException` has data with google recaptcha error codes. | ||
`GoogleRecaptchaException` ← `BadRequestException` ← `HttpException` ← `Error`. | ||
You can handle it via [ExceptionFilter](https://docs.nestjs.com/exception-filters). | ||
Example exception filter implementation. | ||
```typescript | ||
GoogleRecaptchaModule.forRoot({ | ||
secretKey: process.env.GOOGLE_RECAPTCHA_SECRET_KEY, | ||
response: req => req.headers.recaptcha, | ||
skipIf: () => process.env.NODE_ENV !== 'production', | ||
onError: (errorCodes: ErrorCode[]) => { | ||
switch (errorCodes.shift()) { | ||
case ErrorCode.MissingInputSecret: | ||
return 'The secret parameter is missing.'; | ||
case ErrorCode.InvalidInputSecret: | ||
return 'The secret parameter is invalid or malformed.'; | ||
@Catch(GoogleRecaptchaException) | ||
export class GoogleRecaptchaFilter implements ExceptionFilter { | ||
catch(exception: GoogleRecaptchaException, host: ArgumentsHost): any { | ||
const res: Response = host.switchToHttp().getResponse(); | ||
const firstErrorCode = exception.errorCodes.shift(); | ||
const transformedError = this.transformError(firstErrorCode); | ||
res.status(transformedError.status).send({ | ||
type: 'GoogleRecaptchaError', | ||
message: transformedError.message, | ||
}); | ||
} | ||
transformError(errorCode: ErrorCode): {status: number, message: string} { | ||
switch (errorCode) { | ||
case ErrorCode.InvalidInputResponse: | ||
return { | ||
status: HttpStatus.BAD_REQUEST, | ||
message: 'The response parameter is invalid or malformed.', | ||
}; | ||
case ErrorCode.MissingInputResponse: | ||
return 'The response parameter is missing.'; | ||
case ErrorCode.InvalidInputResponse: | ||
return 'The response parameter is invalid or malformed.'; | ||
case ErrorCode.BadRequest: | ||
return 'The request is invalid or malformed.'; | ||
return { | ||
status: HttpStatus.BAD_REQUEST, | ||
message: 'The response parameter is missing.', | ||
}; | ||
case ErrorCode.TimeoutOrDuplicate: | ||
return 'The response is no longer valid: either is too old or has been used previously.'; | ||
return { | ||
status: HttpStatus.BAD_REQUEST, | ||
message: 'The response is no longer valid: either is too old or has been used previously.', | ||
}; | ||
case ErrorCode.InvalidInputSecret: | ||
case ErrorCode.MissingInputSecret: | ||
return { | ||
status: HttpStatus.INTERNAL_SERVER_ERROR, | ||
message: 'Invalid module configuration. Please check public-secret keys.', | ||
}; | ||
case ErrorCode.UnknownError: | ||
case ErrorCode.BadRequest: | ||
default: | ||
return new BadGatewayException('Unknown error when checking captcha.'); | ||
return { | ||
status: HttpStatus.INTERNAL_SERVER_ERROR, | ||
message: 'Unexpected error. Please submit issue to @nestlab/google-recaptcha.', | ||
}; | ||
} | ||
}, | ||
}) | ||
} | ||
} | ||
``` | ||
And add your filter to application | ||
```typescript | ||
async function bootstrap() { | ||
const app = await NestFactory.create(AppModule); | ||
app.useGlobalFilters(new ErrorFilter(), new GoogleRecaptchaFilter()); | ||
await app.listen(3000); | ||
} | ||
bootstrap(); | ||
``` | ||
Enjoy! |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
23716
250
151