Maybe it’s strange, or it can be done in another way. I tell you what I want.
I use web3Auth for users to login (using 2.0 and 3.0 methods), but I don’t want to return any data like ethAddress, username, etc. on the client when I use the Moralis.authenticate function, and I would like to get a token generated in a External API.
I use the Molaris user data to create a user in another DB with: objectId, ethAddress,and username. Once the user is created, I create the token and return it to the client.
I’ve come up with a solution that works, but it’s not pretty at all.
I have a function in the cloud (Moralis.Cloud.beforeLogin), and inside it I take the user data, and call another function (Moralis.Cloud.httpRequest) that calls the external API. This API returns the token to me in the cloud function.
Here comes the problem. If I return the token, it doesn’t reach the client, because the usual response from the Moralis.authenticate call arrives. So what I do is return an error in the cloud function, and I intercept it on the client (I had to modify the moralis.js library to be able to handle the response), and fudge to use the token and other data that I also return in the cloud function.
The cloud function:
Moralis.Cloud.beforeLogin(async (request, res) => {
const { object: user } = request;
const fileObject = await makerequest(user, res);
return fileObject;
});
async function makerequest(user, res){
let results = "";
await Moralis.Cloud.httpRequest({
method: 'POST',
url: 'https://raito.care/api/signin',
followRedirects: true,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: {"objectId":"************","ethAddress":"****************","username":"***************","lang":"en","email":""}
})
.then((res) => {
results = res;
})
.catch((err) => {
results = err;
});
var resp = JSON.parse(results.text)
var dev = {code:results.text.status,error:resp};
throw dev;
//return results.text;
}
Client code:
authenticate(){
return Moralis.authenticate({ provider: 'web3Auth', clientId: environment.moralisClientId, appLogo: 'https://raito.care/assets/img/logo-raito.png', theme: 'light' })
.then( (user : any) => {
}, (err) => {
console.log(err);
if(err.message=='You have successfully logged in'){
return err;
}else{
this.logout();
}
})
}
I am not posting the code that I have modified from moralis.js because it is already too long
I am using [email protected]/dist/moralis.js and https://cdn.jsdelivr.net/npm/@web3auth/[email protected], and an Angular app.
Is there any simpler solution? Thanks in advance!