AuthenticationViewModel.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. @MainActor func signIn() {
  46. authenticator.signIn()
  47. }
  48. /// Signs the user out.
  49. func signOut() {
  50. authenticator.signOut()
  51. }
  52. /// Disconnects the previously granted scope and logs the user out.
  53. func disconnect() {
  54. authenticator.disconnect()
  55. }
  56. var hasBirthdayReadScope: Bool {
  57. return authorizedScopes.contains(BirthdayLoader.birthdayReadScope)
  58. }
  59. /// Adds the requested birthday read scope.
  60. /// - parameter completion: An escaping closure that is called upon successful completion.
  61. @MainActor func addBirthdayReadScope(completion: @escaping () -> Void) {
  62. authenticator.addBirthdayReadScope(completion: completion)
  63. }
  64. }
  65. extension AuthenticationViewModel {
  66. /// An enumeration representing logged in status.
  67. enum State {
  68. /// The user is logged in and is the associated value of this case.
  69. case signedIn(GIDGoogleUser)
  70. /// The user is logged out.
  71. case signedOut
  72. }
  73. }