2

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?

varimax
  • 111
  • 1
  • 13

1 Answers1

1

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:

  1. Create a content type, let's call it "homepage".
  2. Open node_modules\@strapi\plugin-users-permissions\server\controllers\auth.js and copy "callback()" function, paste it in homepage's controller at src\api\homepage\controllers\homepage.ts (Make sure to convert it to typescript if you're using it). Change the function name to login()
  3. Import the missing functions:
import { getService } from "@strapi/plugin-users-permissions/server/utils";
import { validateCallbackBody } from "@strapi/plugin-users-permissions/server/controllers/validation/auth";
  1. 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!
                    ],
                },
            });
  1. Add a custom route for login API by create a file at src\api\homepage\routes\custom-routes.ts with following content:
export default {
    routes: [
        {
            method: 'POST',
            path: '/login',
            handler: 'homepage.login',
            config: {
                middlewares: ['plugin::users-permissions.rateLimit'],
                prefix: '',
            },
        },
    ]
}
  1. Important Rebuild your Strapi using strapi build then start it, go to:

Strapi Admin > User & Permission > Roles > Public > Homepage > login < Enable it

DucViet321
  • 26
  • 4