@@ -35,8 +35,11 @@ export function useAuth(): AuthContextType {
35
35
setError ( null ) ;
36
36
37
37
const token = getCookie ( "accessToken" ) ;
38
+
39
+ console . log ( "[Auth] 尝试获取accessToken:" , token ? "存在" : "不存在" ) ;
40
+
38
41
if ( ! token ) {
39
- console . log ( "No access token found" ) ;
42
+ console . log ( "[Auth] No access token found" ) ;
40
43
setIsLoading ( false ) ;
41
44
return ;
42
45
}
@@ -49,32 +52,33 @@ export function useAuth(): AuthContextType {
49
52
return '%' + ( '00' + c . charCodeAt ( 0 ) . toString ( 16 ) ) . slice ( - 2 ) ;
50
53
} ) . join ( '' ) ) ;
51
54
52
- console . log ( "JWT Payload:" , JSON . parse ( jsonPayload ) ) ;
55
+ console . log ( "[Auth] JWT Payload:" , JSON . parse ( jsonPayload ) ) ;
53
56
} catch ( e ) {
54
- console . error ( "Failed to decode JWT:" , e ) ;
57
+ console . error ( "[Auth] Failed to decode JWT:" , e ) ;
55
58
}
56
59
57
60
// In a real implementation, you would fetch from your API
58
61
const apiUrl = process . env . NEXT_PUBLIC_API_URL || "http://127.0.0.1:8000" ;
59
- console . log ( `Fetching user data from ${ apiUrl } /api/v1/users/me` ) ;
62
+ console . log ( `[Auth] Fetching user data from ${ apiUrl } /api/v1/users/me` ) ;
60
63
61
64
const response = await fetch ( `${ apiUrl } /api/v1/users/me` , {
62
65
headers : {
63
66
Authorization : `Bearer ${ token } ` ,
64
67
} ,
68
+ credentials : 'include' , // 包含cookies
65
69
} ) ;
66
70
67
71
if ( ! response . ok ) {
68
72
const errorText = await response . text ( ) ;
69
- console . error ( "API Error:" , response . status , errorText ) ;
73
+ console . error ( "[Auth] API Error:" , response . status , errorText ) ;
70
74
throw new Error ( `Failed to fetch user data: ${ response . status } ${ errorText } ` ) ;
71
75
}
72
76
73
77
const userData = await response . json ( ) ;
74
- console . log ( "User data fetched successfully:" , userData ) ;
78
+ console . log ( "[Auth] User data fetched successfully:" , userData ) ;
75
79
setUser ( userData ) ;
76
80
} catch ( err ) {
77
- console . error ( "Error in fetchUser:" , err ) ;
81
+ console . error ( "[Auth] Error in fetchUser:" , err ) ;
78
82
setError (
79
83
err instanceof Error ? err : new Error ( "An unknown error occurred" ) ,
80
84
) ;
@@ -98,6 +102,7 @@ export function useAuth(): AuthContextType {
98
102
"Content-Type" : "application/json" ,
99
103
} ,
100
104
body : JSON . stringify ( userData ) ,
105
+ credentials : 'include' , // 包含cookies
101
106
} ) ;
102
107
103
108
if ( ! response . ok ) {
@@ -108,7 +113,7 @@ export function useAuth(): AuthContextType {
108
113
const updatedUser = await response . json ( ) ;
109
114
setUser ( updatedUser ) ;
110
115
} catch ( err ) {
111
- console . error ( "Error in updateUser:" , err ) ;
116
+ console . error ( "[Auth] Error in updateUser:" , err ) ;
112
117
setError (
113
118
err instanceof Error ? err : new Error ( "An unknown error occurred" ) ,
114
119
) ;
@@ -117,31 +122,51 @@ export function useAuth(): AuthContextType {
117
122
} ;
118
123
119
124
const login = ( token : string ) => {
120
- // Store the token in a cookie
121
- document . cookie = `accessToken=${ token } ;path=/;max-age=${ 60 * 60 * 24 * 7 } ` ; // 7 days
122
- console . log ( "Access token stored in cookie" ) ;
123
- // Fetch user data after login
124
- fetchUser ( ) ;
125
+ try {
126
+ console . log ( "[Auth] Setting access token in cookie" ) ;
127
+
128
+ // 确保token有效
129
+ if ( ! token || token . trim ( ) === '' ) {
130
+ console . error ( "[Auth] Invalid token provided" ) ;
131
+ return ;
132
+ }
133
+
134
+ // 设置cookie,添加更多安全选项
135
+ const cookieValue = `accessToken=${ token } ;path=/;max-age=${ 60 * 60 * 24 * 7 } ` ;
136
+ document . cookie = cookieValue ;
137
+
138
+ // 验证cookie是否设置成功
139
+ const savedToken = getCookie ( "accessToken" ) ;
140
+ console . log ( "[Auth] Token saved in cookie:" , savedToken ? "成功" : "失败" ) ;
141
+
142
+ // 打印所有的cookie以便调试
143
+ console . log ( "[Auth] Current cookies:" , document . cookie ) ;
144
+
145
+ // Fetch user data after login
146
+ fetchUser ( ) ;
147
+ } catch ( error ) {
148
+ console . error ( "[Auth] Error setting token in cookie:" , error ) ;
149
+ }
125
150
} ;
126
151
127
152
const logout = ( ) => {
128
153
// Clear the token
129
154
document . cookie = "accessToken=;path=/;max-age=0" ;
130
- console . log ( "Access token cleared" ) ;
155
+ console . log ( "[Auth] Access token cleared" ) ;
131
156
// Reset user
132
157
setUser ( null ) ;
133
158
// Redirect to login page
134
159
router . push ( "/login" ) ;
135
160
} ;
136
161
137
162
useEffect ( ( ) => {
138
- console . log ( "Auth hook mounted, checking for token" ) ;
163
+ console . log ( "[Auth] Auth hook mounted, checking for token" ) ;
139
164
const token = getCookie ( "accessToken" ) ;
140
165
if ( token ) {
141
- console . log ( "Token found, fetching user" ) ;
166
+ console . log ( "[Auth] Token found, fetching user" ) ;
142
167
fetchUser ( ) ;
143
168
} else {
144
- console . log ( "No token found" ) ;
169
+ console . log ( "[Auth] No token found" ) ;
145
170
setIsLoading ( false ) ;
146
171
}
147
172
} , [ ] ) ;
@@ -158,12 +183,24 @@ export function useAuth(): AuthContextType {
158
183
159
184
// Helper to get cookie value on client side
160
185
function getCookie ( name : string ) : string | undefined {
161
- if ( typeof document === "undefined" ) return undefined ;
186
+ if ( typeof document === "undefined" ) {
187
+ console . log ( "[Auth] getCookie: document is undefined (server side)" ) ;
188
+ return undefined ;
189
+ }
162
190
163
- const value = `; ${ document . cookie } ` ;
164
- const parts = value . split ( `; ${ name } =` ) ;
165
- if ( parts . length === 2 ) {
166
- return parts . pop ( ) ?. split ( ";" ) . shift ( ) ;
191
+ console . log ( "[Auth] getCookie: 搜索cookie:" , name ) ;
192
+ console . log ( "[Auth] getCookie: 所有cookie:" , document . cookie ) ;
193
+
194
+ const cookies = document . cookie . split ( ';' ) ;
195
+ for ( let i = 0 ; i < cookies . length ; i ++ ) {
196
+ const cookie = cookies [ i ] . trim ( ) ;
197
+ if ( cookie . startsWith ( name + '=' ) ) {
198
+ const value = cookie . substring ( name . length + 1 ) ;
199
+ console . log ( `[Auth] getCookie: 找到 ${ name } = ${ value . substring ( 0 , 10 ) } ...` ) ;
200
+ return value ;
201
+ }
167
202
}
203
+
204
+ console . log ( `[Auth] getCookie: ${ name } 未找到` ) ;
168
205
return undefined ;
169
206
}
0 commit comments