User and Groups Management in SharePoint/Online using Rest and Jquery

Managing a user and groups in SharePoint is a fairly simple and easy for any SharePoint administrators. The problem is when you have to do multiple user and groups management at a time. 

Let’s say you want to check all the groups who have permission in a site with their permission definition, remove the group permission from the site, drill inside the group and see the list of members present inside the group, remove the members or add new members. Check access of a user in the site, add a new user or groups to the site.

Imagine the number of routes and clicks you have to go through for getting all this done.  If you are looking for a better solution for this using jquery and client-side interaction then you are in right place. 

A01
User Groups Management

User Groups Management

As you see in the above image this is a single HTML page which uses rest and jquery to perform the various jobs inside a SharePoint administration on one screen. Let’s get more details on the sections and what and how they work.

  • Site Url Tex Box

    • This is an input field for entering the site URL. remember it has to be a site URL, not the URL to the home page or pages lists or libraries. You can defer this and create a site collection tree and on click for each site, run the rest of the logic. I have this textbox because now I can do this for multiple site collections that I own from anywhere. Remember the URL can be a root site URL, site URL or any subsite URL just has to be a valid SharePoint Site URL.
  • Check Site Permission

    • This button displays the lists of groups that have permission to a particular site that is entered in the text box. It also provides you few more interface options as below.
      • Expand to view lists of users inside each group
      • Remove any particular user from the group with the remove button next to the user.
      • Add user button will open a pop up with the group name and UI for finding any existing user inside SharePoint. It opens the out of the box Add user interface for a group.
        • This URL yoursite+’_layouts/15/aclinv.aspx?GroupId=’+CurrGroupId lets you add any user as desired to the particular group. This will open the SharePoint out of the box add user screen for a group.
      • Email the user with a click on the username
      • Click on the group name that opens the group settings SharePoint page.
  • Check User Access

    • This button opens the SharePoint check user access UI, where you can search any existing user and check his/her permission in the site
    • This URL “yoursite+/_layouts/15/chkperm.asp” will let you open the SharePoint check permission window in a pop-up or in any other form as desired. You can use the SharePoint out of the box check user functionality with this.
  • Add New Access

    • This button opens the SharePoint add user pop up which lets you add any new user or groups to the site mentioned in the textbox. 
    • this URL”yoursiteurl+ _layouts/15/aclinv.aspx” will let you open the assign permission SharePoint out of the box pop up. Where you can add a user like in SharePoint out of the box way.

As stated above in this article I am using some hacks to get the SharePoint URL for the dialog that is used to add users, check permissions for a user and add a user to a group. This way it helps us to resolve any user and we don’t have to worry about adding a non-existing user in the application. In my previous articles, we have been using this but this one is a collective and much better version of all.

Following is the code that I am using.

CSS

[code languge=css]

.expand{
background-image:URL(‘/Style%20Library/SiteImages/plus.jpg’);
background-repeat:no-repeat;
float: left;
min-height: 14px;
padding-right: 18px;
cursor: pointer;

}

.collapse{
background-image:URL(‘/Style%20Library/SiteImages/minus.jpg’);
background-repeat:no-repeat;
float: left;
padding-right: 18px;
min-height: 14px;
cursor: pointer;

}

.users {
padding-left: 10%;
padding-top: 15px;
}

.div_usrdetails {
width: 85%;
margin: 5px;
border: 1px solid;
padding: 10px;
min-height:25px;
}

.remove{
font-weight:normal !important;
color: #12ef4e;
font-weight: bolder;
background-color: #0072C6;
text-align: right;
cursor:pointer;

}

.user_data {
width: 60%;
/* text-align: left; */
float: left;
}

input#txtbox {
width: 350px;
height: 30px;
}

div#permission {
color: #36f708;
font-weight: bolder;
}

#div_sitegrpdisplay>div {
background-color: #0072C6;
padding: 5px;
color: white;
width: 85%;
margin-bottom: 15px;
padding-left: 25px;
padding-bottom: 25px;
}

