How to extend the expirationTime in the Firestore response? Here using Firestore JavaScript SDK. And need to access accessToken too in React Native mobile development.
import firebase from 'firebase/app';
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
export const login = (email, password) => {
return async dispatch => {
try {
const response = await auth.signInWithEmailAndPassword(email, password);
//console.log(response);
dispatch(authenticate(response.user.uid, ""));
//console.log(response.user.stsTokenManager.expirationDate, " AAA");
const expirationDate = new Date(
new Date().getTime() + parseInt(response.user.stsTokenManager.expirationTime) * 1000
);
saveDataToStorage( response.user.uid, expirationDate);
} catch (error) {
throw new Error(error?.message || 'Authenticating user failed');
}
};
};
console.log(response) output
Object {
"user": Object {
"stsTokenManager": Object {
"accessToken": "",
"apiKey": "",
"expirationTime": 1597168005772,
"refreshToken": "",
},
"tenantId": null,
"uid": "",
},
}
You can't change the expiration time of the provided token. It will expire 1 hour after the last refresh. Then token will need to be refreshed again, and the new token will last another hour. There is no alternative to this - the refresh is required for security reasons.
The Firebase Auth SDK will automatically refresh the token for signed-in users. There is nothing you have to do to implement this. If you want to know when the token was refreshed, you should use onIdTokenChanged to set up a listener for that.
Related
Is it ok to set the value of a cookie to a token? I'm using js-cookie, Firebase auth/firestore and Next.js and I have my cookie set like this inside of my handleUser function:
const handleUser = async (rawUser) => {
if (rawUser) {
const user = await formatUser(rawUser)
const { token, ...userWithoutToken } = user
createUser(user.uid, userWithoutToken)
setUser(user)
cookie.set('colorizer-auth', token, {
expires: 1
})
setLoading(false)
return user
} else {
setUser(false)
cookie.remove('colorizer-auth')
setLoading(false)
return false
}
}
and the token is decoded and set here:
const formatUser = async (user) => {
const decodedToken = await user.getIdTokenResult(true);
const { token, expirationTime } = decodedToken;
return {
uid: user.uid,
email: user.email,
name: user.displayName,
provider: user.providerData[0].providerId,
photoUrl: user.photoURL,
token,
expirationTime,
}
}
I've seen some projects that use the Firebase Auth ID Token (access_token) itself in the cookies but that token is valid only for 1 hour. You'll have to securely store the refresh_token as well so you can refresh the cookie once it expires.
However, I would recommend using session cookies instead for such SSR application. You can set the expiration time ranging 5 minutes to 2 weeks. It might be best to reauthenticate user after this expires.
I'm new to react and firebase and was trying to create a firestore document only during the creation of user.
Its working fine on the local provider as there sign in and sign up are two different things but when it comes to google o Auth both the options use same function.
So how do i create my initial documnet during creation of user via google o Auth as it just resets my entire document when i log out and log in back.
googleAuth function
function googleAuth(provider) {
return firebase
.auth()
.signInWithPopup(provider)
.then(async function createUserDb(userCredentials) {
await setDoc(doc(db, "users", userCredentials.user.uid), {myList: []},{ merge: true })
})
}
sign up and sign in functions
function signUp(email, password) {
return auth.createUserWithEmailAndPassword(email, password).then(
async function createUserDb(userCredentials) {
console.log(userCredentials.user.uid);
await setDoc(doc(db, "users", userCredentials.user.uid), {myList: []})
})
}
function signIn(email, password) {
return auth.signInWithEmailAndPassword(email, password)
}
my firestore users collection when a new user is created (google auth user here)
it should save the data even after sign in (local auth user here)
after scraping through some posts found .additionalUserInfo.isNewUser method which checks if the user has created new account or is already a user which fixed my issue.
Thank you for any help that you guys provided.
function googleAuth(provider) {
return firebase
.auth()
.signInWithPopup(provider)
.then(async function createUserDb(userCredentials) {
if(userCredentials.additionalUserInfo.isNewUser) {
await setDoc(doc(db, "users", userCredentials.user.uid), {myList: []},{ merge: true })
}
})
}
I'm looking to make a NodeJS scraper that will automatically log in and POST some data but I'm struggling with getting the session to persist with the axios library (since request is now deprecated). I looking for user to get logged in and keep user logged in and whenever the script is run i don't want to signin again also let me fetch other api request without passing cookie everytime, Here is my code.
index.js
async function main() {
const account = {
email: prompt('Enter Truepush Email: '),
password: prompt('Enter Password: '),
}
console.log(`Processing account ${account.email}----------`);
await downloadStatsForAccount(account);
}
async function downloadStatsForAccount(account) {
if (!account.email || !account.password) throw new Error("Input cannot be empty");
let client = new ScrapeTruepush();
let loginResult = await client.getLoginResult(account);
console.log(loginResult)
}
apicalls:
const axios = require("axios");
const axiosCookieJarSupport = require('axios-cookiejar-support').default;
const tough = require('tough-cookie');
axiosCookieJarSupport(axios);
class ScrapeTruepush {
_api;
constructor() {
this._api = axios.create({
baseURL: 'https://app.truepush.com/',
withCredentials: true,
});
axiosCookieJarSupport(this._api);
this._api.defaults.jar = new tough.CookieJar();
}
async getLoginResult(account) {
if (!account) throw new Error("No account found");
return await this._api.post('api/v1/login', account).then((r) => r)
}
}
I want to login and save my cookies to avoid login again. error when trying to login:
data: {
status_code: 'XSRF-ERROR',
status: 'ERROR',
message: 'Cross domain requests are not accepting to this endpoint. If you cleared the cookies, please refresh your browser.'
}
I'm using NuxtJS's auth module and trying to get the Bearer token and a custom cookie that contains a sessionType on nuxtServerInit so I can update the store with a mutation, but it only works when I reload the page.
If I close the browser and go directly to my app url, I keep getting undefined for auth._token.local because nuxtServerInit executes before the cookies are ready.
My code in store/index.js looks like this:
export const actions = {
async nuxtServerInit({ commit, dispatch }, { req }) {
// Parse cookies with cookie-universal-nuxt
const token = this.$cookies.get('token')
const sessionType = this.$cookies.get('sessionType')
// Check if Cookie user and token exists to set them in 'auth'
if (token && user) {
commit('auth/SET_TOKEN', token)
commit('auth/SET_SESSION_TYPE', user)
}
}
}
I'm using nuxt-universal-cookies library.
What's the way to execute the action after the cookies are loaded on the browser?
Having it work with F5 and not by hitting enter makes me suspect that it just works sometimes and sometimes it doesn't, because F5 and Enter should trigger same behaviour on Nuxt (apart from some cache headers).
The only suspicious thing about you code is the usage of an async function when the function is not returning or awaiting any promise.
So you either await for an action
export const actions = {
async nuxtServerInit({ commit, dispatch }, { req }) {
// Parse cookies with cookie-universal-nuxt
const token = this.$cookies.get('token')
const sessionType = this.$cookies.get('sessionType')
// Check if Cookie user and token exists to set them in 'auth'
if (token && user) {
await dispatch('SET_SESSION', {token, user})
//commit('auth/SET_TOKEN', token)
//commit('auth/SET_SESSION_TYPE', user)
}
}
}
or you remove the async from the declaration
export const actions = {
nuxtServerInit({ commit, dispatch }, { req }) {
// Parse cookies with cookie-universal-nuxt
const token = this.$cookies.get('token')
const sessionType = this.$cookies.get('sessionType')
// Check if Cookie user and token exists to set them in 'auth'
if (token && user) {
commit('auth/SET_TOKEN', token)
commit('auth/SET_SESSION_TYPE', user)
}
}
}
I've had the same issue and found out that nuxtServerInit is triggered first before the cookie was set like via a express middleware.
I am new in using Firebase Cloud Functions and JavaScript and I was able to send notification to a single device using Firebase Cloud Functions(JavaScript). Now I am trying to send push notification to multiple device token and I think I have a problem on it.
I want to send the notification to these device tokens in my firebase database:
/receivers
/event1
/uid1: device_token1
/uid2: device_token2
/uid3: device_token3
/uid4: device_token4
This is my code so far but it doesn't work..
exports.sendSOSNotif = functions.database.ref('/SOSNotifs/{sosId}').onWrite((data, context) => {
const eventId=data.after.child("eventId").val();
const uid=data.after.child("uid").val();
const displayName=data.after.child("displayName").val();
const photoUrl=data.after.child("photoUrl").val();
const status=data.after.child("status").val();
console.log("eventId:", eventId);
console.log("displayName:", displayName);
console.log("uid", uid);
const payload = {
notification: {
title: "SOS Alert",
body: displayName + " sent an alert!",
sound: "default"
},
data: {
eventId: eventId,
displayName: displayName
}
};
return Promise.all([admin.database().ref("/receivers/event1").once('value')]).then(results => {
const tokens = results[0];
if (!tokens.hasChildren()) return null;
const tokensList = Object.keys(tokens.val());
return admin.messaging().sendToDevice(tokensList, payload);
});
});
First of all, you shouldn't be adding tokens like below, if that's how you've organised your DB. There might be multiple token for a single uid
/receivers
/event1
/uid1: device_token1
/uid2: device_token2
/uid3: device_token3
/uid4: device_token4
And for sending notifications to multiple UIDs, I've written a script here
Also, update your question about what exactly the problem you are facing.