简体   繁体   中英

How can I allow to delete only for logged in users

I'm trying to create a delete function that deletes a MySQL row only if that row was created by the same logged-in user. So if the row is not created by that user, it cannot delete that row.

Here's what I have so far (Javascript):

app.post('/Update_Award', function(request, response) {
        var connection = request.app.get('pool');
        if (request.session.loggedin) {
            //delete query
        connection.query('SELECT username FROM accounts', [request.session.username], function (error, results, fields) {
            //if (results[0].username === request.session.username) {

            connection.query('DELETE FROM award WHERE id = ?', [request.body.id], function(error, results, fields) {
             //do something
            } else {
                console.log("No access");
            }

The MySQL table for accounts has "id" column and "username" column. I want to make is so that only rows created by the same logged in user id can be deleted.

The rows created are identified by issuerID. So I am deleting the rows by the row ID and the rows created by isserID.

You can change your code to

app.post('/Update_Award', function(request, response) {
  var connection = request.app.get('pool');
  if (request.session.loggedin) {
    connection.query('DELETE FROM award WHERE id IN (SELECT id FROM accounts WHERE username = ?)', [request.session.username], function(error, results, fields) {
      if (//your condition) {
        //do something
      } else {
        console.log("No access");
      }
    })
  }
})

You can do it like below.

app.post('/Update_Award', function(request, response) {
  var connection = request.app.get('pool');
  if (request.session.loggedin) {
    connection.query('DELETE FROM award WHERE id = ? AND issuerID IN (SELECT 
     id FROM accounts WHERE username = ?)', [request.body.id, 
    request.session.username], function(error, results, fields) {
      if (//your condition) {
        //do something
      } else {
        console.log("No access");
      }
    })
  }
})

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