diff --git a/src/functions-templates/js/create-user/.netlify-function-template.js b/src/functions-templates/js/create-user/.netlify-function-template.js new file mode 100644 index 0000000..030d6a2 --- /dev/null +++ b/src/functions-templates/js/create-user/.netlify-function-template.js @@ -0,0 +1,11 @@ +module.exports = { + name: "create-user", + description: + "Programmatically create a Netlify Identity user by invoking a function", + onComplete() { + console.log(`create-user function created from template!`); + console.log( + "REMINDER: Make sure to call this function with a Netlify Identity JWT. See https://netlify-gotrue-in-react.netlify.com/ for demo" + ); + } +}; diff --git a/src/functions-templates/js/create-user/create-user.js b/src/functions-templates/js/create-user/create-user.js new file mode 100644 index 0000000..91b46f1 --- /dev/null +++ b/src/functions-templates/js/create-user/create-user.js @@ -0,0 +1,35 @@ +const fetch = require("node-fetch"); + +exports.handler = async (event, context) => { + if (event.httpMethod !== "POST") + return { statusCode: 400, body: "Must POST to this function" }; + + // send account information along with the POST + const { email, password, full_name } = JSON.parse(event.body); + if (!email) return { statusCode: 400, body: "email missing" }; + if (!password) return { statusCode: 400, body: "password missing" }; + if (!full_name) return { statusCode: 400, body: "full_name missing" }; + + // identity.token is a short lived admin token which + // is provided to all Netlify Functions to interact + // with the Identity API + const { identity } = context.clientContext; + + await fetch(`${identity.url}/admin/users`, { + method: "POST", + headers: { Authorization: `Bearer ${identity.token}` }, + body: JSON.stringify({ + email, + password, + confirm: true, + user_metadata: { + full_name + } + }) + }); + + return { + statusCode: 200, + body: "success!" + }; +}; diff --git a/src/functions-templates/js/create-user/package.json b/src/functions-templates/js/create-user/package.json new file mode 100644 index 0000000..b36a1a7 --- /dev/null +++ b/src/functions-templates/js/create-user/package.json @@ -0,0 +1,21 @@ +{ + "name": "create-user", + "version": "1.0.0", + "description": "netlify functions:create - Programmatically create a Netlify Identity user by invoking a function", + "main": "create-user.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [ + "netlify", + "serverless", + "js", + "identity", + "authentication" + ], + "author": "Netlify", + "license": "MIT", + "dependencies": { + "node-fetch": "^2.3.0" + } +}