How to get id from response and verify OTP in Javascript - javascript

I am working with simple HTML and JS code to create a OTP verification form and when user submit the email he will receive an otp and to get verified we need to take id from response.
Here is my response JSON:-
{
"createdBy": null,
"createdAt": "2022-08-20 18:31:14",
"lastModifiedBy": null,
"lastModifiedAt": "2022-08-20 18:31:14",
"id": "huuhby667-4124-41e1-7gt6-t7thgfy7t",
"username": null,
"email": "username#gmail.com",
"phoneNumber": null,
"countryCode": null,
"isEmailVerified": false,
}
Here is my Email Code:-
const emailForm = document.getElementById('email-form');
if(!!emailForm) {
emailForm.addEventListener('submit', function(e) {
e.preventDefault();
const email = document.getElementById('email').value;
const response = fetch('api-email-link', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email: email }),
}).then(function(response){
return response.json()}).then(function(data){
console.log(data)
document.getElementById('verify-modal-background').style.display = "flex";
}).catch(error => console.error('Error:', error))
});
};
Here is My OTP Verification Code:-
const inputOtp = document.getElementById("otp-input-form");
const id = JSON.parse(response.id);
inputOtp.addEventListener('submit', async function (e) {
e.preventDefault();
let inputs = document.getElementsByClassName("otp-input-box");
let referralCodeInput = document.getElementById("referral-input").value;
let getOtpInput = [];
for (let i=0; i<inputs.length; i++) {
getOtpInput.push(inputs[i].value);
}
const data = {
otp: getOtpInput
};
const response = await fetch(`https://otp-verification/api/auth/${id}/register-email`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
body: JSON.stringify(data)
}).catch(e => console.log(e));
I'm trying this but unable to get the ID properly so i can verify this otp for the particular register email.

Related

Error response graph.microsoft.com/v1.0/me/manager

Look at my code, what am I doing wrong? I need to get https://graph.microsoft.com/v1.0/users/${uniqueName}/manager. But the request fails
But when I try to execute the https://graph.microsoft.com/v1.0/${uniqueName} query, everything goes well. What to fix so that the https://graph.microsoft.com/v1.0/users/${uniqueName}/manager request is successful?
fastify.post('/login', {
preHandler: (request, _, next) => {
if (!request.body || !request.body.username || !request.body.password) {
const error = new Error('Credentials are missing');
error.statusCode = 400;
return next(error);
}
return next();
},
}, async (request, reply) => {
const { username, password } = request.body;
const userData = await fastify.helpers.authentication.getUserTokens(username, password, azureConfig.CLIENT_SCOPE);
await replyWithTokens(fastify, reply, userData);
});
And next
const getUserTokens = async (username, password, scope) => {
const authUrl = `https://login.microsoftonline.com/${azureConfig.TENANT_NAME}/oauth2/v2.0/token`;
const body = {
client_id: azureConfig.CLIENT_ID,
client_secret: azureConfig.CLIENT_SECRET,
grant_type: 'password',
password,
scope,
username,
};
const authResponse = await fetch(authUrl, {
body: new URLSearchParams(body).toString(),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'POST',
});
if (!authResponse.ok) {
fastify.helpers.error.throwError(422, 'Authentication failed');
}
const result = await authResponse.json();
const decodedData = jwt.decode(result.access_token);
const uniqueName = String(decodedData.unique_name || '').toLowerCase();
const name = String(decodedData.upn || uniqueName).toLowerCase();
const agentAttributes = {};
if (!uniqueName) {
fastify.helpers.error.throwError(400, 'Unique name not found');
}
let recheckSan = true;
let san = name.split('#').shift();
let agent = await fastify.db.models.Agent.findOne({
where: { uniqueName },
});
let radId = '';
const graphAuthResponse = await fetch(authUrl, {
body: new URLSearchParams({
...body,
scope: 'email openid profile https://graph.microsoft.com/User.Read',
}).toString(),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'POST',
});
if (graphAuthResponse.ok) {
const graphAuthResult = await graphAuthResponse.json();
const { access_token: graphAccessToken = '' } = graphAuthResult;
// eslint-disable-next-line max-len
const graphResponse = await fetch(`https://graph.microsoft.com/v1.0/users/${uniqueName}/manager`, {
headers: {
authorization: `Bearer ${graphAccessToken}`,
'content-type': 'application/json',
},
});
if (graphResponse.ok) {
const graphResult = await graphResponse.json();
console.log(graphResult)
}
}
}
I want to receive such response
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#directoryObjects/$entity",
"#odata.type": "#microsoft.graph.user",
"id": "1111112-68cf-4896-b2d0-13b5c6264113",
"businessPhones": [
"111 111 11111"
],
"displayName": "Wer, John",
"givenName": "John",
"jobTitle": "SENIOR DEVELOPMENT ARCHITECT",
"mail": "somemail#mail.com",
"mobilePhone": "111 111 1111",
"officeLocation": "Atlanta",
"preferredLanguage": null,
"surname": "John",
"userPrincipalName": "somemail#mail.com"
}
But I get such an error response. What am I doing wrong? Thanks!
{
"error": {
"code": "Authorization_RequestDenied",
"message": "Insufficient privileges to complete the operation.",
"innerError": {
"date": "2022-01-14T20:40:30",
"request-id": "9e2b5937-4bd0-4fdb-a1ae-1b22cef09772",
"client-request-id": "9e2b5937-4bd0-4fdb-a1ae-1b22cef09772"
}
}
}
To get the managers of other users in your organization on your behalf, you need to have User.Read.All delegated permission
Once the permission is assigned, admin consent needs to be granted for the same.
Then you would be able to fetch the managers info of other users in your organization
You can test the same in Graph Explorer first. If it is successful, you can make the changes accordingly in your JavaScript code

