Te hanga Kaiwhakamahi Google mai i PowerShell ma te API

Kia pai!

Ma tenei tuhinga e whakaatu te whakatinanatanga o te taunekeneke PowerShell me te API a Google hei whakahaere i nga kaiwhakamahi G Suite.

Ka whakamahia e matou etahi ratonga o roto me te kapua puta noa i te whakahaere. Ko te nuinga, ko te whakamanatanga kei roto i a raatau ka heke mai ki a Google, ki te Active Directory ranei, i waenga e kore e taea e taatau te pupuri i tetahi tauira; na reira, ka wehe mai tetahi kaimahi hou, me hanga e koe he kaute ki enei punaha e rua. Hei whakaaunoa i te tukanga, i whakatau matou ki te tuhi i tetahi tuhinga hei kohi korero ka tukuna ki nga ratonga e rua.

Whakaaetanga

I te wa e whakarite ana i nga whakaritenga, i whakatau matou ki te whakamahi i nga tino kaiwhakahaere tangata mo te whakamanatanga; ma tenei ka whakamaarama te tātaritanga o nga mahi mena ka puta nga huringa nui ohorere ranei.

Ka whakamahi nga API Google i te kawa OAuth 2.0 mo te motuhēhēnga me te whakamana. Ka taea te kite i nga keehi me nga whakaahuatanga taipitopito i konei: Ma te whakamahi i te OAuth 2.0 ki te uru ki nga API Google.

I whiriwhiria e ahau te tuhinga e whakamahia ana mo te whakamana i nga tono papamahi. He waahi ano hoki ki te whakamahi i tetahi kaute ratonga, kaore e hiahiatia nga nekehanga kore mai i te kaiwhakamahi.

Ko te pikitia kei raro nei he whakamaarama whakamaarama mo te ahuatanga kua tohua mai i te wharangi Google.

Te hanga Kaiwhakamahi Google mai i PowerShell ma te API

  1. Tuatahi, ka tukuna e matou te kaiwhakamahi ki te wharangi motuhēhēnga a Google Account, me te tohu i nga tawhā GET:
    • tono id
    • nga waahi e hiahia ana te tono ki te uru atu
    • te wāhitau ka tukuna te kaiwhakamahi i muri i te otinga o te mahi
    • te huarahi ka whakahouhia e matou te tohu
    • Waehere Haumarutanga
    • hōputu tuku waehere manatoko

  2. Ka oti te whakamanatanga, ka tukuna te kaiwhakamahi ki te wharangi kua tohua i te tono tuatahi, me te hapa, te waehere whakamana ranei i tukuna e nga tawhā GET
  3. Me whiwhi te tono (tuhituhi) i enei tawhā, a, ki te riro i te waehere, me tono e whai ake nei kia whiwhi tohu
  4. Mena he tika te tono, ka hoki mai te Google API:
    • Tohu uru hei tono tono
    • Te wa mana o tenei tohu
    • Te tohu tāmata e hiahiatia ana hei tāmata i te tohu Uru.

Tuatahi me haere koe ki te papatohu Google API: Taipitopito - Google API Papatohu, tīpakohia te tono e hiahiatia ana, i roto i te waahanga Taipitopito hanga he kaitautuhi OAuth kiritaki. I reira (i muri mai ranei, i roto i nga taonga o te kaitautuhi i hangaia) me tohu e koe nga wahitau e whakaaetia ana te hurihanga. I a maatau, he maha nga whakaurunga localhost me nga tauranga rereke (tirohia i raro).

Kia pai ake ai te panui i te tuhinga algorithm, ka taea e koe te whakaatu i nga kaupae tuatahi i roto i tetahi mahi motuhake ka whakahoki mai i nga tohu Uru me te whakahou i nga tohu mo te tono:

