Twilioapp-admin/pages/api/auth/verify-token.ts

71 lines
1.7 KiB
TypeScript
Raw Permalink Normal View History

import { NextApiRequest, NextApiResponse } from 'next';
import jwt from 'jsonwebtoken';
interface JWTPayload {
userId: string;
email: string;
userType: string;
name: string;
iat?: number;
exp?: number;
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'POST') {
return res.status(405).json({ success: false, error: '方法不允许' });
}
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({
success: false,
error: '缺少授权令牌'
});
}
const token = authHeader.substring(7); // 移除 "Bearer " 前缀
const jwtSecret = process.env.JWT_SECRET || 'your-secret-key';
try {
// 验证并解码 JWT 令牌
const decoded = jwt.verify(token, jwtSecret) as JWTPayload;
// 构造用户对象
const user = {
id: decoded.userId,
email: decoded.email,
name: decoded.name,
userType: decoded.userType,
phone: '13800138000', // 从硬编码数据中获取
avatarUrl: null
};
res.status(200).json({
success: true,
user,
valid: true
});
} catch (jwtError) {
// JWT 令牌无效或过期
console.log('JWT验证失败:', jwtError);
return res.status(401).json({
success: false,
error: '令牌无效或已过期',
valid: false
});
}
} catch (error) {
console.error('令牌验证错误:', error);
res.status(500).json({
success: false,
error: '服务器内部错误'
});
}
}