Reset password.

This commit is contained in:
Bradley Shellnut 2021-04-26 13:14:54 -07:00
parent 3bc880559f
commit 6c282c734c
2 changed files with 51 additions and 1 deletions

View file

@ -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)
}
}

View file

@ -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