Skip to content

Commit 49cd11c

Browse files
committed
Fixed the problem of synchronization of home page authentication status after login: Add delay to ensure cookies take effect and optimize user status check
1 parent 30a3278 commit 49cd11c

File tree

6 files changed

+68
-21
lines changed

6 files changed

+68
-21
lines changed

app/(main)/page.tsx

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -379,24 +379,37 @@ IMPORTANT: Apart from the initial <think>...</think> block, do NOT use markdown
379379
// 获取用户信息
380380
const fetchUser = async () => {
381381
try {
382-
const response = await fetch('/api/auth/me');
382+
const response = await fetch('/api/auth/me', {
383+
credentials: 'include',
384+
cache: 'no-cache'
385+
});
383386
if (response.ok) {
384387
const userData = await response.json();
385388
setUser(userData);
389+
} else {
390+
console.log('用户未登录或登录已过期');
391+
setUser(null);
386392
}
387393
} catch (error) {
388394
console.error('获取用户信息失败:', error);
395+
setUser(null);
389396
}
390397
};
391398

392-
fetchUser();
399+
// 添加短暂延迟,确保从登录页跳转过来时 cookie 已经生效
400+
const timer = setTimeout(() => {
401+
fetchUser();
402+
}, 100);
393403

394404
// Simulate loading time
395-
const timer = setTimeout(() => {
405+
const loadingTimer = setTimeout(() => {
396406
setIsLoading(false)
397407
}, 1250)
398408

399-
return () => clearTimeout(timer)
409+
return () => {
410+
clearTimeout(timer);
411+
clearTimeout(loadingTimer);
412+
}
400413
}, [])
401414

402415
// 加载项目版本历史

components/login-form.tsx

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,10 @@ export default function LoginForm() {
1919
useEffect(() => {
2020
if (loginSuccess && redirectTo) {
2121
toast.success("Login successful");
22-
window.location.href = redirectTo;
22+
// 添加短暂延迟确保 cookie 设置生效
23+
setTimeout(() => {
24+
window.location.href = redirectTo;
25+
}, 150);
2326
}
2427
}, [loginSuccess, redirectTo, router]);
2528

lib/db.ts

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,41 @@
11
import mysql from 'mysql2/promise';
22

3-
// Check required environment variables
4-
const requiredEnvVars = ['DB_HOST', 'DB_PORT', 'DB_USER', 'DB_PASSWORD', 'DB_NAME'];
5-
for (const envVar of requiredEnvVars) {
6-
if (!process.env[envVar]) {
7-
throw new Error(`Missing required environment variable: ${envVar}`);
3+
// Check required environment variables (only when actually using the database)
4+
function checkRequiredEnvVars() {
5+
const requiredEnvVars = ['DB_HOST', 'DB_PORT', 'DB_USER', 'DB_PASSWORD', 'DB_NAME'];
6+
for (const envVar of requiredEnvVars) {
7+
if (!process.env[envVar]) {
8+
throw new Error(`Missing required environment variable: ${envVar}`);
9+
}
810
}
911
}
1012

11-
// Database connection configuration (excluding database name)
12-
const dbConfig = {
13-
host: process.env.DB_HOST,
14-
port: parseInt(process.env.DB_PORT || '3306'),
15-
user: process.env.DB_USER,
16-
password: process.env.DB_PASSWORD
17-
};
13+
// Get database connection configuration (excluding database name)
14+
function getDbConfig() {
15+
checkRequiredEnvVars();
16+
return {
17+
host: process.env.DB_HOST,
18+
port: parseInt(process.env.DB_PORT || '3306'),
19+
user: process.env.DB_USER,
20+
password: process.env.DB_PASSWORD
21+
};
22+
}
1823

19-
// Database name
20-
const DATABASE_NAME = process.env.DB_NAME;
24+
// Get database name
25+
function getDatabaseName() {
26+
checkRequiredEnvVars();
27+
return process.env.DB_NAME!;
28+
}
2129

2230
// Global connection pool instance
2331
let poolInstance: mysql.Pool | null = null;
2432

2533
// Create database and initialize tables
2634
export async function initDatabase() {
2735
try {
36+
const dbConfig = getDbConfig();
37+
const DATABASE_NAME = getDatabaseName();
38+
2839
// Create connection pool without specifying database
2940
const pool = mysql.createPool(dbConfig);
3041
const connection = await pool.getConnection();
@@ -219,6 +230,9 @@ export async function initDatabase() {
219230
// Get database connection pool (used for database operations in the application)
220231
export function getPool() {
221232
if (!poolInstance) {
233+
const dbConfig = getDbConfig();
234+
const DATABASE_NAME = getDatabaseName();
235+
222236
poolInstance = mysql.createPool({
223237
...dbConfig,
224238
database: DATABASE_NAME,

next.config.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,11 @@ const nextConfig = {
1515
serverActions: true,
1616
serverComponents: true,
1717
typedRoutes: true,
18-
// 启用新的 params 行为
19-
serverComponentsExternalPackages: ['@prisma/client', 'mysql2', 'canvas']
2018
},
2119

20+
// 将过时的配置移到新位置
21+
serverExternalPackages: ['@prisma/client', 'mysql2', 'canvas'],
22+
2223
// 配置图片处理
2324
images: {
2425
unoptimized: true, // 禁用图片优化,支持所有域名

package-lock.json

Lines changed: 15 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
"class-variance-authority": "^0.7.1",
5353
"clsx": "^2.1.1",
5454
"cmdk": "1.0.4",
55+
"coffee-script": "^1.12.7",
5556
"date-fns": "^4.1.0",
5657
"dom-to-image-more": "^3.6.0",
5758
"dotenv": "^16.5.0",

0 commit comments

Comments
 (0)