Invoke-MetasysMethod.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
function Invoke-MetasysMethod {
    <#
    .SYNOPSIS
        Invokes methods of the Metasys REST API

    .DESCRIPTION
        This function allows you to invoke various methods of the Metasys REST API.
        Once a session is established (on the first invocation) the session state
        is maintained in the terminal session. This allows you to make additional
        calls with less boilerplate text for each call.

    .OUTPUTS
        The payloads from Metasys as Powershell objects.

    .EXAMPLE
        Invoke-MetasysMethod -Reference thesun:thesun

        This will prompt you for a hostname and your credentials and then attempt
        to look up the id of the object with the specified reference

    .EXAMPLE
        Invoke-MetasysMethod -Path /objects/$id

        After retrieving an id of an object (like in the previous example) and
        string it in variable $id, this example will read the default view of the
        object.

    .EXAMPLE
        Invoke-MetasysMethod -Path /alarms

        This will read the first page of alarms from the site.

    .EXAMPLE
        Invoke-MetasysMethod -Method Put -Path /objects/$id/commands/adjust -Body '[72.5]'

        This example will send the adjust command to the specified object (assuming
        a valid id is stored in $id).

    .LINK

        https://github.jci.com/cwelchmi/metasys-powershell-tutorial/blob/main/invoke-metasys-method.md

    #>


    [CmdletBinding(PositionalBinding = $false)]
    param(
        # The hostname or ip address of the site you wish to interact with
        [string]$SiteHost,
        # The username of the account you wish to use on this Site
        [string]$UserName,
        # A switch used to force Login. This isn't normally needed except
        # when you wish to switch accounts or switch sites. By using this
        # switch you will be prompted for the site or your credentials if
        # not supplied on the command line.
        [switch]$Login,
        # The relative path to an endpont. For example: /alarms
        # All of the relative paths are listed in the API Documentation
        # Path and Reference are mutally exclusive.
        [string]$Path,
        # Session information is stored in environment variables. To force a
        # cleanup use this switch to remove all environment variables. The next
        # time you invoke this function you'll need to provide credentials and
        # a SiteHost.
        [switch]$Clear,
        # The json payload to send with your request.
        [string]$Body,
        # The HTTP Method you are sending.
        [string]$Method = "Get",
        # The version of the API you intent to use
        [Int]$Version = 3,
        # NOTE: Insecure. DO NOT use in production. This switch will cause
        # all checks of the certificate to be skipped.
        [switch]$SkipCertificateCheck,
        # A short cut for looking up the id of an object.
        [string]$Reference,
        # Rather than just returning the content, return the full web response
        # object will include extra like the response headers.
        [switch]$FullWebResponse
    )

    class MetasysEnvVars {
        static [string] getSiteHost() {
            return $env:METASYS_SITE_HOST
        }

        static [void] setSiteHost([string]$siteHost) {
            $env:METASYS_SITE_HOST = $siteHost
        }

        static [int] getVersion() {
            return $env:METASYS_VERSION
        }

        static [void] setVersion([int]$version) {
            $env:METASYS_VERSION = $version
        }

        static [string] getExpires() {
            return $env:METASYS_EXPIRES
        }

        static [void] setExpires([string]$expires) {
            $env:METASYS_EXPIRES = $expires
        }

        static [string] getToken() {
            return $env:METASYS_SECURE_TOKEN
        }

        static [void] setToken([string]$token) {
            $env:METASYS_SECURE_TOKEN = $token
        }

        static [string] getLast() {
            return $env:METASYS_LAST_RESPONSE
        }

        static [void] setLast([string]$last) {
            $env:METASYS_LAST_RESPONSE = $last
        }

        static [void] clear() {
            $env:METASYS_SECURE_TOKEN = $null
            $env:METASYS_SITE_HOST = $null
            $env:METASYS_VERSION = $null
            $env:METASYS_LAST_RESPONSE = $null
            $env:METASYS_EXPIRES = $null
        }

        static [System.Boolean] getDefaultSkipCheck() {
            return $env:METASYS_SKIP_CHECK_NOT_SECURE
        }

    }

    Set-StrictMode -Version 2

    # In Windows Powershell the $IsMacOS variable doesn't exist so calls to check
    # it's value fail. This function wraps the call.

    function isMacOS {
        if ($PSVersionTable.PSEdition -eq "Core") {
            return $IsMacOS
        }

        return $False
    }

    function buildUri {
        param (
            [string]$siteHost = [MetasysEnvVars]::getSiteHost(),
            [int]$version = [MetasysEnvVars]::getVersion(),
            [string]$baseUri = "api",
            [string]$path
        )

        $uri = [System.Uri] ("https://" + $siteHost + "/" + ([System.IO.Path]::Join($baseUri, "v" + $version, $path)))
        return $uri
    }

    function buildRequest {
        param (
            [string]$method = "Get",
            [string]$uri,
            [string]$body = $null,
            [string]$token = [MetasysEnvVars]::getToken()
        )

        return @{
            Method               = $method
            Uri                  = buildUri -path $Path
            Body                 = $body
            Authentication       = "bearer"
            Token                = ConvertTo-SecureString $token
            SkipCertificateCheck = $SkipCertificateCheck
            ContentType          = "application/json"
        }
    }

    function executeRequest {
        param (
            [string]$method = "Get",
            [string]$uri,
            [string]$body = $null,
            [string]$token = [MetasysEnvVars]::getToken()
        )

        return Invoke-RestMethod @(buildRequest -uri (buildUri -path $Path) -method $Method -body $Body)
    }

    function find-internet-user {
        param (
            [string]$siteHost
        )

        if (!(isMacOS)) {
            return
        }

        $cred = Invoke-Expression "security find-internet-password -s $siteHost 2>/dev/null"
        if ($cred) {
            $userNameLine = $cred | Where-Object { $_.StartsWith(" ""acct") }
            if ($userNameLine) {
                $userName = $userNameLine.Split('=')[1].Trim('"')
                return $userName
            }
        }
    }

    function find-internet-password {
        param (
            [string]$siteHost,
            [string]$userName
        )

        if (!(isMacOS)) {
            return
        }

        $passwordEntry = Invoke-Expression "security find-internet-password -s $siteHost -a $userName -w 2>/dev/null"
        if ($passwordEntry) {
            return ConvertTo-SecureString $passwordEntry -AsPlainText
        }
    }

    function add-internet-password {
        param(
            [string]$siteHost,
            [string]$userName,
            [SecureString]$password
        )

        if (!(isMacOS)) {
            return
        }

        $plainText = ConvertFrom-SecureString -SecureString $password -AsPlainText

        Invoke-Expression "security add-internet-password -U -s $siteHost -a $userName -w $plainText -c mgw1 "

    }

    If (($Version -lt 2) -or ($Version -gt 3)) {
        Write-Error -Message "Version out of range. Should be 2 or 3"
        return
    }

    if ($Clear.IsPresent) {
        [MetasysEnvVars]::clear()
        return # end the program
    }

    if (!$SkipCertificateCheck.IsPresent) {
        $SkipCertificateCheck =[MetasysEnvVars]::getDefaultSkipCheck()
    }

    # Login Region

    $ForceLogin = $false

    if ([MetasysEnvVars]::getExpires()) {
        $expiration = [Datetime]::Parse([MetasysEnvVars]::getExpires())
        if ([Datetime]::now -gt $expiration) {
            # Token is expired, require login
            $ForceLogin = $true
        }
        else {
            # attempt to renew the token to keep it fresh
            $refreshRequest = @{
                Method               = "Get"
                Uri                  = buildUri -path "/refreshToken"
                Authentication       = "bearer"
                Token                = ConvertTo-SecureString -String ([MetasysEnvVars]::getToken())
                SkipCertificateCheck = $SkipCertificateCheck
            }
            try {
                $refreshResponse = Invoke-RestMethod @refreshRequest
                [MetasysEnvVars]::setExpires($refreshResponse.expires)
                [MetasysEnvVars]::setToken( (ConvertFrom-SecureString -SecureString $refreshResponse.accessToken) )

            }
            catch {
                # refreshing doesn't seem to work
            }


        }
    }

    if (($Login) -or (![MetasysEnvVars]::getToken()) -or ($ForceLogin) -or ($SiteHost -and ($SiteHost -ne [MetasysEnvVars]::getSiteHost()))) {
        if (!$SiteHost) {
            $SiteHost = Read-Host -Prompt "Site host"
        }

        if (!$UserName) {
            # attempt to find a user name in keychain
            $UserName = find-internet-user($SiteHost)

            if (!$UserName) {
                $UserName = Read-Host -Prompt "UserName"
            }
        }

        $password = find-internet-password $SiteHost $UserName

        if (!$password) {
            $password = Read-Host -Prompt "Password" -AsSecureString

            ## Attempt to store credentials
            add-internet-password $SiteHost  $UserName  $password
        }

        $jsonObject = @{
            username = $UserName
            password = ConvertFrom-SecureString -SecureString $password -AsPlainText
        }
        $json = (ConvertTo-Json $jsonObject)

        $loginRequest = @{
            Method               = "Post"
            Uri                  = buildUri -siteHost $SiteHost -version $Version -path "login"
            Body                 = $json
            ContentType          = "application/json"
            SkipCertificateCheck = $SkipCertificateCheck
        }

        try {
            $loginResponse = Invoke-RestMethod @loginRequest
            $secureToken = ConvertTo-SecureString -String $loginResponse.accessToken -AsPlainText
            [MetasysEnvVars]::setToken((ConvertFrom-SecureString -SecureString $secureToken))
            [MetasysEnvVars]::setSiteHost($SiteHost)
            [MetasysEnvVars]::setExpires($loginResponse.expires)
            [MetasysEnvVars]::setVersion($Version)
        }
        catch {
            Write-Host "An error occurred:"
            Write-Host $_
            return
        }
    }

    if ($Path -and $Reference) {
        Write-Warning "-Path and -Reference are mutually exclusive"
        return
    }

    if (!$Path -and !$Reference) {
        return
    }

    if ($Reference) {
        $Path = "/objectIdentifiers?fqr=" + $Reference
        $request = buildRequest -uri (buildUri -path $Path)
    }

    if ($Path) {
        $request = buildRequest -uri (buildUri -path $Path) -method $Method -body $Body
    }

    $responseObject = Invoke-WebRequest @request
    $response = $null
    if ($FullWebResponse.IsPresent) {
        $response = $responseObject
    }
    else {
        if ($responseObject -and $responseObject.Content) {
            $response = ConvertFrom-Json ([String]::new($responseObject.Content))
        }
    }
    Write-Verbose ("Http Status: " + $responseObject.StatusCode)
    [MetasysEnvVars]::setLast((ConvertTo-Json $response -Depth 15))
    return $response

}

