使用EJS护照有条件地渲染导航栏

时间:2019-06-22 10:42:56

标签: javascript express mongoose passport.js ejs

我正在尝试动态渲染导航栏,我正在使用ejs和通行证,我遇到的问题是它一直在说用户未定义,但是在尝试req.isAuthenticated以及后我仍然不知道该怎么办呈现中用户的req.user。我将它们呈现在管理控制器中,但我将发布admin和auth控制器,以及app.js

navigation.ejs

<% if (!user) { %>

<ul>
    <li><a href="/">home</a></li>
    <li><a href="/signup">signup</a></li>
    <li><a href="/login">login</a></li>
</ul>



<% } else { %>

<ul>
    <li><a href="/">posts</a> </li>
    <li><a href="/myposts">myposts</a> </li>
    <li><a href="/createpost">createpost</a></li>
    <li>
        <form action="/logout" method="post">
            <input type="hidden" name="_csrf" value="<%= csrfToken %>">
            <button type="submit">Logout</button>
        </form>
    </li>
</ul>

<% } %>

Auth.js

function getErrorMessage(req) {
    const message = req.flash("error");
    if (!message.length) {
        return null;
    }
    return message[0];
}

exports.getLoginPage = (req, res) => {
    res.render("blog/login", {
        pageTitle: "login",
        path: "/login",
        errorMessage: getErrorMessage(req)
    });
}


exports.getsignUpPage = (req, res) => {
    res.render("blog/signup", {
        pageTitle: "signup",
        path: "/signup",
        errorMessage: getErrorMessage(req)
    });
}


exports.postLogin = (req, res) => {
    passport.authenticate("local", {
        successRedirect: "/",
        failureRedirect: "/login",
        failureFlash: true
    })

}


exports.postLogout = (req, res, next) => {
    req.logout();
    res.redirect("/")
}


exports.postSignup = (req, res, next) => {
    User.register(new User({
            username: req.body.username
        }),
        req.body.password, (err, user) => {
            if (err) {
                console.log(err);
                return res.redirect("/signup")
            } else {
                passport.authenticate("local")(req, res, () => {
                    res.redirect("/login")
                })
            }
        })
}

admin.js

    exports.getMyPostsPage = (req, res) => {
    res.render("admin/myposts", {
        path: "/myposts",
        pageTitle: "myposts",
        user: req.user
    })
}

exports.getCreatepostPage = (req, res) => {
    res.render("admin/createpost", {
        path: "/createpost",
        pageTitle: "createpost",
        user: req.user
    });
}


exports.getPostsPage = (req, res) => {
    res.render("admin/posts", {
        path: "/",
        pageTitle: "posts",
        user: req.user
    });
}

app.js

require('dotenv').config({path: "node.env"});
const path = require('path');
const express = require('express');

const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const flash = require("connect-flash");
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const passportLocalMongoose = require("passport-local-mongoose");

const session = require("express-session");
const MongoDBStore = require("connect-mongodb-session")(session);
const errorController = require('./controllers/error');

const adminRoutes = require("./routes/admin");
const blogRoutes = require("./routes/blog");
const authRoutes = require("./routes/auth");

const mongodb_uri = process.env.MONGODB_URI;
const app = express();
const csrf = require("csurf");
const User = require("./models/user");

// Store for the sessions
const store = new MongoDBStore({
    uri: mongodb_uri,
    collection: "sessions"
});

const csrfProtection = csrf();

app.use(express.static(path.join(__dirname, 'public')));

app.use(bodyParser.urlencoded({
    extended: false
}));


// template engine
app.set('view engine', 'ejs');
app.set('views', 'views');

// express session
app.use(
    session({
        secret: process.env.SECRET,
        cookie: {
            maxAge: 1000 * 60 * 60 * 24 * 7
        },
        store: store,
        resave: false,
        saveUninitialized: false,

    })
);


app.use(flash());
app.use(csrfProtection);

// passport set up 
passport.use(new LocalStrategy(
    (username, password, done) => {
        User.findOne({username: username}, (err, user) => {
            if (err) {return done(err); }
            if (!user) {
                return done (null, false, {message: "Incorrect username."})
            }
            if (!user.validPassword(password)) {
                return done(null, false, { message: "Incorrect password." })
            }
            return done(null, user);
        })
    }
))

app.use(passport.initialize());
app.use(passport.session());

passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

// Using the routes
app.use(adminRoutes);
app.use(blogRoutes);
app.use(authRoutes);


// Error Page not found
app.use(errorController.get404);


mongoose.set('useCreateIndex', true);

// connecting to the database
mongoose.connect(mongodb_uri, {
    useNewUrlParser: true
});

// connecting to localhost 3000
app.listen(3000, function () {
    console.log("listening to port 3000")
})

0 个答案:

没有答案