$client_secret = 'Our Client Secret'
$client_id = 'Our Client ID'
function Get-GoogleAuthToken {
  if (-not [System.Net.HttpListener]::IsSupported) {
    "HttpListener is not supported."
    exit 1
  }
  $codeverifier = -join ((65..90) + (97..122) + (48..57) + 45 + 46 + 95 + 126 |Get-Random -Count 60| % {[char]$_})
  $hasher = new-object System.Security.Cryptography.SHA256Managed
  $hashByteArray = $hasher.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($codeverifier))
  $base64 = ((([System.Convert]::ToBase64String($hashByteArray)).replace('=','')).replace('+','-')).replace('/','_')
  $ports = @(10600,15084,39700,42847,65387,32079)
  $port = $ports[(get-random -Minimum 0 -maximum 5)]
  Write-Host "Start browser..."
  Start-Process "https://accounts.google.com/o/oauth2/v2/auth?code_challenge_method=S256&code_challenge=$base64&access_type=offline&client_id=$client_id&redirect_uri=http://localhost:$port&response_type=code&scope=https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/admin.directory.group"
  $listener = New-Object System.Net.HttpListener
  $listener.Prefixes.Add("http://localhost:"+$port+'/')
  try {$listener.Start()} catch {
    "Unable to start listener."
    exit 1
  }
  while (($code -eq $null)) {
    $context = $listener.GetContext()
    Write-Host "Connection accepted" -f 'mag'
    $url = $context.Request.RawUrl
    $code = $url.split('?')[1].split('=')[1].split('&')[0]
    if ($url.split('?')[1].split('=')[0] -eq 'error') {
      Write-Host "Error!"$code -f 'red'
      $buffer = [System.Text.Encoding]::UTF8.GetBytes("Error!"+$code)
      $context.Response.ContentLength64 = $buffer.Length
      $context.Response.OutputStream.Write($buffer, 0, $buffer.Length)
      $context.Response.OutputStream.Close()
      $listener.Stop()
      exit 1
    }
    $buffer = [System.Text.Encoding]::UTF8.GetBytes("Now you can close this browser tab.")
    $context.Response.ContentLength64 = $buffer.Length
    $context.Response.OutputStream.Write($buffer, 0, $buffer.Length)
    $context.Response.OutputStream.Close()
    $listener.Stop()
  }
  Return Invoke-RestMethod -Method Post -Uri "https://www.googleapis.com/oauth2/v4/token" -Body @{
    code = $code
    client_id = $client_id
    client_secret = $client_secret
    redirect_uri = 'http://localhost:'+$port
    grant_type = 'authorization_code'
    code_verifier   = $codeverifier
  }
  $code = $null

I tautuhia e matou te TT Kiritaki me te Mea ngaro Kiritaki i whiwhi i roto i nga taonga o te kaitautuhi kiritaki OAuth, a ko te manatoko waehere he aho o te 43 ki te 128 nga tohu me hanga matapōkeretia mai i nga tohu kore i rahuitia: [AZ] / [az] / [0-9 ] / "-" / "." / "_" / "~".

Ka tukuna ano tenei waehere. Ka whakakorehia te whakaraeraetanga e taea ai e te kaitukino te haukoti i te whakautu i whakahokia mai ano he whakatika i muri i te whakamanatanga a te kaiwhakamahi.
Ka taea e koe te tuku he kaiwhakatika waehere i roto i te tono o naianei i roto i nga tuhinga maamaa (e kore e whai tikanga - he pai noa tenei mo nga punaha kaore e tautoko ana i te SHA256), ma te hanga ranei i te hash ma te whakamahi i te SHA256 algorithm, me whakauru ki BASE64Url (he rerekee. mai i te Base64 e rua nga tohu ripanga) me te tango i nga pito raina tohu: =.

I muri mai, me timata taatau ki te whakarongo ki te http i runga i te miihini a-rohe kia whiwhi urupare i muri i te whakamanatanga, ka whakahokia mai ano he reanga.

Ka mahia nga mahi whakahaere i runga i te tūmau motuhake, kaore e taea e matou te whakakore i te tupono ka whakahaerehia e te maha o nga kaiwhakahaere te tuhinga i te wa kotahi, na reira ka kowhiri matapōkeretia he tauranga mo te kaiwhakamahi o naianei, engari i tohua e au nga tauranga kua tautuhia na te mea me taapiri ano kia whakawhirinakihia ki te papatohu API.