POST Javascript; Error in JSON (FCM, Push to mobile)

I am trying to send a push to my phone through rest.
i tried:
async function SendPush(event)
{
event = event || window.event;
event.preventDefault();
var tokenID = "xxx"
let url = "https://fcm.googleapis.com/fcm/send";
let serverkey = 'yyy';
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'key=' + serverkey);
var dict = {
to : tokenID
};
let body = Object.entries(dict).map(([key, value]) =>
encodeURIComponent(`params[${key}]`) + '=' + encodeURIComponent(value)).join('&');
var res
await fetch(url, {
method: 'POST',
headers: {
Authorization: 'key=' + serverkey,
"Content-Type": "application/json"
},
body: body
}).then(response => response.json())
.then(data =>
{
//console.log(data);
res = data; // cannot return here. must await or something idk
});
console.log(res);
}
This object works on c# and in postman. I followed this convention:
URL:
https://fcm.googleapis.com/fcm/send
Header:
"Content-Type": "application/json",
"Authorization": "key=<Server_key>"
BODY:
{
"to": "<Device FCM token>",
"notification": {
"title": "Check this Mobile (title)",
"body": "Rich Notification testing (body)",
"mutable_content": true,
"sound": "Tri-tone"
},
"data": {
"url": "<url of media image>",
"dl": "<deeplink action on tap of notification>"
}
}
But I am getting:
JSON.parse: unexpected character at line 1 column 1 of the JSON data
Can you tell me, where my error is?
try
let body = JSON.stringify(dict)
instead of
let body = Object.entries(dict).map(([key, value]) =>
encodeURIComponent(`params[${key}]`) + '=' + encodeURIComponent(value)).join('&');
The body in fetch must match "Content-Type" header

Issue with fetch: Getting type error failed to fetch

I'm trying to make a post call to the backend server, but I keep running into this error:
TypeError: Failed to fetch
I've looked over the code a bunch of times but can't seem to find the issue. Here is the code:
async doLogin() {
if(!this.state.email || !this.state.password) {
return
}
this.setState({
buttonDisabled : true
})
try {
let res = await fetch('/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
console.log(res)
let result = await res.json()
console.log(result)
if(result && result.success) {
UserStores.isLoggedIn = true
UserStores.email = result.email
alert(result.msg)
} else if(result && result.success === false) {
this.resetForm()
alert(result.msg)
}
} catch(e) {
console.log('doLogin error: ', e)
this.resetForm()
}
}
This is an example response payload:
{
"success": true,
"email": "mfultz956#gmail.com",
"msg": "Login Verified!"
}
Login Call - Network Tab
Login Call - Headers
change it to :
let res = await fetch('http://localhost:your_api_server_port/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})

Cookies not being set immediately in react

I am using djangorestauth for the backend and the token it returns back is not saved in the cookies from universal cookies immediately. I have this handle login:
const handleLogin = (e) => {
e.preventDefault();
setIsClicked(true);
const csrftoken = getCookie("csrf");
const url = "http://localhost:8000/rest-auth/login/";
const cookies = new Cookies();
fetch(url, {
method: "POST",
headers: {
"Content-type": "application/json",
"X-CSRFToken": csrftoken,
},
body: JSON.stringify({
username: username,
password: password,
}),
})
.then((response) => response.json())
.then((key) => setToken(key.key));
cookies.set("token", token);
};
and a useEffect() to test
useEffect(() => {
if (isClicked) {
const cookies = new Cookies();
console.log("THE TOKEN COOKIE: ", cookies.get("token"));
setIsClicked(false);
}
}, [isClicked]);
The problem: When I click the Login button, the token returned was obviously not set immediately because it returns undefined or blank at the first click. And when I input the wrong username and password, the token is still being output
const handleLogin = (e) => {
e.preventDefault();
const csrftoken = getCookie("csrf");
const url = "http://localhost:8000/rest-auth/login/";
const cookies = new Cookies();
fetch(url, {
method: "POST",
headers: {
"Content-type": "application/json",
"X-CSRFToken": csrftoken,
},
body: JSON.stringify({
username: username,
password: password,
}),
})
.then((response) => response.json())
.then((key) => {
setToken(key.key)
cookies.set("token", key.key);
setIsClicked(true);
})
};
explanation
you need to await to finish the fetch
NOTE: setIsClicked change the name to isSubmitSuccess

How to do a login verification

I am creating a system in nodejs + mongodb but I am having difficulty checking if the email and password match.
this is the function that sends the parameters to the api:
function log(e){
e.preventDefault();
let email = document.querySelector('input[name="email"]').value;
let password = document.querySelector('input[name="password"]').value;
let loginstatus = document.querySelector('#loginstatus');
fetch('http://localhost:3000/userV', { method: 'post', headers: {Accept: 'application/json', 'Content-Type': 'application/json'}, body: JSON.stringify({
email: email,
senha: password
})
}).then((resp) => {
if(resp.status == 200){
}else{
loginstatus.textContent = 'Usuario ou senha incorretos!';
loginstatus.style.color = 'red';
}
}).catch((err) => {
alert("Ouve um erro no servidor.\nErro:"+err);
});}
here is where it should be doing the verification but always returns "yes", what is wrong in my form? would you have another recommended way to do it?
async index(req, res) {
let reqemail = req.params.email;
let reqsenha = req.params.senha;
const users = await Users.find({ email: reqemail });
if(reqsenha == users.senha){
return res.send('yes')
}else{
return res.send('no')
}
}

Categories

Resources