function Invoke-MetasysGet {
    param([Parameter(Position = 0)][string]$Path)
    Invoke-MetasysMethod -Path $Path
}
function Invoke-MetasysPatch {
    param([Parameter(Position = 0)][string]$Path, [Parameter(Position = 1)][string]$Body)
    Invoke-MetasysMethod -Method Patch -Body $Body -Path $Path
}

function Invoke-MetasysPut {
    param([Parameter(Position = 0)][string]$Path, [Parameter(Position = 1)][string]$Body)
    Invoke-MetasysMethod -Method Put -Body $Body -Path $Path
}

function Invoke-MetasysGetObject {
    <#
    .SYNOPSIS
        Reads the default view of a Metasys object

    .DESCRIPTION
        This function allows you to read a Metasys object given the specified
        Reference. You will be prompted for a site host and your credentials unless a
        session has already been established.

    .OUTPUTS
        The object payload returned by the server.

    .EXAMPLE
        Invoke-MetasysGet-Object -Reference thesun:thesun

        This will prompt you for the Site host and your credentials and read the default view of this object.

    .LINK

        https://github.jci.com/cwelchmi/metasys-powershell-tutorial/blob/main/invoke-metasys-method.md

    #>

    param(
        # The fully qualified references of a Metasys object
        [Parameter(Position = 0)][string]$Reference
    )
    $id = [System.Environment]::GetEnvironmentVariable("idFor:" + $Reference)
    if (!$id) {
        $id = Invoke-MetasysGet -Path ("/objectIdentifiers?fqr=" + $Reference)
        [System.Environment]::SetEnvironmentVariable("idFor:" + $Reference, $id)
    }
    Invoke-MetasysGet ("/objects/" + $id)
}

New-Alias -Name mget -Value Invoke-MetasysGet
New-Alias -Name mpatch -Value Invoke-MetasysPatch
New-Alias -Name mput -Value Invoke-MetasysPut
New-Alias -Name mget-object -Value Invoke-MetasysGetObject

Export-ModuleMember -Function 'Invoke-MetasysMethod', 'Invoke-MetasysGet', 'Invoke-MetasysPut', 'Invoke-MetasysGetObject'
Export-ModuleMember -Alias 'mget', 'mpatch', 'mput', 'mget-object'