access_type=tuimotu Ko te tikanga ka taea e te tono te whakahou i tetahi tohu kua pau i a ia ano me te kore he taunekeneke a te kaiwhakamahi me te kaitirotiro,
momo_whakautu=waehere ka tohu i te whakatakotoranga me pehea te whakahoki mai i te waehere (he tohutoro mo te tikanga whakamana tawhito, i te wa i kapehia e te kaiwhakamahi te waehere mai i te kaitirotiro ki te tuhinga),
awhe e tohu ana i te whānuitanga me te momo urunga. Me wehe ma te mokowā, ma te %20 ranei (e ai ki te Whakawaehere URL). He rarangi o nga waahi uru me nga momo ka kitea i konei: Ko te OAuth 2.0 mo nga API Google.

I muri i te whiwhi i te waehere whakamanatanga, ka whakahoki te tono i tetahi karere tata ki te kaitirotiro, ka mutu te whakarongo ki runga i te tauranga ka tukuna he tono POST kia whiwhi i te tohu. Ka tohuhia e matou te id kua tohua me te mea ngaro mai i te API papatohu, te wahitau ka tukuna ano te kaiwhakamahi me te tuku_type kia rite ki te tohu kawa.

Hei whakautu, ka whiwhi matou i tetahi tohu Access, tona wa whaimana i roto i nga hēkona, me te tohu Refresh, e taea ai e matou te whakahou i te tohu Access.

