Skip to content

Instantly share code, notes, and snippets.

@abachuk
Created December 24, 2017 05:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abachuk/30c8a9e70f4baff65f706789bac6b4b1 to your computer and use it in GitHub Desktop.
Save abachuk/30c8a9e70f4baff65f706789bac6b4b1 to your computer and use it in GitHub Desktop.
import AWS from 'aws-sdk';
import { CognitoUserPool, AuthenticationDetails, CognitoUser } from 'amazon-cognito-identity-js';
export default function signinHandler(body) {
const authData = JSON.parse(body);
AWS.config.region = 'us-east-1';
const authenticationDetails = {
Username: authData.username,
Password: authData.password,
};
const poolData = {
UserPoolId: 'us-east-1_xxxxx',
ClientId: 'xxxxxxxxxxxxxxxxxx'
};
const authDetails = new AuthenticationDetails(authenticationDetails);
const userPool = new CognitoUserPool(poolData);
const userData = {
Username: authData.username,
Pool: userPool,
};
const cognitoUser = new CognitoUser(userData);
return new Promise((resolve, reject) => {
cognitoUser.authenticateUser(authDetails, {
onSuccess(result) {
const response = {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
token: result.getIdToken().getJwtToken(),
authenticated: true,
}),
isBase64Encoded: false,
};
return resolve(response);
},
onFailure(error) {
const response = {
statusCode: 200,
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ error, authenticated: false }),
isBase64Encoded: false,
};
return reject(response);
},
});
});
}
exports.signin = async (event, context, callback) => {
try {
const response = await signinHandler(event.body);
callback(null, response);
} catch (error) {
callback(error);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment