This is a recaptcha protected POST that I made.
It is generic, the security (so user can’t create any model) is a hard coded array of allowed models
'use strict';
const recaptcha = require('recaptcha-validator');
const allowedPosts = ['exemption_request']
module.exports = {
index: async (ctx, next) => {
ctx.response.status = 400;
const body = ctx.request.body;
let code;
let modelName;
let modelData;
if (body) {
code = body.code;
modelName = body.model;
modelData = body.data;
}
if (!code) {
ctx.send({error: 'No code'});
return;
}
if (!modelName) {
ctx.send({error: 'No model name'});
return;
}
if (!modelData) {
ctx.send({error: 'No data'});
return;
}
if (!allowedPosts.includes(modelName)) {
ctx.send({error: 'Forbidden'});
}
try {
await recaptcha(process.env.RECAPTCHA_SECERET, code);
} catch {
ctx.send({error: 'Failed recaptcha'});
return;
}
try {
const newModel = await strapi.query(modelName).create(modelData);
if (!newModel) {
ctx.send({error: 'Model creation failed'})
} else {
ctx.response.status = 201;
ctx.send(newModel);
}
} catch(err) {
ctx.send({error: 'Model creation failed'})
}
}
};