This repository has been archived by the owner on Jan 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 642
/
Copy pathSecurityExtensions.cs
1597 lines (1415 loc) · 69.7 KB
/
SecurityExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
#if NETSTANDARD2_0
using System.Net;
#endif
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.Online.SharePoint.TenantManagement;
using OfficeDevPnP.Core;
using OfficeDevPnP.Core.AppModelExtensions;
using OfficeDevPnP.Core.Entities;
using OfficeDevPnP.Core.Enums;
using OfficeDevPnP.Core.Utilities;
namespace Microsoft.SharePoint.Client
{
/// <summary>
/// This manager class holds security related methods
/// </summary>
public static partial class SecurityExtensions
{
#region Site collection administrator management
/// <summary>
/// Get a list of site collection administrators
/// </summary>
/// <param name="web">Site to operate on</param>
/// <returns>List of <see cref="OfficeDevPnP.Core.Entities.UserEntity"/> objects</returns>
public static List<UserEntity> GetAdministrators(this Web web)
{
var retrievalExpressions = new Expression<Func<User, object>>[]
{
u => u.Title,
u => u.LoginName,
u => u.Email
};
var users = web.SiteUsers.Where(u => u.IsSiteAdmin);
var adminUsers = web.Context.LoadQuery(users.Include(retrievalExpressions));
web.Context.ExecuteQueryRetry();
List<UserEntity> admins = new List<UserEntity>();
foreach (var u in adminUsers)
{
admins.Add(new UserEntity()
{
Title = u.Title,
LoginName = u.LoginName,
Email = u.Email,
});
}
return admins;
}
/// <summary>
/// Add a site collection administrator to a site collection
/// </summary>
/// <param name="web">Site to operate on</param>
/// <param name="adminLogins">Array of admins loginnames to add</param>
/// <param name="addToOwnersGroup">Optionally the added admins can also be added to the Site owners group</param>
public static void AddAdministrators(this Web web, List<UserEntity> adminLogins, bool addToOwnersGroup = false)
{
var users = web.SiteUsers;
web.Context.Load(users);
foreach (var admin in adminLogins)
{
UserCreationInformation newAdmin = new UserCreationInformation();
newAdmin.LoginName = admin.LoginName;
//User addedAdmin = users.Add(newAdmin);
User addedAdmin = web.EnsureUser(newAdmin.LoginName);
web.Context.Load(addedAdmin);
web.Context.ExecuteQueryRetry();
//now that the user exists in the context, update to be an admin
addedAdmin.IsSiteAdmin = true;
addedAdmin.Update();
if (addToOwnersGroup)
{
web.AssociatedOwnerGroup.Users.AddUser(addedAdmin);
web.AssociatedOwnerGroup.Update();
}
web.Context.ExecuteQueryRetry();
}
}
/// <summary>
/// Removes an administrators from the site collection
/// </summary>
/// <param name="web">Site to operate on</param>
/// <param name="admin"><see cref="OfficeDevPnP.Core.Entities.UserEntity"/> that describes the admin to be removed</param>
public static void RemoveAdministrator(this Web web, UserEntity admin)
{
var retrievalExpressions = new Expression<Func<User, object>>[]
{
u => u.Title,
u => u.LoginName,
u => u.Email
};
var users = web.SiteUsers.Where(u => u.IsSiteAdmin);
var adminUsers = web.Context.LoadQuery(users.Include(retrievalExpressions));
web.Context.ExecuteQueryRetry();
var adminToRemove = adminUsers.FirstOrDefault(u => String.Equals(u.LoginName, admin.LoginName, StringComparison.CurrentCultureIgnoreCase));
if (adminToRemove != null)
{
adminToRemove.IsSiteAdmin = false;
adminToRemove.Update();
web.Context.ExecuteQueryRetry();
}
}
#endregion
#region Permissions management
/// <summary>
/// Add read access to the group "Everyone except external users".
/// </summary>
/// <param name="web">Site to be processed - can be root web or sub site</param>
public static User AddReaderAccess(this Web web)
{
return AddReaderAccessImplementation(web, BuiltInIdentity.EveryoneButExternalUsers);
}
/// <summary>
/// Add read access to the group "Everyone except external users".
/// </summary>
/// <param name="web">Site to be processed - can be root web or sub site</param>
/// <param name="user">Built in user to add to the visitors group</param>
public static User AddReaderAccess(this Web web, BuiltInIdentity user)
{
return AddReaderAccessImplementation(web, user);
}
private static User AddReaderAccessImplementation(Web web, BuiltInIdentity user)
{
switch (user)
{
case BuiltInIdentity.Everyone:
{
const string userIdentity = "c:0(.s|true";
User spReader = web.EnsureUser(userIdentity);
web.Context.Load(spReader);
web.Context.ExecuteQueryRetry();
web.AssociatedVisitorGroup.Users.AddUser(spReader);
web.AssociatedVisitorGroup.Update();
web.Context.ExecuteQueryRetry();
return spReader;
}
case BuiltInIdentity.EveryoneButExternalUsers:
{
User spReader = null;
try
{
// New tenant
string userIdentity =
$"c:0-.f|rolemanager|spo-grid-all-users/{web.GetAuthenticationRealm()}";
spReader = web.EnsureUser(userIdentity);
web.Context.Load(spReader);
web.Context.ExecuteQueryRetry();
}
catch (ServerException)
{
// old tenant?
string userIdentity = string.Empty;
userIdentity = web.GetEveryoneExceptExternalUsersClaimName();
if (!string.IsNullOrEmpty(userIdentity))
{
spReader = web.EnsureUser(userIdentity);
web.Context.Load(spReader);
web.Context.ExecuteQueryRetry();
}
else
{
throw new Exception("Language currently not supported");
}
}
web.AssociatedVisitorGroup.Users.AddUser(spReader);
web.AssociatedVisitorGroup.Update();
web.Context.ExecuteQueryRetry();
return spReader;
}
}
return null;
}
/// <summary>
/// Returns the correct value of the "Everyone except external users" string value
/// </summary>
/// <param name="web">Web to get the language from</param>
/// <returns>String in correct translation</returns>
public static string GetEveryoneExceptExternalUsersClaimName(this Web web)
{
string userIdentity = string.Empty;
web.EnsureProperty(p => p.Language);
switch (web.Language)
{
case 1025: // Arabic
userIdentity = "الجميع باستثناء المستخدمين الخارجيين";
break;
case 1069: // Basque
userIdentity = "Guztiak kanpoko erabiltzaileak izan ezik";
break;
case 1026: // Bulgarian
userIdentity = "Всички освен външни потребители";
break;
case 1027: // Catalan
userIdentity = "Tothom excepte els usuaris externs";
break;
case 2052: // Chinese (Simplified)
userIdentity = "除外部用户外的任何人";
break;
case 1028: // Chinese (Traditional)
userIdentity = "外部使用者以外的所有人";
break;
case 1050: // Croatian
userIdentity = "Svi osim vanjskih korisnika";
break;
case 1029: // Czech
userIdentity = "Všichni kromě externích uživatelů";
break;
case 1030: // Danish
userIdentity = "Alle undtagen eksterne brugere";
break;
case 1043: // Dutch
userIdentity = "Iedereen behalve externe gebruikers";
break;
case 1033: // English
userIdentity = "Everyone except external users";
break;
case 1061: // Estonian
userIdentity = "Kõik peale väliskasutajate";
break;
case 1035: // Finnish
userIdentity = "Kaikki paitsi ulkoiset käyttäjät";
break;
case 1036: // French
userIdentity = "Tout le monde sauf les utilisateurs externes";
break;
case 1110: // Galician
userIdentity = "Todo o mundo excepto os usuarios externos";
break;
case 1031: // German
userIdentity = "Jeder, außer externen Benutzern";
break;
case 1032: // Greek
userIdentity = "Όλοι εκτός από εξωτερικούς χρήστες";
break;
case 1037: // Hebrew
userIdentity = "כולם פרט למשתמשים חיצוניים";
break;
case 1081: // Hindi
userIdentity = "बाह्य उपयोगकर्ताओं को छोड़कर सभी";
break;
case 1038: // Hungarian
userIdentity = "Mindenki, kivéve külső felhasználók";
break;
case 1057: // Indonesian
userIdentity = "Semua orang kecuali pengguna eksternal";
break;
case 1040: // Italian
userIdentity = "Tutti tranne gli utenti esterni";
break;
case 1041: // Japanese
userIdentity = "外部ユーザー以外のすべてのユーザー";
break;
case 1087: // Kazakh
userIdentity = "Сыртқы пайдаланушылардан басқасының барлығы";
break;
case 1042: // Korean
userIdentity = "외부 사용자를 제외한 모든 사람";
break;
case 1062: // Latvian
userIdentity = "Visi, izņemot ārējos lietotājus";
break;
case 1063: // Lithuanian
userIdentity = "Visi, išskyrus išorinius vartotojus";
break;
case 1086: // Malay
userIdentity = "Semua orang kecuali pengguna luaran";
break;
case 1044: // Norwegian (Bokmål)
userIdentity = "Alle bortsett fra eksterne brukere";
break;
case 1045: // Polish
userIdentity = "Wszyscy oprócz użytkowników zewnętrznych";
break;
case 1046: // Portuguese (Brazil)
userIdentity = "Todos exceto os usuários externos";
break;
case 2070: // Portuguese (Portugal)
userIdentity = "Todos exceto os utilizadores externos";
break;
case 1048: // Romanian
userIdentity = "Toată lumea, cu excepția utilizatorilor externi";
break;
case 1049: // Russian
userIdentity = "Все, кроме внешних пользователей";
break;
case 10266: // Serbian (Cyrillic, Serbia)
userIdentity = "Сви осим спољних корисника";
break;
case 2074:// Serbian (Latin)
userIdentity = "Svi osim spoljnih korisnika";
break;
case 1051:// Slovak
userIdentity = "Všetci okrem externých používateľov";
break;
case 1060: // Slovenian
userIdentity = "Vsi razen zunanji uporabniki";
break;
case 3082: // Spanish
userIdentity = "Todos excepto los usuarios externos";
break;
case 1053: // Swedish
userIdentity = "Alla utom externa användare";
break;
case 1054: // Thai
userIdentity = "ทุกคนยกเว้นผู้ใช้ภายนอก";
break;
case 1055: // Turkish
userIdentity = "Dış kullanıcılar hariç herkes";
break;
case 1058: // Ukranian
userIdentity = "Усі, крім зовнішніх користувачів";
break;
case 1066: // Vietnamese
userIdentity = "Tất cả mọi người trừ người dùng bên ngoài";
break;
}
return userIdentity;
}
#endregion
#if !ONPREMISES
#region External sharing management
/// <summary>
/// Get the external sharing settings for the provided site. Only works in Office 365 Multi-Tenant
/// </summary>
/// <param name="web">Tenant administration web</param>
/// <param name="siteUrl">Site to get the sharing capabilities from</param>
/// <returns>Sharing capabilities of the site collection</returns>
public static string GetSharingCapabilitiesTenant(this Web web, Uri siteUrl)
{
if (siteUrl == null)
throw new ArgumentNullException("siteUrl");
Tenant tenant = new Tenant(web.Context);
SiteProperties site = tenant.GetSitePropertiesByUrl(siteUrl.OriginalString, true);
web.Context.Load(site);
web.Context.ExecuteQueryRetry();
return site.SharingCapability.ToString();
}
/// <summary>
/// Returns a list all external users in your tenant
/// </summary>
/// <param name="web">Tenant administration web</param>
/// <returns>A list of <see cref="OfficeDevPnP.Core.Entities.ExternalUserEntity"/> objects</returns>
public static List<ExternalUserEntity> GetExternalUsersTenant(this Web web)
{
Tenant tenantAdmin = new Tenant(web.Context);
Office365Tenant tenant = new Office365Tenant(web.Context);
List<ExternalUserEntity> externalUsers = new List<ExternalUserEntity>();
const int pageSize = 50;
int position = 0;
while (true)
{
var results = tenant.GetExternalUsers(position, pageSize, string.Empty, SortOrder.Ascending);
web.Context.Load(results, r => r.UserCollectionPosition, r => r.TotalUserCount, r => r.ExternalUserCollection);
web.Context.ExecuteQueryRetry();
foreach (var externalUser in results.ExternalUserCollection)
{
externalUsers.Add(new ExternalUserEntity()
{
DisplayName = externalUser.DisplayName,
AcceptedAs = externalUser.AcceptedAs,
InvitedAs = externalUser.InvitedAs,
UniqueId = externalUser.UniqueId,
InvitedBy = externalUser.InvitedBy,
WhenCreated = externalUser.WhenCreated,
});
}
position = results.UserCollectionPosition;
if (position == -1 || position == results.TotalUserCount)
{
break;
}
}
return externalUsers;
}
/// <summary>
/// Returns a list all external users for a given site that have at least the viewpages permission
/// </summary>
/// <param name="web">Tenant administration web</param>
/// <param name="siteUrl">Url of the site fetch the external users for</param>
/// <returns>A list of <see cref="OfficeDevPnP.Core.Entities.ExternalUserEntity"/> objects</returns>
public static List<ExternalUserEntity> GetExternalUsersForSiteTenant(this Web web, Uri siteUrl)
{
if (siteUrl == null)
throw new ArgumentNullException("siteUrl");
Tenant tenantAdmin = new Tenant(web.Context);
Office365Tenant tenant = new Office365Tenant(web.Context);
Site site = tenantAdmin.GetSiteByUrl(siteUrl.OriginalString);
web = site.RootWeb;
List<ExternalUserEntity> externalUsers = new List<ExternalUserEntity>();
const int pageSize = 50;
int position = 0;
while (true)
{
var results = tenant.GetExternalUsersForSite(siteUrl.OriginalString, position, pageSize, string.Empty, SortOrder.Ascending);
web.Context.Load(results, r => r.UserCollectionPosition, r => r.TotalUserCount, r => r.ExternalUserCollection);
web.Context.ExecuteQueryRetry();
foreach (var externalUser in results.ExternalUserCollection)
{
User user = web.SiteUsers.GetByEmail(externalUser.AcceptedAs);
web.Context.Load(user);
web.Context.ExecuteQueryRetry();
var permission = web.GetUserEffectivePermissions(user.LoginName);
web.Context.ExecuteQueryRetry();
var doesUserHavePermission = permission.Value.Has(PermissionKind.ViewPages);
if (doesUserHavePermission)
{
externalUsers.Add(new ExternalUserEntity()
{
DisplayName = externalUser.DisplayName,
AcceptedAs = externalUser.AcceptedAs,
InvitedAs = externalUser.InvitedAs,
UniqueId = externalUser.UniqueId,
InvitedBy = externalUser.InvitedBy,
WhenCreated = externalUser.WhenCreated,
});
}
}
position = results.UserCollectionPosition;
if (position == -1 || position == results.TotalUserCount)
{
break;
}
}
return externalUsers;
}
#endregion
#endif
#region Group management
/// <summary>
/// Returns the integer ID for a given group name
/// </summary>
/// <param name="web">Site to be processed - can be root web or sub site</param>
/// <param name="groupName">SharePoint group name</param>
/// <returns>Integer group ID</returns>
public static int GetGroupID(this Web web, string groupName)
{
if (string.IsNullOrEmpty(groupName))
throw new ArgumentNullException("groupName");
int groupID = 0;
var manageMessageGroup = web.SiteGroups.GetByName(groupName);
web.Context.Load(manageMessageGroup);
web.Context.ExecuteQueryRetry();
if (manageMessageGroup != null)
{
groupID = manageMessageGroup.Id;
}
return groupID;
}
/// <summary>
/// Adds a group
/// </summary>
/// <param name="web">Site to add the group to</param>
/// <param name="groupName">Name of the group</param>
/// <param name="groupDescription">Description of the group</param>
/// <param name="groupIsOwner">Sets the created group as group owner if true</param>
/// <param name="updateAndExecuteQuery">Set to false to postpone the executequery call</param>
/// <param name="onlyAllowMembersViewMembership">Set whether members are allowed to see group membership, defaults to false</param>
/// <returns>The created group</returns>
public static Group AddGroup(this Web web, string groupName, string groupDescription, bool groupIsOwner, bool updateAndExecuteQuery = true, bool onlyAllowMembersViewMembership = false)
{
if (string.IsNullOrEmpty(groupName))
throw new ArgumentNullException("groupName");
GroupCreationInformation groupCreationInformation = new GroupCreationInformation();
groupCreationInformation.Title = groupName;
groupCreationInformation.Description = groupDescription;
Group group = web.SiteGroups.Add(groupCreationInformation);
if (groupIsOwner)
{
group.Owner = group;
}
group.OnlyAllowMembersViewMembership = onlyAllowMembersViewMembership;
group.Update();
if (updateAndExecuteQuery)
{
web.Context.ExecuteQueryRetry();
}
return group;
}
/// <summary>
/// Associate the provided groups as default owners, members or visitors groups. If a group is null then the
/// association is not done
/// </summary>
/// <param name="web">Site to operate on</param>
/// <param name="owners">Owners group</param>
/// <param name="members">Members group</param>
/// <param name="visitors">Visitors group</param>
public static void AssociateDefaultGroups(this Web web, Group owners, Group members, Group visitors)
{
if (owners != null)
{
web.AssociatedOwnerGroup = owners;
web.AssociatedOwnerGroup.Update();
}
if (members != null)
{
web.AssociatedMemberGroup = members;
web.AssociatedMemberGroup.Update();
}
if (visitors != null)
{
web.AssociatedVisitorGroup = visitors;
web.AssociatedVisitorGroup.Update();
}
web.Update();
web.Context.ExecuteQueryRetry();
}
/// <summary>
/// Adds a user to a group
/// </summary>
/// <param name="web">web to operate against</param>
/// <param name="groupName">Name of the group</param>
/// <param name="userLoginName">Loginname of the user</param>
public static void AddUserToGroup(this Web web, string groupName, string userLoginName)
{
if (string.IsNullOrEmpty(groupName))
throw new ArgumentNullException("groupName");
if (string.IsNullOrEmpty(userLoginName))
throw new ArgumentNullException("userLoginName");
//Ensure the user is known
UserCreationInformation userToAdd = new UserCreationInformation();
userToAdd.LoginName = userLoginName;
User user = web.EnsureUser(userToAdd.LoginName);
web.Context.Load(user);
//web.Context.ExecuteQueryRetry();
//Add the user to the group
var group = web.SiteGroups.GetByName(groupName);
web.Context.Load(group);
web.Context.ExecuteQueryRetry();
if (group != null)
{
web.AddUserToGroup(group, user);
}
}
/// <summary>
/// Adds a user to a group
/// </summary>
/// <param name="web">web to operate against</param>
/// /// <param name="groupId">Id of the group</param>
/// <param name="userLoginName">Login name of the user</param>
public static void AddUserToGroup(this Web web, int groupId, string userLoginName)
{
if (string.IsNullOrEmpty(userLoginName))
throw new ArgumentNullException("userLoginName");
Group group = web.SiteGroups.GetById(groupId);
web.Context.Load(group);
User user = web.EnsureUser(userLoginName);
web.Context.ExecuteQueryRetry();
if (user != null && group != null)
{
AddUserToGroup(web, group, user);
}
}
/// <summary>
/// Adds a user to a group
/// </summary>
/// <param name="web">Web to operate against</param>
/// <param name="group">Group object representing the group</param>
/// <param name="user">User object representing the user</param>
public static void AddUserToGroup(this Web web, Group group, User user)
{
if (group == null)
throw new ArgumentNullException("group");
if (user == null)
throw new ArgumentNullException("user");
group.Users.AddUser(user);
web.Context.ExecuteQueryRetry();
}
/// <summary>
/// Adds a user to a group
/// </summary>
/// <param name="web">Web to operate against</param>
/// <param name="group">Group object representing the group</param>
/// <param name="userLoginName">Login name of the user</param>
public static void AddUserToGroup(this Web web, Group group, string userLoginName)
{
if (group == null)
throw new ArgumentNullException("group");
if (string.IsNullOrEmpty(userLoginName))
throw new ArgumentNullException("userLoginName");
User user = web.EnsureUser(userLoginName);
web.Context.ExecuteQueryRetry();
if (user != null)
{
group.Users.AddUser(user);
web.Context.ExecuteQueryRetry();
}
}
/// <summary>
/// Add a permission level (e.g.Contribute, Reader,...) to a user
/// </summary>
/// <param name="securableObject">Web/List/Item to operate against</param>
/// <param name="userLoginName">Loginname of the user</param>
/// <param name="permissionLevel">Permission level to add</param>
/// <param name="removeExistingPermissionLevels">Set to true to remove all other permission levels for that user</param>
public static void AddPermissionLevelToUser(this SecurableObject securableObject, string userLoginName, RoleType permissionLevel, bool removeExistingPermissionLevels = false)
{
if (string.IsNullOrEmpty(userLoginName))
throw new ArgumentNullException("userLoginName");
Web web = securableObject.GetAssociatedWeb();
User user = web.EnsureUser(userLoginName);
securableObject.AddPermissionLevelToPrincipal(user, permissionLevel, removeExistingPermissionLevels);
}
/// <summary>
/// Add a role definition (e.g.Contribute, Read, Approve) to a user
/// </summary>
/// <param name="securableObject">Web/List/Item to operate against</param>
/// <param name="userLoginName">Loginname of the user</param>
/// <param name="roleDefinitionName">Name of the role definition to add, Full Control|Design|Contribute|Read|Approve|Manage Hierarchy|Restricted Read. Use the correct name of the language of the root site you are using</param>
/// <param name="removeExistingPermissionLevels">Set to true to remove all other permission levels for that user</param>
public static void AddPermissionLevelToUser(this SecurableObject securableObject, string userLoginName, string roleDefinitionName, bool removeExistingPermissionLevels = false)
{
if (string.IsNullOrEmpty(userLoginName))
throw new ArgumentNullException("userLoginName");
if (string.IsNullOrEmpty(roleDefinitionName))
throw new ArgumentNullException("roleDefinitionName");
Web web = securableObject.GetAssociatedWeb();
User user = web.EnsureUser(userLoginName);
securableObject.AddPermissionLevelToPrincipal(user, roleDefinitionName, removeExistingPermissionLevels);
}
/// <summary>
/// Add a permission level (e.g.Contribute, Reader,...) to a group
/// </summary>
/// <param name="securableObject">Web/List/Item to operate against</param>
/// <param name="groupName">Name of the group</param>
/// <param name="permissionLevel">Permission level to add</param>
/// <param name="removeExistingPermissionLevels">Set to true to remove all other permission levels for that group</param>
public static void AddPermissionLevelToGroup(this SecurableObject securableObject, string groupName, RoleType permissionLevel, bool removeExistingPermissionLevels = false)
{
if (string.IsNullOrEmpty(groupName))
throw new ArgumentNullException("groupName");
Web web = securableObject.GetAssociatedWeb();
var group = web.SiteGroups.GetByName(groupName);
securableObject.AddPermissionLevelToPrincipal(group, permissionLevel, removeExistingPermissionLevels);
}
/// <summary>
/// Add a permission level (e.g.Contribute, Reader,...) to a group
/// </summary>
/// <param name="securableObject">Web/List/Item to operate against</param>
/// <param name="principal">Principal to add permission to</param>
/// <param name="permissionLevel">Permission level to add</param>
/// <param name="removeExistingPermissionLevels">Set to true to remove all other permission levels for that group</param>
public static void AddPermissionLevelToPrincipal(this SecurableObject securableObject, Principal principal, RoleType permissionLevel, bool removeExistingPermissionLevels = false)
{
if (principal == null)
throw new ArgumentNullException("principal");
Web web = securableObject.GetAssociatedWeb();
securableObject.Context.Load(principal);
securableObject.Context.ExecuteQueryRetry();
RoleDefinition roleDefinition = web.RoleDefinitions.GetByType(permissionLevel);
securableObject.AddPermissionLevelImplementation(principal, roleDefinition, removeExistingPermissionLevels);
}
/// <summary>
/// Add a role definition (e.g.Contribute, Read, Approve) to a group
/// </summary>
/// <param name="securableObject">Web/List/Item to operate against</param>
/// <param name="groupName">Name of the group</param>
/// <param name="roleDefinitionName">Name of the role definition to add, Full Control|Design|Contribute|Read|Approve|Manage Hierarchy|Restricted Read. Use the correct name of the language of the root site you are using</param>
/// <param name="removeExistingPermissionLevels">Set to true to remove all other permission levels for that group</param>
public static void AddPermissionLevelToGroup(this SecurableObject securableObject, string groupName, string roleDefinitionName, bool removeExistingPermissionLevels = false)
{
if (string.IsNullOrEmpty(groupName))
throw new ArgumentNullException("groupName");
if (string.IsNullOrEmpty(roleDefinitionName))
throw new ArgumentNullException("roleDefinitionName");
Web web = securableObject.GetAssociatedWeb();
var group = web.SiteGroups.GetByName(groupName);
securableObject.AddPermissionLevelToPrincipal(group, roleDefinitionName, removeExistingPermissionLevels);
}
/// <summary>
/// Add a role definition (e.g.Contribute, Read, Approve) to a group
/// </summary>
/// <param name="securableObject">Web/List/Item to operate against</param>
/// <param name="principal">Principal to add permission to</param>
/// <param name="roleDefinitionName">Name of the role definition to add, Full Control|Design|Contribute|Read|Approve|Manage Hierarchy|Restricted Read. Use the correct name of the language of the root site you are using</param>
/// <param name="removeExistingPermissionLevels">Set to true to remove all other permission levels for that group</param>
public static void AddPermissionLevelToPrincipal(this SecurableObject securableObject, Principal principal, string roleDefinitionName, bool removeExistingPermissionLevels = false)
{
if (principal == null)
throw new ArgumentNullException("principal");
if (string.IsNullOrEmpty(roleDefinitionName))
throw new ArgumentNullException("roleDefinitionName");
Web web = securableObject.GetAssociatedWeb();
securableObject.Context.Load(principal);
securableObject.Context.ExecuteQueryRetry();
RoleDefinition roleDefinition = web.RoleDefinitions.GetByName(roleDefinitionName);
securableObject.AddPermissionLevelImplementation(principal, roleDefinition, removeExistingPermissionLevels);
}
private static void AddPermissionLevelImplementation(this SecurableObject securableObject, Principal principal, RoleDefinition roleDefinition, bool removeExistingPermissionLevels = false)
{
if (principal == null)
{
return;
}
var roleAssignments = securableObject.RoleAssignments;
securableObject.Context.Load(roleAssignments);
securableObject.Context.ExecuteQueryRetry();
var roleAssignment = roleAssignments.FirstOrDefault(ra => ra.PrincipalId.Equals(principal.Id));
//current principal doesn't have any roles assigned for this securableObject
if (roleAssignment == null)
{
var rdc = new RoleDefinitionBindingCollection(securableObject.Context);
rdc.Add(roleDefinition);
securableObject.RoleAssignments.Add(principal, rdc);
securableObject.Context.ExecuteQueryRetry();
}
else //current principal has roles assigned for this securableObject, then add new role definition for the role assignment
{
var roleDefinitionBindings = roleAssignment.RoleDefinitionBindings;
securableObject.Context.Load(roleDefinitionBindings);
securableObject.Context.ExecuteQueryRetry();
// Load the role definition to add (e.g. contribute)
if (removeExistingPermissionLevels)
{
// Remove current role definitions by removing all current role definitions
roleDefinitionBindings.RemoveAll();
}
// Add the selected role definition
if (!roleDefinitionBindings.Any(r => r.Name.Equals(roleDefinition.EnsureProperty(rd => rd.Name))))
{
roleDefinitionBindings.Add(roleDefinition);
//update
roleAssignment.ImportRoleDefinitionBindings(roleDefinitionBindings);
roleAssignment.Update();
securableObject.Context.ExecuteQueryRetry();
}
}
}
/// <summary>
/// Removes a permission level from a user
/// </summary>
/// <param name="securableObject">Web/List/Item to operate against</param>
/// <param name="userLoginName">Loginname of user</param>
/// <param name="permissionLevel">Permission level to remove. If null all permission levels are removed</param>
/// <param name="removeAllPermissionLevels">Set to true to remove all permission level.</param>
public static void RemovePermissionLevelFromUser(this SecurableObject securableObject, string userLoginName, RoleType permissionLevel, bool removeAllPermissionLevels = false)
{
if (string.IsNullOrEmpty(userLoginName))
throw new ArgumentNullException("userLoginName");
Web web = securableObject.GetAssociatedWeb();
User user = web.EnsureUser(userLoginName);
securableObject.RemovePermissionLevelFromPrincipal(user, permissionLevel, removeAllPermissionLevels);
}
/// <summary>
/// Removes a permission level from a user
/// </summary>
/// <param name="securableObject">Web/List/Item to operate against</param>
/// <param name="principal">Principal to remove permission from</param>
/// <param name="permissionLevel">Permission level to remove. If null all permission levels are removed</param>
/// <param name="removeAllPermissionLevels">Set to true to remove all permission level.</param>
public static void RemovePermissionLevelFromPrincipal(this SecurableObject securableObject, Principal principal, RoleType permissionLevel, bool removeAllPermissionLevels = false)
{
if (principal == null)
throw new ArgumentNullException("principal");
Web web = securableObject.GetAssociatedWeb();
securableObject.Context.Load(principal);
securableObject.Context.ExecuteQueryRetry();
RoleDefinition roleDefinition = web.RoleDefinitions.GetByType(permissionLevel);
securableObject.RemovePermissionLevelImplementation(principal, roleDefinition, removeAllPermissionLevels);
}
/// <summary>
/// Removes a permission level from a user
/// </summary>
/// <param name="securableObject">Web/List/Item to operate against</param>
/// <param name="userLoginName">Loginname of user</param>
/// <param name="roleDefinitionName">Name of the role definition to add, Full Control|Design|Contribute|Read|Approve|Manage Heirarchy|Restricted Read. Use the correct name of the language of the site you are using</param>
/// <param name="removeAllPermissionLevels">Set to true to remove all permission level.</param>
public static void RemovePermissionLevelFromUser(this SecurableObject securableObject, string userLoginName, string roleDefinitionName, bool removeAllPermissionLevels = false)
{
if (string.IsNullOrEmpty(userLoginName))
throw new ArgumentNullException("userLoginName");
Web web = securableObject.GetAssociatedWeb();
User user = web.EnsureUser(userLoginName);
securableObject.RemovePermissionLevelFromPrincipal(user, roleDefinitionName, removeAllPermissionLevels);
}
/// <summary>
/// Removes a permission level from a user
/// </summary>
/// <param name="securableObject">Web/List/Item to operate against</param>
/// <param name="principal">Principal to remove permission from</param>
/// <param name="roleDefinitionName">Name of the role definition to add, Full Control|Design|Contribute|Read|Approve|Manage Heirarchy|Restricted Read. Use the correct name of the language of the site you are using</param>
/// <param name="removeAllPermissionLevels">Set to true to remove all permission level.</param>
public static void RemovePermissionLevelFromPrincipal(this SecurableObject securableObject, Principal principal, string roleDefinitionName, bool removeAllPermissionLevels = false)
{
if (principal == null)
throw new ArgumentNullException("principal");
Web web = securableObject.GetAssociatedWeb();
securableObject.Context.Load(principal);
securableObject.Context.ExecuteQueryRetry();
RoleDefinition roleDefinition = web.RoleDefinitions.GetByName(roleDefinitionName);
securableObject.RemovePermissionLevelImplementation(principal, roleDefinition, removeAllPermissionLevels);
}
/// <summary>
/// Removes a permission level from a group
/// </summary>
/// <param name="securableObject">Web/List/Item to operate against</param>
/// <param name="groupName">name of the group</param>
/// <param name="permissionLevel">Permission level to remove. If null all permission levels are removed</param>
/// <param name="removeAllPermissionLevels">Set to true to remove all permission level.</param>
public static void RemovePermissionLevelFromGroup(this SecurableObject securableObject, string groupName, RoleType permissionLevel, bool removeAllPermissionLevels = false)
{
if (string.IsNullOrEmpty(groupName))
throw new ArgumentNullException("groupName");
Web web = securableObject.GetAssociatedWeb();
var group = web.SiteGroups.GetByName(groupName);
securableObject.Context.Load(group);
securableObject.Context.ExecuteQueryRetry();
RoleDefinition roleDefinition = web.RoleDefinitions.GetByType(permissionLevel);
securableObject.RemovePermissionLevelImplementation(group, roleDefinition, removeAllPermissionLevels);
}
/// <summary>
/// Removes a permission level from a group
/// </summary>
/// <param name="securableObject">Web/List/Item to operate against</param>
/// <param name="groupName">name of the group</param>
/// <param name="roleDefinitionName">Name of the role definition to add, Full Control|Design|Contribute|Read|Approve|Manage Heirarchy|Restricted Read. Use the correct name of the language of the site you are using</param>
/// <param name="removeAllPermissionLevels">Set to true to remove all permission level.</param>
public static void RemovePermissionLevelFromGroup(this SecurableObject securableObject, string groupName, string roleDefinitionName, bool removeAllPermissionLevels = false)
{
if (string.IsNullOrEmpty(groupName))
throw new ArgumentNullException("groupName");
Web web = securableObject.GetAssociatedWeb();
var group = web.SiteGroups.GetByName(groupName);
securableObject.Context.Load(group);
securableObject.Context.ExecuteQueryRetry();
RoleDefinition roleDefinition = web.RoleDefinitions.GetByName(roleDefinitionName);
securableObject.RemovePermissionLevelImplementation(group, roleDefinition, removeAllPermissionLevels);
}
private static void RemovePermissionLevelImplementation(this SecurableObject securableObject, Principal principal, RoleDefinition roleDefinition, bool removeAllPermissionLevels = false)
{
if (principal == null)
{
return;
}
var roleAssignments = securableObject.RoleAssignments;
securableObject.Context.Load(roleAssignments);
securableObject.Context.ExecuteQueryRetry();
var roleAssignment = roleAssignments.FirstOrDefault(ra => ra.PrincipalId.Equals(principal.Id));
if (roleAssignment != null)
{
// load the role definitions for this role assignment
var rdc = roleAssignment.RoleDefinitionBindings;
securableObject.Context.Load(rdc);
securableObject.Context.ExecuteQueryRetry();
if (removeAllPermissionLevels)
{
// Remove current role definitions by removing all current role definitions
rdc.RemoveAll();
}
else
{
// Load the role definition to remove (e.g. contribute)
rdc.Remove(roleDefinition);
}
//update
roleAssignment.ImportRoleDefinitionBindings(rdc);
roleAssignment.Update();
securableObject.Context.ExecuteQueryRetry();
}
}
private static Web GetAssociatedWeb(this SecurableObject securable)
{
if (securable is Web)
{
return (Web)securable;
}
if (securable is List)