Cognito forget password function is not check user existence? - amazon-web-services

Here is my code
import { Auth } from 'aws-amplify';
function forgotPassword() {
Auth.forgotPassword(phoneNumber)
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err);
});
}
function forgotPasswordSubmit() {
Auth.forgotPasswordSubmit(
phoneNumber,
code,
password
)
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err);
});
}
I am using Auth.forgotPassword from amplify sdk. When I submit phone number that is not existed in Cognito, Auth.forgotPassword function will not throw any error. I wonder if this function will check user existence? If not, any other method I can use to check it?
Thanks.

Related

Get user's phone number from google people api?

Can I get the phone number of a user using People API? If not is there any other API that I can use to get a user's phone number? I can't seem to find a anything on that.
below code is what I've tried
First I signIn using auth2.
useEffect(() => {
console.log("window: ", window);
window.gapi.load("client:auth2", initClient);
}, []);
const initClient = () => {
window.gapi.auth2.init({
client_id: "CLIENT_ID",
});
authenticate().then(loadClient);
};
const authenticate = () => {
return window.gapi.auth2
.getAuthInstance()
.signIn({
scope:
"https://www.googleapis.com/auth/contacts
https://www.googleapis.com/auth/contacts.readonly
https://www.googleapis.com/auth/directory.readonly
https://www.googleapis.com/auth/user.addresses.read
https://www.googleapis.com/auth/user.birthday.read
https://www.googleapis.com/auth/user.emails.read
https://www.googleapis.com/auth/user.gender.read
https://www.googleapis.com/auth/user.organization.read
https://www.googleapis.com/auth/user.phonenumbers.read
https://www.googleapis.com/auth/userinfo.email
https://www.googleapis.com/auth/userinfo.profile",
})
.then(
(response) => {
console.log("sign in successful: ", response);
},
(err) => {
console.log("error signing in: ", err);
}
);
};
Then I load the client using.
const loadClient = () => {
window.gapi.client.setApiKey("API_KEY");
return window.gapi.client
.load("https://people.googleapis.com/$discovery/rest?version=v1")
.then(
() => {
console.log("GAPI client loaded for api");
},
(err) => {
console.log("error loading GAPI client for api: ", err);
}
);
};
Finally I execute this request to people api to get the info.
I can get the name and email address of the logged in user but I am not getting phone number.
const execute = () => {
return window.gapi.client.people.people
.get({
resourceName: "people/me",
personFields: "names,emailAddresses,phoneNumbers",
})
.then(
(response) => {
console.log("people response: ", response);
},
(err) => {
console.log("people err: ", err);
}
);
};
You will need the user.phonenumbers scope. From the OAuth 2.0 Scopes section:
View your/current user phone numbers
https://www.googleapis.com/auth/user.phonenumbers.read
You can then use people.get("people/me") with personFields="phoneNumbers" to get a Person instance with the phoneNumbers field populated.

Error after firebase authentication using facebook

