GoogleTests.swift 3.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright 2020 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import FirebaseAuth
  18. import GTMSessionFetcher
  19. import XCTest
  20. class GoogleTests: TestsBase {
  21. func testSignInWithGoogle() {
  22. let auth = Auth.auth()
  23. let userInfoDict = self.getGoogleAccessToken()
  24. guard let googleAccessToken = userInfoDict["access_token"] as! String? else {
  25. XCTAssertTrue(false, "Failed to get googleAccessToken")
  26. return
  27. }
  28. guard let googleIDToken = userInfoDict["id_token"] as! String? else {
  29. XCTAssertTrue(false, "Failed to get googleIDToken")
  30. return
  31. }
  32. let credential = GoogleAuthProvider.credential(withIDToken: googleIDToken,
  33. accessToken: googleAccessToken)
  34. let expectation = self.expectation(description: "Signing in with Google finished.")
  35. auth.signIn(with: credential) { (result, error) in
  36. if let error = error {
  37. print("Signing in with Google had error: \(error)")
  38. }
  39. expectation.fulfill()
  40. }
  41. waitForExpectations(timeout:TestsBase.kExpectationsTimeout)
  42. }
  43. ///** Sends http request to Google OAuth2 token server to use refresh token to exchange for Google
  44. // * access token. Returns a dictionary that constains "access_token", "token_type", "expires_in" and
  45. // * sometimes the "id_token". (The id_token is not guaranteed to be returned during a refresh
  46. // * exchange; see https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse)
  47. // */
  48. func getGoogleAccessToken() -> Dictionary<String, Any> {
  49. var returnValue : Dictionary<String, Any> = [:]
  50. let googleOauth2TokenServerUrl = "https://www.googleapis.com/oauth2/v4/token"
  51. let bodyString = "client_id=\(Credentials.kGoogleClientID)&grant_type=refresh_token" +
  52. "&refresh_token=\(Credentials.kGoogleTestAccountRefreshToken)"
  53. let postData = bodyString.data(using: .utf8)
  54. let service = GTMSessionFetcherService.init()
  55. let fetcher = service.fetcher(withURLString: googleOauth2TokenServerUrl)
  56. fetcher.bodyData = postData
  57. fetcher.setRequestValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
  58. let expectation = self.expectation(description: "Exchanging Google account tokens finished.")
  59. fetcher.beginFetch { (data, error) in
  60. if let error = error {
  61. XCTAssertTrue(false, "Exchanging Google account tokens finished with error: \(error)")
  62. } else {
  63. do {
  64. let data = try XCTUnwrap(data)
  65. let userInfo = String.init(data: data, encoding: .utf8)
  66. print("The info of exchanged result is: \(String(describing: userInfo))")
  67. returnValue = try JSONSerialization.jsonObject(with: data, options: [])
  68. as! Dictionary<String, Any>
  69. } catch (let error) {
  70. XCTAssertTrue(false, "Failed to unwrap data \(error)")
  71. }
  72. }
  73. expectation.fulfill()
  74. }
  75. waitForExpectations(timeout:TestsBase.kExpectationsTimeout)
  76. return returnValue
  77. }
  78. }