System Information
- Strapi Version: 3.6.8
- Operating System: windows
- Database: mongodb
- Node Version: 18.1.0
- NPM Version: 8.8.0
- Yarn Version: nil
I need to login with phone number and password instead of email and password. Following is my code
‘use strict’;
/**
- api/password/controllers/password.js
*/
const { sanitizeEntity } = require(“strapi-utils”);
const formatError = (error) => [
{ messages: [{ id: error.id, message: error.message, field: error.field }] },
];
module.exports = {
index: async (ctx) => {
// const params = JSON.parse(ctx.request.body);
const params = ctx.request.body;
console.log("paarams is ",params)
// The identifier is required
if (!params.identifier) {
return ctx.badRequest(
null,
formatError({
id: "Auth.form.error.email.provide",
message: "Please provide your username or your Phone number.",
})
);
}
// Phone number verification
// if(params.phone==user.phoneNumber)
// {
// }
const phoneNumberRegExp = /^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$/;
const query = { provider };
// Check if the provided identifier is an email or not.
const isEmail = emailRegExp.test(params.identifier);
// Check if the provided identifier is a phone number or not.
const isPhoneNumber = phoneNumberRegExp.test(params.identifier);
// Set the identifier to the appropriate query field.
if (isEmail) {
query.email = params.identifier.toLowerCase();
} else if (isPhoneNumber) {
query.phoneNumber = params.identifier;
} else {
query.username = params.identifier;
}
/* left out for brevity */
// }
// The password is required
if (!params.password) {
return ctx.badRequest(
null,
formatError({
id: "Auth.form.error.password.provide",
message: "Please provide your password.",
})
);
}
if (!params.identifier && !params.password )
{
return ctx.badRequest(
null,
formatError({
id: "Auth.form.error.password.matching",
message: "New passwords do not match.",
})
);
} else if (
params.identifier &&
params.password
) {
// Get user based on identifier
const user = await strapi
.query("user", "users-permissions")
.findOne({ phone: params.phone });
// Validate given password against user query result password
const validPassword = await strapi.plugins["user","users-permissions"].services.user.validatePassword(params.password, user.password);
// const validPhone = await strapi.plugins["user","users-permissions"].services.user.validatePhone(params.phone, user.phoneNumber);
if (!validPassword) {
return ctx.badRequest(
null,
formatError({
id: "Auth.form.error.invalid",
message: "Identifier or password invalid.",
})
);
// } else if(!validPhone){
// return ctx.badRequest(
// null,
// formatError({
// id: "Auth.form.error.invalid",
// message: "Identifier or password invalid.",
// })
// );
}
// Return new jwt token
ctx.send({
jwt: strapi.plugins["user","users-permissions"].services.jwt.issue({
id: user.id,
}),
user: sanitizeEntity(user.toJSON ? user.toJSON() : user, {
model: strapi.query("user", "users-permissions").model,
}),
});
}
}
};