.removeperm {
font-weight: bolder;
color: #12ef4e;
font-weight: bolder;
background-color: #0072C6;
WIDTH: 100%;
text-align: right;
padding-right: 5px;

}

div>i>a {
color: #06fd32 !important;
font-weight: bold !important;
text-decoration: underline;
}

.users a {
color: white !important;
}

.add_user {
width: 75px;
float: right;
display:none;
cursor: pointer;
background-color: #f1f4f7;
padding: 5px;
border-radius: 10px;
text-align: center;
color: #fda703;
font-weight: 800;
}

.div_perm {
margin-top: -10px;
padding-left: 50px;
}

#addnewuser{
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 40%;
top: 30%;
background-color: #d1d4e6;
color: #1d1c1c;
font-weight: bold;
padding: 25px;
}

input#txtbox {
width: 350px;
height: 30px;
}

input#btnadduser {
float: right;
margin-top: 15px;
color: #1d1c1c;
font-weight: bold;
margin-right: 2px;
}

.close {
color: #131212;
font-size: 28px;
font-weight: bold;
top: -5%;
position: absolute;
right: 1%;
cursor: pointer;
}
input.input_btn{
border-radius: 10px;
background-color: steelblue;
color: whitesmoke;
font-size: 20px;
margin-top:20px;
outline:none;
}

input.input_btn:hover{
border-radius: 10px;
background-color: steelblue;
color: whitesmoke;
font-size: 20px;
margin-top:20px;
outline:none;

}

div#chkpermissoin{
min-width:750px !important;
padding-bottom:20px;
}

input.input_txt {
height:40px;
min-width:650px;
margin-top:20px;
font-size: 18px;

}

div#div_sitegrpdisplay {
padding: 20px;

}

.sitegrpmngment{
background-color:#e3e4e4;
padding:20px;
}

.remove_group {
width: 125px;
float: right;
cursor: pointer;
background-color: #f1f4f7;
padding: 5px;
border-radius: 10px;
text-align: center;
color: #fda703;
font-weight: 800;
margin-right: 10px;
display:none;
}

[/code]

Javascript

[code language=”Javascript”]

