react-native-firebase: How to delete a token at logout? - react-native

I'd like to stop receiving notifications to the app once the user logs out.
I guess I'd have to remove the device token generated by react-native-firebase but I can't find any functionality to do this.
Does anyone know how to do this?

🔥 messaging().deleteToken()
You could achieve like this:
import auth from '#react-native-firebase/auth';
import messaging from '#react-native-firebase/messaging';
auth().onAuthStateChanged(user => {
if (!user) // Signed out
messaging().deleteToken();
});

The documentation isn't great, but I have found a working solution in v4.3.x
// login
const authorizedEntity = firebase.iid().app.options.messagingSenderId;
firebase.iid().getToken(authorizedEntity).then(token => token);
// logout
const authorizedEntity = firebase.iid().app.options.messagingSenderId;
firebase.iid().deleteToken(authorizedEntity, '*').then(nullToken => nullToken);

First of all, you shouldn't store Firebase token inside the app, you should store it in the database.
Firebase token is a device identifier for notifications, if someone steals it they could bomb someone with notifications.
Create a API route that handles logout (ex. POST /user/logout) on your backend, and on that request remove the firebase token from the database.

The firebase token is per app instance. The token will remain the same as long as the app is installed on the device. To remove the token you will have to uninstall the app.
To solve your problem, you should disocciate the token from the logged-in user when they log out. You can do this by sending a request to you server on user logout in order to update your database record where the token is associated with the user. Then, when a new user logs in, you should send another request to the server to associate the token with that user.

Related

What should be the scope that can be mentioned to generate code to get refresh token for fcm push notification?

I am new to firebase push notification.
https://accounts.google.com/o/oauth2/auth?client_id=CLIENT_ID&scope=https://gdata.youtube.com&response_type=code&access_type=offline&redirect_uri=urn:ietf:wg:oauth:2.0:oob
When I type above url in browser I get a code to to be used in following client side post call
{
grant_type=authorization_code,
redirect_uri=urn:ietf:wg:oauth2.0:oob,
code=code get from browser
client_id=your_client_id,
client_secret=your_client_secret,
}
But scope=https://gdata.youtube.com in above url should be replaced with firebase push notification url. Then only I can do above call. So I would like to know what should be the scope for firebase push notification? I mean what is replacement of https://gdata.youtube.com in above url. Please help me.
At last I found the answer from What Bearer token should I be using for Firebase Cloud Messaging testing? link. It is https://www.googleapis.com/auth/firebase.messaging

How to use auth0s refresh token when using webauth.authorize()

I am using the Auth0 webauth.authorize() pop up to log in to my react native app.
I receive the refreshToken back after log in but how do I use this refresh token to get a new access token? Is it possible with webauth or do I need to use the sdk?
It looks like you are already using the SDK if you are using webauth.authorize(). Using the react-native-auth0 package, you can use the following code to exchange a refresh token for an access token:
auth0.auth
.refreshToken({refreshToken: 'the user refresh_token'})
.then(console.log)
.catch(console.error);

How can I retrive the AWS Cognito user from from a valid access token using aws-amplify library?

I just want to retrieve the Cognito user attributes and other details by using a valid jwt access token produced when the user signed in earlier.
I use Nodejs and want to know whether there is a way to do this with the aws-amplify library.
We can decode the JWT using a third-party library like jwt-decode. The payload contains the details themselves.
There is a method in aws-amplify library that you can use for this purpose.
import { Auth } from 'aws-amplify';
Auth.currentAuthenticatedUser({
bypassCache: false // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
}).then(user => console.log(user))
.catch(err => console.log(err));
You will see attributes field in the response's payload.
If you face any problems, please check the official documentation
This method can be used to check if a user is logged in when the page is loaded. It will throw an error if there is no user logged in. This method should be called after the Auth module is configured or the user is logged in.

Using Firebase for server side authentication

I have Firebase authentication set up on the client side, and on the server side I can take a JWT token and decode the account ID. But how does this work when I want each page load to be authenticated on the server before the page is generated?
On login or each page load, can I simply store the last JWT token into cookies so that I can read them on my server? Aside from that, I don't know how else for my server to get that information aside from each link being an AJAX call.
This seems to be the only way to do it presuming you're using the firebase auth library to decode and verify the tokens on the server and not some kind of JWT parsing library.
Firebase admin includes methods for decoding and verifying id tokens and extrapolating all the information. This prevents cookie forgery and keeps firebase auth as your single source of truth for whether or not a user is authenticated.
for example (in node):
const admin = require("firebase-admin");
admin.initalizeApp({
credential: admin.credential.cert(yourServiceAccountJsonHere),
databaseURL: "http://YOURDATABASE.firebaseio.com/"
});
admin.verifyIdToken("usertokenasastring") //returns a promise
.then(function(decodedToken){
//process the decoded user token somehow
});
Firebase makes a call to your database, and makes sure that that user is logged in and that all the other information in the JWT makes sense, so you don't have to worry about implementing any kind of verification server side.

