I want to implement an "isActive" feature on my app that is built using firebase firestore. I am using firebase functions along with authentication in my React App.
Is there a way of detecting if the user is "active" or "inActive" on my app by triggering a cloud function when they login or disconnect to the app?
If i can determine this i would store the value in firestore and handle it in the frontend to display a UI.
Thanks
I see two aspects to the question here:
Auth state: You want to track the logged-in duration of the user.
Focus state: You want to track when the user is active on the app.
For #1, you will have to listen to the auth state changes, and you may also want to change your auth state persistence strategy accordingly. From https://firebase.google.com/docs/auth/web/auth-state-persistence:
Enum
Value
Description
firebase.auth.Auth.Persistence.LOCAL
'local'
Indicates that the state will be persisted even when the browser window is closed or the activity is destroyed in React Native. An explicit sign out is needed to clear that state. Note that Firebase Auth web sessions are single host origin and will be persisted for a single domain only.
firebase.auth.Auth.Persistence.SESSION
'session'
Indicates that the state will only persist in the current session or tab, and will be cleared when the tab or window in which the user authenticated is closed. Applies only to web apps.
firebase.auth.Auth.Persistence.NONE
'none'
Indicates that the state will only be stored in memory and will be cleared when the window or activity is refreshed.
import { getAuth, setPersistence, signInWithRedirect, inMemoryPersistence, GoogleAuthProvider } from "firebase/auth";
const auth = getAuth();
setPersistence(auth, inMemoryPersistence)
.then(() => {
const provider = new GoogleAuthProvider();
// In memory persistence will be applied to the signed in Google user
// even though the persistence was set to 'none' and a page redirect
// occurred.
return signInWithRedirect(auth, provider);
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
});
You don't need a cloud function for th
For #2, you might want to check out this blog. https://javascript.plainenglish.io/validate-your-apps-session-on-focus-892f610f7e23.
import { useLocation } from '#reach/router';
import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
export function WindowFocusHandler() {
const dispatch = useDispatch()
const location = useLocation()
useEffect(() => {
window.addEventListener("focus", onFocus)
return () => {
window.removeEventListener("focus", onFocus)
}
}, [])
const onFocus = () => dispatch(session.effects.checkSessionOnFocus(location))
return <></>
}
The Focus event on a window might get triggered more often if it is a browser app. Depending on what you want to achieve, both things should be possible in
your front-end code without the need for cloud functions. Although, you might opt to code the logic as a firebase function and invoke it from your react code when onFocus.
Related
I've noticed a problem with splitting responsibilities in React components based on the fetched data using RTK Query.
Basically, I have two components like HomePage and NavigationComponent.
On HomePage I'd like to fetch the information about the user so that I can modify NavigationComponent accordingly.
What I do inside HomePage:
import { setNavigationMode } from "features/nav/navSlice";
export default function HomePage() {
const {data: user} = useGetUserDataQuery();
const dispatch = useAppDispatch();
const navMode = user ? "all-options" : "none";
dispatch(setNavigationMode(navMode)); // here I change the default Navigation mode
return <MainLayout>
<Navigation/>
<Content/>
<Footer/>
</MainLayout>;
}
The HomePage is a special Page when the NavigationComponent shouldn't display any options for the not logged in user.
Other pages presents additional Logo and Title on Nav.
React communicates:
Warning: Cannot update a component (NavComponent) while rendering a different component (HomePage). To locate the bad setState() call inside HomePage, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
Not sure what is the right way to follow.
Whether the state should be changed in GetUser query after it is loaded - that doesn't seem to be legit.
problem is dispatch calls every render. Instead you can create a navigationSlice (if you don't have already) and use extraReducers for matching your authorization action like:
extraReducers: (builder) => {
builder.addMatcher(
usersApi.endpoints.login.matchFulfilled,
(state, { payload }) => {
if (payload.user) {
state.navigationMode = "all-options"
}
}
);
}
This way, state.navigationMode will only change when authorization changes
The solution was too obvious. The dispatch should be run in useEffect.
import { setNavigationMode } from "features/nav/navSlice";
export default function HomePage() {
const {data: user} = useGetUserDataQuery();
const dispatch = useAppDispatch();
const navMode = user ? "all-options" : "none";
// changed lines
useEffect( () => {
dispatch(setNavMode(navMode));
}, [navMode, dispatch]);
// /changed lines
return <MainLayout>
<Navigation/>
<Content/>
<Footer/>
</MainLayout>;
}
Thank you #papa-xvii for the hint with changing the navMode after user login. That solves the second problem I had.
However I cannot accept the answer as it does not solve the problem I described above.
The alternative title is "How to check the logged-in Realm user logged in via certain authentication provider?" OR "How to check a user is using a specific authentication provider/method?"
For an app start with an anonymous user and then linked to another authentication provider using user.linkUser(credentials: credential). Since the user always has a value either an anonymous user or a linked user.
How can I know if the current logged-in user is already linked with another auth provider e.g. "Sign in with Apple" or "Google"? This information needs to be known in order to hide the auth provider sign-in button.
In RealmSwift 10.12.0
There is an identifiers property under user. It is an array of RLMUserIdentity. the user identity contains a providerType string, https://docs.mongodb.com/realm-sdks/objc/latest/Classes/RLMUserIdentity.html#/c:objc(cs)RLMUserIdentity(py)providerType
Below is a sample output
print(">>> DEBUG:", user.identities.map { identity in (identity.identifier, identity.providerType)
[("611a27f9a1575af5ed15234e-lnnaeteekatdftrnsmpbpldr", "anon-user"), ("000766.23cbd125344c140b18ef0baa4deccaf32.61234", "oauth2-apple")]
Now you can check if the user identities contains the provider you care and hide the "sign in" button/link for that provider
https://github.com/realm/realm-cocoa/blob/d407cdc1c8be5f04c3decd37b88524855edfa7e8/Realm/RLMCredentials.mm
When you initialize a realm app, it checks by default for the accessToken, refresh token and other stuff that Realm does to store user data on the device after successful login. So, the default value when you declare your current user should be retrieved from Realm app instance. In my case, I use web development and it looks like this for React application.
import React, { useState } from 'react';
import LoginPage from 'containers/LoginPage';
import { RealmApp, getCustomCredentials } from './RealmApp';
function App() {
const [currentUser, setCurrentUser] = useState(RealmApp.currentUser);
const onAuth = async (data) => {
const credentials = getCustomCredentials(data);
const user = await RealmApp.logIn(credentials);
setCurrentUser(user);
};
const App = () => {
return (
<Box className="app-root-component" sx={{ display: 'flex' }}>
<h1>App</>
</Box>
);
};
return currentUser ? <App /> : <LoginPage onAuth={onAuth} />;
}
export default App;
here I have my variable & it's setter function
const [currentUser, setCurrentUser] = useState(RealmApp.currentUser);
I wish that helps you to get closer with apple sign in
Ive created 2 route guards... one which checks if the user is logged in and one if they are unauthenticated
When the app starts, very briefly it determines, while looking for the localstorage cookie, that the user doest exist and so shows the unauth page (i.e login page)
Im wondering what is the best approach to solve this - in my eyes the authguard with observale to see if the user is logged in or not was the best approach but there is that split second while the code runs that it cannot determine and it wants to show something.
Anyone have any similar issues/creative solutions to solve it.
I had this same issue a few months ago, and I solved it by creating an Auth Guard and returning a promise...
auth.guard.ts
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
): Observable<boolean> | Promise<boolean> | boolean {
return new Promise(resolve => {
const userAuthObs = this.afAuth.user.subscribe(user => {
if (user) {
resolve(true);
} else {
this.router.navigate(['signup']);
resolve(false);
}
});
});
}
The app just continues to load normally while it waits for this promise to decide where to direct the user.
You can watch a great video about creating auth guards here...
https://www.youtube.com/watch?v=RxLI9_ub6PM
From the docs it seems like there is no other way to sign-in using Google other than using the GoogleCredential constructor which takes an authCode as a mandatory parameter, how should I get it?
For an example of [[loginWithRedirect]], see Facebook Authentication
Also, there are multiple references in the docs to a function called loginWithRedirect, but they don't link anywhere and there is no property in the auth object called loginWithRedirect.
Indeed, the RN and server SDKs do not support the redirect concept. You have to get your own authCode.
Stitch's GoogleCredential constructor just expects a valid server auth code so that the Stitch service can use offline access.
Use a third-party OAuth module
I had no luck using the official google-auth-library SDK with RN. I was able to make it work (on iOS, at least -- haven't tried Android, yet) with react-native-google-signin from react-native-community. The installation process is a bit involved, so be sure to follow their instructions carefully!
I will show how I used this specific library to sign in. Hopefully this information can be applied to other OAuth libraries and other Authentication providers (e.g. Facebook).
Configure GoogleSignin
The webClientId must be specified and must match the Client ID under the Google Oauth2 configuration on the Stitch UI (see screenshot). The iosClientId is found in the GoogleService-Info.plist you download after following these steps. Finally, set offlineAccess to true.
If you use the Google iOS SDK directly or another library, note that webClientId is called serverClientID and iosClientId is simply called clientId.
Here's my configure code (see my complete App.js file):
componentDidMount() {
// ...
GoogleSignin.configure({
webClientId: '<id>', // from Stitch UI > Users > Providers > Google
offlineAccess: true,
iosClientId: '<id>', // CLIENT_ID in GoogleService-Info.plist
});
}
Render GoogleSigninButton
react-native-google-signin provides a nice button to use, which I rendered out (see screenshot):
const loginButton = <GoogleSigninButton
style={{ width: 192, height: 48 }}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Dark}
onPress={this._onPressLogin}
disabled={this.state.isSigninInProgress}
/>
Give Stitch the serverAuthCode from GoogleSignin
My _onPressLogin function uses GoogleSignin to get the serverAuthCode. It then passes that code to Stitch:
_onPressLogin = async () => {
// They recommend calling this before signIn
await GoogleSignin.hasPlayServices();
// Call signIn to get userInfo
const userInfo = await GoogleSignin.signIn();
// Check if serverAuthCode was received -- it will be null
// if something wasn't configured correctly. Be sure to
// log out after changing a configuration.
const {serverAuthCode} = userInfo;
if (serverAuthCode === null) {
throw new Error('Failed to get serverAuthCode!');
}
try {
// Pass serverAuthCode to Stitch via GoogleCredential
const user = await this.state.client.auth.loginWithCredential(new GoogleCredential(serverAuthCode));
console.log(`Successfully logged in as user ${user.id}`);
this.setState({ currentUserId: user.id });
} catch(err) {
console.error(`Failed to log in anonymously: ${err}`);
this.setState({ currentUserId: undefined })
}
Logging out
I found I had to log out several times while testing (and figuring out which client IDs to use where), or else serverAuthCode would come back null. It was good to have the logout button visible at all times. My logout code looks like this:
_onPressLogout = async () => {
await GoogleSignin.revokeAccess();
await GoogleSignin.signOut();
const user = await this.state.client.auth.logout();
console.log(`Successfully logged out`);
this.setState({ currentUserId: undefined })
}
I hope this helps!
Here is my use case:
I have two different apps, react client app and express/node backend server app having REST APIs. I want the react client app to refresh the component states, every time the Server sends an event on the socket which has change of the data on the server side.
I have seen examples of websocket doing this (http://www.thegreatcodeadventure.com/real-time-react-with-socket-io-building-a-pair-programming-app/) but in this case the client and the server components are in the same app. How to do this when you different apps for client and the server components.
Should I use Timer (https://github.com/reactjs/react-timer-mixin) to make a call from the client to the server rest endpoint and refresh the components on the client if there is any change in data. Or does redux middleware provide those capabilities..
thanks, Rajesh
I think what you are looking for is something like react-redux. This allows you to connect the component to depend on a piece of the state tree and will be updated whenever the state changes (as long as you are applying new references). See below:
UserListContainer.jsx
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as UserActions from '../actions/userActions';
import UserList from '../components/UserList';
class UserListContainer {
// Subscribe to changes when the component mounts
componentDidMount() {
// This function
this.props.UserActions.subscribe();
}
render() {
return <UserList {...props} />
}
}
// Add users to props (this.props.users)
const mapStateToProps = (state) => ({
users: state.users,
});
// Add actions to props
const mapDispatchToProps = () => ({
UserActions
});
// Connect the component so that it has access to the store
// and dispatch functions (Higher order component)
export default connect(mapStateToProps)(UserListContainer);
UserList.jsx
import React from 'react';
export default ({ users }) => (
<ul>
{
users.map((user) => (
<li key={user.id}>{user.fullname}</li>
));
}
</ul>
);
UserActions.js
const socket = new WebSocket("ws://www.example.com/socketserver");
// An action creator that is returns a function to a dispatch is a thunk
// See: redux-thunk
export const subscribe = () => (dispatch) => {
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'user add') {
// Dispatch ADD_USER to be caught in the reducer
dispatch({
type: 'ADD_USER',
payload: {
data.user
}
});
}
// Other types to change state...
};
};
Explanation
Essentially what is happening is that when the container component mounts it will dispatch a subscribe action which will then listed for messages from the socket. When it receives a message it will dispatch another action base off of its type with the corresponding data which will be caught in the reducer and added to state. *Note: Do not mutate the state or the component will not reflect the changes when it is connected.
Then we connect the container component using react-redux which applies state and actions to props. So now any time the users state changes it will send it to the container component and down to the UserList component for rendering.
This is a naive approach but I believe it illustrates the solution and gets you on the right track!
Good luck and hope this helped!