简体   繁体   中英

Using roles and specific user id to limit what sections can be viewed in react / node / express / mysql?

I am creating a web app using MySQL, express, react, node and it my first time using JavaScript. I have used sessions before when i done a project with PHP and am having trouble understanding how to add role-based-access or access specific for particular user.

The code i have at the minute in the front end is:

export const login = user => {
    return axios
        .post('users/login', {
            userName: user.userName,
            password: user.password,
        })
        .then(res => {
            localStorage.setItem('usertoken', res.data);
            return res.data
        })
        .catch(err => {
            console.log(err)
        })
}; 

and in the back end.

// login
users.post('/login', (req, res) => {
    User.findOne({
            where: {
                userName: req.body.userName
            }
        })
        .then(user => {
            if (bcrypt.compareSync(req.body.password, user.password)) {
                let token = jwt.sign(user.dataValues, process.env.SECRET_KEY, {
                    expiresIn: 1440
                })
                res.json({
                    token: token
                })
            } else {
                res.send('User doesnt exist')
            }
        })
        .catch(err => {
            res.send('error: ' + err)
        })
});

How would I go about requesting / returning the user type / user_id from the MySQL database using Express when the jwt token is sent back? would the user type and user_id be stored in the JWT 'usertoken' and stored in the local storage?

How would I go about requesting / returning the user type / user_id from the MySQL database using Express when the jwt token is sent back?

        if (bcrypt.compareSync(req.body.password, user.password)) {
            // place your query here - use `username` as a key to get user row
            // store results in user object, then:
            let token = jwt.sign(user.dataValues, process.env.SECRET_KEY, {
                expiresIn: 1440
            })
            res.json({
                token: token
            })

would the user type and user_id be stored in the JWT 'usertoken' and stored in the local storage?

As long as it's not sensitive data - you are on the safe side. Note that due to encryption you are reletavly safe even if passing sensitive data, but - it is not a good practice (send only what you must back to the user stored inside your JWT)

I am creating a web app using MySQL, express, react, node and it my first time using JavaScript

Great! Welcome to modern stack development :)

Edit:

I admit - my original answer may be confusing. so:

  • As a rule of thumb - never ever (ever ever never) write sql queries inside you front-end project (security wise)
  • Your backend should manage connectivity against db (in most cases you should use a single connection per db)
  • Extend your backend with Api entries that query your database. Allow these entries to accept query parameters and / or request headers
  • Call your api with specific query parameters to query your db

In your example I simply used your login entry to place your query. Because you are using mysql , please consider using a third-party library to help you out (such as mysql2 )

Eventually, it should looks something like this:

    if (bcrypt.compareSync(req.body.password, user.password)) {
        connection.query('SELECT * FROM `users` WHERE `name` = ?', ['user name to query' ], function(err, results) {
        if (err) return res.send('error: ' + err)

        let token = jwt.sign(user.dataValues, process.env.SECRET_KEY, {
            expiresIn: 1440
        })
        res.json({
            token: token
        })

} );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM