OAuth2: how to get token? - javascript

I'm getting this error
RequestError: Error: Argument error, options.body
after sending a request. I saw this in the API:
grant_type = partner
partner_id = partner id
partner_secret = partner secret
This is the source code:
getToken() {
let data = {
grant_type: 'partner',
partner_id: config.id,
partner_secret: config.secret,
};
const url = config.url;
return this.postRequest(url, data)
.then((result) => {
console.log(result);
if (result) {
console.log(result);
return result;
}
})
.catch((err) => console.log(err));
}
postRequest(url, data) {
const options = {
uri: url,
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: data,
};
return request(options);
}
This code should return a token like this:
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"bearer",
"expires_in":1119,
"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA"
}
What's wrong with the code?

Data should be an query string!
getToken() {
let data = {
grant_type: 'partner',
partner_id: 'config.id',
partner_secret: 'config.secret',
};
data = querystring.stringify(data);
const url = config.url;
return this.postRequest(url, data)
.then((result) => {
if (result) {
console.log(result);
return result;
}
})
.catch((err) => console.log(err));
}

Related

"message": "Unauthorized Access" is showing, get method is not working

when I post this method in my MongoDB database it's working properly, but when I wanted to get it it's showing {"message": "Unauthorized Access"} in my http://localhost:5000/my site. The thing which I wanted everything is ok. But get is not working
//server side code
app.post("/my", async (req, res) => {
const my = req.body;
const result = await myCollection.insertOne(my);
res.send(result);
});
app.get("/my", async (req, res) => {
const query = {};
const cursor = myCollection.find(query);
const services = await cursor.toArray();
res.send(services);
});
//client side code
const onSubmit = (data, event) => {
const url = `http://localhost:5000/service`;
fetch(url, {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(data),
})
.then((res) => res.json())
.then((result) => {
setIsReload(!isReload);
if (result) {
alert("Add Successful");
}
});
const order = {
email: user.email,
name: event.target.name.value,
description: event.target.description.value,
price: event.target.price.value,
quantity: event.target.quantity.value,
};
axios.post(`http://localhost:5000/my`, order).then((res) => {
const { data } = res;
console.log(data);
if (data.insertedId) {
alert("Inserted");
}
event.target.reset();
console.log(res);
});
};

how to use Access-Tokens for CRUD REACT JS

