Drupal 8 hook example: hook_node_access

You can deny or allow access for some users based on user id or user role or another conditions via custom module

  1. function custom_module_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {
  2.  
  3. $type_name = $node->type->entity->id();
  4.  
  5. if ($type_name == 'content_type_id') {
  6.  
  7. $current_user = \Drupal::currentUser();
  8. $roles = $current_user->getRoles();
  9.  
  10. if ($node->hasField('field_test_field')) {
  11. $field_test_field = $node->get('field_test_field')->getValue();
  12. } else {
  13. $field_test_field[0]['value'] = 0;
  14. }
  15.  
  16. if (in_array('mas', $roles) || in_array('anonymous', $roles)) {
  17.  
  18. if ($field_test_field[0]['value'] != 1) {
  19. return AccessResult::forbidden();
  20. } else {
  21. return AccessResult::neutral();
  22. }
  23.  
  24. else {
  25. return AccessResult::neutral();
  26. }
  27. } else {
  28. return AccessResult::neutral();
  29. }
  30. }
  31. }

In example above module return access forbidden if user has "mas" role or user is anonymous, filed ''field_test_field' value not 1 and content type is 'content_type_id'. Otherwise it is important to return access neutral: return AccessResult::neutral();