Я хочу условно визуализировать навигационную панель с помощью EJS. Я попробовал несколько вещей, но они не работали, моя цель - визуализировать навигационную панель другого типа, если пользователь вошел в систему.
Я публикую много кодов, но я очень признателен, если вы не пожалеете времени и поможете мне, я не думаю, что все коды даже необходимы, но я не хотел ничего забывать
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 session = require("express-session");
const MongoDBStore = require("connect-mongodb-session")(session);
const errorController = require('./controllers/error');
const mongodb_uri = process.env.MONGODB_URI;
const app = express();
const csrf = require("csurf");
const User = require("./models/user");
const store = new MongoDBStore({
uri: mongodb_uri,
collection: "sessions"
});
const csrfProtection = csrf();
app.set('view engine', 'ejs');
app.set('views', 'views');
const adminRoutes = require("./routes/admin");
const blogRoutes = require("./routes/blog");
const authRoutes = require("./routes/auth");
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(path.join(__dirname, 'public')));
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);
app.use((req, res, next) => {
if (!req.session.user) {
return next();
}
User.findById(req.session.user._id)
.then(user => {
if (!user) {
return next();
}
req.user = user;
next();
})
.catch(err => console.log(err));
})
app.use((req, res, next) => {
res.locals.isauthenticated = req.session.isLoggedIn;
res.locals.csrfToken = req.csrfToken();
next();
});
app.use("/admin", adminRoutes);
app.use(blogRoutes);
app.use(errorController.get404);
mongoose.set('useCreateIndex', true);
mongoose.connect(mongodb_uri, {
useNewUrlParser: true
});
app.listen(3000, function () {
console.log("listening to port 3000")
})
navigation.ejs
<% if (isAuthenticated) { %>
<ul>
<li><a href="/posts">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>
<% } else { %>
<ul>
<li><a href="/">home</a></li>
<li><a href="/signup">signup</a></li>
<li><a href="/login">login</a></li>
</ul>
<% } %>
adminjs controller
const path = require('path');
const bcrypt = require("bcryptjs");
const User = require("../models/user");
const isAuthenticated = require("../middleware/is-auth");
exports.getMyPostsPage = (req, res) => {
res.render("admin/myposts", {
path: "/myposts",
pageTitle: "myposts",
isAuthenticated: isAuthenticated
})
}
exports.getCreatepostPage = (req, res) => {
res.render("admin/createpost", {
path: "/createpost",
pageTitle: "createpost",
isAuthenticated: isAuthenticated
});
}
exports.getPostsPage = (req, res) => {
res.render("admin/posts", {
path: "/posts",
pageTitle: "posts",
isAuthenticated: isAuthenticated
});
}
auth.js
const path = require('path');
const bcrypt = require("bcryptjs");
const User = require("../models/user");
exports.postLogin = (req, res, next) => {
const {
username,
password
} = req.body;
User.findOne({
username: username
})
.then(user => {
if (!user) {
req.flash("error", "Invalid email or password.");
return res.redirect("/login");
}
bcrypt
.compare(password, user.password)
.then(doMatch => {
if (doMatch) {
req.session.isLoggedIn = true;
req.session.user = user;
return req.sesson.save(err => {
console.log(err);
res.redirect("/");
});
}
req.flash("error", "invalid email or password.");
res.redirect("/login");
})
.catch(err => {
console.log(err);
res.redirect("/login");
})
})
.catch(err => console.log);
}
exports.postLogout = (req, res, next) => {
req.session.destroy(err => {
console.log(err);
res.redirect("/");
})
}
exports.postSignup = (req, res, next) => {
const {
username,
password
} = req.body;
User.findOne({
username
})
.then(userDoc => {
if (userDoc) {
req.flash("error", "email exists already, please pick a different one.");
return res.redirect("/signup")
}
return bcrypt
.hash(password, 12)
.then(hashedPassword => {
const user = new User({
username: username,
password: password
});
return user.save();
})
.then(result => {
res.redirect("/login");
})
.catch(err => {
console.log(err);
})
})
}
является промежуточным программным обеспечением
if (!req.session.isLoggedIn) {
return res.redirect('/login');
}
next();
}```
admin.js router
```const path = require('path');
const express = require('express');
const adminController = require("../controllers/admin")
const router = express.Router();
const isAuth = require("../middleware/is-auth");
router.get("/posts", isAuth, adminController.getPostsPage);
router.get("/myposts", isAuth, adminController.getMyPostsPage);
router.get("/createpost", isAuth, adminController.getCreatepostPage);
module.exports = router;```
auth js routes
```const path = require('path');
const express = require('express');
const authController = require("../controllers/auth");
const router = express.Router();
router.post("/signup", authController.postSignup);
router.post("/login", authController.postLogin);
router.post("/logout", authController.postLogout);
module.exports = router;```