GoogleSignInAuthenticator.swift 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. /*
  2. * Copyright 2021 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 GoogleSignIn
  18. /// An observable class for authenticating via Google.
  19. final class GoogleSignInAuthenticator: ObservableObject {
  20. // TODO: Replace this with your own ID.
  21. #if os(iOS)
  22. private let clientID = "687389107077-8qr6dh8fr4uaja89sdr5ieqb7mep04qv.apps.googleusercontent.com"
  23. #elseif os(macOS)
  24. private let clientID = "687389107077-8qr6dh8fr4uaja89sdr5ieqb7mep04qv.apps.googleusercontent.com"
  25. #endif
  26. private lazy var configuration: GIDConfiguration = {
  27. return GIDConfiguration(clientID: clientID)
  28. }()
  29. private var authViewModel: AuthenticationViewModel
  30. /// Creates an instance of this authenticator.
  31. /// - parameter authViewModel: The view model this authenticator will set logged in status on.
  32. init(authViewModel: AuthenticationViewModel) {
  33. self.authViewModel = authViewModel
  34. }
  35. /// Signs in the user based upon the selected account.'
  36. /// - note: Successful calls to this will set the `authViewModel`'s `state` property.
  37. func signIn() {
  38. let challengeDelay = 0.200;
  39. let assertionDelay = 0.160;
  40. let totalDelay = challengeDelay + assertionDelay;
  41. DispatchQueue.main.asyncAfter(deadline: .now() + totalDelay) {
  42. #if os(iOS)
  43. guard let rootViewController = UIApplication.shared.windows.first?.rootViewController else {
  44. print("There is no root view controller!")
  45. return
  46. }
  47. GIDSignIn.sharedInstance.signIn(with: self.configuration,
  48. presenting: rootViewController) { user, error in
  49. guard let user = user else {
  50. print("Error! \(String(describing: error))")
  51. return
  52. }
  53. self.authViewModel.state = .signedIn(user)
  54. }
  55. #elseif os(macOS)
  56. guard let presentingWindow = NSApplication.shared.windows.first else {
  57. print("There is no presenting window!")
  58. return
  59. }
  60. GIDSignIn.sharedInstance.signIn(with: self.configuration,
  61. presenting: presentingWindow) { user, error in
  62. guard let user = user else {
  63. print("Error! \(String(describing: error))")
  64. return
  65. }
  66. self.authViewModel.state = .signedIn(user)
  67. }
  68. #endif
  69. }
  70. }
  71. /// Signs out the current user.
  72. func signOut() {
  73. GIDSignIn.sharedInstance.signOut()
  74. authViewModel.state = .signedOut
  75. }
  76. /// Disconnects the previously granted scope and signs the user out.
  77. func disconnect() {
  78. GIDSignIn.sharedInstance.disconnect { error in
  79. if let error = error {
  80. print("Encountered error disconnecting scope: \(error).")
  81. }
  82. self.signOut()
  83. }
  84. }
  85. // Confines birthday calucation to iOS for now.
  86. /// Adds the birthday read scope for the current user.
  87. /// - parameter completion: An escaping closure that is called upon successful completion of the
  88. /// `addScopes(_:presenting:)` request.
  89. /// - note: Successful requests will update the `authViewModel.state` with a new current user that
  90. /// has the granted scope.
  91. func addBirthdayReadScope(completion: @escaping () -> Void) {
  92. #if os(iOS)
  93. guard let rootViewController = UIApplication.shared.windows.first?.rootViewController else {
  94. fatalError("No root view controller!")
  95. }
  96. GIDSignIn.sharedInstance.addScopes([BirthdayLoader.birthdayReadScope],
  97. presenting: rootViewController) { user, error in
  98. if let error = error {
  99. print("Found error while adding birthday read scope: \(error).")
  100. return
  101. }
  102. guard let currentUser = user else { return }
  103. self.authViewModel.state = .signedIn(currentUser)
  104. completion()
  105. }
  106. #elseif os(macOS)
  107. guard let presentingWindow = NSApplication.shared.windows.first else {
  108. fatalError("No presenting window!")
  109. }
  110. GIDSignIn.sharedInstance.addScopes([BirthdayLoader.birthdayReadScope],
  111. presenting: presentingWindow) { user, error in
  112. if let error = error {
  113. print("Found error while adding birthday read scope: \(error).")
  114. return
  115. }
  116. guard let currentUser = user else { return }
  117. self.authViewModel.state = .signedIn(currentUser)
  118. completion()
  119. }
  120. #endif
  121. }
  122. }