For some reason, only the adminConfirmSignup gives the user pool does not exist error. The CognitoUser doesn't give that error.
Please refer to the code below:
let cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData)
var cognitoAdmin = new AWS.CognitoIdentityServiceProvider({ region: process.env.COGNITO_POOL_REGION! });
await cognitoAdmin.adminConfirmSignUp(confirmParams, async(err, data) => { //Only this gives the user pool does not exist error
if (err) {
console.log(`This is the admin user confirm error ---> ${err}`)
} else {
console.log(`Entered else`);
await cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: async(result) => {
cognitoUser.changePassword(resetDetails.currentPassword, resetDetails.newPassword, (err, data) => {
if (err) {
reject(err);
} else {
console.log(`This is the success response of cognito change password -----> ${JSON.stringify(data)}`);
resolve(data);
}
})
},
onFailure: (error) => {
console.log(`This is the onFailure error ----> ${JSON.stringify(error)}`);
reject(error);
}
})
}
})
The password reset works if I use the CognitoUser methods (when I manually confirm the user and use only the cognitoUser methods to authenticate and reset the password).
Your param UserPoolId in SDK calls is incorrect. Won't be able to see that with only what you have posted.
Need another await in front of calling that function
await cognitoUser.changePassword(...)
like this
Related
Node.js CODE
exports.user = async (req, res) => {
try {
const { wallet } = req.body;
if (!wallet) {
res.status(400).json({ error: "Not logged in" });
return;
} else {
user = User.findone(wallet);
// if user is not found then create a new user and mark as loggged In
if (!user) {
User.create({
user: wallet,
});
}
// if user found then create a session token and mark as logged
in
res.send({
user: wallet,
});
}
} catch (error) {
console.log(`ERROR::`, error);
}
};
REACTJs CODE
// post call/update
const axiosCall = async () => {
// core login will give a unique username by fulling a transcation
// core.login i dont have any control
const userAccount = await core.login();
try {
const res = await Axios.post(`${API}/user`, userAccount, dataToken);
setData({
...data,
error: "",
success: res.data.message,
});
} catch (error) {
setData({
...data,
error: error.response.data.error,
});
}
};
Now here the problem occurs when some one could modify userAccount in the front-end or someone could send a body with wallet: anything to my route localhost:3000/api/user
There is no option for me to check if some actually used core.login(); to get the wallet address.
So is there any solution?
I was thinking to allow only my server IP or localhost to hit the route localhost:3000/api/user and is that even possible?
Also there is another issue anyone could modify userAccount in front-end.
I'm working on creating a table of users using Bcrypt and keep getting an error:
(node:54133) UnhandledPromiseRejectionWarning: Error: Client was closed and is not queryable
I'm recycling some code from a previous project that is working on that project and not sure where I'm going wrong with it. Below is my test function sitting in my seed.js as well as the function it's calling. As far as I'm seeing it's hitting the helper function but then erroring out, when I console.log my fields in the helper function, I'm getting all the fields, but it's not inserting into my Postgres table.
Seed function
async function testUsers() {
try {
console.log("testing");
bcrypt.hash("bertie99", SALT_COUNT, async function (err, hashedPassword) {
console.log("71", err);
const starter = await createUser({
username: "userone",
password: hashedPassword,
email: "123#yahoo.com",
});
console.log(starter);
});
} catch (error) {
console.log(error);
}
}
Helper function
async function createUser({ username, password, email }) {
try {
console.log("email", email);
console.log("username", username);
console.log("password", password);
const result = await client.query(
`
INSERT INTO users(username, password, email)
VALUES ($1, $2, $3);
`,
[username, password, email]
);
return result;
} catch (error) {
throw error;
}
}
So, it appears that the hashing need an await on it, I edited the function as below and it is working.
try {
console.log("testing");
const hash = await bcrypt.hashSync("bertie99", saltRounds);
const starter = await createUser({
username: "userone",
password: hash,
email: "123#yahoo.com",
});
console.log(starter);
} catch (error) {
console.log(error);
}
}
I'm building RESTful api with adonisjs. I face this problem in jwt login module. Look at the code below:
async login({request, auth, response}) {
let {email, password} = request.all()
try {
if (await auth.attempt(email, password)) {
let user = await User.findBy('email', email)
let token = await auth.generate(user)
user.password = undefined
Object.assign(user, token)
//------------------------------------------
const assignedToken = await Token.create({
user_id: user.id,
token,
})
// -------- i'd like to catch exception here...
return response.json({
success: true,
user
})
}
} catch(e) {
return response.json({
success: false,
message: 'login_failed'
})
}
}
I'd like to catch possible exception while persisting jwt token to database. I am rather new to adonis. I checked their doc but cannot find exact return type. Do they throw an exception? Or just return null/false? I have no idea. Do you have any?
Do they throw an exception?
Yes
An exception will appear if there is a problem during creation. You can create a new try/catch inside you try/catch. Like:
async login({request, auth, response}) {
...
try {
...
try { // New try/catch
const assignedToken = await Token.create({
user_id: user.id,
token,
})
} catch (error) {
// Your exception
return ...
}
return response.json({
success: true,
user
})
}catch (e) {
...
}
}
It's the simplest solution. I would do it this way because there can be different types of errors.
My res.json in my first block of code works, but in the else part of my if statement, it does not. The block that doesnt work, checks for a record in a database then im trying to return the response but im not receiving it.
I've checked and the response is a string, I thought it would have worked as the top part of the code successfully returns the string and it shows in dialogflow (where im trying to return it)
The response is successfully consoled right before the res.json but I do not receive it from the source of the request.
code:
app.post('/webhook/orderinfo', (req, res) => {
const intent = req.body.queryResult.intent.displayName;
const domain = "chatbotdemo.myshopify.com";
const order = req.body.queryResult.parameters["number-sequence"];
if (intent.includes('Order Number')) {
url = "https://test-hchat.com/api/orders/" + domain + "/" + order;
request(url)
.then(function (response) {
order_res = JSON.parse(response)
order_res["fullfillmentText"] = "Hi, Please find your order details below:";
res.json({
"fulfillmentText": JSON.stringify(order_res)
})
})
.catch(function (err) {
console.log(err)
});
// THIS PART DOESNT RETURN THE RESPONSE.
} else {
const domain = 'testStore'
db.getClientsDialog(domain, intent, (response) => {
const fullResponse = response.response
res.json({
fullResponse
})
})
}
});
The database code:
getClientsDialog: function (domain, intent, callback) {
MongoClient.connect('mongodb://efwefewf#wefwef.mlab.com:15799/wefwef', function (err, client) {
if (err) throw err;
var db = client.db('asdsad');
db.collection('dialog').findOne({ domain: domain, intent: intent }, function (err, doc) {
if (!err) {
callback(doc)
} else {
throw err;
callback(err)
}
client.close();
});
console.dir("Called findOne");
});
}
Could it be because this second use of the res.json in the else statement, is trying to call the db first and therefore the link is lost to send the data back?
This is a real niche question regarding Twitter OAuth with passport.js ()
I have a controller which updates the user's avatar using their Twitter "avatar":
const signInViaTwitter = (twitterProfile) => {
return new Promise((resolve, reject) => {
console.log(twitterProfile);
// find if user exist on in
User.findOne({ username: twitterProfile.username }, (error, user) => {
if (error) { console.log(error); reject(error); }
else {
// user existed on db
if (user) {
// update the user with latest git profile info
user.name = twitterProfile.displayName;
user.username = twitterProfile.username;
user.avatarUrl = twitterProfile.photos.value;
user.email = '';
// save the info and resolve the user doc
user.save((error) => {
if (error) { console.log(error); reject(error); }
else { resolve(user); }
});
}
// user doesn't exists on db
else {
// check if it is the first user (Adam/Eve) :-p
// assign him/her as the admin
User.count({}, (err, count) => {
console.log('usercount: ' + count);
let assignAdmin = false;
if (count === 0) assignAdmin = true;
// create a new user
const newUser = new User({
name: twitterProfile.displayName,
username: twitterProfile.username,
avatarUrl: twitterProfile.photos.value,
email: '',
role: assignAdmin ? 'admin' : 'user',
});
// save the user and resolve the user doc
newUser.save((error) => {
if (error) { console.log(error); reject(error); }
else { resolve(newUser); }
});
});
}
}
});
});
};
The authentication of the user works - but for some reason, the avatar won't show...here is the following console output:
Refused to load the image 'https://api.twitter.com/favicon.ico'
because it violates the following Content Security Policy directive:
"img-src https://abs.twimg.com https://*.twimg.com
https://pbs.twimg.com data:".
Does anyone know what this means? I'm thinking it's probably due to being in development mode - that is, http://localhost:8080/ ... and it won't accept https?? Or won't pass it back?
UPDATE: ^I think the above error is unrelated to the image not being display...
A little look at the html source gives:
<img class="styles__userAvatar___2x2U9" src="{unknown}" alt="Wind Up Lord Vexxos Avatar">
So it's obviously passing in an unknown variable for the src - rather than the user's display avatar...
So, for me it looks like the offending line is:
user.avatarUrl = twitterProfile.photos.value;
What should I be setting this to?
Just a thought, isn't twitterProfile.photos an array? probably you should try accessing twitterProfile.photos[0].value