hapijs yar doesn't work - node.js

I am having this in one handler (api/user/login):
request.yar.set('userSession', {userId: doc.userId});
console.log(request.yar.get('userSession'));
in second handler I have this (api/user/isLoggedIn):
console.log(request.yar.get('userSession'));
when I go in browser and do this in console:
$.ajax({
url: 'http://localhost:3004/api/user/login',
method: 'POST',
data: {
email: 'durisvk2#gmail.com',
password: 'jjuurr123'
},
success: function(data) {
console.log(data);
}
})
the server outputs: {userId: 'ASDFGHJKLZX'}
BUT when I do this in Chrome Console:
$.ajax({
url: 'http://localhost:3004/api/user/isLoggedIn',
method: 'GET',
data: {
},
success: function(data) {
console.log(data);
}
})
I get in console undefined
why isn't it storing session from one request to another?

Related

Auth0 sync userinfo

I'm trying to sync my auth0 userinfo with my local database:
userRouter.get("/sync", validateAccessToken, (req, res) => {
var request = require("request");
var usertoken;
var options = { method: 'POST',
url: 'https://MYDOMAN.eu.auth0.com/oauth/token',
headers: { 'content-type': 'application/json' },
body: '{"client_id":"myclienttoken","client_secret":"myclientsecret","audience":"https://MYDOMAIN.eu.auth0.com/api/v2/","grant_type":"client_credentials"}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
usertoken = body;
console.log(body);
});
var auth0options = {
method: "GET",
url: "https://MYDOMAIN.eu.auth0.com/api/v2/users",
params: {id: 'email:"testuser"', search_engine: 'v3'},
headers: {
"content-type": "application/json",
authorization: `Bearer` + usertoken.access_token,
},
};
axios.request(auth0options).then(function (response) {
console.log("RES DATA: ", response.data);
})
.catch(function (error) {
console.error(error);
});
console.log("called");
res.status(200).json("message");
});
The following line, results in a error:
authorization: Bearer + usertoken.access_token,
"Cannot read properties of Undefined (reading 'access_token)"
But I don't get the userinfo when calling the auth0 api with that token.
I'm using the audience from the Auth0 Management API ex:
https://MYDOMAIN.eu.auth0.com/api/v2/
And not the audience from my own API, as I have read that's the correct way:
https://mydomain
Any ideas on what I'm doing wrong?

JOI [ValidationError] when validating req.body

Hello I am learning the basics of node. The issue im having is that I want to validate the data passed into the post request from a html form. The data is being passed in but im also getting an error in the console.
Here is the server code:
app.post('/', (req, res)=> {
const schema = Joi.object({
username: Joi.string().trim().required(),
password: Joi.string().min(3).max(10).required(),
})
const validation = schema.validate(req.body);
console.log(req.body)
if(validation.error){
console.log(validation.error)
// res.send('an error has occurred')
}
res.send('successfully posted data')
})
the console error (with sample data: username: test & password: test):
[Error [ValidationError]: "value" must be of type object] {
_original: [
{ name: 'username', value: 'test' },
{ name: 'password', value: 'test' }
],
details: [
{
message: '"value" must be of type object',
path: [],
type: 'object.base',
context: [Object]
}
]
}
I dont understand why I am getting a validation error. The req.body appears to be an object when printed to the console with console.log(req.body) but when I try to use validation it appears inside of an array? Kind of confused.
Additional Info:
I am using express.urlencoded() and express.json() if that matters.
Here is the JQuery from the HTML page:
<script>
$(document).ready(()=>{
$('#form').submit((e)=>{
e.preventDefault();
$.ajax({
url: '/',
type: 'post',
contentType: 'application/json',
data: JSON.stringify($('#form').serializeArray()),
success: (response)=>{
console.log('successfully got response');
console.log(response)
}
})
})
});
</script>
The error clearly states that req.body is an array.
[
{ name: 'username', value: 'test' },
{ name: 'password', value: 'test' }
]
From jQuery documentation page, we also have .serializeArray() method creates a JavaScript array of objects. So, you're actually sending an array of objects to the server-side and that's why you have the error.
To fix the problem, I think you should modify the frontend part. Since you already have
express.urlencoded(), you can use serialize.
<script>
$(document).ready(()=>{
$('#form').submit((e)=>{
e.preventDefault();
$.ajax({
url: '/',
type: 'post',
contentType: 'application/json',
data: JSON.stringify($('#form').serialize()),
success: (response)=>{
console.log('successfully got response');
console.log(response)
}
})
})
});
</script>

