/** * 测试用:获取认证 Session * 运行方式:node scripts/test-auth.js */ const http = require('http'); const baseUrl = 'http://localhost:3000'; async function login(username, password) { return new Promise((resolve, reject) => { const postData = JSON.stringify({ username, password, }); const options = { method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData), }, }; const req = http.request(`${baseUrl}/api/auth/callback/credentials`, options, (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { // 提取 session cookie const setCookie = res.headers['set-cookie']; if (setCookie) { const sessionCookie = setCookie.find(cookie => cookie.startsWith('next-auth.session-token=') ); if (sessionCookie) { const token = sessionCookie.split(';')[0].split('=')[1]; console.log('\n✅ 登录成功!'); console.log('\nSession Token:', token); console.log('\n使用此 Token 进行 API 测试:'); console.log(`curl -H "Cookie: next-auth.session-token=${token}" http://localhost:3000/api/materials\n`); resolve(token); return; } } console.log('❌ 登录失败'); console.log('响应:', data); reject(new Error('登录失败')); }); }); req.on('error', (error) => { console.error('请求失败:', error.message); reject(error); }); req.write(postData); req.end(); }); } // 从命令行参数获取用户名和密码 const username = process.argv[2]; const password = process.argv[3]; if (!username || !password) { console.log('用法: node scripts/test-auth.js '); console.log('\n提示:请使用已存在的用户账号'); process.exit(1); } console.log(`正在登录: ${username}...`); login(username, password).catch(err => { console.error('错误:', err.message); process.exit(1); });