One Time Login in App - Firebaseauth

One time login in app - FirebaseAuth

The simplest way to achieve this is to use a listener. Let's assume you have two activities, the LoginActivity and the MainActivity. The listener that can be created in the LoginActivity should look like this:

FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
};

This basically means that if the user is logged in, skip the LoginActivity and go to the MainActivity.

Instantiate the FirebaseAuth object:

FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();

And start listening for changes in your onStart() method like this:

@Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(authStateListener);
}

In the MainActivity, you should do the same thing:

FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser == null) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
}
};

Which basically means that if the user is not logged in, skip the MainActivity and go to the LoginActivity. In this activity you should do the same thing as in the LoginActivity, you should start listening for changes in the onStart().

In both activities, don't forget to remove the listener in the moment in which is not needed anymore. So add the following line of code in your onStop() method:

@Override
protected void onStop() {
super.onStop();
firebaseAuth.removeAuthStateListener(authStateListener);
}

Is there any way to figure out the user is already login in any device Firebase Auth

UserMetaData has the last sign in time. You can also set auth state persistence to be either local, session, or none.

You could use these to approximate whether a given user could be authenticated elsewhere, but it doesn't seem like there's data on whether a user is definitely currently authenticated somewhere. For that you'd need to store login/logout data separately, such as in a a Firestore document for each user.

Note that the auth service doesn't typically know (or care) whether the user is actively using the app... it just issues each user an authentication token, which is used over some period of time to prove that they are who they say the are. The token can be invalidated/refreshed from time to time for security reasons (according to the persistence setting), but it's not an indication of whether they're "active". You don't mention your use case, but if you're trying to figure out whether users are on or offline (say for a chat application), you should look at Firebase's offline capabilities.

Firebase auth - Login and then redirect to app - How to fetch user

You can not use multiple domain for same authentication.

Each domain/subdomain have their own cookies and localstorage and those can't be shared with another domain.

For your case login subdomain can't able to share credentials (auth token) with your app domain.

I highly suggest you to move from subdomain to path
Like app.domain.com/login

If you still want this with subdomain look for this medium blog

Stay Logged in with Firebase to the app when closed

In the onCreate function, you need to add this piece of code

FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();

This code will fetch you the currently logged in user if the user has previously signed in, else will return null.

Check this link for further understanding.

Get the currently signed-in user - Firebase Docs

I hope this solved your problem. If you feel this answer is correct, please accept the answer.

Firebase Auth login and logout based on user's account status

First set up a listener to authentication state changes like:

FirebaseAuth.instance.authStateChanges().listen((User? user) {
// execute any logic depending on current authentication state
});

This will be called when user is logged in or out. The next step is to update you application's home route based on this change. One possible solution is to use provider for state management, check here.

Create a class in main.dart for the provider:

class AuthState with ChangeNotifier {
User? _user;
User? get user => _user;
set user(User? currentUser) {
_user = currentUser;
notifyListeners();
}
AuthState() {
FirebaseAuth.instance.authStateChanges().listen((User? currentUser) {
user = currentUser;
});
}
}

Don't forget to add provider package and import it into main.dart.

After this you can create your MaterialApp like this (you don't really need MultiProvider but later if you add more providers it can be useful):

return MultiProvider(
providers: [
ChangeNotifierProvider<AuthState>(
create: (context) => AuthState()),
],
builder: (context, child) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: context.watch<AuthState>().user == null ?
splashScreen() : app(),
);
});

EDIT: simplified sample without Firebase Authentication

This example demonstrates how the UI is updated on changes in the provider. It can be run on dartpad.dev as well and seems to work. In this example listening to authentication state changes I simply simulate it with explicitly setting an int? value, since during the tests the Firebase part worked, only UI was not updated on logout.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class AuthState with ChangeNotifier {
int? _user;
int? get user => _user;
set user(int? newUser) {
_user = newUser;
notifyListeners();
}
}

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<AuthState>(create: (context) => AuthState()),
],
builder: (context, child) {
return MaterialApp(
home: context.watch<AuthState>().user == null
? const Login()
: const Main(),
);
});
}
}

class Login extends StatelessWidget {
const Login({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) => Scaffold(
body: Center(
child: Column(children: [
const Text('You are not logged in'),
ElevatedButton(
child: const Text('Login'),
onPressed: () => context.read<AuthState>().user = 1)
])));
}

class Main extends StatelessWidget {
const Main({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) => Scaffold(
body: Center(
child: Column(children: [
const Text('You are logged in'),
ElevatedButton(
child: const Text('Logout'),
onPressed: () => context.read<AuthState>().user = null)
])));
}


Related Topics



Leave a reply



Submit