AuthenticationViewModel.swift 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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. Task { @MainActor in
  52. do {
  53. let user = try await authenticator.signIn(with: rootViewController)
  54. self.state = .signedIn(user)
  55. } catch {
  56. print("Error signing in: \(error)")
  57. }
  58. }
  59. #elseif os(macOS)
  60. guard let presentingWindow = NSApplication.shared.windows.first else {
  61. print("There is no presenting window!")
  62. return
  63. }
  64. Task { @MainActor in
  65. do {
  66. let user = try await authenticator.signIn(with: presentingWindow)
  67. self.state = .signedIn(user)
  68. } catch {
  69. print("Error signing in: \(error)")
  70. }
  71. }
  72. #endif
  73. }
  74. /// Signs the user out.
  75. func signOut() {
  76. authenticator.signOut()
  77. }
  78. /// Disconnects the previously granted scope and logs the user out.
  79. func disconnect() {
  80. Task { @MainActor in
  81. do {
  82. try await authenticator.disconnect()
  83. authenticator.signOut()
  84. } catch {
  85. print("Error disconnecting: \(error)")
  86. }
  87. }
  88. }
  89. var hasBirthdayReadScope: Bool {
  90. return authorizedScopes.contains(BirthdayLoader.birthdayReadScope)
  91. }
  92. #if os(iOS)
  93. /// Adds the requested birthday read scope.
  94. /// - parameter viewController: A `UIViewController` to use while presenting the flow.
  95. /// - returns: A `GIDGoogleUser` with the authorized scope.
  96. /// - throws: Any error that may arise while adding the read birthday scope.
  97. func addBirthdayReadScope(viewController: UIViewController) async throws -> GIDGoogleUser {
  98. return try await authenticator.addBirthdayReadScope(viewController: viewController)
  99. }
  100. #endif
  101. #if os(macOS)
  102. /// adds the requested birthday read scope.
  103. /// - parameter window: An `NSWindow` to use while presenting the flow.
  104. /// - returns: A `GIDGoogleUser` with the authorized scope.
  105. /// - throws: Any error that may arise while adding the read birthday scope.
  106. func addBirthdayReadScope(window: NSWindow) async throws -> GIDGoogleUser {
  107. return try await authenticator.addBirthdayReadScope(window: window)
  108. }
  109. #endif
  110. }
  111. extension AuthenticationViewModel {
  112. /// An enumeration representing logged in status.
  113. enum State {
  114. /// The user is logged in and is the associated value of this case.
  115. case signedIn(GIDGoogleUser)
  116. /// The user is logged out.
  117. case signedOut
  118. }
  119. }