Me rokiroki e te tono nga tohu ki tetahi waahi haumaru me te roa o te oranga, na kia whakakorea e matou te urunga kua tae mai, kaore te tono e whakahoki mai i te tohu whakahou. I te mutunga, ka tapiritia e ahau he tono kia whakakorehia te tohu; ki te kore i tutuki pai te tono me te kore i whakahokia mai te tohu whakahou, ka timata ano te mahi (i whakaaro matou he kino te penapena tohu i te rohe ki te tauranga, a ka 'kare e hiahia ki te whakararu i nga mea ki te tuhi tuhi, ki te whakatuwhera i te kaitirotiro i nga wa katoa).

do {
  $token_result = Get-GoogleAuthToken
  $token = $token_result.access_token
  if ($token_result.refresh_token -eq $null) {
    Write-Host ("Session is not destroyed. Revoking token...")
    Invoke-WebRequest -Uri ("https://accounts.google.com/o/oauth2/revoke?token="+$token)
  }
} while ($token_result.refresh_token -eq $null)
$refresh_token = $token_result.refresh_token
$minute = ([int]("{0:mm}" -f ([timespan]::fromseconds($token_result.expires_in))))+((Get-date).Minute)-2
if ($minute -lt 0) {$minute += 60}
elseif ($minute -gt 59) {$minute -=60}
$token_expire = @{
  hour = ([int]("{0:hh}" -f ([timespan]::fromseconds($token_result.expires_in))))+((Get-date).Hour)
  minute = $minute
}

Kua kite koe, ina whakakorehia he tohu, ka whakamahia te Invoke-WebRequest. Kaore i rite ki te Invoke-RestMethod, kaore e whakahokia nga raraunga kua riro mai i roto i te whakatakotoranga ka taea te whakamahi me te whakaatu i te mana o te tono.

I muri mai, ka tono te tuhinga ki a koe ki te whakauru i te ingoa tuatahi me te ingoa whakamutunga o te kaiwhakamahi, te whakaputa i te takiuru + imeera.

Nga tono

Ko nga tono e whai ake nei - ko te mea tuatahi, me tirotiro koe mena kei te noho tonu tetahi kaiwhakamahi he rite tonu te takiuru kia taea ai e koe te whakatau ki te hanga i tetahi mea hou, ki te whakahohe ranei i te mea o naianei.

I whakatau ahau ki te whakatinana i nga tono katoa i roto i te whakatakotoranga o te mahi kotahi me te kowhiringa, ma te whakamahi i te whakawhiti:

function GoogleQuery {
  param (
    $type,
    $query
  )
  switch ($type) {
    "SearchAccount" {
      Return Invoke-RestMethod -Method Get -Uri "https://www.googleapis.com/admin/directory/v1/users" -Headers @{Authorization = "Bearer "+(Get-GoogleToken)} -Body @{
        domain = 'rocketguys.com'
        query  = "email:$query"
      }
    }
    "UpdateAccount" {
      $body = @{
        name  = @{
          givenName = $query['givenName']
          familyName = $query['familyName']
        }
        suspended = 'false'
        password = $query['password']
        changePasswordAtNextLogin = 'true'
        phones = @(@{
          primary = 'true'
          value = $query['phone']
          type = "mobile"
        })
        orgUnitPath = $query['orgunit']
      }
      Return Invoke-RestMethod -Method Put -Uri ("https://www.googleapis.com/admin/directory/v1/users/"+$query['email']) -Headers @{Authorization = "Bearer "+(Get-GoogleToken)} -Body (ConvertTo-Json $body) -ContentType 'application/json; charset=utf-8'
    }
    
    "CreateAccount" {
      $body = @{
        primaryEmail = $query['email']
        name  = @{
          givenName = $query['givenName']
          familyName = $query['familyName']
        }
        suspended = 'false'
        password = $query['password']
        changePasswordAtNextLogin = 'true'
        phones = @(@{
          primary = 'true'
          value = $query['phone']
          type = "mobile"
        })
        orgUnitPath = $query['orgunit']
      }
      Return Invoke-RestMethod -Method Post -Uri "https://www.googleapis.com/admin/directory/v1/users" -Headers @{Authorization = "Bearer "+(Get-GoogleToken)} -Body (ConvertTo-Json $body) -ContentType 'application/json; charset=utf-8'
    }
    "AddMember" {
      $body = @{
        userKey = $query['email']
      }
      $ifrequest = Invoke-RestMethod -Method Get -Uri "https://www.googleapis.com/admin/directory/v1/groups" -Headers @{Authorization = "Bearer "+(Get-GoogleToken)} -Body $body
      $array = @()
      foreach ($group in $ifrequest.groups) {$array += $group.email}
      if ($array -notcontains $query['groupkey']) {
        $body = @{
          email = $query['email']
          role = "MEMBER"
        }
        Return Invoke-RestMethod -Method Post -Uri ("https://www.googleapis.com/admin/directory/v1/groups/"+$query['groupkey']+"/members") -Headers @{Authorization = "Bearer "+(Get-GoogleToken)} -Body (ConvertTo-Json $body) -ContentType 'application/json; charset=utf-8'
      } else {
        Return ($query['email']+" now is a member of "+$query['groupkey'])
      }
    }
  }
}

I ia tono, me tuku he pane Whakamanatanga kei roto te momo tohu me te tohu Uru ake. I tenei wa, ko te momo tohu he Kaimau tonu. No te mea me tirotirohia kaore i pau te tohu me te whakahou i muri i te haora mai i te wa i tukuna ai, i tohua e ahau he tono mo tetahi atu mahi e whakahoki mai ana i te tohu Access. Ko taua waahanga waehere kei te timatanga o te tuhinga i te wa e whiwhi ana i te tohu uru tuatahi:

function Get-GoogleToken {
  if (((Get-date).Hour -gt $token_expire.hour) -or (((Get-date).Hour -ge $token_expire.hour) -and ((Get-date).Minute -gt $token_expire.minute))) {
  Write-Host "Token Expired. Refreshing..."
    $request = (Invoke-RestMethod -Method Post -Uri "https://www.googleapis.com/oauth2/v4/token" -ContentType 'application/x-www-form-urlencoded' -Body @{
      client_id = $client_id
      client_secret = $client_secret
      refresh_token = $refresh_token
      grant_type = 'refresh_token'
    })
    $token = $request.access_token
    $minute = ([int]("{0:mm}" -f ([timespan]::fromseconds($request.expires_in))))+((Get-date).Minute)-2
    if ($minute -lt 0) {$minute += 60}
    elseif ($minute -gt 59) {$minute -=60}
    $script:token_expire = @{
      hour = ([int]("{0:hh}" -f ([timespan]::fromseconds($request.expires_in))))+((Get-date).Hour)
      minute = $minute
    }
  }
  return $token
}

Takina te takiuru mo te noho tonu:

function Check_Google {
  $query = (GoogleQuery 'SearchAccount' $username)
  if ($query.users -ne $null) {
    $user = $query.users[0]
    Write-Host $user.name.fullName' - '$user.PrimaryEmail' - suspended: '$user.Suspended
    $GAresult = $user
  }
  if ($GAresult) {
      $return = $GAresult
  } else {$return = 'gg'}
  return $return
}

Ko te imeera:$query request ka tono te API ki te rapu i tetahi kaiwhakamahi me taua imeera, tae atu ki nga ingoa ingoa. Ka taea hoki e koe te whakamahi i te kaari maori: =, :, :{PREFIX}*.

Ki te whiwhi raraunga, whakamahia te tikanga tono GET, ki te whakauru raraunga (te hanga kaute, te taapiri mema ranei ki te roopu) - POST, ki te whakahou i nga raraunga o mua - PUT, ki te muku i tetahi rekoata (hei tauira, he mema mai i te roopu) - MUMU.

Ka tono ano te tuhinga mo te nama waea (he aho kaore i whakamanahia) me te whakauru ki tetahi roopu tohatoha rohe. Ka whakatauhia ko tehea wae whakahaere ma te kaiwhakamahi i runga i te Active Directory OU kua tohua, ka puta mai he kupuhipa:

do {
  $phone = Read-Host "Телефон в формате +7хххххххх"
} while (-not $phone)
do {
    $moscow = Read-Host "В Московский офис? (y/n) "
} while (-not (($moscow -eq 'y') -or ($moscow -eq 'n')))
$orgunit = '/'
if ($OU -like "*OU=Delivery,OU=Users,OU=ROOT,DC=rocket,DC=local") {
    Write-host "Будет создана в /Team delivery"
    $orgunit = "/Team delivery"
}
$Password =  -join ( 48..57 + 65..90 + 97..122 | Get-Random -Count 12 | % {[char]$_})+"*Ba"

Na ka timata ia ki te raweke i te kaute:

$query = @{
  email = $email
  givenName = $firstname
  familyName = $lastname
  password = $password
  phone = $phone
  orgunit = $orgunit
}
if ($GMailExist) {
  Write-Host "Запускаем изменение аккаунта" -f mag
  (GoogleQuery 'UpdateAccount' $query) | fl
  write-host "Не забудь проверить группы у включенного $Username в Google."
} else {
  Write-Host "Запускаем создание аккаунта" -f mag
  (GoogleQuery 'CreateAccount' $query) | fl
}
if ($moscow -eq "y"){
  write-host "Добавляем в группу moscowoffice"
  $query = @{
    groupkey = '[email protected]'
    email = $email
  }
  (GoogleQuery 'AddMember' $query) | fl
}

Ko nga mahi mo te whakahou me te hanga i tetahi kaute he rite tonu te syntax; ehara i te mea e hiahiatia ana nga waahanga taapiri katoa; i roto i te waahanga me nga nama waea, me tohu e koe he huinga ka taea te whakauru ki te kotahi rekoata me te tau me tona momo.

Kia kore ai e puta he hapa i te taapiri i tetahi kaiwhakamahi ki tetahi roopu, ka taea e tatou te tirotiro tuatahi mena he mema kee ia mo tenei roopu ma te tango i te rarangi o nga mema o te roopu me te titohanga mai i te kaiwhakamahi ake.

Ko te patai mo te mema-rōpū o tetahi kaiwhakamahi motuhake kare e hoki whakamuri, ka whakaatu noa i te mema tika. Ka angitu te whakauru i tetahi kaiwhakamahi i roto i te roopu matua kua whai roopu tamariki kei te mema te kaiwhakamahi.

mutunga

Ko nga mea e toe ana ko te tuku ki te kaiwhakamahi te kupuhipa mo te kaute hou. Ka mahia e matou tenei ma te SMS, ka tuku korero whanui me nga tohutohu me te takiuru ki tetahi imeera whaiaro, me te nama waea, na te tari whakauru. Hei rereke, ka taea e koe te penapena moni me te tuku i to kupu huna ki te korerorero waea waea ngaro, ka taea hoki te whakaaro ko te take tuarua (ka waiho ko MacBooks he rereke).

Mauruuru koe mo te panui ki te mutunga. Ka koa ahau ki te kite i nga whakaaro mo te whakapai ake i te ahua o te tuhi tuhinga me te hiahia kia iti ake nga hapa ina tuhi tuhinga =)

Rarangi o nga hononga e whai hua ana ki te kaupapa, ki te whakautu noa i nga paatai:

Source: will.com

Tāpiri i te kōrero