how to detect after FB authentication and before FB authorization

In my MVC application, I have below code in JQuery to check if user is connected to Facebook app or not
FB.login(function (response) {
switch (response.status) {
case "connected":
case "unknown":
break;
}
}, { scope: "#MyPermissions" });
Now, when I do FB login through my app, it authenticates and immediately starts FB app authorization and finally it comes to Connected case, when authorization is done.
My Question is : Can I detect when Facebook authentication in done and before authorization starts ? So that my debugger can catch the position before authorization takes place. I have to actually avoid the authorization.
Actually oAuth is two steps authorization you cannot stop it at authentication.
You can do a trick, Usually people are at already login to facebook therefore you can try getLoginStatus() on first load which will sure surely return you not_authorized as it has not yet authorize your app, You can perform your check their and then get user authorize.
FB.getLoginStatus(function(response) {
if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
EDIT: is this what you what? Facebook account delink or deauthorize facebook app and check status of linking from facebook app
Otherwise
Firstly Facebook login and app auth are inseparable for security reasons. Being logged into Facebook and being logged into Facebook through an app are different. To login using Facebook from an external site you are actually logging in through an app that requires the user to allow the app to access certain parts of their profile.
So when a user clicks login. First they will be asked to login to Facebook if they are not already. You can check this before login using FB.getLoginStatus https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
Once the user is logged into Facebook they will have to authenticate your app for you to gain access to their info. This info is also available using FB.getLoginStatus
What you need tough is an accessToken to make calls to the api with. The fb js sdk stores this internally when you run the login dialog. So if you don't login using it. The api calls will fail unless you build them yourself.
Based on the information give, I am assuming you want to avoid showing the logging / auth dialog every time a previously logged in user visits the page. This is the only situation I can think of that you might what to avoid showing the dialogs.
In this case you can use cookies and access tokens to keep a logged in state across page visit.
Use a cookie to store the accessToken locally after the first login. Then code your login logic to check for and validate the token on load or login.
This way returning to the site wont launch the login / auth dialog unless the accessToekn session runs out, but will just change the user state to logged in. Then using your access token build your graph api calls.
I use https://graph.facebook.com/oauth/access_token_info with parameter client_id: APPID, access_token: token to validate the token.
If the token is valid The the session is good, the user is logged in and has authorized the app. If this fails, the cookie is deleted and i kick of the login dialog.
There are a few more cases where you should delete the cookie, like authResponseChange or log out.
On that note; I believe what you want for post authorization is to subscribe to the authResponseChange event https://developers.facebook.com/docs/facebook-login/login-flow-for-web/. Here is a gutted implementation:
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.authResponse) {
if (response.status === 'connected') {
// User logged in and User has authorized the app
}
else if (response.status === 'not_authorized') {
// User logged in but has not authorized app
}
else {
// User logged out
}
} else {
// No valid authResponse found, user logged out or should be logged out
}
});
There is more doco here https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/
And there are other events that you may be able to take advantage of
auth.login - fired when the auth status changes from unknown to connected
auth.authResponseChange - fired when the authResponse changes
auth.statusChange - fired when the status changes (see FB.getLoginStatus for additional information on what this means)
I haven't tried this for myself but a look through the FB.getLoginStatus page in the documentation suggests the following.
FB.getLoginStatus
FB.getLoginStatus allows you to determine if a user is logged in to
Facebook and has authenticated your app. There are three possible
states for a user:
the user is logged into Facebook and has authenticated your application (connected)
the user is logged into Facebook but has not authenticated your application (not_authorized)
the user is not logged into Facebook at this time and so we don't know if they've authenticated your application or not (unknown)
If I understand your question correctly, you may check the status for a case being not_authorized which will allow you to break out, in case the user is indeed logged in but has not authorized your application yet.
Make sure you place this case above the connected case though.
Also, this should work even though you're using FB.login instead of FB.getLoginStatus since according to the following quote from the same page,
The response object returned to all these events is the same as the
response from FB.getLoginStatus, FB.login or FB.logout. This response
object contains:
status The status of the User. One of connected, not_authorized or
unknown.
authResponse The authResponse object.
the returned object is the same.