Sunday, May 21, 2017

List of sites user has access in SharePoint Online


Getting a list of sites that a user has access to in SharePoint Online

My customer needed a way to show all the sites and site collection where the user had access. This is for an the sharepoint online site which they have. Since we cannot have any server side code and also looping through all sites and checking whether user has got access to the site is difficult.
So I came up with the option of using search api which is already security trimmed and based on contentclass, we can get the list. Below is the sample code for the same.
You can build your html and apply.
<button id='btnGetSites'>Get Sites</button>

<div id='list'>

</div>
<script src="https://tenant.sharepoint.com/sites/spdev/SiteAssets/jquery.min.js" type="text/javascript"></script>
<script type='text/javascript'>


(function(){
    var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
    var url = siteUrl + "/_api/search/query?querytext='(contentclass:STS_Site)'";
    $('#btnGetSites').click(function(){
        console.log('start..');

        $.ajax({
            method: 'GET',
            url: url,
            dataType: 'json',
            success: success,
            error: error
        });

        function success(data){
            var html = '';

            $.each(data.PrimaryQueryResult.RelevantResults.Table.Rows, function(index, row){              
                var title = '';
                var url = '';
                $.each(row.Cells, function(i, obj){            
                    if(obj.Key === 'Title'){
                        html += obj.Value;
                    }
                    else if(obj.Key === 'Path'){
                        html += ": " + obj.Value + "<br/>";
                    }              
                });        
            });

            $('#list').append(html);
        }
        function error(err){
            console.log(err);
        }      
        return false;
    });

}());

</script>

No comments:

Post a Comment