Ho theha Basebelisi ba Google ho PowerShell ka API

Lumela!

Sengoliloeng sena se tla hlalosa ts'ebetsong ea tšebelisano ea PowerShell le Google API ho thetsa basebelisi ba G Suite.

Re sebelisa litšebeletso tse 'maloa tsa ka hare le tsa maru ho pholletsa le mokhatlo. Hangata, tumello ho tsona e theohela ho Google kapa Active Directory, eo re ke keng ra khona ho boloka replica; ka hona, ha mosebeletsi e mocha a tloha, o hloka ho theha / ho nolofalletsa akhaonto lits'ebetsong tsena tse peli. Ho iketsetsa ts'ebetso, re nkile qeto ea ho ngola mongolo o bokellang tlhahisoleseling ebe o o romella lits'ebeletso ka bobeli.

Tlhahiso

Ha re etsa litlhokahalo, re nkile qeto ea ho sebelisa batsamaisi ba 'nete ba batho bakeng sa tumello; sena se nolofatsa tlhahlobo ea liketso ha ho ka ba le liphetoho tse kholo tsa kotsi kapa tsa boomo.

Li-API tsa Google li sebelisa protocol ea OAuth 2.0 bakeng sa netefatso le tumello. Lintlha tsa tšebeliso le litlhaloso tse qaqileng li ka fumanoa mona: Ho sebelisa OAuth 2.0 ho kena ho Google API.

Ke khethile sengoloa se sebelisetsoang tumello lits'ebetsong tsa komporo. Hape ho na le khetho ea ho sebelisa ak'haonte ea ts'ebeletso, e sa hlokeng metsamao e sa hlokahaleng ho tsoa ho mosebelisi.

Setšoantšo se ka tlase ke tlhaloso ea moralo ea boemo bo khethiloeng leqepheng la Google.

Ho theha Basebelisi ba Google ho PowerShell ka API

  1. Taba ea pele, re romella mosebelisi leqepheng la netefatso ea Ak'haonte ea Google, re totobatsa lintlha tsa GET:
    • ID ea kopo
    • libaka tseo kopo e hlokang ho fihlella ho tsona
    • aterese eo mosebedisi a tla fetisetswa ho yona ka mora ho qeta tshebetso
    • tsela eo re tla ntlafatsa token
    • K'houtu ea tšireletso
    • mokhoa oa phetiso ea khoutu ea netefatso

  2. Kamora hore tumello e phetheloe, mosebelisi o tla fetisetsoa leqepheng le boletsoeng kopong ea pele, ka phoso kapa khoutu ea tumello e fetisitsoeng ke paramente ea GET.
  3. Kopo (script) e tla hloka ho amohela liparamente tsena, 'me, haeba e amohetse khoutu, etsa kopo e latelang ho fumana li-tokens.
  4. Haeba kopo e nepahetse, Google API e khutlisa:
    • Letšoao la phihlello leo re ka etsang likopo ka lona
    • Nako ea bonnete ba tokene ena
    • Letshwao la ho hlabolla le a hlokahala ho qala letshwao la ho kena hape.

Pele u lokela ho ea ho Google API console: Lintlha - Google API Console, khetha sesebelisoa se lakatsehang 'me karolong ea Lintlha u thehe sekhetho sa OAuth ea moreki. Ha u le moo (kapa hamorao, thepa ea sekhetho se entsoeng) u hloka ho hlakisa liaterese tseo ho fetisetsoang ho tsona ho lumelletsoeng. Molemong oa rona, tsena e tla ba likenyelletso tse 'maloa tsa lehae tse nang le likou tse fapaneng (sheba ka tlase).

Ho etsa hore ho be bonolo haholoanyane ho bala algorithm ea script, o ka bonts'a mehato ea pele ts'ebetsong e fapaneng e tla khutlisa Access le tokens ea ho khatholla bakeng sa ts'ebeliso:

$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

Re seta ID ea Client le Lekunutu la Client tse fumanoeng ho thepa ea boitsebiso ba moreki oa OAuth, 'me se netefatsang khoutu ke letoto la litlhaku tse 43 ho isa ho tse 128 tse tlamehang ho hlahisoa ka mokhoa o sa reroang ho tsoa ho litlhaku tse sa bolokehang: [AZ] / [az] / [0-9 ] / "-" / "." / "_" / "~".