Given is an application for managing users. Following help files are used for this purpose:
AuthenticationAction.js
ManagementAction.js
AuthenticationAction.js is used for authentication:
export function authenticateUser(userID, password) {
console.log("Authenticate")
return dispatch => {
dispatch(getAuthenticateUserPendingAction());
login(userID, password).then(userSession => {
const action = getAuthenticationSuccessAction(userSession);
dispatch(action);
}, error => {
dispatch(getAuthenticationErrorAction(error));
}).catch(error => {
dispatch(getAuthenticationErrorAction(error));
})
}
}
function login(userID, password) {
const hash = Buffer.from(`${userID}:${password}`).toString('base64')
const requestOptions = {
method: 'POST',
headers: {
'Authorization': `Basic ${hash}`
},
};
return fetch('https://localhost:443/authenticate', requestOptions)
.then(handleResponse)
.then(userSession => {
return userSession;
});
}
function handleResponse(response) {
console.log(response)
const authorizationHeader = response.headers.get('Authorization');
return response.text().then(text => {
if (authorizationHeader) {
var token = authorizationHeader.split(" ")[1];
}
if (!response.ok) {
if (response.status === 401) {
logout();
}
const error = response.statusText;
return Promise.reject(error);
} else {
let userSession = {
/* user: data, */
accessToken: token
}
return userSession;
}
});
}
ManagementAction.js is there for the Crud Functions.
export function createUser(userID, username, password) {
console.log("Create a User")
return dispatch => {
dispatch(getShowUserManagementAction());
createaUser(userID, username, password).then(userSession => {
const action = getShowUserManagementActionSuccess(userSession);
dispatch(action);
}, error => { dispatch(getShowUserManagementErrorAction(error)); }).catch(error => { dispatch(getShowUserManagementErrorAction(error)); })
}
}
function createaUser(userID, username, password) {
const token = "whatever"
const requestOptions = {
method: 'POST',
headers: { 'Authorization': `Basic ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ userID: userID, userName: username, password: password })
};
console.log(requestOptions)
return fetch('https://localhost:443/user/', requestOptions)
.then(handleResponse)
.then(userSession => {
return userSession;
});
}
question:
Now if I want to use the createaUser function instead of the hardcoded token value with the accestoken I created in login, how do I get the accesstoken and how do I have to rewrite the createaUser function ?
you can store the token you created in the local storage like this:
AuthenticationAction.js
let userSession = {
/* user: data, */
accessToken: token
}
localStorage.setItem("token", userSession.accessToken)
and you can access it as below:
ManagementAction.js
function createaUser(userID, username, password) {
const token = localStorage.getItem("token")
const requestOptions = {
method: 'POST',
headers: { 'Authorization': `Basic ${token}`, 'Content-Type': 'application/json' },
then
so you can send your token value with the request

Nodejs async loop function returns blank [duplicate]

I'm doing requests to my API server to authenticate a user, that's not the problem. The problem is that I don't know why my async function doesn't return anything, and I get an error because the data that I want from this function is undefined.
Don't worry if the error management is ugly and in general I can do this better, I'll do that after fixing this problem.
Utils.js class
async Auth(username, password) {
const body = {
username: username,
password: password
};
let req_uuid = '';
await this.setupUUID()
.then((uuid) => {
req_uuid = uuid;
})
.catch((e) => {
console.error(e);
});
let jwtData = {
"req_uuid": req_uuid,
"origin": "launcher",
"scope": "ec_auth"
};
console.log(req_uuid);
let jwtToken = jwt.sign(jwtData, 'lulz');
await fetch('http://api.myapi.cc/authenticate', {
method: 'POST',
headers: { "Content-Type": "application/json", "identify": jwtToken },
body: JSON.stringify(body),
})
.then((res) => {
// console.log(res);
// If the status is OK (200) get the json data of the response containing the token and return it
if (res.status == 200) {
res.json()
.then((data) => {
return Promise.resolve(data);
});
// If the response status is 401 return an error containing the error code and message
} else if (res.status == 401) {
res.json()
.then((data) => {
console.log(data.message);
});
throw ({ code: 401, msg: 'Wrong username or password' });
// If the response status is 400 (Bad Request) display unknown error message (this sould never happen)
} else if (res.status == 400) {
throw ({ code: 400, msg: 'Unknown error, contact support for help. \nError code: 400' });
}
})
// If there's an error with the fetch request itself then display a dialog box with the error message
.catch((error) => {
// If it's a "normal" error, so it has a code, don't put inside a new error object
if(error.code) {
return Promise.reject(error);
} else {
return Promise.reject({ code: 'critical', msg: error });
}
});
}
Main.js file
utils.Auth('user123', 'admin')
.then((res) => {
console.log(res); // undefined
});
Your Async function must return the last promise:
return fetch('http://api.myapi.cc/authenticate', ...);
or await the result and return it:
var x = await fetch('http://api.myapi.cc/authenticate', ...);
// do something with x and...
return x;
Notice that you don’t need to mix promise syntax (.then) with await. You can, but you don’t need to, and probably shouldn’t.
These two functions do exactly the same thing:
function a() {
return functionReturningPromise().then(function (result) {
return result + 1;
});
}
async function b() {
return (await functionReturningPromise()) + 1;
}
await is not to be used with then.
let data = await this.setupUUID();
or
let data=null;
setupUUID().then(res=> data = res)
I would try something like this:
const postReq = async (jwtToken) => {
const body = {
username: username,
password: password,
};
try {
const res = await fetch('http://api.myapi.cc/authenticate', {
method: 'POST',
headers: { "Content-Type": "application/json", "identify": jwtToken },
body: JSON.stringify(body),
})
if (res) {
if (res.status == 200) {
return res.json();
} else if (res.status == 401) {
const data = res.json();
console.log(data.message)
throw ({ code: 401, msg: 'Wrong username or password' });
} else if (res.status == 400) {
throw ({ code: 400, msg: 'Unknown error, contact support for help. \nError code: 400' });
}
}
} catch (err) {
console.error(err)
}
};
const Auth = async (username, password) => {
const jwtData = {
"origin": "launcher",
"scope": "ec_auth"
};
try {
const req_uuid = await this.setupUUID();
if (req_uuid) {
jwtData["req_uuid"] = req_uuid;
const jwtToken = jwt.sign(jwtData, 'lulz');
return await postReq(jwtToken);
}
} catch (err) {
console.error(err);
};
}

Send data to Express backend

I'm having trouble sending data to the Backend. I want to send data f1 to QueryBackend.js but when I try to console.log(req.body.f1) it's always undefined but in Services.js get the value.
Toolbar.js
handlePrintLetter = async(fieldName, fieldValue) => {
const { formId, selectedRows, displayData, onNotification } = this.props;
const idSelected = selectedRows.data.map(d => displayData[d.dataIndex].id);
const res = await getBookmarkDocument(idSelected); // Send Data to Backend
if (res.success) {
onNotification({ mode: 'success', text: 'success' });
} else {
onNotification({ mode: 'error', text: fieldName + ' ' + fieldValue });
}
}
Service.js
export const getBookmarkDocument = async (f1) => {
console.log(f1) // get value from Toolbar.js
const token = localStorage.getItem('token');
return axios.get(API + 'doc/show', { f1 },
{
headers: {
Authorization: `Bearer ${token}`
}
})
.then((response) => response.data || [])
.catch((error) => {
ErrorAPI(error);
return [];
});
}
How to get data f1 in here?
QueryBackend.js
router.get('/show', async (req, res) => {
try {
console.log(req.body.f1) // undefined
const pool = await poolPromise;
const result = await pool.query('SELECT sid_ddocument_key FROM sid_ddocument WHERE sid_ddocument_key = $1', ['I WANNA PUT DATA 'f1' IN HERE']); // Put Data f1
res.status(200).json({
success: true,
data: result.rows
});
} catch (err) {
res.status(500).json({
success: false,
response: err.message
});
}
});
GET requests can't have bodies. Encode the data in the query string and read it with req.query
const f1 = 'example';
const API = 'http://example.com/';
const url = new URL(`${API}doc/show`);
url.searchParams.append("f1", f1);
console.log(url.toString());

Unable to convert file to binary format for sending to wit.ai api using node.js

I am facing an issue in converting Audio file to Binary format. I need to send it to Wit.AI api which is expecting the data in that format. I am using node.js. In my front-end I am recording the user voice using Mic-recorder Module. Any suggestions are welcome.
My front end code:
var recorder;
function startRecording() {
recorder = new MicRecorder({
bitRate: 128
});
recorder.start()
}
function stopRecording() {
recorder.stop().getMp3().then(([buffer, blob]) => {
console.log(buffer, blob);
const file = new File(buffer, 'music.mp3', {
type: blob.type,
lastModified: Date.now()
})
console.log(file)
axios({
method: 'post',
url: `${appUrl}/open_api/voice/send?data=${buffer}`
}).then(function (res) {
console.log(res)
if (res.data.success) {
console.log('done',res)
} else {
console.log(res.data)
}
})
})
};
After recording Successfully, I want to send the file to my api in order to call wit.ai /speech api.
My back end code is:
router.post('/voice/send', //chatbot response api
async (req, res, next) => {
let thread_id = '99-99-99-99'
let audioBinary = req.query.data
console.log(audioBinary)
let appId = "5d07621d6b79be66a73f4005"
let sessionId ="10-10-10-10"
let accessToken = await db.model('ChatBotApp').findOne({
_id: req.query.key
}, {
access_token: 1
}).lean()
var options = {
method: 'POST',
uri: 'https://api.wit.ai/speech?v=20190513',
body : audioBinary,
encoding: null,
headers: {
'Authorization': 'Bearer ' + "HY3ZWSUGPBPD5LWZLRSZ3QJCDC27M6EW",
'Content-Type': 'audio/mpeg',
},
// json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(async function (parsedBody) {
console.log('this called',parsedBody)
return
// let response = await firstEntityValue(parsedBody, appId, message, thread_id)
// events.emit('Chats', appId, thread_id, message, sessionId, response);
return res.apiOk(response)
})
.catch(function (err) {
console.log(err)
return res.apiError('Issue while creating app!', err);
})
}
)
var recorder
function startRecording() {
recorder = new MicRecorder({
bitRate: 128
});
recorder.start()
}
function stopRecording() {
recorder.stop().getMp3().then(([buffer, blob]) => {
console.log(buffer, blob);
const file = new File(buffer, 'music.mp3', {
type: blob.type,
lastModified: Date.now()
})
var bodyFormData = new FormData();
bodyFormData.append('file', file);
console.log(file)
axios({
method: 'post',
url: `${appUrl}/open_api/voice/send`,
headers: {
'Content-Type': 'multipart/form-data'
},
data: bodyFormData
}).then(function (res) {
console.log(res)
if (res.data.success) {
console.log('done', res)
} else {
console.log(res.data)
}
})
})
};
API
router.post('/voice/send',upload.single('file'), //chatbot response api
async (req, res, next) => {
console.log(req.file)
let thread_id = '99-99-99-99'
let audioBinary = req.file.buffer
let appId = "5d07621d6b79be66a73f4005"
let sessionId = "10-10-10-10"
let accessToken = await db.model('ChatBotApp').findOne({
_id: req.query.key
}, {
access_token: 1
}).lean()
var options = {
method: 'POST',
uri: 'https://api.wit.ai/speech?v=20190513',
headers: {
'Authorization': 'Bearer ' + "HY3ZWSUGPBPD5LWZLRSZ3QJCDC27M6EW",
'Content-Type': 'audio/mpeg',
},
body: audioBinary
// json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(async function (parsedBody) {
console.log('this called', parsedBody)
return
// let response = await firstEntityValue(parsedBody, appId, message, thread_id)
// events.emit('Chats', appId, thread_id, message, sessionId, response);
return res.apiOk(response)
})
.catch(function (err) {
console.log(err)
return res.apiError('Issue while creating app!', err);
})
})

Categories