-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathUMN-Google.psm1
2660 lines (2103 loc) · 93.3 KB
/
UMN-Google.psm1
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
###############
# Module for interacting with Google API
# More details found at https://developers.google.com/sheets/ and https://developers.google.com/drive/
#
###############
###
# Copyright 2024 University of Minnesota, Office of Information Technology
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Foobar. If not, see <http://www.gnu.org/licenses/>.
###
#region Dependancies
function ConvertTo-Base64URL
{
<#
.Synopsis
Convert text or byte array to URL friendly Base64
.DESCRIPTION
Used for preparing the JWT token format.
.PARAMETER bytes
The bytes to be converted
.PARAMETER text
The text to be converted
.EXAMPLE
ConvertTo-Base64URL -text $headerJSON
.EXAMPLE
ConvertTo-Base64URL -Bytes $rsa.SignData($toSign,"SHA256")
#>
param
(
[Parameter(ParameterSetName='Bytes')]
[System.Byte[]]$Bytes,
[Parameter(ParameterSetName='String')]
[string]$text
)
if($Bytes){$base = $Bytes}
else{$base = [System.Text.Encoding]::UTF8.GetBytes($text)}
$base64Url = [System.Convert]::ToBase64String($base)
$base64Url = $base64Url.Split('=')[0]
$base64Url = $base64Url.Replace('+', '-')
$base64Url = $base64Url.Replace('/', '_')
$base64Url
}
#endregion
#region oAuth 2.0
#region Get-GOAuthTokenService
function Get-GOAuthTokenService
{
<#
.Synopsis
Get google oAuth 2 token for a service account
.DESCRIPTION
This is used in server-server OAuth token generation
This function will use a certificate to generate an RSA token that will be used to sign a JWT token which is needed to generate the access key.
The certificate can be specified as file path and password to read the certificate from.
It can also be specified as an object, such was when running in Automation that will return a certificate object
The RSA token can also be specified directly if needed instead of generating it from a certificate
.PARAMETER jsonPath
Local or network path to JSON auth file generated from GCP Service Principal
.PARAMETER certPath
Local or network path to .p12 used to sign the JWT token, requires certPswd to also be specified
.PARAMETER certPswd
Password to access the private key in the .p12, requires certPath to also be specified
.PARAMETER certObj
Certificate object that will be used to sign the JWT token
.PARAMETER RSA
provide the System.Security.Cryptography.RSACryptoServiceProvider object directly that will be used to sign the JWT token
.PARAMETER iss
This is the Google Service account address
.PARAMETER scope
The API scopes to be included in the request. Space delimited, "https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/drive".
.PARAMETER jsonString
A JSON object where the RSA Content is stored as "private_key" such as from a keyVault. Expecting the string as Google provided from GCP IAM Service Principal.
.EXAMPLE
Get-GOAuthTokenService -scope "https://www.googleapis.com/auth/spreadsheets" -certPath "C:\users\$env:username\Desktop\googleSheets.p12" -certPswd 'notasecret' -iss "[email protected]"
Generates an access token using the given certificate file and password
.EXAMPLE
Get-GOAuthTokenService -rsa $rsaSecurityObject -scope "https://www.googleapis.com/auth/spreadsheets" -iss "[email protected]"
Generates an access token using the given rsa object
.EXAMPLE
Get-GOAuthTokenService -certObj $GoogleCert -scope "https://www.googleapis.com/auth/spreadsheets" -iss "[email protected]"
Generates an access token using the given certificate object
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory)]
[string]$iss,
[Parameter(Mandatory)]
[string]$scope,
[Parameter(Mandatory,ParameterSetName='CertificateFile')]
[string]$certPath,
[Parameter(Mandatory,ParameterSetName='CertificateFile')]
[string]$certPswd,
[Parameter(Mandatory,ParameterSetName='CertificateObject')]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$certObj,
[Parameter(Mandatory,ParameterSetName='jsonFile')]
[string]$jsonPath,
[Parameter(Mandatory,ParameterSetName='jsonString')]
[string]$jsonString,
[Parameter(Mandatory,ParameterSetName='RSA')]
[System.Security.Cryptography.RSACryptoServiceProvider]$rsa
)
Begin
{
# build JWT header
$headerJSON = [Ordered]@{
alg = "RS256"
typ = "JWT"
} | ConvertTo-Json -Compress
$headerBase64 = ConvertTo-Base64URL -text $headerJSON
}
Process
{
# Build claims for JWT
$iat = [int64]([double]::Parse((get-date -date ([DateTime]::UtcNow) -uformat "%s"),[cultureinfo][system.threading.thread]::currentthread.currentculture))
$exp = $iat + 59*60
$aud = "https://www.googleapis.com/oauth2/v4/token"
$claimsJSON = [Ordered]@{
iss = $iss
scope = $scope
aud = $aud
exp = $exp
iat = $iat
} | ConvertTo-Json -Compress
$claimsBase64 = ConvertTo-Base64URL -text $claimsJSON
################# Create JWT
# Prep JWT certificate signing
switch ($PSCmdlet.ParameterSetName) {
'CertificateFile' {
Write-Verbose "Assembling RSA object based on given certificate file and password"
$googleCert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certPath, $certPswd,[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable )
$rsaPrivate = $googleCert.PrivateKey
$rsa = New-Object System.Security.Cryptography.RSACryptoServiceProvider
$null = $rsa.ImportParameters($rsaPrivate.ExportParameters($true))
}
'CertificateObject' {
Write-Verbose "Assembling RSA object based on given certificate object"
$rsaPrivate = $certObj.PrivateKey
$rsa = New-Object System.Security.Cryptography.RSACryptoServiceProvider
$null = $rsa.ImportParameters($rsaPrivate.ExportParameters($true))
}
'RSA' {
Write-Verbose "Using given RSA object as is"
}
'jsonFile' {
Write-Verbose "Pulling private key from jsonAuth file"
$versionTest = $psversiontable.psversion.major
If ($versionTest -eq '5')
{
write-error "powerShell major version 5 detected, and not supported for JSON Auth file. Please use .p12 or RSA key"
}
Else
{
$jsonContents = Get-Content -Raw -Path $jsonPath | ConvertFrom-Json
$privateKeyRSA = $jsonContents.private_key
$rsa_parameters = [System.Security.Cryptography.RSA]::create()
[System.Security.Cryptography.RSACryptoServiceProvider]$rsa_parameters.ImportFromPem($privateKeyRSA)
$rsa = New-Object System.Security.Cryptography.RSACryptoServiceProvider
$rsa.ImportParameters($rsa_parameters.ExportParameters($true))
}
}
'jsonString' {
Write-Verbose "Pulling private key from jsonString"
$versionTest = $psversiontable.psversion.major
If ($versionTest -eq '5')
{
write-error "powerShell major version 5 detected, and not supported for JSON Auth string. Please use .p12 or RSA key"
}
Else
{
$privateKeyRSA = ($jsonString | ConvertFrom-Json).private_key
$rsa_parameters = [System.Security.Cryptography.RSA]::create()
[System.Security.Cryptography.RSACryptoServiceProvider]$rsa_parameters.ImportFromPem($privateKeyRSA)
$rsa = New-Object System.Security.Cryptography.RSACryptoServiceProvider
$rsa.ImportParameters($rsa_parameters.ExportParameters($true))
}
}
Default {
throw "Unknown parameter set"
}
}
# Signature is our base64urlencoded header and claims, delimited by a period.
$toSign = [System.Text.Encoding]::UTF8.GetBytes($headerBase64 + "." + $claimsBase64)
$signature = ConvertTo-Base64URL -Bytes $rsa.SignData($toSign,"SHA256") ## this needs to be converted back to regular text
# Build request
$jwt = $headerBase64 + "." + $claimsBase64 + "." + $signature
$fields = 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion='+$jwt
# Fetch token
$response = Invoke-RestMethod -Uri "https://www.googleapis.com/oauth2/v4/token" -Method Post -Body $fields -ContentType "application/x-www-form-urlencoded"
}
End
{
return $response.access_token
}
}
#endregion
#region Get-GOAuthTokenUser
function Get-GOAuthTokenUser
{
<#
.Synopsis
Get Valid OAuth Token. Requires a version of Selenium Web Browser driver to work with web interface.
.PARAMETER appKey
The google project App Key
.PARAMETER appSecret
The google project application secret
.PARAMETER redirectUri
An https project redirect. Can be anything as long as https
.PARAMETER refreshToken
A refresh token if refreshing
.PARAMETER scope
The API scopes to be included in the request. Space delimited, "https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/drive"
.PARAMETER webDriverPath
File path to selenium webdriver.dll - will add-type the driver .dll if needed and provided.
.EXAMPLE
Get-GOAuthTokenUser -appKey $appKey -appSecret $appSecret -redirectUri $redirectUri -scope $scope
.EXAMPLE
Get-GOAuthTokenUser -appKey $appKey -appSecret $appSecret -redirectUri $redirectUri -scope $scope -refreshToken $refreshToken
.NOTES
Requires GUI with Internet Explorer to get first token.
#>
[CmdletBinding()]
[OutputType([array])]
Param
(
[Parameter(Mandatory)]
[string]$appKey,
[Parameter(Mandatory)]
[string]$appSecret,
[Parameter(Mandatory)]
[string]$redirectUri,
[Parameter(Mandatory)]
[string]$scope,
[string]$refreshToken,
[string]$webDriverPath
)
Begin
{
$requestUri = "https://accounts.google.com/o/oauth2/token"
}
Process
{
if(!($refreshToken))
{
### Get the authorization code - browser Popup and user interaction section
$auth_string = "https://accounts.google.com/o/oauth2/auth?scope=$scope&response_type=code&redirect_uri=$redirectUri&client_id=$appKey&access_type=offline&approval_prompt=force"
Add-Type -Path ("$($webDriverPath)\WebDriver.dll")
$edgeDriver = New-Object OpenQA.Selenium.Edge.EdgeDriver
start-sleep 2
$edgeDriver.Navigate().GoToURL("$auth_string")
#Wait for user interaction in selenium browser, manual approval
do{Start-Sleep 1}until($edgeDriver.Url -match 'code=([^&]*)')
$null = $edgeDriver.LocationURL -match 'code=([^&]*)'
$authorizationCode = $matches[1]
$null = $edgeDriver.Quit()
# exchange the authorization code for a refresh token and access token
$requestBody = "code=$authorizationCode&client_id=$appKey&client_secret=$appSecret&grant_type=authorization_code&redirect_uri=$redirectUri"
$response = Invoke-RestMethod -Method Post -Uri $requestUri -ContentType "application/x-www-form-urlencoded" -Body $requestBody
}
else
{
# Exchange the refresh token for new tokens
$requestBody = "refresh_token=$refreshToken&client_id=$appKey&client_secret=$appSecret&grant_type=refresh_token"
$response = Invoke-RestMethod -Method Post -Uri $requestUri -ContentType "application/x-www-form-urlencoded" -Body $requestBody
Add-Member -InputObject $response -NotePropertyName refreshToken -NotePropertyValue $refreshToken
}
}
End
{
# add alias for backwards compatability
Add-Member -InputObject $response -MemberType AliasProperty -Name accesstoken -Value access_token
return $response
}
}
#endregion
#region Get-GOAuthTokenDevice
function Get-GOAuthTokenDevice
{
<#
.Synopsis
Get Valid OAuth Token. Provides login URL for any browser to allow for lack of web driver.
.PARAMETER appKey
The google project App Key
.PARAMETER appSecret
The google project application secret
.PARAMETER redirectUri
An https project redirect. Can be anything as long as https
.PARAMETER refreshToken
A refresh token if refreshing
.PARAMETER scope
The API scopes to be included in the request. Space delimited, "https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/drive"
.EXAMPLE
Get-GOAuthTokenDevice -appKey $appKey -redirectUri $redirectUri -scope $scope
.EXAMPLE
Get-GOAuthTokenDevice -appKey $appKey -appSecret $appSecret -redirectUri $redirectUri -scope $scope -refreshToken $refreshToken
.NOTES
Requires 2nd device with browser. User interaction required.
#>
[CmdletBinding()]
[OutputType([array])]
Param
(
[Parameter(Mandatory)]
[string]$appKey,
[Parameter(Mandatory)]
[string]$appSecret,
[Parameter(Mandatory)]
[string]$redirectUri,
[Parameter(Mandatory)]
[string]$scope,
[string]$refreshToken
)
Begin
{
$requestUri = "https://accounts.google.com/o/oauth2/token"
}
Process
{
if(!($refreshToken))
{
### Get the authorization code - browser Popup and user interaction section
$auth_string = "https://accounts.google.com/o/oauth2/auth?scope=$scope&response_type=code&redirect_uri=$redirectUri&client_id=$appKey&access_type=offline&approval_prompt=force"
$authorizationUrl = Read-Host -Prompt "Visit ` $auth_string ` to authenticate and authorize the app. Paste the all text beyond the code= response in order to continue" -MaskInput
$authorizationUrl -match 'code=([^&]*)'
$authorizationCode = $matches[1]
# exchange the authorization code for a refresh token and access token
$requestBody = "code=$authorizationCode&client_id=$appKey&client_secret=$appSecret&grant_type=authorization_code&redirect_uri=$redirectUri"
$response = Invoke-RestMethod -Method Post -Uri $requestUri -ContentType "application/x-www-form-urlencoded" -Body $requestBody
}
else
{
# Exchange the refresh token for new tokens
$requestBody = "refresh_token=$refreshToken&client_id=$appKey&client_secret=$appSecret&grant_type=refresh_token"
$response = Invoke-RestMethod -Method Post -Uri $requestUri -ContentType "application/x-www-form-urlencoded" -Body $requestBody
Add-Member -InputObject $response -NotePropertyName refreshToken -NotePropertyValue $refreshToken
}
}
End
{
# add alias for backwards compatability
Add-Member -InputObject $response -MemberType AliasProperty -Name accesstoken -Value access_token
return $response
}
}
#endregion
#region Get-GOAuthIdTokenSelenium
function Get-GOAuthIdTokenSelenium
{
<#
.Synopsis
Get Valid OAuth ID token for a user.
.DESCRIPTION
The ID token is signed by google to represent a user https://developers.google.com/identity/sign-in/web/backend-auth.
.PARAMETER clientID
Client ID within app project
.PARAMETER redirectUri
An https project redirect. Can be anything as long as https
.PARAMETER scope
The API scopes to be included in the request. Space delimited, "https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/drive"
.PARAMETER webDriverPath
Path to selenium webdriver - will update path of system to include.
.EXAMPLE
Get-GOAuthIdToken -clientID $clientID -scope $scope -redirectUri $redirectURI
.NOTES
Requires GUI with Edge and Selenium web browser.
#>
[CmdletBinding()]
[OutputType([array])]
Param
(
[Parameter(Mandatory)]
[string]$clientID,
[Parameter(Mandatory)]
[string]$redirectUri,
[Parameter(Mandatory)]
[string]$scope,
[string]$webDriverPath
)
Begin
{
$requestUri = "https://accounts.google.com/o/oauth2/token"
Add-Type -Path ("$($webDriverPath)\WebDriver.dll")
}
Process
{
### Get the ID Token - Browser Popup and user interaction section
$auth_string = "https://accounts.google.com/o/oauth2/auth?scope=$scope&response_type=token%20id_token&redirect_uri=$redirectUri&client_id=$clientID&approval_prompt=force"
$edgeDriver = New-Object OpenQA.Selenium.Edge.EdgeDriver
start-sleep 2
$edgeDriver.Navigate().GoToURL("$auth_string")
#Wait for user interaction in selenium browser, manual approval
do{Start-Sleep 1}until($edgeDriver.Url -match 'id_token=([^&]*)')
$null = $edgeDriver.LocationURL -match 'id_token=([^&]*)'
$id_token = $matches[1]
$null = $edgeDriver.Quit()
return $id_token
}
End{}
}
#endregion
#region Get-GOAuthIdToken
function Get-GOAuthIdToken
{
<#
.Synopsis
Get Valid OAuth ID token for a user.
.DESCRIPTION
The ID token is signed by google to represent a user https://developers.google.com/identity/sign-in/web/backend-auth.
.PARAMETER clientID
Client ID within app project
.PARAMETER redirectUri
An https project redirect. Can be anything as long as https
.PARAMETER scope
The API scopes to be included in the request. Space delimited, "https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/drive"
.EXAMPLE
Get-GOAuthIdToken -clientID $clientID -scope $scope -redirectUri $redirectURI
.NOTES
Requires GUI with Internet Explorer to get first token.
#>
[CmdletBinding()]
[OutputType([array])]
Param
(
[Parameter(Mandatory)]
[string]$clientID,
[Parameter(Mandatory)]
[string]$redirectUri,
[Parameter(Mandatory)]
[string]$scope
)
Begin
{
$requestUri = "https://accounts.google.com/o/oauth2/token"
}
Process
{
### Get the ID Token - IE Popup and user interaction section
$auth_string = "https://accounts.google.com/o/oauth2/auth?scope=$scope&response_type=token%20id_token&redirect_uri=$redirectUri&client_id=$clientID&approval_prompt=force"
$ie = New-Object -comObject InternetExplorer.Application
$ie.visible = $true
$null = $ie.navigate($auth_string)
#Wait for user interaction in IE, manual approval
do{Start-Sleep 1}until($ie.LocationURL -match 'id_token=([^&]*)')
$null = $ie.LocationURL -match 'id_token=([^&]*)'
Write-Debug $ie.LocationURL
$id_token = $matches[1]
$null = $ie.Quit()
return $id_token
}
End{}
}
#endregion
#region invoke wrapper
function Invoke-GWrapper
{
<#
.Synopsis
Wraps any invoke-restmethod in a retry wrapper. Needs work...
.DESCRIPTION
Finding many Google APIs fail for many non critical reasons.
.PARAMETER uri
The uri to be invoked
.PARAMETER headers
The provided header
.PARAMETER method
The method to invoke
.PARAMETER body
A hashtable body
.EXAMPLE
Invoke-GWrapper -uri $uri -header $header
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]
$uri,
[Parameter(Mandatory=$true)]
[hashtable]
$headers,
[Parameter(Mandatory=$true)]
[ValidateSet("get","post","patch","delete")]
$method,
[hashtable]
$body
)
Begin{
$completed = $false
[int]$retrycount = 0
[int]$SecondsDelay = 5
[int]$retries = 5
if ($body) {
$bodyJson = $body | ConvertTo-Json -Depth 10
Write-Verbose -Message "Method set to: Post"
}
}
Process
{
while (-not $completed) {
try{
If($bodyJson){$response = Invoke-RestMethod -Uri $uri -Headers $header -Body $bodyJson -Method $method}
Else{$response = Invoke-RestMethod -Uri $uri -Headers $headers -Method $method}
$completed = $true
}
catch {
if ($retrycount -ge $Retries) {
throw
}
else {
Start-Sleep $SecondsDelay
$retrycount++
$secondsDelay = $SecondsDelay * $retryCount
}
}
}
}
End{return $response}
}
#endregion
#region Get-GFile
function Get-GFile
{
<#
.Synopsis
Download a Google File.
.DESCRIPTION
Download a Google File based on a case sensative file or fileID.
.PARAMETER accessToken
access token used for authentication. Get from Get-GOAuthTokenUser or Get-GOAuthTokenService
.PARAMETER fileName
Name of file to retrive ID for. Case sensitive
.PARAMETER fileID
File ID. Can be gotten from Get-GFileID
.PARAMETER outFilePath
Path to output file including file name.
.EXAMPLE
Get-GFile -accessToken $accessToken -fileName 'Name of some file'
.EXAMPLE
Get-GFile -accessToken $accessToken -fileID 'ID of some file'
.NOTES
Written by Travis Sobeck
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory)]
[string]$accessToken,
[Parameter(ParameterSetName='fileName')]
[string]$fileName,
[Parameter(ParameterSetName='fileID')]
[string]$fileID,
[Parameter(Mandatory)]
[string]$outFilePath
#[string]$mimetype
)
Begin{}
Process
{
if ($fileName){$fileID = Get-GFileID -accessToken $accessToken -fileName $fileName}
If ($fileID.count -eq 0 -or $fileID.count -gt 1){break}
$uri = "https://www.googleapis.com/drive/v3/files/$($fileID)?alt=media"
Invoke-RestMethod -Method Get -Uri $uri -Headers @{"Authorization"="Bearer $accessToken"} -OutFile $outFilePath
}
End{}
}
#endregion
#region Get-GFileRevisions
function Get-GFileRevisions
{
<#
.Synopsis
Get a files revision history
.DESCRIPTION
Get a files revision history
.PARAMETER accessToken
access token used for authentication. Get from Get-GOAuthTokenUser or Get-GOAuthTokenService
.PARAMETER fileName
Name of file to retrive ID for. Case sensitive
.PARAMETER fileID
File ID. Can be gotten from Get-GFileID
.EXAMPLE
Get-GFileRevisions -accessToken $accessToken -fileName 'Name of some file'
# Get last modified
Get-Date ((Get-GFileRevisions -fileName $filename -accessToken $accessToken).revisions.modifiedTime[-1])
.EXAMPLE
Get-GFileRevisions -accessToken $accessToken -fileID 'ID of some file'
# Get last modified
Get-Date ((Get-GFileRevisions -fileName $filename -accessToken $accessToken).revisions.modifiedTime[-1])
.NOTES
Written by Travis Sobeck
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory)]
[string]$accessToken,
[Parameter(ParameterSetName='fileName')]
[string]$fileName,
[Parameter(ParameterSetName='fileID')]
[string]$fileID
)
Begin{}
Process
{
if ($fileName){$fileID = Get-GFileID -accessToken $accessToken -fileName $fileName}
If ($fileID.count -eq 0 -or $fileID.count -gt 1){break}
$uri = "https://www.googleapis.com/drive/v3/files/$($fileID)/revisions"
Invoke-RestMethod -Method Get -Uri $uri -Headers @{"Authorization"="Bearer $accessToken"}
}
End{}
}
#endregion
#region Get-GFileID
function Get-GFileID
{
<#
.Synopsis
Get a Google File ID.
.DESCRIPTION
Provide a case sensative file name to the function to get back the gFileID used in many other API calls.
.PARAMETER accessToken
access token used for authentication. Get from Get-GOAuthTokenUser or Get-GOAuthTokenService
.PARAMETER fileName
Name of file to retrive ID for. Case sensitive
.PARAMETER mimetype
Use this to specify a specific mimetype. See google docs https://developers.google.com/drive/api/v3/search-parameters
.EXAMPLE
Get-GFileID -accessToken $accessToken -fileName 'Name of some file'
.NOTES
Written by Travis Sobeck
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory)]
[string]$accessToken,
[Parameter(Mandatory)]
[string]$fileName,
[string]$mimetype
)
Begin{}
Process
{
$uri = "https://www.googleapis.com/drive/v3/files?q=name%3D'$fileName'"
if ($mimetype){$fileID = (((Invoke-RestMethod -Method get -Uri $uri -Headers @{"Authorization"="Bearer $accessToken"}).files) | Where-Object {$_.mimetype -eq $mimetype}).id}
else{$fileID = (((Invoke-RestMethod -Method get -Uri $uri -Headers @{"Authorization"="Bearer $accessToken"}).files)).id}
# Logic on multiple IDs being returned
If ($fileID.count -eq 0){Write-Warning "There are no files matching the name $fileName"}
If ($fileID.count -gt 1){Write-Warning "There are $($fileID.Count) files matching the provided name. Please investigate the following sheet IDs to verify which file you want.";return($fileID)}
Else{return($fileID)}
}
End{}
}
#endregion
#region Permissions for Google Drive files
function Get-GFilePermissions
{
<#
.Synopsis
Get Permissions on Google Drive File
.DESCRIPTION
Get Permission ID list on Google File
.PARAMETER accessToken
OAuth Access Token for authorization.
.PARAMETER fileID
The fileID to query. This is returned when a new file is created.
.PARAMETER permissionID
If specified will query only that specific permission for the file, rather than all permissions
.PARAMETER DefaultFields
If specified, will only query "default" rather than querying all fields of Permission object. Added primarily for backwards compatibility
.EXAMPLE
Get-GFilePermissions -accessToken $accessToken -fileID 'String of File ID' -permissionID 'String of Permission ID'
.OUTPUTS
If only a fileID, this will return an object with two properties, the first is kind, and will always be drive#permissionList
The second will be permissions, which includes the individual permissions objects. Each one of these will have the same format as if a specific PermissionID was requested
If a permissionID is also specified, only that specific permission will be returned. It will have a kind property of drive#permission as well as all properties of that specific permission.
More details on the permission object available here: https://developers.google.com/drive/api/v2/reference/permissions
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory)]
[string]$accessToken,
#[Alias("spreadSheetID")]
[Parameter(Mandatory)]
[string]$fileID,
# Parameter help description
[Parameter()]
[string]
$permissionID,
# Parameter help description
[Parameter()]
[switch]
$DefaultFields
)
Begin
{
$uri = "https://www.googleapis.com/drive/v3/files/$fileID/permissions"
if ($permissionID) {
$uri += "/$permissionID"
}
if (-not $DefaultFields) {
$uri += "/?fields=*"
}
$headers = @{"Authorization"="Bearer $accessToken"}
}
Process
{
write-host $uri
Invoke-RestMethod -Method Get -Uri $uri -Headers $headers
}
End{}
}
function Move-GFile
{
<#
.Synopsis
Change parent folder metadata
.DESCRIPTION
A function to change parent folder metadata of a file.
.PARAMETER accessToken
OAuth Access Token for authorization.
.PARAMETER fileID
The fileID to move.
.PARAMETER folderID
The fileID of the new parent folder.
.PARAMETER parentFolderID
The fileID of the parentFolder. Optional parameter. root (My Drive) is assumed if not specified.
.EXAMPLE
MoveGFile -fileID 'String of File ID' -folderID 'String of folder's File ID'
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory)]
[string]$accessToken,
#[Alias("spreadSheetID")]
[Parameter(Mandatory)]
[string]$fileID,
[Parameter(Mandatory)]
[string]$folderID,
[string]$parentFolderID='root'
)
Begin
{
$uriAdd = "https://www.googleapis.com/drive/v3/files/$fileID"+"?removeParents=$parentFolderID"
$uriRemove = "https://www.googleapis.com/drive/v3/files/$fileID"+"?addParents=$folderID"
$headers = @{"Authorization"="Bearer $accessToken"}
}
Process
{
Invoke-RestMethod -Method patch -Uri $uriAdd -Headers $headers
Invoke-RestMethod -Method patch -Uri $uriRemove -Headers $headers
}
End{}
}
function Remove-GFilePermissions
{
<#
.Synopsis
Remove Permissions on Google Drive File
.DESCRIPTION
Remove Permission ID list on Google File
.PARAMETER accessToken
OAuth Access Token for authorization.
.PARAMETER fileID
The fileID to query. This is returned when a new file is created.
.PARAMETER permissionsID
The permission ID to be removed. See Get-GFilePermissions
.EXAMPLE
Remove-GFilePermissions -fileID 'String of File ID' -accessToken $accessToken -permissionID 'ID of the permission'
.NOTES
A successfull removal returns no body data.
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory)]
[string]$accessToken,
#[Alias("spreadSheetID")]
[Parameter(Mandatory)]
[string]$fileID,
[Parameter(Mandatory)]
[string]$permissionID
)
Begin
{
$uri = "https://www.googleapis.com/drive/v3/files/$fileId/permissions/$permissionId"
$headers = @{"Authorization"="Bearer $accessToken"}
}
Process
{
Invoke-RestMethod -Method Delete -Uri $uri -Headers $headers
}
End{}
}