登入


程式在登入流程時做了哪些事情


用express-session來實作登入功能

先安裝

npm i express-session --save

接著引用

var session = require('express-session');
app.use(session({ secret: 'this is session' }));

實際上的使用方式

app.post('/login', function (req, res) {

    var user;
    //TODO 用req.body.username去lowdb找資料回傳給user 

    if (user) {

        if (user.password == req.body.password) {
            delete user.password;
            req.session.user = user;
            /* TODO 回傳登入成功 */
        } else { 
            /*TODO 回傳密碼錯誤*/
        }

    } else { /*TODO 回傳此帳號不存在*/ }

});

登出的實作方式


app.get('/logout', function (req, res) {

    //刪除session
    delete req.session.user;

    res.redirect('/login');
});

正解


app.post('/login', function (req, res) {

    var user =
        db.get('users')
            .find({ username: req.body.username })
            .value();

    if (user) {
        //有使用者資料,檢查輸入的密碼是否正確
        if (user.password == req.body.password) {

            // delete user.password
            req.session.user = user;

            res.send({
                code: 200,
                msg: "login successfully"
            });
        } else {
            res.send({
                code: 400,
                msg: "password is wrong"
            });
        }
    } else {
        //此使用者不存在
        res.send({
            code: 404,
            msg: "username is not existed",
        });
    }

});

app.get('/', function (req, res) {
    if (!req.session.user) {
        res.redirect("/login");
    } else {
        res.render('index', { user: req.session.user });
    }
});


app.get('/logout', function (req, res) {
    delete req.session.user;
    res.redirect('/login');
});

results matching ""

    No results matching ""