-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcreate.ps1
350 lines (303 loc) · 12.2 KB
/
create.ps1
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
#region Initialize default properties
$config = ConvertFrom-Json $configuration
$p = $person | ConvertFrom-Json
$pp = $previousPerson | ConvertFrom-Json
$pd = $personDifferences | ConvertFrom-Json
$m = $manager | ConvertFrom-Json
$success = $False
$auditLogs = [Collections.Generic.List[PSCustomObject]]@()
#endregion Initialize default properties
#region Support Functions
function Get-ConfigProperty
{
[cmdletbinding()]
Param (
[object]$object,
[string]$property
)
Process {
$subItems = $property.split('.')
$value = $object.psObject.copy()
for($i = 0; $i -lt $subItems.count; $i++)
{
$value = $value."$($subItems[$i])"
}
return $value
}
}
function New-RandomPassword($PasswordLength)
{
# Length of the password to be generated
#$PasswordLength = 20
if($PasswordLength -lt 4) {$PasswordLength = 4}
# Used to store an array of characters that can be used for the password
$CharPool = [System.Collections.ArrayList]@()
# Add characters a-z to the arraylist
for ($index = 97; $index -le 122; $index++) { [Void]$CharPool.Add([char]$index) }
# Add characters A-Z to the arraylist
for ($index = 65; $index -le 90; $index++) { [Void]$CharPool.Add([Char]$index) }
# Add digits 0-9 to the arraylist
$CharPool.AddRange(@("0","1","2","3","4","5","6","7","8","9"))
# Add a range of special characters to the arraylist
$CharPool.AddRange(@("!","""","#","$","%","&","'","(",")","*","+","-",".","/",":",";","<","=",">","?","@","[","\","]","^","_","{","|","}","~","!"))
$password=""
$rand= [System.Random]::new()
# Generate password by appending a random value from the array list until desired length of password is reached
1..$PasswordLength | foreach { $password = $password + $CharPool[$rand.Next(0,$CharPool.Count)] }
#print password
$password
}
function Get-GoogleAccessToken() {
### exchange the refresh token for an access token
$requestUri = "https://www.googleapis.com/oauth2/v4/token"
$refreshTokenParams = @{
client_id=$config.clientId;
client_secret=$config.clientSecret;
redirect_uri=$config.redirectUri;
refresh_token=$config.refreshToken;
grant_type="refresh_token"; # Fixed value
};
$response = Invoke-RestMethod -Method Post -Uri $requestUri -Body $refreshTokenParams -Verbose:$false
$accessToken = $response.access_token
#Add the authorization header to the request
$authorization = [ordered]@{
Authorization = "Bearer $($accesstoken)";
'Content-Type' = "application/json; charset=utf-8";
Accept = "application/json";
}
$authorization
}
#Primary Email Generation
# 1. <First Name>.<Last Name>@<Domain> (e.g john.williams@yourdomain.com)
# 2. <First Name>.<Last Name><Iterator>@<Domain> (e.g john.williams2@yourdomain.com)
function New-PrimaryEmail {
[cmdletbinding()]
Param (
[object]$person,
[string]$domain,
[int]$Iteration
)
Process {
$suffix = "";
if($Iteration -gt 0) { $suffix = "$($Iteration+1)" };
#Check Nickname
if([string]::IsNullOrEmpty($p.Name.Nickname)) { $tempFirstName = $p.Name.GivenName } else { $tempFirstName = $p.Name.Nickname }
$tempLastName = $person.Name.FamilyName;
$tempUsername = ("{0}.{1}" -f $tempFirstName,$tempLastName);
$tempUsername = $tempUsername.substring(0,[Math]::Min(20-$suffix.Length,$tempUsername.Length));
$result = ("{0}{1}@{2}" -f $tempUsername, $suffix, $domain);
$result = $result.toLower();
return $result;
}
}
function Get-CorrelationResult {
[cmdletbinding()]
Param (
[object]$authorization,
[string]$field,
[string]$value
)
Process {
$splat = @{
Body = @{
customer = "my_customer"
query = "$($field)=$($value)"
projection="FULL"
}
Uri = "https://www.googleapis.com/admin/directory/v1/users"
Method = 'GET'
Headers = $authorization
Verbose = $False
}
$correlationResponse = Invoke-RestMethod @splat
return $correlationResponse
}
}
#endregion Support Functions
#region Change mapping here
#Defaults, create only
$usePasswordHash = $true
$defaultPassword = New-RandomPassword(8)
$passwordHash = [System.BitConverter]::ToString(([System.Security.Cryptography.SHA1CryptoServiceProvider]::new()).ComputeHash((([System.Text.UTF8Encoding]::new()).GetBytes($defaultPassword)))).Replace("-","")
$defaultDomain = $config.defaultDomain
$defaultOrgUnitPath = "/Disabled"
$defaultSuspended = $true
#Correlation
$useCorrelation = $config.correlationEnabled;
$correlationPersonField = Get-ConfigProperty -object $p -property ($config.correlationPersonField -replace '\$p.','')
$correlationAccountField = $config.correlationAccountField
#Username Generation
$maxUsernameIterations = 10
$calcPrimaryEmail = New-PrimaryEmail -person $p -domain $defaultDomain -Iteration 0
Write-Information "Initial Generated Email: $($calcPrimaryEmail)"
#Determine First Name (NickName vs GivenName)
if([string]::IsNullOrEmpty($p.Name.Nickname)) { $calcFirstName = $p.Name.GivenName } else { $calcFirstName = $p.Name.Nickname }
#For all of the supported attributes please check https://developers.google.com/admin-sdk/directory/v1/guides/manage-users
$account = [ordered]@{
primaryEmail = $calcPrimaryEmail
name = @{
givenName = "$($calcFirstName)"
familyName = "$($p.Name.FamilyName)"
fullName = "$($calcFirstName) $($p.Name.FamilyName)"
}
externalIds = @(@{
value = "$($p.ExternalId)"
type = "organization" # EmployeeID
})
organizations = @(@{
title = "$($p.primaryContract.Title.name)"
department = "$($p.primaryContract.Department.name)"
})
# phones = @(@{
# value = "$($p.contact.business.phone.mobile)"
# type = 'mobile'
# })
# relations = @(@{
# value = "$($p.primaryManager.email)"
# type = 'manager'
# })
# includeInGlobalAddressList = $false
}
#endregion Change mapping here
#region Execute
try
{
#Add the authorization header to the request
$authorization = Get-GoogleAccessToken
if($useCorrelation)
{
#Check if account exists (based on externalId), else create
$splat = @{
authorization = $authorization
field = $correlationAccountField
value = $correlationPersonField
}
$correlationResponse = Get-CorrelationResult @splat
}
if($correlationResponse.users.count -gt 0)
{
Write-Information ("Existing Account found: (Found count: {0}) {1}" -f $correlationResponse.users.count,($correlationResponse.users | ConvertTo-Json -Depth 20))
$aRef = $correlationResponse.users[0].id
#Use existing primaryEmail and OrgUnitPath
$calcPrimaryEmail = $correlationResponse.users[0].primaryEmail
$account.primaryEmail = $calcPrimaryEmail
$account.orgUnitPath = $correlationResponse.users[0].orgUnitPath
# Update Existing User
if(-Not($dryRun -eq $True)){
$previousAccount = $correlationResponse.users[0]
$auditLogs.Add([PSCustomObject]@{
Action = "CreateAccount"
Message = "Found and correlated account with PrimaryEmail $($previousAccount.primaryEmail)"
IsError = $false;
});
$splat = [ordered]@{
body = [System.Text.Encoding]::UTF8.GetBytes(($account | ConvertTo-Json -Depth 10))
Uri = "https://www.googleapis.com/admin/directory/v1/users/$($aRef)"
Method = 'PUT'
Headers = $authorization
Verbose = $False
}
$newAccount = Invoke-RestMethod @splat
$auditLogs.Add([PSCustomObject]@{
Action = "UpdateAccount"
Message = "Updated Existing Account"
IsError = $false;
});
Write-Information ("Updated Existing Account: {0}" -f ($newAccount | ConvertTo-Json -Depth 10))
}
}
else
{
# Verify Primary Email Uniqueness (NOTE: only checks against other Google accounts)
$Iterator = 0
do {
#Check if username taken
$splat = [ordered]@{
Body = @{
customer = "my_customer"
query = "Email=$($account.primaryEmail)"
projection="FULL"
}
Uri = "https://www.googleapis.com/admin/directory/v1/users"
Method = 'GET'
Headers = $authorization
Verbose =$False
}
$calcPrimaryEmailResponse = Invoke-RestMethod @splat
if($calcPrimaryEmailResponse.users.count -gt 0)
{
#Iterate
Write-Information "$($account.primaryEmail) already in use, iterating)"
$Iterator++
$calcPrimaryEmail = New-PrimaryEmail -person $p -domain $defaultDomain -Iteration $Iterator
$account.primaryEmail = $calcPrimaryEmail
Write-Information "Iteration $($Iterator) - $($account.primaryEmail)"
}
} while ($calcPrimaryEmailResponse.users.count -gt 0 -AND $Iterator -lt $maxUsernameIterations)
#Check for exceeding max namegen iterations
if($Iterator -ge $maxUsernameIterations)
{
throw "Max NameGen Iterations tested. No unique Primary Email values found. Iterated values may not be allowed in NameGen algorithm."
}
#Proceed with account creation, set additional defaults
if($usePasswordHash -eq $true)
{
$account.password = $passwordHash
$account.hashFunction = "SHA-1"
}
else
{
$account.password = $defaultPassword
}
$account.orgUnitPath = $defaultOrgUnitPath
$account.suspended = $defaultSuspended
if(-Not($dryRun -eq $True)){
$splat = [ordered]@{
Body = [System.Text.Encoding]::UTF8.GetBytes(($account | ConvertTo-Json -Depth 10))
Uri = "https://www.googleapis.com/admin/directory/v1/users/$($aRef)"
Method = 'POST'
Headers = $authorization
Verbose = $False
}
$newAccount = Invoke-RestMethod @splat
$aRef = $newAccount.id
Write-Information ("New Account Created: {0}" -f ($newAccount | ConvertTo-Json -Depth 10))
# Add Password for use in Onboard Notification
$newAccount | Add-Member -NotePropertyName password -NotePropertyValue $defaultPassword
$auditLogs.Add([PSCustomObject]@{
Action = "CreateAccount"
Message = "Created account with PrimaryEmail $($newAccount.primaryEmail)"
IsError = $false;
});
}
else
{
$newAccount = $account;
}
}
$success = $True
}catch{
$auditLogs.Add([PSCustomObject]@{
Action = "CreateAccount"
Message = "Error creating account with PrimaryEmail $($account.primaryEmail) - Error: $($_)"
IsError = $true;
});
Write-Error $_
Write-Error $_.ErrorDetails.Message
}
#endregion Execute
#region Build up result
$result = [PSCustomObject]@{
Success = $success
AccountReference = $aRef
AuditLogs = $auditLogs;
Account = $newAccount
PreviousAccount = $previousAccount
# Optionally return data for use in other systems
ExportData = [PSCustomObject]@{
PrimaryEmail = $newAccount.PrimaryEmail
OrgUnitPath = $newAccount.orgUnitPath
}
}
Write-Output ($result | ConvertTo-Json -Depth 10)
#endregion build up result