Skip to content

Instantly share code, notes, and snippets.

@nosvalds
Last active October 18, 2020 13:41
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 nosvalds/bb023e1a993918c4f4fd86b19fb5e81e to your computer and use it in GitHub Desktop.
Save nosvalds/bb023e1a993918c4f4fd86b19fb5e81e to your computer and use it in GitHub Desktop.
Function to set a users existing un-used password reset tokens to used
const table = process.env.USERS_TABLE;
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB.DocumentClient();
/**
* Set a user's existing un-used reset tokens to used
* @param {object} user user object
*/
const expirePasswordTokens = async (user) => {
if (!user) throw new Error(`"user" is required`);
if (!user.password_reset_tokens) return true // if the user has no tokens we don't need to do anything
let updated_tokens = {...user.password_reset_tokens}; // make copy
// loop through tokens and update unused tokens to used
Object.keys(user.password_reset_tokens).forEach((tokenStr) => {
if (user.password_reset_tokens[tokenStr].used === false) {
updated_tokens[tokenStr].used = true
}
})
// prepare params to update User with new password_reset_tokens item
const params = {
TableName: table,
Key: {
email: user.email
},
UpdateExpression: "set password_reset_tokens=:v",
ExpressionAttributeValues: { ":v": updated_tokens },
ReturnValues: "ALL_NEW"
};
// use DynamoDB.DocumentClient to update
await dynamodb.update(params).promise();
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment