Last active
October 29, 2023 16:26
-
-
Save abanobmikaeel/2426a2ef6bd763028c6143ab90f2c9d6 to your computer and use it in GitHub Desktop.
Migration Lambda from Basic Auth to Cognito
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Client } = require('pg'); | |
const AmazonCognitoIdentity = require('amazon-cognito-identity-js'); | |
exports.handler = async (event) => { | |
const { username, password } = JSON.parse(event.body); | |
// Validate credentials against PostgreSQL database | |
const postgresClient = new Client({ | |
host: process.env.RDS_HOST, | |
user: process.env.RDS_USER, | |
password: process.env.RDS_PASSWORD, | |
database: process.env.RDS_DATABASE, | |
port: process.env.RDS_PORT | |
}); | |
return new Promise((resolve, reject) => { | |
// Validate credentials against PostgreSQL database | |
postgresClient.connect(); | |
const postgresQuery = 'SELECT * FROM users WHERE username = $1 AND password = $2'; | |
const postgresValues = [username, password]; | |
postgresClient.query(postgresQuery, postgresValues, (postgresError, postgresResults) => { | |
// Add basic auth code of choice (must match your old password checking code) | |
// ON FAILURE DO NOTHING | |
// ON SUCCESS, UPDATE COGNITO USER | |
// Configuration for Amazon Cognito User Pool | |
const poolData = { | |
UserPoolId: process.env.COGNITO_USER_POOL_ID, | |
ClientId: process.env.COGNITO_CLIENT_ID | |
}; | |
const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData); | |
const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData); | |
const userData = { | |
Username: username, | |
Pool: userPool | |
}; | |
const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData); | |
cognitoUser.authenticateUser(authenticationDetails, { | |
onSuccess: (session) => { | |
// Update password in Cognito to match the database password | |
cognitoUser.changePassword(password, password, (cognitoChangePasswordError, result) => { | |
if (cognitoChangePasswordError) { | |
resolve({ | |
statusCode: 500, | |
body: JSON.stringify({ message: 'Error updating password in Cognito' }) | |
}); | |
} else { | |
resolve({ | |
statusCode: 200, | |
body: JSON.stringify({ message: 'Login successful. Password updated in Cognito.' }) | |
}); | |
} | |
}); | |
}, | |
onFailure: (cognitoError) => { | |
resolve({ | |
statusCode: 401, | |
body: JSON.stringify({ message: 'Invalid credentials or user not found in Cognito' }) | |
}); | |
} | |
}); | |
} else { | |
resolve({ | |
statusCode: 401, | |
body: JSON.stringify({ message: 'Invalid credentials' }) | |
}); | |
} | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment