35 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
			
		
		
	
	
			35 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
| //File: frontend/app/_auth/drivers/cookieDriver.js
 | |
| const API = process.env.NEXT_PUBLIC_API_BASE;
 | |
| 
 | |
| export default {
 | |
|   mode: 'cookie',
 | |
|   async login({ username, password }) {
 | |
|     const r = await fetch(`${API}/api/auth/login`, {
 | |
|       method: 'POST',
 | |
|       headers: { 'Content-Type': 'application/json' },
 | |
|       credentials: 'include',         // สำคัญสำหรับคุกกี้
 | |
|       body: JSON.stringify({ username, password })
 | |
|     });
 | |
|     if (!r.ok) throw new Error(`Login failed: ${r.status}`);
 | |
|     return true; // คุกกี้ถูกตั้งแล้วโดย backend
 | |
|   },
 | |
|   async me() {
 | |
|     const r = await fetch(`${API}/api/auth/me`, { credentials: 'include' });
 | |
|     if (!r.ok) return { ok: false };
 | |
|     return r.json();
 | |
|   },
 | |
|   async refresh() {
 | |
|     // ถ้า backend ออก access ใหม่ผ่าน refresh (ในคุกกี้) ก็เรียกได้
 | |
|     const r = await fetch(`${API}/api/auth/refresh`, {
 | |
|       method: 'POST',
 | |
|       credentials: 'include'
 | |
|     });
 | |
|     return r.ok;
 | |
|   },
 | |
|   authHeaders(h = {}) { return h; }, // คุกกี้ไม่ต้องใส่ Authorization
 | |
|   credentials() { return 'include'; },
 | |
|   async logout() {
 | |
|     await fetch(`${API}/api/auth/logout`, { method: 'POST', credentials: 'include' });
 | |
|   }
 | |
| };
 | 
