GoogleTests.swift 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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 FirebaseAuth
  17. import Foundation
  18. import GTMSessionFetcherCore
  19. import XCTest
  20. class GoogleTests: TestsBase {
  21. func testSignInWithGoogle() throws {
  22. let auth = Auth.auth()
  23. let userInfoDict = getGoogleAccessToken()
  24. let googleAccessToken: String = try XCTUnwrap(userInfoDict["access_token"] as? String)
  25. let googleIDToken: String = try XCTUnwrap(userInfoDict["id_token"] as? String)
  26. let credential = GoogleAuthProvider.credential(withIDToken: googleIDToken,
  27. accessToken: googleAccessToken)
  28. let expectation = self.expectation(description: "Signing in with Google finished.")
  29. auth.signIn(with: credential) { result, error in
  30. if let error = error {
  31. XCTFail("Signing in with Google had error: \(error)")
  32. }
  33. expectation.fulfill()
  34. }
  35. waitForExpectations(timeout: TestsBase.kExpectationsTimeout)
  36. }
  37. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  38. func testSignInWithGoogleAsync() async throws {
  39. let auth = Auth.auth()
  40. let userInfoDict = try await getGoogleAccessTokenAsync()
  41. let googleAccessToken: String = try XCTUnwrap(userInfoDict["access_token"] as? String)
  42. let googleIDToken: String = try XCTUnwrap(userInfoDict["id_token"] as? String)
  43. let credential = GoogleAuthProvider.credential(withIDToken: googleIDToken,
  44. accessToken: googleAccessToken)
  45. _ = try await auth.signIn(with: credential)
  46. let displayName = try XCTUnwrap(auth.currentUser?.displayName)
  47. XCTAssertEqual(displayName, Credentials.kGoogleUserName)
  48. }
  49. /// Sends http request to Google OAuth2 token server to use refresh token to exchange for Google
  50. /// access token.
  51. /// Returns a dictionary that constains "access_token", "token_type", "expires_in" and sometimes
  52. /// the "id_token". (The id_token is not guaranteed to be returned during a refresh exchange; see
  53. /// https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse)
  54. func getGoogleAccessToken() -> [String: Any] {
  55. var returnValue: [String: Any] = [:]
  56. let googleOauth2TokenServerUrl = "https://www.googleapis.com/oauth2/v4/token"
  57. let bodyString = "client_id=\(Credentials.kGoogleClientID)&grant_type=refresh_token" +
  58. "&refresh_token=\(Credentials.kGoogleTestAccountRefreshToken)"
  59. let postData = bodyString.data(using: .utf8)
  60. let service = GTMSessionFetcherService()
  61. let fetcher = service.fetcher(withURLString: googleOauth2TokenServerUrl)
  62. fetcher.bodyData = postData
  63. fetcher.setRequestValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
  64. let expectation = self.expectation(description: "Exchanging Google account tokens finished.")
  65. fetcher.beginFetch { data, error in
  66. if let error {
  67. XCTFail("Exchanging Google account tokens finished with error: \(error)")
  68. } else {
  69. do {
  70. let data = try XCTUnwrap(data)
  71. returnValue = try JSONSerialization.jsonObject(with: data, options: [])
  72. as! [String: Any]
  73. } catch {
  74. XCTFail("Failed to unwrap data \(error)")
  75. }
  76. }
  77. expectation.fulfill()
  78. }
  79. waitForExpectations(timeout: TestsBase.kExpectationsTimeout)
  80. return returnValue
  81. }
  82. /// Sends http request to Google OAuth2 token server to use refresh token to exchange for Google
  83. /// access token.
  84. /// Returns a dictionary that constains "access_token", "token_type", "expires_in" and sometimes
  85. /// the "id_token". (The id_token is not guaranteed to be returned during a refresh exchange;
  86. /// see https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse)
  87. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  88. func getGoogleAccessTokenAsync() async throws -> [String: Any] {
  89. let googleOauth2TokenServerUrl = "https://www.googleapis.com/oauth2/v4/token"
  90. let bodyString = "client_id=\(Credentials.kGoogleClientID)&grant_type=refresh_token" +
  91. "&refresh_token=\(Credentials.kGoogleTestAccountRefreshToken)"
  92. let postData = bodyString.data(using: .utf8)
  93. let service = GTMSessionFetcherService()
  94. let fetcher = service.fetcher(withURLString: googleOauth2TokenServerUrl)
  95. fetcher.bodyData = postData
  96. fetcher.setRequestValue(
  97. "application/x-www-form-urlencoded",
  98. forHTTPHeaderField: "Content-Type"
  99. )
  100. let data = try await fetcher.beginFetch()
  101. guard let returnValue = try JSONSerialization.jsonObject(with: data, options: [])
  102. as? [String: Any] else {
  103. XCTFail("Failed to serialize userInfo as a Dictionary")
  104. fatalError()
  105. }
  106. return returnValue
  107. }
  108. }