Khoutu ena e tla fetisoa hape. E tlosa ho ba kotsing moo mohlaseli a ka thibelang karabo e khutlisetsoang ka mor'a tumello ea mosebelisi.
U ka romela se netefatsang khoutu ho kopo ea hajoale ka mongolo o hlakileng (o etsang hore e se be le moelelo - sena se loketse feela lits'ebetso tse sa tšehetseng SHA256), kapa ka ho theha hash ho sebelisa algorithm ea SHA256, e tlamehang ho kengoa ka har'a BASE64Url (e fapaneng. ho tloha ho Base64 ka litlhaku tse peli tsa tafole) le ho tlosa lipheletso tsa mohala: =.

Ka mor'a moo, re lokela ho qala ho mamela http mochine oa sebakeng seo e le hore re fumane karabo ka mor'a tumello, e tla khutlisetsoa e le ho tsamaisa hape.

Mesebetsi ea tsamaiso e etsoa ho seva e khethehileng, re ke ke ra thibela monyetla oa hore batsamaisi ba 'maloa ba tla tsamaisa script ka nako e le' ngoe, kahoo e tla khetha ka mokhoa o sa reroang boema-kepe bakeng sa mosebedisi oa hona joale, empa ke hlalositse likou tse boletsoeng esale pele hobane li tlameha ho eketsoa hape joalo ka ha li tšeptjoa ho khomphutha ea API.

access_type=ntle le inthanete e bolela hore sesebelisoa se ka ntlafatsa lets'oao le felileng ka boyona ntle le ho sebelisana le sebatli,
response_type=khoutu e beha sebopeho sa hore na khoutu e tla khutlisoa joang (e bua ka mokhoa oa khale oa tumello, ha mosebelisi a kopitsitse khoutu ho tsoa ho sebatli ho ea ho script),
bophara e bontsha sebaka le mofuta wa phihlello. Li tlameha ho aroloa ke libaka kapa %20 (ho latela URL Encoding). Lethathamo la libaka tsa phihlello tse nang le mefuta li ka bonoa mona: OAuth 2.0 Scopes bakeng sa Google APIs.

Kamora ho amohela khoutu ea tumello, kopo e tla khutlisetsa molaetsa o haufi ho sebatli, emisa ho mamela boema-kepeng mme o romelle kopo ea POST ho fumana letšoao. Re bonts'a ho eona id le lekunutu tse boletsoeng pejana ho tsoa ho console API, aterese eo mosebelisi a tla romelloa ho eona le grant_type ho latela melao ea protocol.

Ha re arabela, re tla fumana lets'oao la Access, nako ea eona ea ho sebetsa ka metsotsoana, le token ea Refresh, eo ka eona re ka ntlafatsang letšoao la Access.

Kopo e tlameha ho boloka li-tokens sebakeng se sireletsehileng se nang le nako e telele ea nako, kahoo ho fihlela re hlakola phihlelo e fumanoeng, kopo e ke ke ea khutlisetsa letšoao la ho tsosolosa. Qetellong, ke kentse kopo ea ho hlakola lets'oao; haeba kopo e sa phethoa ka katleho mme lets'oao la ho khatholla le sa ka la khutlisoa, e tla qala ts'ebetso hape (re ne re nka ho sa sireletseha ho boloka li-tokens sebakeng sa heno ho terminal, mme ha re etse joalo. 'batla ho thatafatsa lintho ka cryptography kapa ho bula sebatli khafetsa).

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
}

Joalo ka ha o se o hlokometse, ha o hlakola lets'oao, ho sebelisoa Invoke-WebRequest. Ho fapana le Invoke-RestMethod, ha e khutlise data e amohetsoeng ka mokhoa o ka sebelisoang mme e bonts'a boemo ba kopo.

Ka mor'a moo, sengoloa se u kopa hore u kenye lebitso la mosebelisi le ho qetela, 'me u hlahise lengolo-tsoibila la ho kena +.

Likopo

