F
F
filisonov2021-04-10 18:30:45
Express.js
filisonov, 2021-04-10 18:30:45

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:

postmodel file
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'
    }


});


Next, I write the data of the authorized user to the global variable: I hide the admin panel from the user with a parameter other than role: "Admin" as follows:
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('/');//
        }
    }


How to write a check for the handlebars template engine, provided that all users other than role:Admin should not see the link to enter the adimi panel, this design does not work:

{{#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

1 answer(s)
I
Ivan Chernyshev, 2021-04-15
@IvanBlacky

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 question

Ask a Question

731 491 924 answers to any question