How to block routing if the user has not logged in

31 Views Asked by At

I'm currently working on a svelte project using express, with a login page. I wanted to make that if the user has not logged in, he will be redirected to the /login until he logs in. If the user has logged in, he can see the /home or every other page. Here is my Login.svelte

<script>
    import { goto } from '$app/navigation';
    import { onMount } from 'svelte';

    let email = '';
    let password = '';
    async function handleLogin() {
        const response = await fetch('http://localhost:3000/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ email, password })
        });
        const data = await response.json();
        if (data.isLogged) {
            console.log('User logged in');
            goto('/home');
        } else {
            console.log('Login failed:', data.message);
        }
    }

    
</script>

This is a component where the user logs in, and the data are fetched from the API. Here is the server.js (express.js)

app.post("/api/login", function (req, res) {
    const { email, password } = req.body;
    con.query(
        `SELECT * FROM Utenti WHERE email = '${email}'`,
        function (err, result) {
            if (err) {
                res.send({ isLogged: false, message: err });
            } else {
                if (result.length === 0) {
                    res.send({ isLogged: false, message: "No user found" });
                } else {
                    const user = result[0];
                    bcrypt.compare(
                        password,
                        user.password,
                        function (err, result) {
                            if (result) {
                                res.send({
                                    isLogged: true,
                                    message: "Login successful",
                                });
                            } else {
                                res.send({
                                    isLogged: false,
                                    message: "Incorrect password",
                                });
                            }
                        }
                    );
                }
            }
        }
    );
});

And I suppose that the login must be saved inside the cookie, but I'm not sure how. And I think I need to modify my +page.server.ts which right now looks like this:

import { redirect } from "@sveltejs/kit";

export function load() {
    throw redirect(307, "/home");

}

Thanks to everyone who'll read this and will try to help me. Thanks!

0

There are 0 best solutions below