Phone Number authentication in Strapi - authentication

I am using Strapi for my android app and I need to login user by their phone number. There are many auth providers like email and password, google, facebook etc. But I can not find any documentation about adding phone number authentication. Please help.

This is possible to do that.
You will have to use the customization concept to customize the callback function of the users-permissions plugin.
Customization concept - https://strapi.io/documentation/v3.x/concepts/customization.html#plugin-extensions
Function to update - https://github.com/strapi/strapi/blob/master/packages/strapi-plugin-users-permissions/controllers/Auth.js#L21
For example:
First, you should define phone_number field inside the User model.
Then, you should overwrite extensions/users-permissions/controllers/Auth.js by add query.phone_number = params.identifier; under const query = { provider };
const query = { provider };
// Check if the provided identifier is an email or not.
const isEmail = emailRegExp.test(params.identifier);
// Set the identifier to the appropriate query field.
if (isEmail) {
query.email = params.identifier.toLowerCase();
} else {
query.phone_number = params.identifier;
}
In this example, we tell Strapi that we can login by entering an email or phone number both are accepted.
And you can remove the if-condition and just write query.phone_number = params.identifier; if you want to login with a phone number only.

I think you can add some change to auth.js
that file is on this address
you can see login for instance.

#Ghadban125's answer is correct, though I'd like to add some more details.
Not only do you need to overwrite the callback function in ./node_modules/#strapi/plugin-users-permissions/server/controllers/auth.js. You'd also need to register your new function in your strapi-server.js (the one that you create under the src directory, not the one under node_modules, similar to how you overwrite the callback function) which looks like this:
const { callback } = require("./controllers/Auth.js");
const utils = require("#strapi/utils");
const { ApplicationError } = utils.errors;
module.exports = (plugin) => {
plugin.controllers.auth.callback = async (ctx) => {
try {
await callback(ctx);
// ctx.send(result);
} catch (error) {
throw new ApplicationError(error.message);
}
};
}
You'll also need to differentiate the request's identifier between an email, username, or phone number. To do this, you'll need to edit your ./src/extensions/users-permissions/controllers/auth.js file:
/* left out for brevity */
const phoneNumberRegExp = /^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$/;
/* left out for brevity */
module.exports = {
async callback(ctx) {
/* left out for brevity */
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 */
},
};

I have implemented the same on this github repo - https://github.com/mayank-budhiraja/strapi-with-otp-integration
A user is authenticated only through the OTP verification and all auth requests are made using the JWT token.

Related

Vue + MSAL2.x + Azure B2C Profile Editing