$(document).ready(function () {

var groupid=”;
var groupname=”

$(“#chksiteperm”).click(function(){
var currsite= checkvalues();//$(‘#txtsite’).val();

var endpointUrl = currsite+”/_api/Web/RoleAssignments?$expand=Member,RoleDefinitionBindings”;
$(‘#divlistperm’).hide();
$(‘#div_sitegrpdisplay’).show();
$(‘#div_sitegrpdisplay’).empty();

if(currsite!=false)
{
$.ajax({
url:endpointUrl,
type: “GET”,
headers: {
“Accept”: “application/json;odata=verbose”
},
success: function(data)
{
var rd= JSON.stringify(data);
if(rd.toLocaleLowerCase().indexOf(“registersod”) == -1)
{
var items = data.d.results;
$.each(items,function(index,item)
{
console.log(items[index]);
groupid= items[index].Member.Id;
groupname=+items[index].Member.Title;
if ((items[index].Member.LoginName.indexOf(“i:0#”) >= 0) || (items[index].Member.Title.indexOf(“System Account”) >= 0 ))
{
//don’t add individual users and system account
}
else
{
$(‘#div_sitegrpdisplay’).append(“

“+items[index].Member.Title+”

Add User
Remove Group

Permissions

"); 

}

var roles= items[index].RoleDefinitionBindings.results;

roles.forEach(function(roledef){

$('#'+items[index].Member.Id+'').parent().find('.div_perm').append(""+roledef.Name+": "+roledef.Description);

});

//
Permissions“+items[index].RoleDefinitionBindings.results[0].Name+”:”+items[index].RoleDefinitionBindings.results[0].Description+”
});
}

else{
alert('Your request returned no results.\nPlease check the site URL');

} 

},
error: function r(xhr) {
alert("Your request returned error:\n please check your site URL and credentials \n" + JSON.stringify(xhr));
} 

});

}

});

/*Start Show the users inside the group*/

$(document).on('click', '.expand', function()
{
var currid= this.id;
var groupname= $(this).data('grpnam');
var currsite= checkvalues();
var tgt_site= currsite; // $('#txtsite').val();
$(this).removeClass("expand");
$(this).addClass("collapse");
$(this).attr('title','Hide Members');
$(this).parent().append("
Members
");
$.ajax({
url: tgt_site+ "/_api/web/sitegroups/getbyID("+currid+")/users",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) { 

//console.log(data);
if (data.d.results.length<1)
{
$("#"+currid).parent().find('.users').append("
No Members Present
");
}
else
{
$.each(data.d.results, function()
{
$("#"+currid).parent().find('.users').append("
"); 

});

} 

}
});

});
/*End Show the users inside the group*/

/*Start hide the users inside the group*/

$(document).on('click', '.collapse', function()
{

var currid= this.id;
$(this).removeClass("collapse");
$(this).addClass("expand");
$(this).attr('title','Display Members');

$("#"+currid).parent().find('.users').remove();

//$("#"+currid).parent().find('#permission').empty();

});
/*End hide the users inside the group*/

/*Start display the adduser button when the radiobutton is selected*/
$(document).on('click', 'input[type="radio"]', function(){
$('.add_user').hide();
$('.remove_group').hide();
$(this).parent().find('.add_user').show();
$(this).parent().find('.remove_group').show();
});
/*End display the adduser button when the radiobutton is selected*/

/*start display the add user popup when the add user button is clicked*/

$(document).on('click','.add_user', function(){
var GroupName =$(this).data('groupname');
GroupName= GroupName.split(' ').join('_');
var CurrGroupId= $(this).data('groupid');
var currsite=checkvalues();
OpenDialog(currsite+'/_layouts/15/aclinv.aspx?GroupId='+CurrGroupId);
});
/*End display the add user popup when the add user button is clicked*/

/*Start check users permission in current site*/
$(document).on('click','#chkuserperm', function(){
var currsite= checkvalues();
OpenDialog(currsite+'/_layouts/15/chkperm.aspx');

});

/*End check users permission in current site*/

/*Start add users/groups permission in current site*/
$(document).on('click','#adduserperm', function(){
var currsite= checkvalues();
OpenDialog(currsite+'/_layouts/15/aclinv.aspx');

});
/*End add users/group permission to current site*/

/*start function to remove a group permission from site*/

// calling the function to remove the group from site collection

$(document).on('click', '.remove_group', function()
{
var groupid= $(this).data('groupid');
var groupname= $(this).data('groupname');
var siteUrl= checkvalues();
var msg= "Are you sure you want to remove permissoin of group"+groupname + " from site"+siteUrl;
confirmation(msg).then(function (answer) {
var ansbool = Boolean.parse(answer.toString());
if(ansbool){
deletegroup(groupid,siteUrl,groupname);//TRUE
}
});

});

/*end function to remove a group permission from site*/

/*start call to function that removes the users from the group*/
$(document).on('click','.remove', function()
{
var userLoginName= $(this).data('userid');
var groupid= $(this).data('groupid');
var username= $(this).data('usertitle');
var siteUrl= checkvalues();

//var groupid= $(this).parent().parent().children('.collapse').attr('id');

var msg= "Are you sure you want to remove user "+username + "";
confirmation(msg).then(function (answer) {
var ansbool = Boolean.parse(answer.toString());
if(ansbool)
{
removeUserFromGroup(siteUrl,userLoginName,groupid).done(function(data)
{
alertbox(""+username +" has been removed from group");
$('.users').hide();
$('.collapse').addClass('expand').removeClass('collapse');

})
.fail(
function(error){
alert(JSON.stringify(error));
});
}

});

});

/*End call to function that removes the users from the group*/

/* start define the funciton that removes user from the group*/

function removeUserFromGroup(webUrl,userLoginName,groupid)
{
var url = webUrl + "/_api/web/sitegroups/GetById('" + encodeURIComponent(groupid) + "')/users/removebyloginname(@u)?@u='" + encodeURIComponent(userLoginName) + "'";
return $.ajax({
url: url,
method: "POST",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
}
});
}

/* End define the funciton that removes user from the group*/

/*End function to remove group permission from the site*/

/*End Document.Ready function */

});

/*Start function to remove group permission from the site*/

function deletegroup(groupid,siteUrl,groupname)
{
var roleid= groupid;
var urls=siteUrl+"/_api/web/roleassignments/getbyprincipalid('"+ roleid +"')";
$.ajax({
url: urls,
type: 'POST',
headers: {
'X-RequestDigest':$('#__REQUESTDIGEST').val(),
'X-HTTP-Method':'DELETE'
},
success: alert("Permission for"+groupname+"from current site"+ siteUrl+"is removed"),
error: function(error){
alert(JSON.stringify(error)); }
});

}

//Remove the current role assignment for the group on the list

//start json call function

function getJson(url)
{
return $.ajax({
url: url,
type: "GET",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose"
}
});
}
//end json call function

//start function to check if site url is null

function checkvalues()
{
var currsite= $('#txtsite').val();
var str='';
if(currsite=='')
{
str +='Site Url cannot be empty'
}

if((currsite.indexOf('lists')!=-1)||(currsite.indexOf('SitePages')!=-1)||(currsite.indexOf('Pages')!=-1)){
str+='Enter the site url only.\n\nDo not include pages,library or list names';
}
if(str=='')
{
var lastChar = currsite.substr(-1); // Selects the last character
if (lastChar == '/') { // If the last character is not a slash
currsite= currsite.slice(0,-1)
}
return currsite;
}
else{
alert(str);
location.reload();
return false;
}
}
//end function that checks if site url is null 

// start function to call dialog for confirmation
function confirmation(question)
{
var defer = $.Deferred();
$('
')
.html(question)
.dialog({
autoOpen: true,
modal: true,
title: '',
buttons: {
"Yes": function () {
defer.resolve("true");//this text 'true' can be anything. But for this usage, it should be true or false.
$(this).dialog("close");
},
"No": function () {
defer.resolve("false");//this text 'false' can be anything. But for this usage, it should be true or false.
$(this).dialog("close");
}
},
close: function () {
$(this).remove();
}
});
return defer.promise();
}
//end function to call dialog for confirmation

//start function for an alert box in a nice dialog
function alertbox(message){
$('
')
.html(message)
.dialog({
autoOpen: true,
modal: true,
title: '',
buttons: {
"Ok": function () {
$(this).dialog("close");
//location.reload();
}

},
close: function () {
$(this).remove();
//location.reload();
}
});

}
//End function for an alert box in a nice dialog 

/*start function to open a dialog with url*/

function OpenDialog(URL){
var options = {

url:URL,

title:"",

dialogReturnValueCallback: DialogCallback

};

SP.UI.ModalDialog.showModalDialog(options);

}
/*End function to open a dialog with url*/

/*Start dialogcallback for the add user dialog*/
function DialogCallback(dialogResult, returnValue){
$('.users').hide();
$('.collapse').addClass('expand').removeClass('collapse');
}

/*End dialogcallback for the add user dialog*/

[/code]

Html

[code language="html"]
Enter the site URL (eg:https://sharepoint.com)
[/code]

Process of adding it to SharePoint

  • If you look at my previous article it is failry very simple to use any of these code.
    • Create an HTML file with all the code contents and save them in a secured location.
    • Add a new web part page
    • Add a content editor web part and in the text, file link put the link to the HTML file.
    • Save the page and publish it
    • You are done with the new interface for managing user and groups.
    • Since this is an administration job I would expect only the site owners or site collections administrators to be able to perform all the actions listed in the page.

This code works for SharePoint on-premise and office 365 has been tested for both environments.

Hope it helps you in your SharePoint journey.

 

Advertisements

Leave a Reply

Your email address will not be published. Required fields are marked *