GoogleTests.swift 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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() 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. print("Signing in with Google had error: \(error)")
  32. }
  33. expectation.fulfill()
  34. }
  35. waitForExpectations(timeout: TestsBase.kExpectationsTimeout)
  36. }
  37. #if compiler(>=5.5.2) && canImport(_Concurrency)
  38. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  39. func testSignInWithGoogleAsync() async throws {
  40. let auth = Auth.auth()
  41. let userInfoDict = try await getGoogleAccessTokenAsync()
  42. let googleAccessToken: String = try XCTUnwrap(userInfoDict["access_token"] as? String)
  43. let googleIDToken: String = try XCTUnwrap(userInfoDict["id_token"] as? String)
  44. let credential = GoogleAuthProvider.credential(withIDToken: googleIDToken,
  45. accessToken: googleAccessToken)
  46. _ = try await auth.signIn(with: credential)
  47. }
  48. #endif
  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 = 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. #if compiler(>=5.5.2) && canImport(_Concurrency)
  83. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  84. /// Sends http request to Google OAuth2 token server to use refresh token to exchange for Google
  85. /// access token.
  86. /// Returns a dictionary that constains "access_token", "token_type", "expires_in" and sometimes
  87. /// the "id_token". (The id_token is not guaranteed to be returned during a refresh exchange;
  88. /// see https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse)
  89. func getGoogleAccessTokenAsync() async throws -> [String: Any] {
  90. let googleOauth2TokenServerUrl = "https://www.googleapis.com/oauth2/v4/token"
  91. let bodyString = "client_id=\(Credentials.kGoogleClientID)&grant_type=refresh_token" +
  92. "&refresh_token=\(Credentials.kGoogleTestAccountRefreshToken)"
  93. let postData = bodyString.data(using: .utf8)
  94. let service = GTMSessionFetcherService()
  95. let fetcher = service.fetcher(withURLString: googleOauth2TokenServerUrl)
  96. fetcher.bodyData = postData
  97. fetcher.setRequestValue(
  98. "application/x-www-form-urlencoded",
  99. forHTTPHeaderField: "Content-Type"
  100. )
  101. let data = try await fetcher.beginFetch()
  102. guard let returnValue = try JSONSerialization.jsonObject(with: data, options: [])
  103. as? [String: Any] else {
  104. XCTFail("Failed to serialize userInfo as a Dictionary")
  105. fatalError()
  106. }
  107. return returnValue
  108. }
  109. #endif
  110. }