Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
69 views
in Technique[技术] by (71.8m points)

javascript - What am I doing wrong with sessions?

so Ive finally deployed my app and resolved all the CORS issues, but I have a problem with user authentification. I can log-in, but when I refresh a site I get automaticly logged out -> on all browsers beside Mozilla Firefox, there it works somehow.

userContext.js -> Front-end

    //XXX Login
const login = () => {
    Axios.post(`${apiUrl}/users/login`, {
        userName: nameLog,
        userPassword: passwordLog,
    }).then((response) => {
        console.log(response);
        if (!response.data.errors) {
            setUser(response.data.name);
            setUserId(response.data.user_id);
        } else {
            console.log(response);
            const errors = response.data.errors;
            console.log(errors);
            processErrors(errors);
        }
    });
};

//Checking if user is logged in on every refresh of a page
useEffect(() => {
    Axios.get(`${apiUrl}/users/login`).then((response, err) => {
        console.log("GET /login RESPONSE: ", response);
        if (response.data.loggedIn === true) {
            setUser(response.data.user[0].name);
            setUserId(response.data.user[0].user_id);
        }
    });
}, []);

First call is a POST request, thats when user logs in using form on my site.

And second one is a GET request, that checks if the session returns loggedIn true, this is called on every refresh of a page as it is inside useEffect hook.

Then I update my userState which acts as auth if user is allowed to do some action or not.

userRoutes.js -> Back-end

//Login user
router.post(
    "/login",
    [
        check("userName").exists().notEmpty().withMessage("Username is empty.").isAlpha().isLength({ min: 3, max: 40 }),
        check("userPassword").exists().notEmpty().withMessage("Password is empty.").isLength({ min: 3, max: 60 }).escape(),
    ],
    (req, res) => {
        const valErr = validationResult(req);
        if (!valErr.isEmpty()) {
            console.log(valErr);
            return res.send(valErr);
        }
        const name = req.body.userName;
        const password = req.body.userPassword;
        const sql = "SELECT * FROM users WHERE name = ?";
        db.query(sql, name, (err, result) => {
            if (err) throw err;
            if (!result.length > 0) {
                res.send({ errors: [{ msg: "User doesn't exist" }] });
            } else {
                //compare hashed password from front end with hashed password from DB
                bcrypt.compare(password, result[0].password, (error, match) => {
                    if (error) throw error;
                    //if passwords match send -> create session and send user data
                    if (match) {
                        req.session.user = result;
                        res.send({ user_id: result[0].user_id, name: result[0].name });
                    } else {
                        res.send({ errors: [{ msg: "Wrong username or password" }] });
                    }
                });
            }
        });
    }
);

//Checking if user is logged in and if so, sending user's data to front-end in session
router.get("/login", (req, res) => {
    console.log("GET /login SESSION: ", req.session);
    if (req.session.user) {
        res.send({ loggedIn: true, user: req.session.user });
    } else {
        res.send({ loggedIn: false });
    }
});

Again first one is for the POST request, where I create session and send it in response filled with user's data (name,id) to front-end (then I update my states accordingly).

Second one belongs to the GET request and returns false if user is not logged in or true + user's data. Then once again I update my states.

However this doesnt work and I dont know why. As I mentioned it returns loggedIn: false on every browser besides Mozzilla Firefox.

This is my first time dealing with sessions and cookies so what am I missing here?

By the way the site url is here if that helps: LINK, I left some console.logs() to display responses.

EDIT: adding all middleware

app.js -> main nodejs file

const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const cors = require("cors");
const { check, validationResult } = require("express-validator");

const userRoutes = require("./routes/userRoutes.js");
const app = express();


app.use(express.json());
app.use(
    cors({
        origin: [
            "http://localhost:3000",
            "https://todo-react-node.netlify.app",
        ],
        methods: ["GET, POST, PATCH, DELETE"],
        credentials: true, //allowing cookies
    })
);
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));

app.use((req, res, next) => {
    console.log("SESSION 2 : ", req.session);
    console.log("Cookies 2 : ", req.cookies);
    next();
});

app.use(
    session({
        key: "userID",
        secret: "subscribe",
        resave: false,
        saveUninitialized: false,
    })
);

app.use("/users", userRoutes);
question from:https://stackoverflow.com/questions/65872514/what-am-i-doing-wrong-with-sessions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your useEffect only called once if you are using [] in useEffect function.

Try to take it out(or add the suitable dependencies) and add a console.log() in that function to test out.

Furthermore, read the following article to gain some insight about useEffect.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...