Perform http request with nodeJS (OAuth2)

I'm have to call an API that use OAuth2 with Client Credentials.
I'm having some trouble to do it...
This is the code I produce (using request package) :
const credentials = {
client: {
id: 'MY_ID',
secret: 'My_PASSWORD'
},
auth: {
tokenHost: 'DOMAIN',
tokenPath: 'PATH',
scope: '',
grantType: "client_credentials"
}
};
var options = {
method: 'POST',
url: credentials.auth.tokenHost + credentials.auth.tokenPath,
headers: { 'content-type': 'application/json' },
body: {
grant_type: credentials.auth.grantType,
client_id: credentials.client.id,
client_secret: credentials.client.secret
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
I have this error :
{ error: 'invalid_request',
error_description: 'Missing form parameter: grant_type' }
Maybe I'm missing something.
It would be very nice of you if you can help me to figure it out :)
PS : It works on Postman so my values are correct.

Back-end API receiving empty request body when making request from front-end

I am building Web application on my localhost.
The front-end is Reactjs framework, running in localhost:3000
The back-end is nodejs + Express, running in localhost:4000
Now, I have created the API below:
router.post('/register', function (req, res) {
console.log(req.body); // {}, why it is empty?
// create new instance, save it to database
User.create(req.body).then(function () {
res.send('success');
});
});
The front-end part is:
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
console.log('Received values of form: ', values); // value is not empty, I have tested! So we did send something to the API
const input = JSON.stringify({
username: values.username,
password: values.password,
});
console.log(input);
$.ajax({
url: `${API_ROOT}/register`,
method: 'POST',
data: JSON.stringify({
username: values.username,
password: values.password,
}),
}).then((response) => {
if (response === 'success') {
this.props.history.push('/login');
} else {
console.log('do not jump');
}
});
}
});
}
I have tested the API by the postman, I can add users to MongoDB, so the API is good.
I have console.log what I sent to API, it is not empty, however, backend API receive d empty request body. I have already fixed the "Access-Control-Allow-Origin" issue, so I think I do send something to the API, but backend API received empty request body.
If you add a content type header saying what type the body of the request is it should work as expected.
$.ajax({
url: `${API_ROOT}/register`,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
data: JSON.stringify({
username: values.username,
password: values.password,
})
})

Docusign legacy header error when making api call

I am receiving an error when attempting to use legacy headers for Docusign API.
here is my code
request({
headers: {
"X-DocuSign-Authentication": [{
"Username": "zabie#toplevelstaging.com",
"Password": "xxxxxxxx",
"IntegratorKey": "xxxxxxxxxxx-11xxx2f567xxxx0dbxxxx2d"
}]
},
url: "https://demo.docusign.net/restapi/v2/accounts/3465212/envelopes",
json: true, // <--Very important!!!
body: data,
method: "POST",
}, function (error, response, body) {
console.log(response.body);
});
console.log(data[0].templateRoles[0].tabs.textTabs[0].value);
console.log(data[0].templateRoles[0].roleName);
res.redirect('/contracts');
});
Here is the error
{
errorCode: 'INVALID_TOKEN_FORMAT',
message: 'The security token format does not conform to expected schema.'
}
The authheader you are passing is incorrect. Try the following instead. SDK Documentation here
// create JSON formatted auth header
var creds = JSON.stringify({
Username: "zabie#toplevelstaging.com",
Password: "xxxxxxx",
IntegratorKey: "xxxxxxxxxxx-11xxx2f567xxxx0dbxxxx2d"
});
request({
headers: { "X-DocuSign-Authentication": creds },
url: "https://demo.docusign.net/restapi/v2/accounts/3465212/envelopes",
json: true, // <--Very important!!!
body: data,
method: "POST",
}, function (error, response, body) {
console.log(response.body);
});

Resources