这是我的 auth.mjs 代码:
import jwt from 'jsonwebtoken';
export function generateToken(userInfo){
if(!userInfo) {
return null;
}
const payload = { username: userInfo.username, exp: Math.floor(Date.now() / 1000) + 30};
const secret = Buffer.from(process.env.JWT_SECRET).toString('base64');
return jwt.sign(payload, secret, {algorithm: 'HS512'});
}
export async function verifyTokens(username, token) {
console.error("Still inside verifyTokens");
try{
console.error('Inside verifyToken');
const response = await new Promise((resolve, reject) => {
jwt.verify(token, Buffer.from(process.env.JWT_SECRET.toString('base64'), {algorithm: 'HS512'}, (err, decoded) => {
if (err) {
reject (err);
} else {
resolve(decoded);
}
})
)})
if (response.username !== username) {
console.error('response.username !== username');
return {
verified: false,
message: 'invalid user'
}
}
console.error('response.username === username');
return {
verified: true,
message: 'verified'
}
} catch (error) {
console.error('Verified Tokens Error: ' + error);
throw {
verified: false,
message: 'invalid token'
}
}
}
export default generateToken;
这是我的 verify.mjs 代码:
import buildResponse from '../utils/util.mjs';
import verifyTokens from '../utils/auth.mjs';
export async function verify(requestBody) {
if(!requestBody.user || !requestBody.user.username || !requestBody.token) {
return buildResponse(401, {
verified: false,
message: 'incorrect request body'
})
}
const user = requestBody.user;
const token = requestBody.token;
try {
console.error("Verifying this token=" + token);
console.error("Verifying this user.username=" + user.username);
const verification = await verifyTokens(user.username, token);
console.error('Are we verified? verification.verified=', verification.verified);
if(!verification.verified) {
console.error("We are NOT verified! verification.verified=", verification.verified)
return await buildResponse(401, verification);
}
}
catch (error) {
console.error("Error: ", error);
}
return buildResponse(200, {
verified: true,
message: 'success',
user: user,
token: token
})
}
export default verify;
日志文件显示我进入“验证此令牌”和“验证此用户.用户名”,但日志文件从未显示“仍在 verifyTokens 内”,所以我认为它没有调用此行。
const verification = await verifyTokens(user.username, token);
在您的文件中
auth.mjs
默认导出为 generateToken
export function generateToken(userInfo) { /* ... */ }
export async function verifyTokens(username, token) { /* ... */ }
export default generateToken;
在您的文件中
verify.mjs
您没有导入verifyTokens
,您正在尝试导入默认导出
import buildResponse from '../utils/util.mjs';
import verifyTokens from '../utils/auth.mjs';
export async function verify(requestBody) {
const verification = await verifyTokens(user.username, token);
}
export default verify;
因此,您应该将其作为命名导出导入到您的
verify.mjs
模块中:
import buildResponse from '../utils/util.mjs';
import { verifyTokens } from '../utils/auth.mjs';
export async function verify(requestBody) {
const verification = await verifyTokens(user.username, token);
}