full
This commit is contained in:
58
utils/loginResponse.js
Normal file
58
utils/loginResponse.js
Normal file
@@ -0,0 +1,58 @@
|
||||
const jwt = require('jsonwebtoken')
|
||||
const { buildAuthResponse } = require('./authSteps')
|
||||
const { readTotpState } = require('./totpStore')
|
||||
|
||||
function signTemp2faToken (userId) {
|
||||
return jwt.sign(
|
||||
{ id: userId, purpose: '2fa' },
|
||||
process.env.APP_SECRET,
|
||||
{ expiresIn: '5m' }
|
||||
)
|
||||
}
|
||||
|
||||
function verifyTemp2faToken (token) {
|
||||
const decoded = jwt.verify(token, process.env.APP_SECRET)
|
||||
if (!decoded?.id || decoded.purpose !== '2fa') {
|
||||
const err = new Error('INVALID_2FA_TOKEN')
|
||||
err.code = 'INVALID_2FA_TOKEN'
|
||||
throw err
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
|
||||
function buildLoginResponse (user, token) {
|
||||
if (user?.totp_enabled && user?.totp_secret) {
|
||||
return {
|
||||
requires_2fa: true,
|
||||
temp_token: signTemp2faToken(user._id),
|
||||
message: 'کد دو مرحلهای را وارد کنید',
|
||||
}
|
||||
}
|
||||
|
||||
return buildAuthResponse(user, token)
|
||||
}
|
||||
|
||||
async function buildLoginResponseForUser (user, token) {
|
||||
try {
|
||||
const state = await readTotpState(user._id)
|
||||
|
||||
if (state?.totp_enabled && state?.totp_secret) {
|
||||
return {
|
||||
requires_2fa: true,
|
||||
temp_token: signTemp2faToken(user._id),
|
||||
message: 'کد دو مرحلهای را وارد کنید',
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[buildLoginResponseForUser] totp check failed:', error)
|
||||
}
|
||||
|
||||
return buildAuthResponse(user, token)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
signTemp2faToken,
|
||||
verifyTemp2faToken,
|
||||
buildLoginResponse,
|
||||
buildLoginResponseForUser,
|
||||
}
|
||||
Reference in New Issue
Block a user