UNPKG

@gp_jcisneros/aws-utils

Version:

AWS SDK utilities for GreenPay microservices

494 lines (439 loc) 13.9 kB
const { CognitoIdentityProviderClient, SignUpCommand, InitiateAuthCommand, AuthFlowType, ConfirmSignUpCommand, ForgotPasswordCommand, ConfirmForgotPasswordCommand, RevokeTokenCommand, CreateGroupCommand, DeleteGroupCommand, ChangePasswordCommand, AdminAddUserToGroupCommand, AdminRemoveUserFromGroupCommand, AdminDeleteUserCommand, } = require('@aws-sdk/client-cognito-identity-provider'); const { AWSError, IntegrationError } = require('@gp_jcisneros/errors'); /** * Utilities for AWS Cognito operations */ class CognitoUtils { constructor(region = process.env.AWS_REGION || 'us-east-1') { this.client = new CognitoIdentityProviderClient({ region }); } /** * Login to Cognito * @param {string} username - Username * @param {string} password - Password * @param {Object} poolData - Pool data * @returns {Promise<Object>} - Cognito response */ async login(username, password, poolData) { try { const command = new InitiateAuthCommand({ AuthFlow: AuthFlowType.USER_PASSWORD_AUTH, ClientId: poolData.ClientId, AuthParameters: { USERNAME: username, PASSWORD: password, SECRET_HASH: poolData.SecretHash, }, }); return await this.client.send(command); } catch (error) { // Si ya es un error personalizado, lo relanzamos if (error instanceof AWSError || error instanceof IntegrationError) { throw error; } throw new AWSError( `Failed to login: ${error.message}`, 'COGNITO', 'LOGIN_ERROR' ); } } /** * Sign up to Cognito * @param {string} username - Username * @param {string} password - Password * @param {Object} poolData - Pool data * @param {Object} userAttributes - User attributes * @returns {Promise<Object>} - Cognito response */ async signUp(username, password, poolData, userAttributes) { try { const command = new SignUpCommand({ ClientId: poolData.ClientId, Username: username, Password: password, SecretHash: poolData.SecretHash, UserAttributes: userAttributes, }); return await this.client.send(command); } catch (error) { // Si ya es un error personalizado, lo relanzamos if (error instanceof AWSError || error instanceof IntegrationError) { throw error; } throw new AWSError( `Failed to sign up: ${error.message}`, 'COGNITO', 'SIGN_UP_ERROR' ); } } /** * Verify a user * @param {string} username - Username * @param {string} code - Code * @param {Object} poolData - Pool data * @returns {Promise<Object>} - Cognito response */ async verify(username, code, poolData) { try { const command = new ConfirmSignUpCommand({ Username: username, ClientId: poolData.ClientId, SecretHash: poolData.SecretHash, ConfirmationCode: code, }); return await this.client.send(command); } catch (error) { // Si ya es un error personalizado, lo relanzamos if (error instanceof AWSError || error instanceof IntegrationError) { throw error; } throw new AWSError( `Failed to verify: ${error.message}`, 'COGNITO', 'VERIFY_ERROR' ); } } /** * Forgot password * @param {string} username - Username * @param {Object} poolData - Pool data * @returns {Promise<Object>} - Cognito response */ async forgotPassword(username, poolData) { try { const command = new ForgotPasswordCommand({ ClientId: poolData.ClientId, SecretHash: poolData.SecretHash, Username: username, }); return await this.client.send(command); } catch (error) { // Si ya es un error personalizado, lo relanzamos if (error instanceof AWSError || error instanceof IntegrationError) { throw error; } throw new AWSError( `Failed to forgot password: ${error.message}`, 'COGNITO', 'FORGOT_PASSWORD_ERROR' ); } } /** * Confirm password * @param {string} username - Username * @param {string} code - Code * @param {string} newPassword - New password * @param {Object} poolData - Pool data * @returns {Promise<Object>} - Cognito response */ async confirmPassword(username, code, newPassword, poolData) { try { const command = new ConfirmForgotPasswordCommand({ ClientId: poolData.ClientId, SecretHash: poolData.SecretHash, Username: username, ConfirmationCode: code, Password: newPassword, }); return await this.client.send(command); } catch (error) { // Si ya es un error personalizado, lo relanzamos if (error instanceof AWSError || error instanceof IntegrationError) { throw error; } throw new AWSError( `Failed to confirm password: ${error.message}`, 'COGNITO', 'CONFIRM_PASSWORD_ERROR' ); } } /** * Refresh token command * @param {string} username - Username * @param {string} refreshToken - Refresh token * @param {Object} poolData - Pool data * @returns {Promise<Object>} - Cognito response */ async refreshToken(username, refreshToken, poolData) { try { const command = new InitiateAuthCommand({ AuthFlow: AuthFlowType.REFRESH_TOKEN_AUTH, ClientId: poolData.ClientId, AuthParameters: { USERNAME: username, REFRESH_TOKEN: refreshToken, SECRET_HASH: poolData.SecretHash, }, }); return await this.client.send(command); } catch (error) { // Si ya es un error personalizado, lo relanzamos if (error instanceof AWSError || error instanceof IntegrationError) { throw error; } throw new AWSError( `Failed to refresh token: ${error.message}`, 'COGNITO', 'REFRESH_TOKEN_ERROR' ); } } /** * Revoke token command * @param {string} token - Token * @param {Object} poolData - Pool data * @returns {Promise<Object>} - Cognito response */ async revokeToken(token, poolData) { try { const command = new RevokeTokenCommand({ Token: token, ClientId: poolData.ClientId, SecretHash: poolData.SecretHash, }); return await this.client.send(command); } catch (error) { // Si ya es un error personalizado, lo relanzamos if (error instanceof AWSError || error instanceof IntegrationError) { throw error; } throw new AWSError( `Failed to revoke token: ${error.message}`, 'COGNITO', 'REVOKE_TOKEN_ERROR' ); } } /** * Change password command * @param {string} accessToken - Access token * @param {string} oldPassword - Old password * @param {string} newPassword - New password * @returns {Promise<Object>} - Cognito response */ async changePassword(accessToken, oldPassword, newPassword) { try { const command = new ChangePasswordCommand({ AccessToken: accessToken, PreviousPassword: oldPassword, ProposedPassword: newPassword, }); return await this.client.send(command); } catch (error) { // Si ya es un error personalizado, lo relanzamos if (error instanceof AWSError || error instanceof IntegrationError) { throw error; } throw new AWSError( `Failed to change password: ${error.message}`, 'COGNITO', 'CHANGE_PASSWORD_ERROR' ); } } /** * Admin add user to group command * @param {string} username - Username * @param {string} groupName - Group name * @param {Object} poolData - Pool data * @returns {Promise<Object>} - Cognito response */ async adminAddUserToGroup(username, groupName, poolData) { try { const command = new AdminAddUserToGroupCommand({ UserPoolId: poolData.UserPoolId, Username: username, GroupName: groupName, }); return await this.client.send(command); } catch (error) { // Si ya es un error personalizado, lo relanzamos if (error instanceof AWSError || error instanceof IntegrationError) { throw error; } throw new AWSError( `Failed to add user to group: ${error.message}`, 'COGNITO', 'ADMIN_ADD_USER_TO_GROUP_ERROR' ); } } /** * Admin remove user from group command * @param {string} username - Username * @param {string} groupName - Group name * @param {Object} poolData - Pool data * @returns {Promise<Object>} - Cognito response */ async adminRemoveUserFromGroup(username, groupName, poolData) { try { const command = new AdminRemoveUserFromGroupCommand({ UserPoolId: poolData.UserPoolId, Username: username, GroupName: groupName, }); return await this.client.send(command); } catch (error) { // Si ya es un error personalizado, lo relanzamos if (error instanceof AWSError || error instanceof IntegrationError) { throw error; } throw new AWSError( `Failed to remove user from group: ${error.message}`, 'COGNITO', 'ADMIN_REMOVE_USER_FROM_GROUP_ERROR' ); } } /** * Add a group to the pool * @param {string} groupName - Group name * @param {string} description - Description * @param {Object} poolData - Pool data * @returns {Promise<Object>} - Cognito response */ async addGroupPool(groupName, description, poolData) { try { const command = new CreateGroupCommand({ GroupName: groupName, UserPoolId: poolData.UserPoolId, Description: description, }); return await this.client.send(command); } catch (error) { // Si ya es un error personalizado, lo relanzamos if (error instanceof AWSError || error instanceof IntegrationError) { throw error; } throw new AWSError( `Failed to add group to pool: ${error.message}`, 'COGNITO', 'ADD_GROUP_POOL_ERROR' ); } } /** * Delete a group from the pool * @param {string} groupName - Group name * @param {Object} poolData - Pool data * @returns {Promise<Object>} - Cognito response */ async deleteGroupPool(groupName, poolData) { try { const command = new DeleteGroupCommand({ GroupName: groupName, UserPoolId: poolData.UserPoolId, }); return await this.client.send(command); } catch (error) { // Si ya es un error personalizado, lo relanzamos if (error instanceof AWSError || error instanceof IntegrationError) { throw error; } throw new AWSError( `Failed to delete group from pool: ${error.message}`, 'COGNITO', 'DELETE_GROUP_POOL_ERROR' ); } } /** * Delete a user from the pool * @param {string} username - Username * @param {Object} poolData - Pool data * @returns {Promise<Object>} - Cognito response */ async deleteUserPool(username, poolData) { try { const command = new AdminDeleteUserCommand({ UserPoolId: poolData.UserPoolId, Username: username, }); return await this.client.send(command); } catch (error) { // Si ya es un error personalizado, lo relanzamos if (error instanceof AWSError || error instanceof IntegrationError) { throw error; } throw new AWSError( `Failed to delete user from pool: ${error.message}`, 'COGNITO', 'DELETE_USER_POOL_ERROR' ); } } // Static methods for convenience static async login(username, password, poolData) { const utils = new CognitoUtils(); return utils.login(username, password, poolData); } static async signUp(username, password, poolData) { const utils = new CognitoUtils(); return utils.signUp(username, password, poolData); } static async verify(username, code, poolData) { const utils = new CognitoUtils(); return utils.verify(username, code, poolData); } static async forgotPassword(username, poolData) { const utils = new CognitoUtils(); return utils.forgotPassword(username, poolData); } static async confirmPassword(username, code, newPassword, poolData) { const utils = new CognitoUtils(); return utils.confirmPassword(username, code, newPassword, poolData); } static async refreshToken(username, refreshToken, poolData) { const utils = new CognitoUtils(); return utils.refreshToken(username, refreshToken, poolData); } static async revokeToken(token, poolData) { const utils = new CognitoUtils(); return utils.revokeToken(token, poolData); } static async changePassword(accessToken, oldPassword, newPassword) { const utils = new CognitoUtils(); return utils.changePassword(accessToken, oldPassword, newPassword); } static async adminAddUserToGroup(username, groupName, poolData) { const utils = new CognitoUtils(); return utils.adminAddUserToGroup(username, groupName, poolData); } static async adminRemoveUserFromGroup(username, groupName, poolData) { const utils = new CognitoUtils(); return utils.adminRemoveUserFromGroup(username, groupName, poolData); } static async addGroupPool(groupName, description, poolData) { const utils = new CognitoUtils(); return utils.addGroupPool(groupName, description, poolData); } static async deleteGroupPool(groupName, poolData) { const utils = new CognitoUtils(); return utils.deleteGroupPool(groupName, poolData); } static async deleteUserPool(username, poolData) { const utils = new CognitoUtils(); return utils.deleteUserPool(username, poolData); } } module.exports = { CognitoUtils };