-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApplyUnclassifiedSettings.cs
206 lines (168 loc) · 8.88 KB
/
ApplyUnclassifiedSettings.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
using System;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Graph;
using Newtonsoft.Json;
using System.Collections.Generic;
using Microsoft.SharePoint.Client;
using PnP.Framework.Entities;
using Azure.Core;
namespace appsvc_fnc_dev_scw_sensitivity_dotnet001
{
public class ApplyUnclassifiedSettings
{
[FunctionName("ApplyUnclassifiedSettings")]
public async Task RunAsync([QueueTrigger("unclassified", Connection = "AzureWebJobsStorage")] string myQueueItem, ILogger log, ExecutionContext functionContext)
{
log.LogInformation($"ApplyUnclassifiedSettings received a request: {myQueueItem}");
dynamic data = JsonConvert.DeserializeObject(myQueueItem);
IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).AddEnvironmentVariables().Build();
string groupId = data?.groupId;
string itemId = data?.itemId;
string labelId = config["unclassifiedLabelId"];
string ownerId = config["ownerId"]; // [email protected]
string readOnlyGroup = config["readOnlyGroup"]; // dgcx_allusers, dgcx_assigned
string requestId = data?.Id;
string SCAGroupName = config["sca_login_name"]; // dgcx_sca
string sharePointUrl = config["sharePointUrl"] + requestId;
string spaceNameEn = data?.SpaceName;
string spaceNameFr = data?.SpaceNameFR;
string supportGroupName = config["support_group_login_name"]; // dgcx_support
string tenantName = config["tenantName"];
ROPCConfidentialTokenCredential auth = new ROPCConfidentialTokenCredential(log);
var graphClient = new GraphServiceClient(auth);
var result = Common.ApplyLabel(graphClient, labelId, groupId, itemId, requestId, spaceNameEn, spaceNameFr, log);
if (result.Result == true)
{
// do not call method to set Visibility = Public
//await SetUnclassified(graphClient, groupId, log);
var scopes = new string[] { $"https://{tenantName}.sharepoint.com/.default" };
var authManager = new PnP.Framework.AuthenticationManager();
var accessToken = await auth.GetTokenAsync(new TokenRequestContext(scopes), new System.Threading.CancellationToken());
var ctx = authManager.GetAccessTokenContext(sharePointUrl, accessToken.Token);
bool result1 = await UpdateSiteCollectionAdministrator(ctx, SCAGroupName, groupId, log);
bool result2 = await AddGroupToFullControl(ctx, supportGroupName, log);
bool result3 = await AddGroupToReadOnly(ctx, readOnlyGroup, log);
bool result4 = await Common.RemoveOwner(graphClient, groupId, ownerId, log);
bool success = result1 && result2 && result3 && result4;
if (success) {
await Common.AddToStatusQueue(itemId, log);
await Common.AddToEmailQueue(requestId, groupId, spaceNameEn, spaceNameFr, (string)data?.RequesterName, (string)data?.RequesterEmail, log);
}
}
log.LogInformation($"ApplyUnclassifiedSettings processed a request.");
}
//private static async Task<IActionResult> SetUnclassified(GraphServiceClient graphClient, string groupId, ILogger log)
//{
// log.LogInformation("SetUnclassified received a request.");
// try
// {
// var group = new Microsoft.Graph.Group { Visibility = "Public" };
// await graphClient.Groups[groupId].Request().UpdateAsync(group);
// }
// catch (Exception e)
// {
// log.LogError($"Message: {e.Message}");
// if (e.InnerException is not null) log.LogError($"InnerException: {e.InnerException.Message}");
// log.LogError($"StackTrace: {e.StackTrace}");
// }
// log.LogInformation("SetUnclassified processed a request.");
// return new OkResult();
//}
public static Task<bool> UpdateSiteCollectionAdministrator(ClientContext ctx, string GroupLoginName, string groupId, ILogger log) // ClientContext ctx,
{
log.LogInformation("UpdateSiteCollectionAdministrator received a request.");
bool result = true;
try
{
ctx.Load(ctx.Web);
ctx.Load(ctx.Site);
ctx.Load(ctx.Site.RootWeb);
ctx.Load(ctx.Web.AssociatedOwnerGroup.Users);
ctx.ExecuteQuery();
// add dgcx_sca as Administrator
List<UserEntity> admins = new List<UserEntity>();
UserEntity adminUserEntity = new UserEntity();
adminUserEntity.LoginName = GroupLoginName;
admins.Add(adminUserEntity);
ctx.Site.RootWeb.AddAdministrators(admins, true);
// remove dgcx_sca from the owner group
ctx.Web.AssociatedOwnerGroup.Users.RemoveByLoginName(GroupLoginName);
// remove the owner group
string loginName = $"c:0o.c|federateddirectoryclaimprovider|{groupId}_o";
log.LogInformation($"Remove loginName = {loginName}");
UserEntity ownerGroupEntity = new UserEntity();
ownerGroupEntity.LoginName = loginName;
ctx.Site.RootWeb.RemoveAdministrator(ownerGroupEntity);
log.LogInformation($"Done!");
}
catch (Exception e)
{
log.LogError($"Message: {e.Message}");
if (e.InnerException is not null) log.LogError($"InnerException: {e.InnerException.Message}");
log.LogError($"StackTrace: {e.StackTrace}");
result = false;
}
log.LogInformation("UpdateSiteCollectionAdministrator processed a request.");
return Task.FromResult(result);
}
public static Task<bool> AddGroupToFullControl(ClientContext ctx, string GroupLoginName, ILogger log)
{
var result = true;
try
{
string permissionLevel = "Full Control";
var adGroup = ctx.Web.EnsureUser(GroupLoginName);
ctx.Load(adGroup);
var spGroup = ctx.Web.AssociatedMemberGroup;
var writeDefinition = ctx.Web.RoleDefinitions.GetByName(permissionLevel);
var roleDefCollection = new RoleDefinitionBindingCollection(ctx) { writeDefinition};
var newRoleAssignment = ctx.Web.RoleAssignments.Add(adGroup, roleDefCollection);
ctx.Load(spGroup, x => x.Users);
ctx.ExecuteQuery();
}
catch (Exception e)
{
log.LogError($"Message: {e.Message}");
if (e.InnerException is not null) log.LogError($"InnerException: {e.InnerException.Message}");
log.LogError($"StackTrace: {e.StackTrace}");
result = false;
}
return Task.FromResult(result);
}
public static Task<bool> AddGroupToReadOnly(ClientContext ctx, string groups, ILogger log)
{
string permissionLevel = "Read";
var result = true;
try
{
// this prevents the Hub Visitor group from being added to site permissions
ctx.Load(ctx.Site);
ctx.Site.CanSyncHubSitePermissions = false;
// break inheritance on the default document library to prevent access to read-only
ctx.Web.DefaultDocumentLibrary().BreakRoleInheritance(true, true);
foreach (string group in groups.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
{
var adGroup = ctx.Web.EnsureUser(group);
ctx.Load(adGroup);
var spGroup = ctx.Web.AssociatedMemberGroup;
var writeDefinition = ctx.Web.RoleDefinitions.GetByName(permissionLevel);
var roleDefCollection = new RoleDefinitionBindingCollection(ctx) { writeDefinition };
var newRoleAssignment = ctx.Web.RoleAssignments.Add(adGroup, roleDefCollection);
ctx.Load(spGroup, x => x.Users);
ctx.ExecuteQuery();
}
}
catch (Exception e)
{
log.LogError($"Message: {e.Message}");
if (e.InnerException is not null) log.LogError($"InnerException: {e.InnerException.Message}");
log.LogError($"StackTrace: {e.StackTrace}");
result = false;
}
return Task.FromResult(result);
}
}
}