First, I am not finding Vue specific examples using MSAL 2.x and we'd like to use the PKCE flow. I am having issues with the way the router guards are run before the AuthService handleResponse so I must be doing something wrong.
In my main.js I am doing this...
// Use the Auth services to secure the site
import AuthService from '#/services/AuthServices';
Vue.prototype.$auth = new AuthService()
And then in my AuthConfig.js I use this request to login:
loginRequest : {
scopes: [
"openid",
"profile",
process.env.VUE_APP_B2C_APISCOPE_READ,
process.env.VUE_APP_B2C_APISCOPE_WRITE
]
},
The docs say it should redirect to the requesting page but that is not happening. If user goes to the protected home page they are redirected to login. They login, everything is stored properly so they are actually logged in, but then they are sent back to the root redirect URL for the site, not the Home page.
When a user wants to login we just send them to the protected home page and there is a login method called in the router guard which looks like this:
router.beforeEach(async (to, from, next) => {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
const IsAuthenticated = await Vue.prototype.$auth.isAuthenticated()
console.log(`Page changing from ${from.name} to ${to.name}, requiresAuth = ${requiresAuth}, IsAuthenticated = ${IsAuthenticated}`)
if (requiresAuth && !IsAuthenticated)
{
next(false)
console.log('STARTING LOGIN')
Vue.prototype.$auth.login()
// Tried this
// Vue.prototype.$auth.login(to.path)
} else {
next()
}
})
In AuthServices.js I have this...
// The user wants to log in
async login(nextPg) {
// Tell B2C what app they want access to and their invitation ID if they are new
if (store.getters.userEmail != null) {
aCfg.loginRequest.loginHint = store.getters.userEmail
}
aCfg.loginRequest.state = "APP=" + store.getters.appCode
if (store.getters.appointmentLink != null && store.getters.appointmentLink != '') {
aCfg.loginRequest.state += ",ID=" + store.getters.appointmentLink
}
// Tried this
// if (nextPg && nextPg != '') {
// aCfg.loginRequest.redirectUrl = process.env.VUE_APP_B2C_REDIRECT_URL + nextPg
// }
return await this.msalInst.loginRedirect(aCfg.loginRequest)
}
I tried puting a nextPg parameter in the login method and adding a redirectUrl property to the login request but that gives me an error saying it is not one of the configured redirect URLs.
Also, I'm trying to make the user experience better when using the above technologies. When you look at the MSAL2.x SPA samples I see that when returning from a Profile Edit, a user is logged out and they are required to log in again. That sounds like a poor user experience to me. Sample here: https://github.com/Azure-Samples/ms-identity-b2c-javascript-spa/blob/main/App/authRedirect.js
Do I need to just create my own profile editing page and save data using MSGraph to prevent that? Sorry for the noob questions. Ideas?
Update - My workaround which seems cheesy is to add these two methods to my AuthService.js:
storeCurrentRoute(nextPath) {
if (!nextPath) {
localStorage[STOR_NEXT_PAGE] = router.history.current.path
} else {
localStorage[STOR_NEXT_PAGE] = nextPath
}
console.log('Storing Route:', localStorage[STOR_NEXT_PAGE])
}
reEstablishRoute() {
let pth = localStorage[STOR_NEXT_PAGE]
if (!!pth && router.history.current.path != pth) {
localStorage[STOR_NEXT_PAGE] = ''
console.log(`Current path is ${router.history.current.path} and reEstablishing route to ${pth}`)
router.push({ path: pth })
}
}
I call storeCurrentRoute() first thing in the login method and then in the handleResponse() I call reEstablishRoute() when its not returning from a profileEdit or password change. Seems like I should be able to make things work without this.
Update Number Two - When returning from B2C's ProfileEdit User Flow the MSAL component is not logging me out properly. Here is my code from my handlePolicyChange() method in my AuthService:
} else if (response.idTokenClaims[clmPolicy] === aCfg.b2cPolicies.names.editProfile) {
Vue.nextTick(() => {
console.log('BACK FROM Profile Change')
Vue.prototype.$swal(
"Success!",
"Your profile has been updated.<br />Please log in again.",
"success"
).then(async () => {
this.logout()
})
})
}
:
// The user wants to log out (all accounts)
async logout() {
// Removes all sessions, need to call AAD endpoint to do full logout
store.commit('updateUserClaims', null)
store.commit('updateUserEmail', null)
let accts = await this.msalInst.getAllAccounts()
for(let i=0; i<accts.length; i++) {
const logoutRequest = {
account: accts[i],
postLogoutRedirectUri: process.env.VUE_APP_B2C_REDIRECT_URL
};
await this.msalInst.logout(logoutRequest);
}
return
}
It is working fine until the call to logout() which runs without errors but I looked in my site storage (in Chrome's debug window > Application) and it looks like MSAL did not clear out its entries like it does on my normal logouts (which always succeed). Ideas?
As part of the MSAL auth request, send a state Parameter. Base64 encode where the user left off inside this parameter. MSAL exposes extraQueryParameters which you can put a dictionary object inside and send in the auth request, put your state Key value pair into extraQueryParameters.
The state param will be returned in the callback response, use it to send the user where you need to.

React native firebase - facebook sign-in not triggering onAuthStateChanged listener

this is the second problem Im having with RNFB facebook login.
Im following the official code sample provided by RNFB....code below
Problem is with the line firebase().signInWithCredential(facebookCredential);....its not triggering the firebase listener auth().onAuthStateChanged
All other code is running as it should and facebookCredential variable is populated correctly
import { firebase } from '#react-native-firebase/auth';
onFacebookButtonPress = async () => {
// Attempt login with permissions
const result = await LoginManager.logInWithPermissions([
'public_profile',
'email',
]);
if (result.isCancelled) {
throw 'User cancelled the login process';
}
// Once signed in, get the users AccesToken
const data = await AccessToken.getCurrentAccessToken();
if (!data) {
throw 'Something went wrong obtaining access token';
}
// Create a Firebase credential with the AccessToken
//const facebookCredential = firebase.FacebookAuthProvider.credential(data.accessToken);
const facebookCredential = firebase.auth.FacebookAuthProvider.credential(
data.accessToken,
);
// Sign-in the user with the credential
firebase().signInWithCredential(facebookCredential);
};
I figured it out by putting a try/catch around the problematic line. Turned out was because I had already once signed in using Google.
An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address
You shouldn't wait till something goes wrong before you add try/ catch's. signInWithCredential returns many different types of errors, which you handle. From the docs:
firebase.auth().signInWithCredential(credential).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
if (errorCode === 'auth/account-exists-with-different-credential') {
alert('Email already associated with another account.');
// Handle account linking here, if using.
} else {
console.error(error);
}
});
Please handle the other error cases too 🙂:
auth/account-exists-with-different-credential
auth/invalid-credential
auth/operation-not-allowed
auth/user-disabled
and more.

