AuthenticationViewModel.swift 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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 SwiftUI
  17. import GoogleSignIn
  18. /// A class conforming to `ObservableObject` used to represent a user's authentication status.
  19. final class AuthenticationViewModel: ObservableObject {
  20. /// The user's log in status.
  21. /// - note: This will publish updates when its value changes.
  22. @Published var state: State
  23. private var authenticator: GoogleSignInAuthenticator {
  24. return GoogleSignInAuthenticator(authViewModel: self)
  25. }
  26. /// The user-authorized scopes.
  27. /// - note: If the user is logged out, then this will default to empty.
  28. var authorizedScopes: [String] {
  29. switch state {
  30. case .signedIn(let user):
  31. return user.grantedScopes ?? []
  32. case .signedOut:
  33. return []
  34. }
  35. }
  36. /// Creates an instance of this view model.
  37. init() {
  38. if let user = GIDSignIn.sharedInstance.currentUser {
  39. self.state = .signedIn(user)
  40. } else {
  41. self.state = .signedOut
  42. }
  43. }
  44. /// Signs the user in.
  45. func signIn() {
  46. #if os(iOS)
  47. guard let rootViewController = UIApplication.shared.windows.first?.rootViewController else {
  48. print("There is no root view controller!")
  49. return
  50. }
  51. #elseif os(macOS)
  52. guard let presentingWindow = NSApplication.shared.windows.first else {
  53. print("There is no presenting window!")
  54. return
  55. }
  56. #endif
  57. Task { @MainActor in
  58. do {
  59. #if os(iOS)
  60. let signInResult = try await authenticator.signIn(with: rootViewController)
  61. #elseif os(macOS)
  62. let signInResult = try await authenticator.signIn(with: presentingWindow)
  63. #endif
  64. self.state = .signedIn(signInResult.user)
  65. } catch {
  66. print("Error signing in: \(error)")
  67. }
  68. }
  69. }
  70. /// Signs the user out.
  71. func signOut() {
  72. authenticator.signOut()
  73. }
  74. /// Disconnects the previously granted scope and signs the user out.
  75. func disconnect() {
  76. Task { @MainActor in
  77. do {
  78. try await authenticator.disconnect()
  79. } catch {
  80. print("Error disconnecting: \(error)")
  81. }
  82. }
  83. }
  84. var hasBirthdayReadScope: Bool {
  85. return authorizedScopes.contains(BirthdayLoader.birthdayReadScope)
  86. }
  87. #if os(iOS)
  88. /// Adds the requested birthday read scope.
  89. /// - parameter viewController: A `UIViewController` to use while presenting the flow.
  90. /// - returns: The `GIDSignInResult`.
  91. /// - throws: Any error that may arise while adding the read birthday scope.
  92. func addBirthdayReadScope(viewController: UIViewController) async throws -> GIDSignInResult {
  93. return try await authenticator.addBirthdayReadScope(viewController: viewController)
  94. }
  95. #endif
  96. #if os(macOS)
  97. /// adds the requested birthday read scope.
  98. /// - parameter window: An `NSWindow` to use while presenting the flow.
  99. /// - returns: The `GIDSignInResult`.
  100. /// - throws: Any error that may arise while adding the read birthday scope.
  101. func addBirthdayReadScope(window: NSWindow) async throws -> GIDSignInResult {
  102. return try await authenticator.addBirthdayReadScope(window: window)
  103. }
  104. #endif
  105. }
  106. extension AuthenticationViewModel {
  107. /// An enumeration representing logged in status.
  108. enum State {
  109. /// The user is logged in and is the associated value of this case.
  110. case signedIn(GIDGoogleUser)
  111. /// The user is logged out.
  112. case signedOut
  113. }
  114. }