Skip to content

Instantly share code, notes, and snippets.

@guzmonne
Created June 25, 2017 14:02
Show Gist options
  • Save guzmonne/38143d1c45a17c710fc50ab067260fa8 to your computer and use it in GitHub Desktop.
Save guzmonne/38143d1c45a17c710fc50ab067260fa8 to your computer and use it in GitHub Desktop.
cognito-auth.Login-example.js
/**
* Signup function that uses AWS Cognito SDK. It wraps its API into a promise
* to consume it easily from other parts of the app.
*/
function logIn(username, password) {
var authenticationDetails = new AuthenticationDetails({
Username: username,
Password: password,
});
User = new CognitoUser({
Username: username,
Pool: UserPool,
});
return new Promise(function(resolve, reject) {
// Some of the AWS Cognito Identity functions take an object instead of
// a callback to handle success and error cases. Wrapping them with
// promises cleans up the inner workings of this library IMO.
User.authenticateUser(authenticationDetails, {
onSuccess: resolve,
onFailure: reject,
})
})
}
/**
* Function to handle the login form submit event.
* It gets the values from the inputs, handles error and success cases, and
* other UI related actions.
*/
function handleSubmit(event) {
event.preventDefault()
var $inputs = $container.getElementsByTagName('input');
// Blocks the submit button.
startLoading()
// Starts the login flow through Cognito.
Cognito.logIn($inputs.email.value, $inputs.password.value)
.then(function(result) {
addAlert({
type: 'success',
message: 'Log in successful!'
})
console.log(result)
})
.catch(function(error) {
// Unblocks the submit button
stopLoading()
// If the user needs to enter its confirmation code switch to the
// confirmation form page.
if (error.message === 'User is not confirmed.') {
EventEmitter.emit('ConfirmForm:mount', {
// We send the current user email just in case.
email: $inputs.email.value,
});
EventEmitter.emit('LoginForm:unmount');
return;
}
addAlert({
type: 'error',
message: error.message,
})
console.error(error)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment