Last active
October 18, 2020 13:41
-
-
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
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 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