FeatherJS - Get user information with hook?

So im trying out FeatherJS and i was able to register a new user, request a token and also request protected data (using Authorization in the header).
Very important: I am using HTTP Rest API only. The docs seem to point often times to the client feathers module, which i don't use.
So currently i have a super simple setup, i have a message service with a text. One before hook to process the message. Here i want to get back the user information:
module.exports = function (options = {}) {
return async context => {
const text = context.data.text
const user = context.params.user;
context.data = {
text,
userId: user._id
}
return context;
};
};
this doesn't work. In my mdb i only get back:
{
"_id": "5c35ce18523501803f6a8d8d",
"text": "123",
"createdAt": "2019-01-09T10:34:00.774Z",
"updatedAt": "2019-01-09T10:34:00.774Z",
"__v": 0
}
i've tried to add the token, that i always submit when i post a message via Authorization, like so:
module.exports = function (options = {}) {
return async context => {
const text = context.data.text
const user = context.params.user;
const token = context.params.accessToken
context.data = {
text,
userId: user._id,
tokId: token
}
return context;
};
};
but it seems like i always just get the same result back like shown above.
Any ideas how i can get the user information back of the current user by using the accessToken?
Never used FeathersJS before, so just trying to understand the ecosystem and how to approach this in FeathersJS.
Any advice is appreciated! Thanks in advance everyone!
Not quite sure what exactly went wrong, but i got it now working by just creating a new project.
Now i did recreate this project actually before and got the issue as above , but this time it somehow worked.
For anyone who wants to know the steps i did to 'fix' it:
1.Create a new folder
2. feathers generate app
3. feathers generate authentication
4. feathers generate service (name for the service: messages)
5. feathers generate hook (name: process-msg, before hook, model: messages)
6. Add this to the hook process-msg:
module.exports = function (options = {}) {
return async context => {
const user = context.params.user;
const text = context.data.text;
context.data = {
userId: user.email,
text,
dateTime: new Date().getTime()
}
return context;
};
};
Use postman, register a new account then authenticate to get the token. Save token and add it as Authoriztation Header inside Postman. You should then get also back the user email from the user that is registered, simply because of the token that was added to the Authorization Header.
Greetings!
go to authentication.js and find app.service definition. Right in there, create an after hook and add the details you want the client to receive
app.service('authentication').hooks({
before: {
...//as you currently have it
},
after: {
create: {
hook => {
// hook.result.accessToken is already provided
delete hook.params.user.password
hook.result.user = hook.params.user;
hook.result.token_type = 'Bearer';
hook.result.exp = 3600;
}
}
}
})
I hope this helps
So, if I understand it correctly, you want to get the user object from the hook?
You can just use const user = context.user;to accomplish this.

Authenticate with Moodle from a mobile app

My mobile app needs to log in to Moodle to get Json data from a webservice and display it using Angular.
In order to do that, I need to pass in a username and password and get a Moodle webservice token back, so my app doesn't need to log in again (at least until the token expires).
(this is one of those "ask and answer your own question" things, so my solution is below, but comments & suggestions welcome.)
With thanks to all the other StackOverflow pages I have used to create this solution!
See also - how to get data from your Moodle webservice with Angular.
Step 1. Check if a token already exists
jQuery(document).ready(function () {
/* when the user clicks log-out button, destroy the session */
$('#btn_logout').on('click', function () {
$('.pane').hide(); /* hide all screens */
$('#menu').toggleClass('ui-panel-open ui-panel-closed');
$.jStorage.deleteKey('session');
makeUserLogin();
});
var session = $.jStorage.get('session', ''); // syntax: $.jStorage.get(keyname, "default value")
if (session) { // if there is already a session, redirect to landing pane
showApp();
} else { // if there is no session *then* redirect to the login pane
makeUserLogin();
}
});
Step 2. create functions to show app & redirect to login page
function showApp() {
$('#home-pane').show(); /* show home screen */
$('#system-message').hide();
$('#login-pane').hide(); /* hide login screen*/
$('#menu_btn').removeClass('hidden'); /* show menu button so user can see rest of app */
}
function makeUserLogin() {
$('#btn_login').click(function () {
console.log('click event for login_button');
var username = $('#username').val();
var password = $('#password').val();
postCredentials(username, password, createSession);
});
$('#menu_btn').addClass('hidden'); /* hide menu button so user cannot see rest of app */
$('#home-pane').hide(); /* hide home screen */
$('#login-pane').show(); /* show login screen */
}
function postCredentials(username, password, callback) {
if ((username.length && password.length) && (username !== '' && password !='')) {
var url = 'https://moodle.yourcompany.com/local/login/token.php';
$.post(url, {
username: username,
password: password,
service: 'webservice_ws' // your webservice name
}).done(function (data) {
token = data.token;
dataString = JSON.stringify(data);
if (dataString.indexOf('error') > 0) {
showErrorDialog('<p class="error">Invalid user credentials, please try again</p>');
}
else {
createSession(token);
}
}).fail(function () {
showErrorDialog('<p class="error">Login failed</p>');
});
} else {
showErrorDialog('<p class="error">Please enter a username and password</p>');
}
}
function createSession(token) {
// syntax: $.jStorage.set('keyname', 'keyvalue', {TTL: milliseconds}); // {TTL... is optional time, in milliseconds, until key/value pair expires}
$.jStorage.set('session', token, { TTL: 28800000 });
// redirect to whatever page you need after a successful login
showApp();
}
function showErrorDialog(errorMsg) {
$('#system-message').html(errorMsg);
$('#system-message').fadeIn();
}

How to test a meteor method that relies on Meteor.user()

I am trying to determine the best way to test my code and am running into complications from every direction I've tried.
The basic code is this (though far more complex due to several layers of "triggers" that actually implement this):
Client populates an object
Client calls a meteor method and passes the object
Meteor method uses Meteor.user() to get the current user, adds a "createdby" attribute to the object, inserts the object and then creates another object (of a different type) with various attributes that depend on the first object, as well as a bunch of other things already in the database
I'm trying to use Velocity and Jasmine. I'd prefer to integration test these steps to create the first object and then test that the second object is properly created.
My problem is that if I do it on the server, the Meteor.user() call doesn't work. If I do it on the client, I need to subscribe to a large number of collections in order for the logic to work, which seems kludgy.
Is there a better approach? Is there a way to simulate or mock a user login in a server integration test?
In your jasmine test you can mock a call to Meteor.user() like so:
spyOn(Meteor, "user").and.callFake(function() {
return 1234; // User id
});
You may want to specify a userId or change logged state depending on executed test. I then recommend to create meteor methods in your test project:
logIn = function(userId) {
Meteor.call('logIn', userId);
};
logOut = function() {
Meteor.call('logOut');
}
Meteor.userId = function() {
return userId;
};
Meteor.user = function() {
return userId ? {
_id: userId,
username: 'testme',
emails: [{
address: 'test#domain.com'
}],
profile: {
name: 'Test'
}
} : null;
};
Meteor.methods({
logIn: function(uid) {
userId = uid || defaultUserId;
},
logOut: function() {
userId = null;
}
});
If you don't want to rely on a complete lib just for this single usecase, you can easily mock your Meteor.urser() with beforeEach and afterEach:
import {chai, assert} from 'meteor/practicalmeteor:chai';
import {Meteor} from 'meteor/meteor';
import {Random} from 'meteor/random';
describe('user mocking', () => {
let userId = null;
let userFct = null;
const isDefined = function (target) {
assert.isNotNull(target, "unexpected null value");
assert.isDefined(target, "unexpected undefined value");
if (typeof target === 'string')
assert.notEqual(target.trim(), "");
};
//------------------------------------------//
beforeEach(() => {
// save the original user fct
userFct = Meteor.user;
// Generate a real user, otherwise it is hard to test roles
userId = Accounts.createUser({username: Random.id(5)});
isDefined(userId);
// mock the Meteor.user() function, so that it
// always returns our new created user
Meteor.user = function () {
const users = Meteor.users.find({_id: userId}).fetch();
if (!users || users.length > 1)
throw new Error("Meteor.user() mock cannot find user by userId.");
return users[0];
};
});
//------------------------------------------//
afterEach(() => {
//remove the user in the db
Meteor.users.remove(userId);
// restore user Meteor.user() function
Meteor.user = userFct;
// reset userId
userId = null;
});
it("works...", () => {
// try your methods which make use of
// Meteor.user() here
});
});
It makes sure, that Meteor.user() only returns the user you created in beforeEach. This it at least a fine thing, when you want to test everything else and assume, that the user creation and Meteor.user() is working as expected (which is the essence of mocking, as I can see so far).