I would like a way for users to login to Strapi by entering a phone number, receiving a text verification code and entering the code to my app. There is an old thread that talked about this Phone Number authentication in Strapi, but the information there seems to be in Strapi v3. Is this still possible in Strapi v4?
1 Answer
I've successfully made it work, although my version only allow user to login with their registered phone number, no OPT yet. But you'll get the idea:
- Create a content type, let's call it "homepage".
- Open
node_modules\@strapi\plugin-users-permissions\server\controllers\auth.jsand copy "callback()" function, paste it in homepage's controller atsrc\api\homepage\controllers\homepage.ts(Make sure to convert it to typescript if you're using it). Change the function name tologin() - Import the missing functions:
import { getService } from "@strapi/plugin-users-permissions/server/utils";
import { validateCallbackBody } from "@strapi/plugin-users-permissions/server/controllers/validation/auth";
- Find & modify the query in the
login()function to look for phone number as well:
// Check if the user exists.
const user = await strapi.query('plugin::users-permissions.user').findOne({
where: {
provider,
$or: [
{ email: identifier.toLowerCase() },
{ username: identifier },
{ phone_number: identifier }, // << Change to your field name!
],
},
});
- Add a custom route for login API by create a file at
src\api\homepage\routes\custom-routes.tswith following content:
export default {
routes: [
{
method: 'POST',
path: '/login',
handler: 'homepage.login',
config: {
middlewares: ['plugin::users-permissions.rateLimit'],
prefix: '',
},
},
]
}
- Important Rebuild your Strapi using
strapi buildthen start it, go to:
Strapi Admin > User & Permission > Roles > Public > Homepage > login < Enable it
2 Comments
Farhan Farooq
how did you manage to make it work when you used import and not require statement, also export default and not module.exports? Also getService import throws "Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './server/utils' is not defined by "exports" in \node_modules\@strapi\plugin-users-permissions\package.json". Do you have any idea how to fix it?
VitSoonYoung
@FarhanFarooq I'm using Strapi typescript, also you can find the original login function in node_modules to replicate it in your own API