A
A
Alexey Konovalov2018-02-22 21:53:30
PHP
Alexey Konovalov, 2018-02-22 21:53:30

Am I assigning and validating user roles correctly?

Hello! I can’t figure out (more precisely, whether I’m doing it right) in the roles of users on the site.
This means that each user in the database has an ID_GROUP field . For example 1 - administrator, 2 - moderator, etc.
Each group has its own permissions in the database, for example:
dell_all_news - can delete any news
dell_my_news - can delete its own news
When requesting any page, the COOKIE or TOKEN file sent along with the request is checked. With this token or cookie, we turn to the "loner" class, which receives data about the user (the class is available in any web application file).
Now... Do I understand correctly... For example, we receive a request from a user to delete news with ID == 33
So the deletion file should contain something like this code?

// подключаемся к классу одиночка, который будет работать с текущим пользователем
$account = Account::getInstance();

try{

  // проверяем авторизован ли пользователь
    // и там же получаем все данные о пользователе, если авторизован
  if(!$account->isAuth()) throw new Exception("Нужна авторизация");
  
  // получаем из БД все разрешенные действия пользователя и храним их в классе account
    $account->getRoles();
    
    // Получаем данные о посте, который пользователь хочет удалять
    $id = intval($_GET['id']);
    
    $res = $db->query("SELECT * FROM `news` WHERE `id` = {$id}");
    $row = $res->fetch_assoc();
    
    // по умолчанию не разрешаем пользователю удалять
    $allow = false;
    
    // проверяем является ли владельцем текущий пользователь
    if($account->getId() == $row['author_id']){
        
        // пользователь автор новости, поэтому проверяем может ли он удалять свои новости
        if($account->checkRoles('dell_my_news')){
            $allow = true;
        }
        
    }else{
        
        // пользователь НЕ автор новости, поэтому проверяем может ли он удалять чужие
    if($account->checkRoles('dell_all_news')){
      $allow = true;
    }
        
    }
    
    // если пользователю разрешено по какому-то параметру удалять, то удаляем новость
    if($allow){
        //..... запрос на удаление
    }else{
        throw new Exception("Нет доступа");
    }

}catch(Exception $e){

    die($e->getMessage());
    
}

It seems to be very cumbersome, so this question arose. After all, if we display a list of news in some section, then when iterating through the array of news, we also need to do the same checks (author / not author, can delete our own / can delete others) only to decide whether to show the user the "delete" button "on the page or not...
Please tell me if I'm doing something wrong...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Bobkov, 2018-02-22
@Alk90

As a matter of fact - it is correct.
Role capabilities can be stored in a config file - you won't need to go to the database for data.
When displaying a list of news, we check once for dell_all_news and for each news we check for dell_my_news
By code - the condition can be written in one line

$allow = ($account->getId() == $row['author_id'] && $account->checkRoles('dell_my_news')) || $account->checkRoles('dell_all_news');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question