implement password reset by code and token

This commit is contained in:
SrGooglo 2025-02-25 23:09:00 +00:00
parent e9dd362d7b
commit 74704cede0

View File

@ -1,15 +1,77 @@
import bcrypt from "bcrypt" import bcrypt from "bcrypt"
import { User, OperationLog } from "@db_models" import { User, OperationLog, PasswordRecover } from "@db_models"
import Account from "@classes/account" import Account from "@classes/account"
import AuthToken from "@shared-classes/AuthToken"
export default async ({ user_id, old_hash, old_password, new_password, log_comment }, req) => { export default async (
let user = await User.findById(user_id).select("+password") {
user_id,
old_hash,
old_password,
new_password,
code,
verificationToken,
log_comment,
},
req,
) => {
if (!code && !old_password) {
throw new OperationError(
400,
"Either code or old_password must be provided",
)
}
user = await Account.loginStrategy({ password: old_password, hash: old_hash }, user) let verificationTokenDecoded = null
if (verificationToken) {
verificationTokenDecoded =
await AuthToken.basicDecode(verificationToken)
}
let user = await User.findById(
verificationTokenDecoded.user_id || user_id,
).select("+password")
if (!user) {
throw new OperationError(404, "User not found")
}
if (code) {
const passwordRecoverSession = await PasswordRecover.findOne({ code })
if (!passwordRecoverSession) {
throw new OperationError(401, "Invalid code")
}
if (
verificationTokenDecoded.recoverySessionId !==
passwordRecoverSession._id.toString()
) {
throw new OperationError(401, "Invalid code")
}
if (passwordRecoverSession.expires < Date.now()) {
throw new OperationError(401, "Code expired")
}
// delete passwordRecoverSession
await PasswordRecover.findByIdAndDelete(
passwordRecoverSession._id.toString(),
)
} else {
user = await Account.loginStrategy(
{ password: old_password, hash: old_hash },
user,
)
}
await Account.passwordMeetPolicy(new_password) await Account.passwordMeetPolicy(new_password)
user.password = bcrypt.hashSync(new_password, parseInt(process.env.BCRYPT_ROUNDS ?? 3)) user.password = bcrypt.hashSync(
new_password,
parseInt(process.env.BCRYPT_ROUNDS ?? 3),
)
await user.save() await user.save()
@ -17,7 +79,7 @@ export default async ({ user_id, old_hash, old_password, new_password, log_comme
type: "password:changed", type: "password:changed",
user_id: user._id.toString(), user_id: user._id.toString(),
date: Date.now(), date: Date.now(),
comments: [] comments: [],
} }
if (log_comment) { if (log_comment) {
@ -25,7 +87,10 @@ export default async ({ user_id, old_hash, old_password, new_password, log_comme
} }
if (typeof req === "object") { if (typeof req === "object") {
operation.ip_address = req.headers["x-forwarded-for"]?.split(",")[0] ?? req.socket?.remoteAddress ?? req.ip operation.ip_address =
req.headers["x-forwarded-for"]?.split(",")[0] ??
req.socket?.remoteAddress ??
req.ip
operation.client = req.headers["user-agent"] operation.client = req.headers["user-agent"]
} }