I'm trying to authenticate user using facebook through firebase:
Login
but getting [object Object] error:
Loginfailed
My code for login is:
facebookLogin(): void {
this.fb.login(['email']).then( (response) => {
const facebookCredential = firebase.auth.FacebookAuthProvider
.credential(response.authResponse.accessToken);
firebase.auth().signInWithCredential(facebookCredential)
.then((success) => {
alert("Firebase success: ");
this.userProfile = success;
})
.catch((error) => {
alert(error);
});
}).catch((error) => {alert(error); });
}
All of the documentation I see requests both the email and the public_profile in the login function, perhaps this is the error.
this.fb.login(['email', 'public_profile']).then( (response) => {

Testing vuex action that contains an async

[This is a Vue app, using Vuex, created with vue-cli, using mocha, chai, karma, sinon]
I'm trying to create tests for my vuex state and I DON'T want to use a mock -- one of my big goals for these tests is to also test the API that data is coming from.
I am trying to follow the docs for chai-as-promised.
This is a simplification of the vuex action I'm trying to test:
const actions = {
login: (context, payload) => {
context.commit('setFlashMessage', "");
axios.get("https://first-api-call")
.then((response) => {
axios.post("https://second-api-call")
.then((response) => {
router.push({ name: "Home"});
context.commit('setFlashMessage', "Logged in successfully");
context.commit('setLogin', response.data);
});
},
Notice that the login action has two promises and doesn't return anything. The login action does two things: it sets some state and it changes the route.
The example that I've seen that using chai-as-promised expects that the promise is returned. That is:
var result = systemUnderTest();
return expect(result).to.eventually.equal(blah);
But in my case, login() doesn't return anything, and I'm not sure what I would return if it did.
This is what I have so far:
import store from '#/src/store/store'
describe('login', () => {
it('bad input', () => {
store.login({ username: "abcd", password: ""});
// What is the test I should use?
}
}
I would return the login response message and make two tests. One to make sure that invalid credentials return a failure message and one to make sure that valid credentials login successfully
My co-worker and I came up with the solution:
The vuex action needs to return the promise, and they can be chained together:
login: (context, payload) => {
context.commit('setFlashMessage', "");
return axios.get("https://first-api-call")
.then((response) => {
return axios.post("https://second-api-call")
})
.then((response) => {
// etc...
router.push({ name: "Home"});
context.commit('setFlashMessage', "Logged in successfully");
context.commit('setLogin', response.data);
return {status: "success"};
});
},
Then we didn't need chai-as-promised because the test looks like this:
it('bad password', () => {
const result = store.dispatch("login", { username: userName, password: password + "bad" });
return result.then((response) => {
expect(response).to.deep.equal({ status: "failed"});
store.getters.getFlashMessage.should.equal("Error logging in");
});
});

Testing catch block via jest mock

I'm trying to test the 'catch' block of an async redux action via jest, but throwing a catch in the mock causes the test as a whole to fail.
My action is as follows:
export function loginUser(username, password) {
return async dispatch => {
dispatch({type: UPDATE_IN_PROGRESS});
try {
let response = await MyRequest.postAsync(
'/login', {username: username, password: password}
);
dispatch({
type: USER_AUTHENTICATED,
username: response.username,
token: response.token,
role: response.role,
id: response.id
});
} catch (error) {
dispatch({type: USER_SIGNED_OUT});
throw error;
} finally {
dispatch({type: UPDATE_COMPLETE});
}
};
}
The test is trying to mock up 'MyRequest.postAsync' to throw an error and thus trigger the catch block, but the test just bails with a 'Failed' message
it('calls expected actions when failed log in', async() => {
MyRequest.postAsync = jest.fn(() => {
throw 'error';
});
let expectedActions = [
{type: UPDATE_IN_PROGRESS},
{type: USER_SIGNED_OUT},
{type: UPDATE_COMPLETE}
];
await store.dispatch(userActions.loginUser('foo', 'bar'));
expect(store.getActions()).toEqual(expectedActions);
});
Is there a way to trigger the catch block to execute in my test via a jest mock function (or any other way for that matter)? Would be annoying to not be able to test a large chunk of code (as all my requests work in the same way).
Thanks in advance for help with this.
I don't know if it's still relevant, but you can do it in this way:
it('tests error with async/await', async () => {
expect.assertions(1);
try {
await store.dispatch(userActions.loginUser('foo', 'bar'));
} catch (e) {
expect(e).toEqual({
error: 'error',
});
}
});
Here is a documentation about error handling
I had the same issue. For me the below works. Wrapping up the await with a try/catch
it('calls expected actions when failed log in', async() => {
MyRequest.postAsync = jest.fn(() => {
throw 'error';
});
let expectedActions = [
{type: UPDATE_IN_PROGRESS},
{type: USER_SIGNED_OUT},
{type: UPDATE_COMPLETE}
];
try {
await store.dispatch(userActions.loginUser('foo', 'bar'));
} catch(e) {
expect(store.getActions()).toEqual(expectedActions);
}
});
I set the instance variable which we will access in our testing function to undefined so that it will go to catch block.
PS : This might not be possible all the times as we might not be having variables all time
class APIStore {
async fetchProductsAPI() {
try {
const products = networkManager.fetch('products')
this.productsStore.setProducts(prodcuts)
}
catch(e) {
this.apiStatus = API_FAILED
this.apiError = e
}
}
}
Test case
it('Check API Error ', async () => {
const toCheckErrorStore = new APIStore()
// Setting products store to undefined so that execution goes to catch block
toCheckErrorStore.productsStore = undefined
await toCheckErrorStore.fetchProductsAPI()
expect(toCheckErrorStore.apiStatus).toBe(API_FAILED)
expect(toCheckErrorStore.apiError).toEqual(errorObjectIWantToCompareWith)
}

How do you test Collection.allow( ) functions that rely on the user ID?

Given the following collection and access control defintion
class TasksCollection extends Mongo.Collection {
insert (task, callback) {
const doc = _.extend({}, task, {
createdOn: new Date(),
owner: this.userId
})
super.insert(doc, callback)
}
}
export const Tasks = new TasksCollection('tasks')
// Simple checks to ensure that the user is logged in before making changes.
Tasks.allow({
insert: (userId, doc) =>=> !!userId,
update: (userId, doc, fields, modifier) => !!userId,
remove: (userId, doc) => !!userId
})
How would you test to ensure that it works using Mocha/Chai/Sinon? This is what I have tried.
import { Meteor } from 'meteor/meteor'
import { resetDatabase } from 'meteor/xolvio:cleaner';
import { assert, expect } from 'chai'
import { Tasks } from '/imports/api/tasks'
import sinon from 'sinon'
describe('collection test', () => {
beforeEach(() => {
resetDatabase()
})
it('can see a collection', () => {
assert(Tasks, 'unable to see sample collection')
})
it('can query an empty collection', () => {
expect(Tasks.find({}).fetch()).to.be.empty
})
it('fails to add to a collection when the user is not logged in', (done) => {
expect(Tasks.find({}).fetch()).to.be.empty
Tasks.insert({
text: 'hello world'
}, (error) => {
console.log('expected', error) // this is also a 404
assert(error)
done()
})
})
describe('logged in', () => {
let sandbox
beforeEach(() => {
sandbox = sinon.sandbox.create()
sandbox.stub(Meteor, 'userId').returns(42)
})
afterEach(() => {
sandbox.restore()
})
it('can add to a collection', (done) => {
expect(Tasks.find({}).fetch()).to.be.empty
Tasks.insert({
text: 'hello world'
}, (error, _id) => {
console.log(error)
assert(!error)
const results = Tasks.find({}).fetch()
expect(results).to.have.lengthOf(1)
expect(results[0].defaultValue).to.equal(42)
expect(results[0]._id).to.equal(_id)
expect(results[0].createdOn).to.not.be.undefined
done()
})
})
})
})
UPDATE: But I get a 404 error when calling the server.
The insecure package is already removed.
UPDATE: I am only testing on the client for now as the authorization can only be done from a client call.