Did not receive SMS from Cognito even thought it's a successful request - amazon-cognito

I'm unable to receive an SMS from using resendConfirmationCode method from amazon-cognito-identity-js. Even thought the request was sent successfully with a sample response of
{
AttributeName: "phone_number",
DeliveryMedium: "SMS",
Destination: "+*******xxxx"
}
I have the following code that will be called once a user submit a form.
function resendConfirmationCode(username) {
const cognitoUser = new CognitoUser({
Username: username,
Pool: userPool,
});
return new Promise((resolve, reject) => {
cognitoUser.resendConfirmationCode(function (err, result) {
if (err) reject(err);
resolve(result);
});
});
}
From my perspective, I think my code works well. I have done signUp, and the SMS got sent if the user was new. However, when I used the resendConfirmationCode I got the above response. I have already verified my phone number in Amazon SNS Sandbox. Is there something I missed?

So I wasn't reading carefully,
Turns out there's a thing called Account spend limit, you can check it on Amazon SNS > Text Messaging (SMS) > Text messaging preferences.
I'm glad that Amazon put $1 on default. Apparently I have no idea that we're charged for SMS verification. (A bit naive, but Amazon got most the free stuff so I thought that's somewhat free too).
Thanks AWS! This information is hard to find thought. Hopefully this helps.

Related

Give web app permanent control of google email

I recently got a domain from Google Domain and it provides professional emails for the domain. So, I made a support#domain email to send and receive emails. Right now, I built a web app that will use this email to send email-verification to new users who sign up.
I got the code working, however, I used OAuth2.0 from Google to allow the web app to sign into the support email. This causes the Access token to expire and forces me to into my .env file and replace BOTH tokens. How tedious! If I were to publish this web app, I can't just go into my heroku vars and replace the tokens every hour. Thats extremely impractical.
I looked into service accounts by google, but they seem to STILL need OAuth anyways as a 3 legged OAuth. As I am using Express.js, I wanted to know if there was a way to set the tokens and be done with it permanently. Essentially giving the web app permanent control of the google account. What do I do? And what do I use? All advice is greatly appreciated.
Code for sending email verification:
const nodemailer = require("nodemailer")
const dotenv = require("dotenv")
const {generateVerifyToken} = require("./auth")
const { print } = require("#AlecRuin/color-logger")
dotenv.config()
let transporter = nodemailer.createTransport({
service:"gmail",
auth: {
type: 'OAuth2',
user: process.env.EMAIL,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
refreshToken: process.env.REFRESH_TOKEN,
accessToken: process.env.ACCESS_TOKEN
}
})
module.exports= async function(email){
try {
let mailOptions={
from: "support#domain.us",
to:email,
subject:"Verify your email",
text:`
Thank you for signing up with redacted!!
To verify your email (and make sure you're not some kind of annoying bot), simply follow this link:
${process.env.NODE_ENV === "production"?"www.redacted.com":"localhost:3001"}/api/user/verify/?token=${generateVerifyToken(email)}
`
}
print("sending email",new Error,{isClient:false})
transporter.sendMail(mailOptions,(err,data)=>{
if (err){
console.error(err);
return err
}else{
print("Email sent!",new Error,{isClient:false})
return true
}
})
} catch (error) {
print(error,new Error, {isClient:true,severity:4})
return error
}
}

Strapi doesn't authorize JWT

Good morning,
I've encountered a weird issue with my strapi-project.
I have a standard user model which I query for info on the user's profile page via the /users/me endpoint. This was all working fine last week but as I tried logging in this morning, the authorization appeared to not work anymore. I log my user in via this code:
....
async submitForm() {
axios.post('http://localhost:1337/auth/local', {
'identifier': this.email,
'password': this.password
})
.then((response) => {
const { jwt, user } = response.data;
window.localStorage.setItem('jwt', jwt);
window.localStorage.setItem('userData', JSON.stringify(user));
router.push('/dashboard');
})
.catch((e) => {
this.$store.commit('LOGIN_ERROR', e)
});
},
...
Which then redirects to my dashboard which queries the /users/me endpoint like so:
let token = localStorage.jwt;
axios.get(`http://localhost:1337/users/me`, {
headers: {
Authorization: `Bearer ${token}`
}
})
.then((response) => {
console.log(response.data);
})
A few days ago this was working fine, also the token variable used in the post contais the token returned from the backend after logging in. Now strapi gives me an error in the console:
[2021-10-16T07:16:52.568Z] debug GET /users/me (5 ms) 500
[2021-10-16T07:17:03.231Z] debug POST /auth/local (76 ms) 200
[2021-10-16T07:17:24.915Z] error TypeError: Cannot read property 'type' of null
at module.exports (/home/user/WebstormProjects/strapi-project/node_modules/strapi-plugin-users-permissions/config/policies/permissions.js:35:14)
at async /home/user/WebstormProjects/strapi-project/node_modules/strapi-utils/lib/policy.js:68:5
at async serve (/home/user/WebstormProjects/strapi-project/node_modules/koa-static/index.js:59:5)
at async /home/user/WebstormProjects/strapi-project/node_modules/strapi/lib/middlewares/parser/index.js:48:23
at async /home/user/WebstormProjects/strapi-project/node_modules/strapi/lib/middlewares/xss/index.js:26:9
My first guess was that maybe something with axios was wrong e.g. that the token wasn't sent correctly in the request so I tried the same thing with webstorm's http client:
POST http://localhost:1337/auth/local
Content-Type: application/json
{
"identifier": "test#test.com",
"password": "..."
}
Which returns the user and token:
"jwt": "<TOKEN>",
If I try using this token to authenticate the user, however a get a 401
GET http://localhost:1337/users/me
Authorization: "Bearer <token>"
Accept: application/json
returns
{
"statusCode": 401,
"error": "Unauthorized",
"message": "Invalid token."
}
So I tried figuring out what was going on there and after an hour I noticed that when looking at the user in the backend the user didn't have the authenticated role assigned. When I changed this manually in the backend, the request authorization works again.
So can anyone maybe tell me what is going on here? Because from my understanding, when POSTing valid credentials to /auth/local the user's role should change to Authenticated, which was working some days back.
Is there something I'm missing?
Any help would be greatly appreciated,
greetings, derelektrischemoench
Okay, so let me reply to your first part:
"Because from my understanding, when POSTing valid credentials to /auth/local the user's role should change to Authenticated"
Answer is, not really. When you send valid credentials to the auth/local, Strapi just checks the database for matching username/email and password. If a user is found, then it fetches the role assigned that user and puts all the data in ctx.state.user.role. So you could have many other roles, like Viewer, Commenter etc with each having different set of access limits.
The different roles can be created here:
http://localhost:1337/admin/settings/users-permissions/roles
So depending on the roles assigned, Strapi will just fetch and store the values in ctx.state.user.role on each request via the strapi-plugin-users-permissions plugin for your convenience, so that you can easily check which user it is and which role it has in any controller or service file using the ctx from the request to provide any additional functionality.
You can check how it does it in the following file:
node_modules/strapi-plugin-users-permissions/config/policies/permissions.js
Now coming to what could have caused it:
Well it could have been you yourself. Possibly while saving the user or viewing user details you could have removed the role from the user and saved the record.
The other possibility could be a database switch.
It can also be a Strapi version upgrade that caused, but it's highly unlikely.
You could have a update query in the your code that updates the user model, where you might have missed the role parameter. So check your code once.
Nevertheless, it can simply be solved by re-assigning the user roles via the users module.

Trying to log in to gmail while using TestCafe

I am learning TestCafe and am trying to create an account on a website and then logging in to Gmail to find the activation link. When I try to do this I just get a browser isn't secure message when I get to the part to enter a password. How do I get Gmail to trust TestCafe?
While you might succeed in doing so, this is not a good approach because:
it's slow doing this via GUI
it's britle because selectors will likely change, and you have no control over Google email selectors, so you won't even know if they change them
A better approach wuld be to use a service like Mailosaur where you can create an account and receive emails that you can later query via an API. Instead of doing a whole e2e flow over GUI, you request an email on Mailosaur's API, and if such an email exists, you'll receive a response you can parse and check for various things.
I've done this in the past, you can see my post here: https://sqa.stackexchange.com/questions/40427/automating-verification-of-sent-email-sms-messages/45721#45721 It's exactly Mailosaur and Testcafe (plus it requires axios as a package), so it seems to be what you're looking for.
To add the same code here:
import config from '../config';
import { customAlphabet } from 'nanoid';
import axios from 'axios';
import Newsletter from '../Objects/newsletter';
async function request (reqObject) {
try {
return await axios(reqObject);
} catch (error) {
console.error(error);
}
}
function serverId () {
return process.env.MAILOSAUR_SERVER_ID;
}
function mailosaurFullEmail (id) {
return (id ? id : nanoid()) + '.' + serverId()
+ '#' + config.mailosaurDomain;
}
fixture `Newsletter`
.page(baseUrl);
test
('Sign Up For Newsletter', async t => {
const id = (customAlphabet('1234567890', 10))();
await t
.typeText(Newsletter.newsEmailInput, mailosaurFullEmail(id))
.click(Newsletter.consent)
.click(Newsletter.sendButton);
let res = await request({
method: 'POST',
url: config.mailosaurUrlEmail + serverId(),
headers: {
'Authorization': 'Basic '
+ Buffer.from(process.env.MAILOSAUR_API_KEY)
.toString('base64'),
'Content-Type': 'application/json'
},
data: {
sentTo: mailosaurFullEmail(id)
}
});
await t
.expect(res.status).eql(200);
});
and it requires some config values:
{
"mailosaurUrlEmail": "https://mailosaur.com/api/messages/await?server=",
"mailosaurDomain": "mailosaur.io"
}
This is definitely much better, but it still has some limitations:
Mailosaur's API can still change, so it won't be exactly without any maintenance
it assumes that an email is sent immediately after a user action (newsletter in my case), but that might be far from reality in many situations such as when emails are sent to a queue where it can easily take several minutes to send an email
If you absolutely have to do it via Gmail, you will still be better off looking at their API that should allow you to search and query email messages as well.
There is an issue related to the Google login. You can try turning on the "Allow less secure apps" Google account setting to workaround this issue. Please note that this setting is available for the disabled 2-Step Verification.

How do you test user flows that involve confirmation by email?

I mean functional or E2E testing. That's all clear with generic flows, but when it comes to transactional emails (signup confirmations, password resets, purchase notifications and others) it's still bringing questions. After some research I came up with a few ideas. One is to leverage Restmail.net API (here examples with Selenium WebDriver and Cypress - http://dsheiko.com/weblog/testing-sign-up-flow-with-activation-by-email). It's free, but API is public. So it's not really suitable for email messages with potentially sensitive information. Another approach to access Gmail inbox via IMAP bridge or Gmail API (here the explanation and code snippets - https://docs.puppetry.app/testing-emails/example-with-imap-bridge). But again, it's rather a workaround.
I know there are guys like Sendgrid, Mailgun, Email Yak, Postmark. I don't want to pay that much. So how do you folks do it? It it a thing to you?
We're doing this using Mailosaur email addresses for our test users. We then use a cypress custom command to query Mailosaur for the expected email. It was super easy to set up.
Here's the main part of that custom command, which is all we had to add to start doing email testing. You can refer to their API docs for what query, mailosaurServer, and MailosaurApiKey should be.
Cypress.Commands.add("getEmailFromMailService", query => {
return cy
.request({
method: "POST",
url: `https://mailosaur.com/api/messages/await?server=${mailosaurServer}`,
body: query,
headers: { "Content-Type": "application/json" },
auth: { user: mailosaurApiKey },
})
.then(response => {
expect(response.status).to.equal(200);
return response.body;
});
});
You could create a post request for the "forgot your password" and then assert on it.
something like:
cy.visit('yoursite')
cy.get('#forgotpassword').click().then(function (xhr) {
cy.server()
cy.request('POST', 'APIforForgotPassword').as('sucessfullemail)
})
cy.get(#sucessfullemail).then(function (xhr) {
expect(xhr.status).to.eq(200)
Cypress.Commands.add('ConfirmUser', () => {
const confirmationToken = null;
cy.request({
url: 'http://localhost:3000/api/confirmation_token?email=test_user#cypress.com',
followRedirect: false
})
.then((resp) => {
confirmationToken = resp.token
})
cy.visit('/en/confirmation?confirmation_token=token')
})
Create the API that requires the email as a parameter and returns the confirmation-token. call the API from cypress commands as ajax-request and get the response token

Cognito unable to signup users that have unconfirmed status already

A Cognito User Pool is configured for the users to use their "email address" to sign up and sign in.
If a user signs up with the email of someone else then that email will get stuck in UNCONFIRMED state and the owner will not be able to use it appropriately.
Having said that let me provide an example with the following scenario:
User signs in with an email address the user doesn't own, let's say it is someone#mail.com. In this step (registration form) some more data is sent like organization name, and user full name.
Verification code is sent to the email
Now the user that owns someone#email.com wants to create an account (maybe some days in the future), so he goes and fills the registration form but an error is thrown by cognito {"__type":"UsernameExistsException","message":"An account with the given email already exists."}
Thinks to consider:
* If the email already exists but is in unconfirmed state then provide the user the option to resend the link. This option is not optimal because additional data might be already in the user profile as the 1st step exemplifies.
* A custom lambda can be done to delete the unconfirmed user before signup or as a maintenance process every day, but I am not sure if this is the best approach.
There is also this configuration under Policies in cognito consol: "How quickly should user accounts created by administrators expire if not used?", but as he name implies this setting will only apply to users if they are invited by admins.
Is there a proper solution for this predicament?
Amazon Cognito has provided pre-signup triggers for these functionality and auto signup also.Your thought is the same way as i have implemented that according to the cognito documentations.
Here I am using the amplify/cli which is the toolchain for my development purpose hence the lambda function used in the trigger is as below:
`
"use strict";
console.log("Loading function");
var AWS = require("aws-sdk"),
uuid = require("uuid");
var cognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider();
exports.handler = (event, context, callback) => {
const modifiedEvent = event;
// check that we're acting on the right trigger
if (event.triggerSource === "PreSignUp_SignUp") {
var params = {
UserPoolId: event.userPoolId,
Username: event.userName
};
cognitoIdentityServiceProvider.adminGetUser(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} // an error occurred
else {
console.log("cognito service", data);
if (data.UserStatus == "UNCONFIRMED") {
cognitoIdentityServiceProvider.adminDeleteUser(params, function(
err,
data
) {
if (err) console.log(err, err.stack);
// an error occurred
else console.log("Unconfirmed user delete successful ");
// successful response
});
}
// successful response
}
});
return;
}
// Throw an error if invoked from the wrong trigger
callback('Misconfigured Cognito Trigger '+ event.triggerSource);
};
`
this will actually check and delete if the status is UNCONFIRMED using the aws-sdk methods adminGetUser and adminDeleteUser
hope this will help ;)
I got around this by setting ForceAliasCreation=True. This would allow the real email owner to confirm their account. The draw back is that you end up with 2 users. One CONFIRMED user and another UNCONFIRMED user.
To clean this up, I have a lambda function that calls list-users with filter for unconfirmed user and delete the accounts which were created before a certain period. This function is triggered daily by CloudWatch.
change to confirm from unconfirm:
aws cognito-idp admin-confirm-sign-up \
--user-pool-id %aws_user_pools_web_client_id% \
--username %email_address%