Last active
May 4, 2025 20:56
-
-
Save workatease/8c2f33f5f6df6de92264eb865c73b1f5 to your computer and use it in GitHub Desktop.
directus - Google reCaptcha v2 using auth.login.before api hook for validation for custom login
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // extensions/hooks/google-recaptcha-v2/index.js | |
| module.exports = function registerHook({ env, exceptions }) { | |
| const querystring = require("querystring"); | |
| const axios = require("axios"); | |
| const { BaseException } = exceptions; | |
| const VERIFY_ENDPOINT = "https://www.google.com/recaptcha/api/siteverify"; | |
| return { | |
| "auth.login.before": async function (input) { | |
| const captcha = input["g-recaptcha-response"]; | |
| if (captcha) { | |
| const postBody = querystring.stringify({ | |
| secret: env.RECAPTCHA_SECRET_KEY, | |
| response: captcha, | |
| remoteip: input?.ip || undefined, | |
| }); | |
| const response = await axios.post(VERIFY_ENDPOINT, postBody); | |
| const { data } = response; | |
| if (data.success === false) { | |
| throw new BaseException(data["error-codes"], 400, "failure"); | |
| } | |
| } | |
| }, | |
| }; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment