Skip to content

Instantly share code, notes, and snippets.

@saikmadana
Created July 19, 2019 09:59
Show Gist options
  • Save saikmadana/06e06ff5c7795a068098745c40e32f68 to your computer and use it in GitHub Desktop.
Save saikmadana/06e06ff5c7795a068098745c40e32f68 to your computer and use it in GitHub Desktop.
AWS Cognito: To handle cognito operations
/**
* Following is extracted from the content `https://github.com/aws-amplify/amplify-js/tree/master/packages/amazon-cognito-identity-js`
*/
import { CognitoUserPool, CognitoUser, CognitoUserAttribute, AuthenticationDetails } from 'amazon-cognito-identity-js'
export class CognitoService {
// Data of admin pool of cognito-user-pools
// TODO: need to secure these
private poolData = {
UserPoolId: "us-east-1_XXXXXXXX",
ClientId: "XXXXXXXXXXXXXXXXXXXX"
};
private userPool: CognitoUserPool = new CognitoUserPool(this.poolData);
constructor() { }
/**
* @desc To return the auth status of the current user
* @returns any (authenticated ? user data object : null)
*/
getAuthenticatedUser(): any {
return this.userPool.getCurrentUser();
}
/**
* @desc To signup user using cognito user pool
* @param {any} userData consists user's name, email, phone, password data
* @param {(data:any)=>any} callback to call after successful signup
* @returns void
*/
signup(userData: any, callback: (data: any) => any): void {
// Preparing data for signup
var attrList = [];
var dataEmail = {
Name: 'email',
Value: userData.email
};
// TODO: confirm the phone-number format
// var dataPhoneNumber = {
// Name: 'phone_number',
// Value: `+91${userData.phone}`
// };
var dataname = {
Name: 'name',
Value: userData.name
};
attrList.push(new CognitoUserAttribute(dataEmail));
// attrList.push(new CognitoUserAttribute(dataPhoneNumber));
attrList.push(new CognitoUserAttribute(dataname));
this.userPool.signUp(userData.email, userData.password, attrList, null, (err, result) => {
// If error, notifying user and asking to signup again
if (err) {
// Work on the error handling
}
// If success, callback
// Work on the success handling
})
}
/**
* @desc To signin user to the application using cognito user pool
* @param {} userData consists user's userName, password data
* @param {} callback to call after successful signin
* @returns void
*/
signin(userData, callback, confirmMail): void {
var that = this;
// Preparing data for signin
var authenticationData = {
Username: userData.email,
Password: userData.password,
};
var authdet = new AuthenticationDetails(authenticationData);
var userDetails: any = {
Username: userData.email,
Pool: this.userPool
};
var cognitoUser = new CognitoUser(userDetails);
// Making signin call
cognitoUser.authenticateUser(authdet, {
onSuccess(result) {
callback(true, result);
},
onFailure(err) {
// If user-not-confirmed error, asking for OTP confirmation which is sent to strong-user-entity(mobile/email)
if (err.code == "UserNotConfirmedException") {
// Confirmation email already sent to mail/password.
// Respective hadler need to work
} else {
// Work on the respective error
}
},
mfaRequired(res) {
// MFA
},
newPasswordRequired(res, req) {
// If a user is created by Admin, then this is triggered to give a new password as then a dummy password is created.
const attrList: CognitoUserAttribute[] = [];
// TODO: Change email to be dynamic
const emailAttribute = {
Name: "email",
Value: res.email
};
if(res.email_verified) {
delete res.email_verified;
}
if(res.phone_number_verified) {
delete res.phone_number_verified;
}
for (var property in res) {
if (res.hasOwnProperty(property) && !res[property]) {
// TODO: use custom popup
res[property] = prompt(`Enter ${property}`);
}
}
attrList.push(new CognitoUserAttribute(emailAttribute));
// TODO: use custom popup
var newPassword = prompt("Please enter your new password...", "");
cognitoUser.completeNewPasswordChallenge(newPassword, res, {
onSuccess: function (result) {
// TODO: use custom notifier
console.log("Successfully Changed Password...");
},
onFailure: function (err) {
// Use respective error handler
}
});
}
});
}
/**
* @desc To verify the user with verification code sent to his email address after successful signup
* @param {object} userDetails contains user-name of the user
*/
verify(userDetails: any, code: string, callback: (data: any)=> any) {
var that = this;
var userPool = new CognitoUserPool(this.poolData);
var userData: any = {
Username: userDetails.userName,
Pool: userPool
};
var cognitoUser = new CognitoUser(userData);
cognitoUser.confirmRegistration(code, true, function (err, res) {
if (err) {
// respective error handler
} else {
// Confirmed registration
}
});
}
/**
* @desc To Start and complete a forgot password flow for an unauthenticated user
* @param {string} username
* @returns void
*/
forgotPassword(username: string, callback: (any)=> any): void {
var that = this;
var userPool: CognitoUserPool = new CognitoUserPool(this.poolData);
var userData: any = {
Username: username,
Pool: userPool
};
var cognitoUser = new CognitoUser(userData);
cognitoUser.forgotPassword({
onSuccess: function (data) {
// successfully initiated reset password request
console.log('CodeDeliveryData from forgotPassword: ' + data);
},
onFailure: function (err) {
// Respective error handler
},
//Optional automatic callback
inputVerificationCode: function (data) {
// Reset instructions have been sent to your email, respective handler need to work
}
});
}
/**
* @desc To confirm the new password after forgot password initiation
* @param {string} code verification code
* @param {string} username user name
* @param {string} password new password
* @param {any} callback callback after successs/failure
* @returns void
*/
confirmForgotPassword(code: string, username: string, password: string, callback: any): void {
var that = this;
var userPool: CognitoUserPool = new CognitoUserPool(this.poolData);
var userData: any = {
Username: username,
Pool: userPool
};
var cognitoUser = new CognitoUser(userData);
cognitoUser.confirmPassword(code, password, {
onSuccess() {
// password confirmed
// Respective handler
},
onFailure(err) {
// Respective failure handler
}
});
}
/**
* @desc To change password of loggedin user
* @param {any} userObj
* @param {(data:any)=>any} callback
*/
changePassword(userObj: any, callback: (data:any)=> any) {
var auth = this.getAuthenticatedUser();
// To get the session
auth.getSession(function (err, session) {
if (err) {
// respective error handler
}
auth.changePassword(userObj.oldpassword, userObj.newpassword, function (err, result) {
if (err) {
// respective error handler
}
// success handler comes here
});
});
}
/**
* @desc To Resend a confirmation code via SMS for confirming registration for a unauthenticated user
* @param {string} username
* @param {(data:any)=>any} callback
* @returns void
* TODO: not tested one
*/
resendConfirmationCode(username: string, callback: (data: any)=> any): void {
var userPool = new CognitoUserPool(this.poolData);
var userData: any = {
Username: username,
Pool: userPool
};
var cognitoUser = new CognitoUser(userData);
cognitoUser.resendConfirmationCode(function(err, result) {
if (err) {
// respective error handler
}
// Success handler
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment