VueRouter throws an undefined error only on mobile when routing with $router.push({ ... }) - vue.js

I have a login that waits for user to be authenticated before routing. When the user is authenticated, I throw an event that is caught in the Login component and then I execute this code :
EventBus.$on('userConnected', (user) =>{
let routeName = isRoleGreaterOrEqual(user.role, 'superadmin') ? 'admin' : 'draw';
this.$router.push({"name" : routeName}).catch(e => {
console.log(e);
});
});
The console.log(e) here will show 'undefined' in chrome's console.
Here's how I throw the event after querying some stuff in firebase firestore:
usersCollection.where("email", "==", email).get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
let user = doc.data();
anotherCollection.doc(user.email).get().then((querySnapshot) => {
let someDatas = querySnapshot.data();
if (someDatas) {
commit(types.MUTATE_LOAD_MORE_DATA, someDatas);
}
commit(types.MUTATE_LOAD_USER, user);
EventBus.$emit('userConnected', user);
});
})
}).catch((e) => {
//handle error
});
The error is only thrown when I'm on mobile (chrome devtools mobile). The only thing I could find is that I can silence the error with the .catch, but I'm not satisfied with only silencing it, I'd like to know why it's thrown in the first place, especially since it's an 'undefined' error so it's really unclear to me.

Related

I keep getting Error: ResizeObserver loop limit exceeded in cypress

