user5156051
user5156051

Reputation:

How to check if user has valid Auth Session Firebase iOS?

I wanna check if the user has still a valid session, before I present the Home View controller of my app. I use the latest Firebase API. I think if I use the legacy, I'll be able to know this.

Here's what I did so far:

I tried typing in Xcode like this:

FIRApp().currentUser()
FIRUser().getCurrentUser()

But I can't seem to find that getCurrentUser function.

Upvotes: 19

Views: 24309

Answers (8)

Mudith Chathuranga Silva
Mudith Chathuranga Silva

Reputation: 7434

All the provided answers only check on currentUser. But you could check the auth session by simple user reload like below:

    // Run on the background thread since this is just a Firestore user reload, But you could also directly run on the main thread.

    DispatchQueue.global(qos: .background).async {
        Auth.auth().currentUser?.reload(completion: { error in
            if error != nil {
                DispatchQueue.main.async {
                    // Authentication Error
                    // Do the required work on the main thread if necessary 
                }
            } else {
                log.info("User authentication successfull!")
            }
        })
    }

Upvotes: 0

DoesData
DoesData

Reputation: 7047

Updated answer

Solution for latest Firebase SDK - DOCS

    // save a ref to the handler
    private var authListener: AuthStateDidChangeListenerHandle?

    // Check for auth status some where
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        authListener = Auth.auth().addStateDidChangeListener { (auth, user) in

            if let user = user {
                // User is signed in
                // let the user in?

                if user.isEmailVerified {
                    // Optional - check if the user verified their email too
                    // let the user in?
                }
            } else {
                // No user
            }
        }
    }

    // Remove the listener once it's no longer needed
    deinit {
        if let listener = authListener {
            Auth.auth().removeStateDidChangeListener(authListener)
        }
    }

Original solution

Solution in Swift 3

override func viewDidLoad() {
    super.viewDidLoad()

    FIRAuth.auth()!.addStateDidChangeListener() { auth, user in
        if user != nil {
            self.switchStoryboard()
        }
    }
}

Where switchStoryboard() is

func switchStoryboard() {
    let storyboard = UIStoryboard(name: "NameOfStoryboard", bundle: nil)
    let controller = storyboard.instantiateViewController(withIdentifier: "ViewControllerName") as UIViewController

    self.present(controller, animated: true, completion: nil)
}

Source

Upvotes: 14

Jordi Bruin
Jordi Bruin

Reputation: 1588

if FIRAuth.auth().currentUser != nil {
   presentHome()
} else {
   //User Not logged in
}

For updated SDK

if Auth.auth().currentUser != nil {

}

Upvotes: 31

Will Ullrich
Will Ullrich

Reputation: 2228

While you can see if there is such a user using Auth.auth().currentUser, this will only be telling you if there was a user authenticated, regardless of whether that users account still exists or is valid.


Complete Solution

The real solution to this should be using Firebase's re-authentication:

open func reauthenticate(with credential: AuthCredential, completion: UserProfileChangeCallback? = nil)

This assures (upon the launch of the application) that the previously signed in / authenticated user still in fact is and can be authenticated through Firebase.

let user = Auth.auth().currentUser    // Get the previously stored current user
var credential: AuthCredential
    
user?.reauthenticate(with: credential) { error in
  if let error = error {
    // An error happened.
  } else {
    // User re-authenticated.
  }
}

Upvotes: 4

shanezzar
shanezzar

Reputation: 1170

An objective-c solution would be (iOS 11.4):

[FIRAuth.auth addAuthStateDidChangeListener:^(FIRAuth * _Nonnull auth, FIRUser * _Nullable user) {
    if (user != nil) {
        // your logic
    }
}];

Upvotes: 0

mut tony
mut tony

Reputation: 407

if Auth.auth().currentUser?.uid != nil {

   //user is logged in

    }else{
     //user is not logged in
    }

Upvotes: 5

Edward
Edward

Reputation: 2974

Solution in Swift 4

override func viewDidLoad() {
    super.viewDidLoad()
    setupLoadingControllerUI()
    checkIfUserIsSignedIn()
}

private func checkIfUserIsSignedIn() {

    Auth.auth().addStateDidChangeListener { (auth, user) in
        if user != nil {
            // user is signed in
            // go to feature controller 
        } else {
             // user is not signed in
             // go to login controller
        }
    }
}

Upvotes: 5

Jeacovy Gayle
Jeacovy Gayle

Reputation: 457

override func viewDidLoad() {
FIRAuth.auth()!.addStateDidChangeListener() { auth, user in
            // 2
            if user != nil {
                let vc = self.storyboard?.instantiateViewController(withIdentifier: "Home")
                self.present(vc!, animated: true, completion: nil)
            }
        }
}

Source: https://www.raywenderlich.com/139322/firebase-tutorial-getting-started-2

Upvotes: 0

Related Questions