Persistent User Session on React Native App - react-native

I have already implemented a user authentication, in which the user can log in again or register.
I would now like to avoid that the user must register again after each closing of the app. For this reason I have to request a refresh token at certain intervals (Max 1 hour, as long as the cookie is valid). my question: how do I do that best? the refresh should work for both open and closed apps. I saw the possibility of the React Native Background task, but apparently only runs when the app is closed.

You have to create a flag in AsyncStorage when the user is authenticated.
And then you have to check that flag each time on opening the app.
Here is the sample snippet.
AsyncStorage.setItem('loggedIn', true);
And in your app.js you can check this flag in constructor
AsyncStorage.getItem('loggedIn').then((value) => {
if (value) {
//user logged in logic goes here
} else {
// user logged out. You need to login him again
}
});

Considering that you need to persist user's login forever and still be able to refresh the token, one possible way is to store the user's credentials (username and password) in some secure storage like react-native-keychain and then refresh the token every time the user opens the app.
Or more precisely, automate the login with the credentials you stored whenever the user launches the app with the help of useEffect hook(componentDidMount).
Note: This is not a good implementation if your app uses push notifications. Push notifications demand the user to be authorized all the time.

Related

Is there a way to re-hydrate the gapi.client access token between page loads?

The use-token-model documentation states that
In the token based authorization model, there is no need to store
per-user refresh tokens on your backend server.
It also states that
In the Token model, an access token is not stored by the OS or
browser, instead a new token is first obtained at page load time, or
subsequently by triggering a call to requestAccessToken() through a
user gesture such as a button press.
The trouble I am having is during development my page is continually reloading and I am having to re-connect each time. I have workaround ideas, but I just wanted to confirm that there is no way to persist the token/session information in local storage to rehydrate gapi.client via gapi.client.setToken.
You can store the access token in local storage. When the page reloads, you can then retrieve it and use gapi.client.setToken() to set the token for use.
Note that you will have to re-auth when the token expires, after 1 hour.
const token = localStorage.getItem("u_token")
if (token) {
gapi.client.setToken({access_token:token});
}

How could i make a firestore cloud function trigger on user login?

Cloud functions doesn't accept onLoging by default, how can i "bypass" this limitation so i can run a cloud function every time a user gets "online".
My thought so far is to run a create document on logIn and listen to it, but what happens when the user is not login in but using his last time session?
Do i run the same post request on the isLogged function ? that function can be run many times when the application is running, so is not optimal.
is running the function on app init (angular 7) the solution here?
Only you can define what a "session" is for your app. There is no universal definition that you can use to trigger a Cloud Function. Firebase Authentication won't help with this either, since users are logged in "forever", until your code explicitly logs them out (it automatically refreshes the user's auth token every hour).
You're going to have to write your own code to figure this out by whatever specification you decide the user has "logged in" or "logged out".
You can create a function that triggers when a Firebase user is created using the functions.auth.user().onCreate() event handler:
exports.sendWelcomeEmail = functions.auth.user().onCreate((user) => {
// ...
});
https://firebase.google.com/docs/functions/auth-events?hl=en-419
but one alternative you have would be , to make a write operation in the client when user login.

AWS Cognito: Restrict users to a one login at a time