sorry I am new to cpyress
enter image description here
Cypress.on('uncaught:exception', (err, runnable) => {
return false;
}
I added this inside my code block
describe('TBoss Account Creation Credentials', () => {
Cypress.on('uncaught:exception', (err, runnable) => {
return false;
});
it('Identification Validation', () => {
cy.visit('our website')
cy.get('.mat-focus-indicator').click()
cy.wait(5000)
cy.origin('https://accounts.google.com/', () => {
cy.get('.Xb9hP').eq(0).type('1234')
cy.get('.VfPpkd-vQzf8d').eq(1).invoke('show').click()
cy.wait(5000)
cy.get('.whsOnd.zHQkBf').eq(0).type('1234', {force: true})
})
})
})
this is the code block, when I access to our website, it redirects me to google sign in page, I couldn't get() the google sign in input box for typing ID, so I used origin, and it works
however, after adding origin, it gives me that error.
on the google sign in page, I can successfully type the ID, and then it shows the password input form, thats where this error occurs
I want to get() the password input and type() the password and log in through google sign in form
please help me
The origin is sandboxed from the main page.
First thing to try is to move or copy the error catcher inside the cy.origion(). It may not work, there are some things that can't be run in there.
describe('TBoss Account Creation Credentials', () => {
it('Identification Validation', () => {
cy.visit('our website')
cy.get('.mat-focus-indicator').click()
cy.wait(5000)
cy.origin('https://accounts.google.com/', () => {
Cypress.on('uncaught:exception', (err, runnable) => {
return false;
});
cy.get('.Xb9hP').eq(0).type('1234')
cy.get('.VfPpkd-vQzf8d').eq(1).invoke('show').click()
cy.wait(5000)
cy.get('.whsOnd.zHQkBf').eq(0).type('1234', {force: true})
})
})
})

PWA fetch request in service worker sends "the site can't be reached" error on login with google the 2nd time

This error is really driving me crazy for the last 2 days. Please help.
So when I try to login with google the 1st time on my website, it doesn't cause any problem but when I try to do it the second time, with any account, it shows this error in the console:
The FetchEvent for "http://localhost:3000/auth/google/callback?code=4%2F0AX4somethingsomethingsomethingsomething&scope=profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile" resulted in a network error response: an object that was not a Response was passed to respondWith().
and the webpage shows this error:
This site can’t be reached The web page at http://localhost:3000/auth/google/callback?code=4%2F0AX4somethingsomethingsomethingsomething&scope=profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile might be temporarily down or it may have moved permanently to a new web address.
I am quite new to pwa and don't understand some of the code in the service worker file (I have copy pasted the 'fetch' part of the code from this webiste: blog.bitsrc.io) so that might be the reason I am not able to identify the error in the code. But you might identify it, this is my service worker code:
const staticCacheName = "site-static-v2";
const dynamicCacheName = "site-dynamic-v2";
const assets = ["/", "/stories", "/groups", "offline.html"];
// cache size limit function
const limitCacheSize = (name, size) => {
caches.open(name).then((cache) => {
cache.keys().then((keys) => {
if (keys.length > size) {
cache.delete(keys[0]).then(limitCacheSize(name, size));
}
});
});
};
// install event
self.addEventListener("install", (evt) => {
//console.log('service worker installed');
evt.waitUntil(
caches.open(staticCacheName).then((cache) => {
console.log("caching shell assets");
cache.addAll(assets);
})
);
});
// activate event
self.addEventListener("activate", (evt) => {
//console.log('service worker activated');
evt.waitUntil(
caches.keys().then((keys) => {
//console.log(keys);
return Promise.all(
keys
.filter((key) => key !== staticCacheName && key !== dynamicCacheName)
.map((key) => caches.delete(key))
);
})
);
});
// fetch events
self.addEventListener("fetch", function (event) {
event.respondWith(
fetch(event.request)
.catch(function () {
return caches.match(event.request);
})
.catch("offline.html")
);
});
This is my script in main.hbs (just like index.html).
if('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/serviceworker.js', { scope: '/' })
.then((reg) => console.log('Success: ', reg.scope))
.catch((err) => console.log('Failure: ', err));
})
}
I am making my website using express by the way.
I have tried pretty much every solution on stackoverflow but none seem to work.
Just for Information, I have also tried this for the 'fetch' part:
self.addEventListener('fetch', evt => {
evt.respondWith(
caches.match(evt.request).then(cacheRes => {
return cacheRes || fetch(evt.request).then(fetchRes => {
return caches.open(dynamicCacheName).then(cache => {
cache.put(evt.request.url, fetchRes.clone());
// check cached items size
limitCacheSize(dynamicCacheName, 15);
return fetchRes;
})
});
}).catch(() => {
return caches.match('offline.html');
})
);
}
);
(The above code also lets me login only once but doesn't let me logout unlike the previous code)
I have copy pasted almost every 'fetch' code on the internet but all of them have a problem with google auth (I am using passport for google auth).
This is my auth.js code:
const express = require("express");
const router = express.Router();
const passport = require("passport");
//Authenticate with google
//GET /auth/google
router.get("/google", passport.authenticate("google", { scope: ["profile"] }));
//Google auth callback
//GET /auth/google/callback
router.get(
"/google/callback",
passport.authenticate("google", { failureRedirect: "/" }),
function (req, res) {
// Successful authentication, redirect home.
res.redirect("/stories");
}
);
router.get("/logout", (req, res) => {
req.logout();
res.redirect("/");
});
module.exports = router;
You can also suggest a workaround with workbox

Error: An error occurred while trying to log in to Facebook expo-facebook android issue

I am trying to implement Facebook login in a simple expo app but on the android expo client, it is not working. Following version, I am using.
"expo-facebook": "~12.0.3",
Method code
const handleAuth = async () => {
try {
let options = null;
if (Platform.OS === "android") {
options = {appId: "xxxxxxxxxxxxxx"};
} else {
options = {
appId: "xxxxxxxxxxxxxx",
version: "v9.0",
appName: "xxxxxxxx",
};
}
let res = await Facebook.initializeAsync(options);
console.log("[init res]", res);
const {type, token, expirationDate, permissions, declinedPermissions} =
await Facebook.logInWithReadPermissionsAsync({
permissions: ["public_profile"],
});
console.log("[type]", type);
console.log("[token]", token);
if (type === "success") {
// SENDING THE TOKEN TO FIREBASE TO HANDLE AUTH
const credential = app.auth.FacebookAuthProvider.credential(token);
app
.auth()
.signInWithCredential(credential)
.then((user) => {
// All the details about user are in here returned from firebase
console.log("Logged in successfully", user);
dispatch(saveUser(user));
navigation.replace("App");
})
.catch((error) => {
console.log("Error occurred ", error);
});
} else {
// type === 'cancel'
}
} catch (res) {
console.log("[res]", res);
// alert(`Facebook Login Error: ${res}`);
}
};
Another error i am facing is FacebookAuthProvider is not available in firebase
firebase": "8.10.0"
I have tried the following ways.
app.auth.FacebookAuthProvider
Or
app.auth().FacebookAuthProvider
but both are not working.
Please help if anyone integrated facbook login in. "expo": "~44.0.0"

Nuxt apollo authentication

I try to build an an authentication with nuxt and apollo.
The login and signup is pretty easy, also to set up the jwt token, but when my token expire and I try to get a refresh token or to logout my user I getting following error.
Invariant Violation
Store reset while query was in flight (not completed in link chain)
Because my Error handler which I define in my nuxt.config.js do not work I try to build my own client.
So I set at apollo.clientConfigs.default my ~/graphql/config.ts which looks like
export default ({ app }: Context) => {
const errorLink = onError(({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
graphQLErrors.map(async (err) => {
if (err?.extensions?.exception.status === 401) {
await app.$apolloHelpers.onLogout()
}
return err
})
return forward(operation)
}
if (networkError) {
console.log(networkError, 'and another one!')
return forward(operation)
}
return forward(operation)
})
return {
httpEndpoint: 'http://localhost:3001/graphql',
link: from([errorLink as any])
}
}

How to store facebook token in AsyncStorage React Native(Expo)

I am using Expo to Login User with Facebook, I am receiving token with Graph Api but when I try to add the token in Async Storage it is not working.
Please see the code below:
async logIn() {
try {
const {
type,
token,
} = await Facebook.logInWithReadPermissionsAsync('<APP_ID>', {
permissions: ['public_profile'],
});
if (type === 'success') {
// Get the user's name using Facebook's Graph API
fetch(`https://graph.facebook.com/me?access_token=${token}`)
.then((res) => res.json())
.then((tokenKey) => AsyncStorage.setItem('userToken',tokenKey))
.then(() => this.props.navigation.navigate('App'))
} else {
// type === 'cancel'
}
} catch ({ message }) {
alert(`Facebook Login Error: ${message}`);
}
}
I am receiving the token when I console it
fetch(`https://graph.facebook.com/me?access_token=${token}`)
.then((res) => res.json())
.then((tokenKey) => console.log('userToken',tokenKey))
.then(() => this.props.navigation.navigate('App'))
Please help, I am new to react native and asynchronous programming in JavaScript. TIA :)
Try this if you want to get item from AsyncStorage
AsyncStorage.getItem('userToken', (error, result) => {
if (result) {
//result
}
else {
//error
}
});
Are you getting token from AsyncStorage with getItem?
AsyncStorage.getItem('userToken').then((token) => {
this.setState({hasToken: token !== null,localToken : token})
});
Sorry folks the problem was from my side, I was trying to store an object directly into Async Storage, whereas Async Storage only accepts values in String format. I used
.then((tokenKey) => AsyncStorage.setItem('userToken',JSON.stringify(tokenKey)))
and it fixed the problem,Thanks all for your help