Changed login to store session tokens in cookies rather than localstorage
This commit is contained in:
@ -19,7 +19,26 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
return NextResponse.json(data);
|
||||
|
||||
// Create a response to send back to the client
|
||||
const response = NextResponse.json(data);
|
||||
|
||||
// Set tokens as HTTP-only cookies
|
||||
response.cookies.set('access_token', data.access_token, {
|
||||
httpOnly: true,
|
||||
sameSite: 'strict',
|
||||
maxAge: 60 * 60, // 1 hour
|
||||
path: '/',
|
||||
});
|
||||
|
||||
response.cookies.set('session_token', data.session_token, {
|
||||
httpOnly: true,
|
||||
sameSite: 'strict',
|
||||
maxAge: 12 * 60 * 60, // 12 hours
|
||||
path: '/',
|
||||
});
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
|
||||
}
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation'; // Use next/navigation for App Router
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
export default function LoginPage() {
|
||||
const [email, setEmail] = useState(''); // Accept email
|
||||
@ -26,11 +26,20 @@ export default function LoginPage() {
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
localStorage.setItem('access_token', data.access_token); // Store the access token
|
||||
router.push('/'); // Redirect on successful login
|
||||
|
||||
// Store access_token in localStorage or sessionStorage
|
||||
localStorage.setItem('access_token', data.access_token);
|
||||
|
||||
// Optionally, store session token if you're not using cookies for it
|
||||
if (data.session_token) {
|
||||
localStorage.setItem('session_token', data.session_token);
|
||||
}
|
||||
|
||||
// Redirect to homepage or dashboard after login
|
||||
router.push('/');
|
||||
} else {
|
||||
const errorData = await res.json();
|
||||
setError(errorData.detail || 'Login failed');
|
||||
setError(errorData.error || 'Login failed');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('An unexpected error occurred.');
|
||||
@ -59,4 +68,4 @@ export default function LoginPage() {
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user