Commit d0fc8b1f authored by Anthony Jacob's avatar Anthony Jacob
Browse files

manage login differently

parent 57df19c5
Loading
Loading
Loading
Loading
+4 −14
Original line number Diff line number Diff line
@@ -2,6 +2,7 @@
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from "next/link";
import { loginAction } from './actions';

export default function LoginClient({ demo = false }: { demo?: boolean }) {
    const [username, setUsername] = useState('');
@@ -45,23 +46,12 @@ export default function LoginClient({ demo = false }: { demo?: boolean }) {
        console.log(JSON.stringify({ username, password }));

        try {
            const res = await fetch('/api/auth', {
                method: 'POST',
                body: JSON.stringify({ username, password }),
                headers: { 'Content-Type': 'application/json' },
            });
            const data = await res.json();

            if (res.ok) {
            await loginAction(username, password);
            router.push('/Admin');
            } else {
                console.error('Login failed:', res.statusText);
                setError(`Login failed. Please check your credentials and try again. ${JSON.stringify(data)}`);

            }
        } catch (error) {
            console.error('Error during login:', error);
            setError('An error occurred while trying to log in. Please try again later.');
            setError('An error occurred while trying to log in. Please check your credentials.');
        }


+38 −0
Original line number Diff line number Diff line
'use server';
import { cookies } from 'next/headers';

const API_URL = process.env.API_URL;

export async function loginAction(username: string, password: string) {
    const res = await fetch(`${API_URL}/auth/login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password }),
    });

    const data = await res.json();

    const access_token = data?.access_token;
    console.log(data);
    console.log(access_token);

    if (!data.access_token) throw new Error('Invalid credentials');

    const cookieStore = cookies();

    const isProduction = process.env.NODE_ENV === 'production';
    console.log("isProduction", isProduction);
    (await cookieStore).set("access_token", data.access_token, {
        path: "/",
        httpOnly: true,
        sameSite: "lax",
        secure: isProduction
    });
    (await cookieStore).set("refresh_token", data.refresh_token, {
        path: "/",
        httpOnly: true,
        sameSite: "lax",
        secure: isProduction
    });
    return true;
}
 No newline at end of file