Is there any way to restrict users to a single [simultaneous] session?
I'd like to be able to check if the current user already has a session. If they do, then they can opt to sign that session out, before continuing.
To be clear, at the moment it is possible to login the same user from multiple browser tabs, (from the same cognito application)
cognitoUser.authenticateUser(authenticationDetails, {
cognitoUser: this.cognitoUser,
onSuccess: (result) => {
this.userSession = result
console.log('successfully logged in', result)
// But are they already logged in somewhere else?
},
onFailure: (error) => {
console.log('Login failed for some reason...')
callback(error)
}
}
I understand that Cognito is built with mobiles/apps in mind so this might not be possible without using a login lambda hook... ? Even then I'm not sure if it's possible without maintaining a table of logged in users...?!
You can signs the current user out globally from all the devices by invalidating all issued tokens
cognitoUser.globalSignOut();
or signs the current user out from the application in existing session in the browser.
if (cognitoUser != null) {
cognitoUser.signOut();
}
You can onvoke either of the above just before user sigins in back again using the login screen.
I used the admin API - "AdminUserGlobalSignOut" for invalidating all the session tokens provided to the user before I send the login request from my lambda to Cognito.
You can refer to this link for official docs from aws.
https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUserGlobalSignOut.html
Pro Tip - AdminUserGlobalSignOut endpoint kills the refresh token
validity not the Id Token validity - so if the creds are shared at
12pm and the user signs in using another device in 5 mins or so - the
first device ID token login will still work on the first device until
its not expired - by default ID Token is valid for 1 hour.

How store login credentials in Redux store?

I'm figuring out the data-flow, and writing action oriented code to deal with Redux.
This is the flow:
I reach SplashScreen and check if accessToken exists. If no, I send the user to LoginScreen. Else, I take him to the HomeScreen.
The flow is rather simple but I'm not able to wrap my head around how to store the token, expire the token or just check if user is logged in. So, technically, when a user logs in, the state(access token) should change. I'm not asking for code, just some pseudo-code and a little explanation will help!
If you want to user the redux store to save token or any user credentials you will need to ensure the state is saved on localStorage, and for that you can use a redux middleware like this or this, or you can use middle-ware of your own :
export default store => next => action => {
let result = next(action)
localStorage.state = JSON.stringify(store.getState())
return result
}
I don't know if you are using react router, If you are, take a look at this example: authenticator I think it's really the best way to do it..
In my app I used react-native-keychain. When a user logs in, I store the accessToken in the redux store. From there, any time I'm making a request, I just get the token from the store, ensure that it's valid, and make the request.

Restrict quickblox user creation

When a user registers at my website I also need to create a quickblox user. I got this procedure to work:
Get a session token from API route "api.quickblox.com/session.json". But to do so I need a user. So I use my own login to quickblox dashboard.
Create the user by hitting API route "/users.json". Fair eanough, it works!
Questions
It feels strange using my own dashboard login as the token generator account. Is there not some other way?
The newly created user can create more users! That is, I created a new token with the details from the just created user, whom in turn was allowed to create further users. This cant be right? What am I doing wrong?
Quickblox chat example available here: http://quickblox.github.io/quickblox-javascript-sdk/samples/chat/# serves the keys and secret in the open, like this:
QBApp = { appId: 46126, authKey: 'Nyc2fwgg8QeFJpS', authSecret: SUv3grsaDMx5'}; Is that the way to do it? Then atleast I would like to control the creation of new users..
Thanks!
Hope you doing well !!
For Quickblox must have manage session for each and every users,you have to download and integrate quickblox SDK into your web app.
You have to follow this steps:
1) Create a app on Quickblox and add credentials into your javascript SDK or configure your javascript SDK.
2) Whenever user is logged-in to you app you must have to login quickblox as well and get session for logged-in user.
3) Do whatever operation with user created session like (chat,viedo call, audio call)
4) When user log-out from your, you have to manage like user also logout form quickblox and destroy previously created sessions.
5) When registering new user you have to also register that user into your quickblox app.
this way you have to manage user management.
hope this will help you.
To create a user with an arbetary session/token this function can be used (for JS SDK)
var params = {login: 'test3', password: '12345678'};
function createUser(params) {
QB.createSession(function(err, result) {
QB.users.create(params, function(err, user) {
if (user) {
// user - JS obejct with QB user
alert("successfully created a user!");
} else {
alert("error!");
}
});
});
}
"The newly created user can create more users!"
After further research I have concuded this is a part of the design and not to worry about. I will add a job to clean up any users created by spammers.