From 6c282c734c5d847d7a9ae2078f32cb4267a80006 Mon Sep 17 00:00:00 2001 From: Bradley Shellnut Date: Mon, 26 Apr 2021 13:14:54 -0700 Subject: [PATCH] Reset password. --- api/src/accounts/user.js | 24 ++++++++++++++++++++++++ api/src/index.js | 28 +++++++++++++++++++++++++++- 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/api/src/accounts/user.js b/api/src/accounts/user.js index b224edf..472b0e4 100644 --- a/api/src/accounts/user.js +++ b/api/src/accounts/user.js @@ -1,5 +1,7 @@ import mongo from 'mongodb' import jwt from 'jsonwebtoken' +import bcrypt from 'bcryptjs' +const { genSalt, hash } = bcrypt import { createTokens } from './tokens.js' const { ObjectId } = mongo @@ -72,4 +74,26 @@ export async function refreshTokens(sessionToken, userId, reply) { } catch (e) { console.error(e) } +} + +export async function changePassword(userId, newPassword) { + try { + const { user } = await import("../user/user.js") + // generate salt + const salt = await genSalt(10) + + // hash with salt + const hashedPassword = await hash(newPassword, salt) + + // Update user + return user.updateOne({ + _id: userId, + }, { + $set: { + password: hashedPassword, + } + }) + } catch (e) { + console.error(e) + } } \ No newline at end of file diff --git a/api/src/index.js b/api/src/index.js index 22b55a7..5921bb4 100644 --- a/api/src/index.js +++ b/api/src/index.js @@ -10,7 +10,7 @@ import { registerUser } from './accounts/register.js' import { authorizeUser } from './accounts/authorize.js' import { logUserIn } from './accounts/logUserIn.js' import { logUserOut } from './accounts/logUserOut.js' -import { getUserFromCookies } from './accounts/user.js' +import { getUserFromCookies, changePassword } from './accounts/user.js' import { sendEmail, mailInit } from './mail/index.js' import { createVerifyEmailLink, validateVerifyEmail } from './accounts/verify.js' @@ -89,6 +89,32 @@ async function startApp() { } }) + app.post('/api/change-password', {}, async (request, reply) => { + try { + const { oldPassword, newPassword } = request.body + // Verify user login + const user = await getUserFromCookies(request, reply) + if (user?.email?.address) { + // Compare current logged in user with form to re-auth + const { isAuthorized, userId } = await authorizeUser( + user.email.address, + oldPassword + ) + console.log('isAuthorized, userId', isAuthorized, userId) + // If user is who they say they are + if (isAuthorized) { + // Update password in DB + await changePassword(userId, newPassword) + return reply.code(200).send('All Good') + } + } + return reply.code(401).send() + } catch (e) { + console.error('e', e); + return reply.code(401).send() + } + }) + app.post('/api/verify', {}, async (request, reply) => { try { const { token, email } = request.body