const CognitoIdentityServiceProvider = require("amazon-cognito-identity-js");
// Required in order to use the cognito js library to work.
global.fetch = require("node-fetch");

/**
 * Authenticate a cognito user and return its authentication token. Use the auth token in the authorization header
 * @param callback Callback function with error as first param and the actual user token in the second param.
 */

function authenticateUser(callback) {
	console.info("Authenticating user");
	const authenticationData = {
		Username: userName,
		Password: password
	};

	const authenticationDetails = new CognitoIdentityServiceProvider.AuthenticationDetails(
		authenticationData
	);
	const poolData = {
		UserPoolId: userPoolId, // Your user pool id here
		ClientId: clientId // Your client id here
	};

	const userPool = new CognitoIdentityServiceProvider.CognitoUserPool(poolData);
	const userData = {
		Username: userName,
		Pool: userPool
	};

	const cognitoUser = new CognitoIdentityServiceProvider.CognitoUser(userData);
	cognitoUser.authenticateUser(authenticationDetails, {
		onSuccess: function(result) {
			const token = result.getIdToken().getJwtToken();
			console.info(`User token: ${token}`);
			callback(null, token);
		},
		onFailure: function(err) {
			callback(err);
		}
	});
}