Get Roles assigned to a User

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • telecastg
    Active Community Member
    • Jun 2018
    • 907

    Get Roles assigned to a User

    Is there a built-in function to retrieve all Roles assigned to a User ?
  • telecastg
    Active Community Member
    • Jun 2018
    • 907

    #2
    Didn't get any replies and couldn't find such function myself, so I resorted to an ajax call in the view to get it done.

    Here's the code for those interested:

    client/custom/src/views/record/detail.js
    Code:
            userRoles: [],
    
            getUserRoles: function() {
                var userId = this.getUser().id;
                var options = {};
                var sqlString = "SELECT role.name FROM role_user INNER JOIN user ON role_user.user_id = user.id INNER JOIN role ON role_user.role_id = role.id WHERE user.id = '"+userId+"'";
                options.sqlString = sqlString;     
                options.queryType = "SELECT";
                var url = '?entryPoint=sqlDataDispatcher';
                var payload = JSON.stringify(options); 
                var xmlhttp = new XMLHttpRequest();
                var self = this;
                xmlhttp.onreadystatechange = function() {                
                    if (xmlhttp.readyState === XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
                        // if the ajax call is successful load the userRoles array
                        if (xmlhttp.status === 200) {
                            var responseObj = JSON.parse(xmlhttp.responseText);
                            var roles = [];
                            options.responseObj = responseObj;
                            responseObj.forEach(function (role) {
                                roles.push(role.name);                            
                            }); 
                            self.userRoles = roles;                        
                        }
                        else if (xmlhttp.status === 400) {
                            alert('There was an error 400');
                        }
                        else {
                            alert('something else other than 200 was returned');
                        }                    
                    }                
                };
                xmlhttp.open("POST",url , true);
                xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");                
                xmlhttp.send("data="+payload);              
            }

    custom/Espo/Custom/EntryPoints/SqlDataDispatcher.php
    Code:
    <?php
    
    namespace Espo\Custom\EntryPoints;
    
    use \Espo\Core\Exceptions\NotFound;
    use \Espo\Core\Exceptions\Forbidden;
    use \Espo\Core\Exceptions\BadRequest;
    
    class SqlDataDispatcher extends \Espo\Core\EntryPoints\Base
    {
    
        public static $authRequired = true;
    
        // default action
        public function run()
        {
            //convert the JSON string into a PHP associative array
            $payload = json_decode($_REQUEST['data'], true);
            $sqlString = $payload["sqlString"];
            $queryType = $payload["queryType"];
            // replace query placeholders
            $startNeedle = '@@{{';
            $endNeedle = '}}/@@';
            $queryPlaceholders = $this->findCustomPlaceholderNames($sqlString,$startNeedle,$endNeedle);
            foreach($queryPlaceholders as $field) {
                $fieldValue = $payload["placeholders"][$field];
                $sqlString = str_replace($startNeedle.$field.$endNeedle,$fieldValue,$sqlString);                
            }               
            // execute the sql command
            $pdo = $this->getEntityManager()->getPDO();
            if($queryType === "SELECT") {
                $data = $pdo->query($sqlString)->fetchAll();
                // return data set
                echo(json_encode($data));                    
            } else {
                $pdo->query($sqlString); 
                echo($queryType." query executed");
            }
        }
    
        public function findCustomPlaceholderNames($haystack,$startNeddle,$endNeedle) {
            $lastPos = 0;
            $placeholderNames = array();
            while (($lastPos = strpos($haystack, $startNeddle, $lastPos))!== false) {
                $placeholderNameStart = $lastPos+strlen($startNeddle);
                $placeholderNameLength = strpos($haystack,$endNeedle,$lastPos)-$placeholderNameStart;
                $placeholderName = substr($haystack,$placeholderNameStart,$placeholderNameLength);
                // avoid repeating field names
                if(!array_search($placeholderName, $placeholderNames)) {
                    $placeholderNames[] = $placeholderName;                            
                }
                $lastPos = $lastPos + strlen($startNeddle);            
            }
            // print("<pre>".print_r($placeholderNames,true)."</pre>");
            return $placeholderNames;
        }
    
    
    }
    I have seen several questions regarding the ability/need to list all Roles assigned to a User, just like Teams are handled so hopefully the developers have a built in function for future releases.

    Comment

    • jurnet
      Member
      • Aug 2019
      • 35

      #3
      I have done like this :
      Code:
      var url = 'User/' + this.getUser().get('id');
      this.wait(true);
      $.ajax({ url: url, dataType: 'json', async: false, }).done(function (json) {
      var myRoles = $.map(json.rolesNames, function (value, index) { return [value]; }); if($.inArray('Commercial', myRoles) != -1 || $.inArray('Directeur', myRoles) != -1 || this.getUser().isAdmin() ) { this.buttonList.push({ 'label': 'Envoyer le dossier', 'name': 'sendRecord', 'style': 'primary' }); }
      this.wait(false);

      Comment

      • tothewine
        Active Community Member
        • Jan 2018
        • 373

        #4
        Be careful with entry points like this because they can easily become a security hole. I'd recommend to put the entire query in the php side if possible.

        Comment


        • telecastg
          telecastg commented
          Editing a comment
          You are absolutely right, the recommended workflow is: Ajax > Backend Controller > Backend Service > Ajax (Process response). The above was experimental code not used anymore.
      • item
        Active Community Member
        • Mar 2017
        • 1476

        #5
        Ha just see now :s

        i am looking too ...and find this (i am searching about LevelList => account, contact, team, own, ... i will add my custom enitity in scope (?) )

        in application/Espo/Core/Acl/Table.php

        PHP Code:
        if (!$this->getUser()->isAdmin()) {
        $roleList = $this->getRoleList();
        
        foreach ($roleList as $role) {
        $aclTableList[] = $role->get('data');
        $fieldTableList[] = $role->get('fieldData');
        
        foreach ($this->valuePermissionList as $permission) {
        $valuePermissionLists->{$permission}[] = $role->get($permission);
        }
        }
        
        $aclTable = $this->mergeTableList($aclTableList);
        $fieldTable = $this->mergeFieldTableList($fieldTableList);
        
        $this->applyDefault($aclTable, $fieldTable);
        $this->applyDisabled($aclTable, $fieldTable);
        $this->applyMandatory($aclTable, $fieldTable);
        $this->applyAdditional($aclTable, $fieldTable, $valuePermissionLists);
        } 
        
        If you could give the project a star on GitHub. EspoCrm believe our work truly deserves more recognition. Thanks.​

        Comment

        Working...