Likopo tse latelang e tla ba - pele ho tsohle, o hloka ho hlahloba hore na mosebelisi ea nang le login e tšoanang o se a ntse a le teng ho fumana qeto ea ho theha e ncha kapa ho nolofalletsa ea hajoale.

Ke nkile qeto ea ho kenya tšebetsong likopo tsohle ka sebopeho sa ts'ebetso e le 'ngoe ka khetho, ke sebelisa switch:

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'])
      }
    }
  }
}

Kopong e 'ngoe le e' ngoe, o hloka ho romella sehlooho sa Authorization se nang le mofuta oa tokens le token ea Access ka boeona. Hajoale, mofuta oa tokens o lula o le Mojari. Hobane re hloka ho hlahloba hore token ha e e-s'o feletsoe ke nako le ho e ntlafatsa ka mor'a hora ho tloha ha e ne e fanoe, ke hlalositse kopo ea mosebetsi o mong o khutlisetsang letšoao la Access. Karolo e tšoanang ea khoutu e qalong ea sengoloa ha u amohela tokene ea pele ea phihlello:

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
}

E lekola sebaka sa ho kena hore se teng:

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
}

Lengolo-tsoibila:$potso e tla kopa API ho batla mosebelisi ea nang le lengolo-tsoibila leo, ho kenyeletsoa le mabitso a mang. U ka boela ua sebelisa wildcard: =, :, :{PREFIX}*.

Ho fumana lintlha, sebelisa mokhoa oa ho kopa GET, ho kenya data (ho theha akhaonto kapa ho eketsa setho ho sehlopha) - POST, ho ntlafatsa lintlha tse teng - PUT, ho hlakola tlaleho (mohlala, setho se tsoang sehlopheng) - HLAKOLA.

Script e tla boela e botse nomoro ea mohala (khoele e sa sebetseng) le ho kenngoa sehlopheng sa kabo ea libaka. E etsa qeto ea hore na mosebelisi o lokela ho ba le yuniti efe ea mokhatlo ho latela Active Directory OU e khethiloeng mme e tla le password:

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"

Ebe o qala ho qhekella ak'haonte:

$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
}

Mesebetsi ea ho ntlafatsa le ho theha ak'haonte e na le syntax e ts'oanang; ha se likarolo tsohle tse ling tse hlokahalang; karolong e nang le linomoro tsa mohala, o hloka ho hlakisa lethathamo le ka bang le rekoto e le 'ngoe e nang le nomoro le mofuta oa eona.

E le hore u se ke ua fumana phoso ha u eketsa mosebedisi sehlopheng, re ka qala ka ho hlahloba hore na e se e le setho sa sehlopha sena ka ho fumana lethathamo la litho tsa sehlopha kapa sebopeho ho mosebedisi ka boeena.

Ho botsa setho sa sehlopha sa mosebelisi ea itseng ho ke ke ha ipheta hape ho tla bontša feela ho ba setho ka kotloloho. Ho kenyelletsa mosebelisi sehlopheng sa motsoali ea seng a ntse a e-na le sehlopha sa bana seo mosebelisi e leng setho sa sona se tla atleha.

fihlela qeto e

Ho setseng ke ho romella mosebelisi phasewete bakeng sa ak'haonte e ncha. Re etsa sena ka SMS, 'me re romela tlhahisoleseding e akaretsang ka litaelo le ho kena ho imeile ea botho, eo, hammoho le nomoro ea mohala, e fanoeng ke lefapha la ho hira. Ka mokhoa o mong, o ka boloka chelete mme oa romella phasewete ea hau moqoqong oa lekunutu oa thelekramo, oo hape o ka nkuoang e le ntlha ea bobeli (MacBooks e tla ba mokhelo).

Kea leboha ha o bala ho fihlela qetellong. Ke tla thabela ho bona litlhahiso tsa ho ntlafatsa mokhoa oa ho ngola lingoliloeng mme ke lakatsa hore u tšoase liphoso tse fokolang ha u ngola mangolo =)

Lethathamo la lihokelo tse ka bang molemo kapa tsa araba lipotso feela:

Source: www.habr.com

Eketsa ka tlhaloso