Answer the question
In order to leave comments, you need to log in
How to hide the admin panel from the user?
The task is as follows on the site when registering a user in the database, I write the following:
const UserSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
role: {
type: String,
default: 'User'
}
});
res.locals.user = req.user || null;
isUserAuthenticated: (req, res, next) => {
if (req.isAuthenticated()){
if(req.user.role === 'Admin'){
next();//если оказался админом то редиректет в админпанель после авторизации
}
else{
res.redirect('/');//если оказался просто юзером то получаешь редирект на главную после авторизации
}
}else{
res.redirect('/');//
}
}
{{#if user.role }}
<li class="nav-item">
<a class="nav-link" href="/admin">Admin</a>
</li>
{{else}}
<li class="nav-item">
<a class="nav-link" href="/login">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/register">Register</a>
</li>
{{/if}}
Answer the question
In order to leave comments, you need to log in
In handlebars, the #if construct checks for the "existence" or non-negation of a value in a variable. Alternatively, you can add the isAdmin field with a boolean value to the user object, and then check exactly this field in handlebars. As an option:
{{#if user.isAdmin }}
<li class="nav-item">
<a class="nav-link" href="/admin">Admin</a>
</li>
{{else}}
<li class="nav-item">
<a class="nav-link" href="/login">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/register">Register</a>
</li>
{{/if}}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question