How to link auth providers with native plugins? - javascript

I'm facing a firebase error auth/account-exists-with-different-credential when I'm trying to sign in an already existing account(with different auth provider) with facebook. I know this question has been asked many times like here and here but all solutions works for web and I'm stuck with native plugins. I'm using Google Plus and Facebook Connect plugins to sign in on native platforms.
Code:
async continueWithGoogle() {
try {
const googleResponse = await this.googlePlus.login({ webClientId: environment.firebaseConfig.webClientId })
const googleCredential = firebase.default.auth.GoogleAuthProvider.credential(googleResponse.idToken);
const firebaseResponse = await firebase.default.auth().signInWithCredential(googleCredential);
return firebaseResponse;
} catch (error) {
console.log('continue with google: ', error);
}
}
async continueWithFacebook() {
try {
const fbResponse = await this.facebook.login(['email']);
const fbCredential = firebase.default.auth.FacebookAuthProvider.credential(fbResponse.authResponse.accessToken);
const firebaseResponse = await firebase.default.auth().signInWithCredential(fbCredential);
return firebaseResponse;
} catch (error) {
if (error.code === 'auth/account-exists-with-different-credential') {
// What should I do here?
}
console.log('continue with fb: ', error);
}
}
Can I solve this error without using any web method like signInWithRedirect() or signInWithPopup()?

Related

AsyncStorage for react native expo with firebase

Everytime when I run the app, I get a warning about the AsyncStorage. But the warning previously was just saying install something else to replace it and thats all. But now the warning is saying it will be removed in future released. So I had no choice to install it by following: https://react-native-async-storage.github.io/async-storage/docs/install
Installing : npm install #react-native-async-storage/async-storage
According to the usage from the link above, AsyncStorage is now added after await
Example from the usage:
const storeData = async (value) => {
try {
await AsyncStorage.setItem('#storage_Key', value)
} catch (e) {
// saving error
}
}
Which I tried to add to the await codes I have for my authentication with firebase.
Original Login:
const handleLogin = async () => {
try {
if (email && password) {
const { user } = await signInWithEmailAndPassword(auth, email, password)
console.log('Logged in as :' , user.email);
}
} catch (error) {
console.log({error});
setShowError(true);
}
}
Edited login for the await line and also importing:
import AsyncStorage from '#react-native-async-storage/async-storage';
const { user } = await AsyncStorage.signInWithEmailAndPassword(auth, email, password)
After editing, my login did not work anymore. I get the error of {"error": [TypeError: _asyncStorage.default.signInWithEmailAndPassword is not a function. (In '_asyncStorage.default.signInWithEmailAndPassword(_firebase.auth, email, password)', '_asyncStorage.default.signInWithEmailAndPassword' is undefined)]} How do I do to correct this? As I have 2 more function that uses await
Under my register screen, i also have the line that uses await:
const handleSignUp = async () => {
try {
if (email && password) {
setShowError(false);
const { user } = await createUserWithEmailAndPassword(auth, email, password)
console.log('Registered as :' , user.email);
try{
await signOut(auth)
console.log("Signed out successfully")
navigation.replace("Login")
}catch (error) {
console.log({error});
}
}
} catch (error) {
console.log({error});
setShowError(true);
}
}
Under my app.js, i also has that line for logout:
const handleSignOut = async () => {
try {
await signOut(auth);
console.log("Signed out successfully");
RootNavigation.navigate('Login');
} catch (error) {
console.log({ error });
}
}
My bad on not linking it to firebase. This is indeed firebase code that is run with expo. I am using firebase authentication with expo thus having this issue. Is there anyway to implement this AsyncStorage with firebase? Or do I not have to worry about this even though the old version is going to be removed?

Firestore offline cache data not fully synced to cloud

I'm doing around 100 writes to Firestore offline. But after connecting to the internet I see some of my data is missing in the cloud. There are no errors in the writing process though.
If I do the same thing online, all the data is synced to the cloud.
Below is the code I'm trying in offline mode. Each function has around 10 iterates. There are 10 functions running one after the other.
const updateCities = async (cities) => {
for (const city of cities) {
try {
const firebaseCity = await firestore().collection('cities').doc(city.id).get();
await firebaseCity.update(city);
} catch (error) {
console.log(error);
}
}
}
const updateUsers = async (users) => {
for (const user of users) {
try {
const firebaseUser = await firestore().collection('users').doc(user.id).get();
await firebaseUser.update(user);
} catch (error) {
console.log(error);
}
}
}
Are there any limitations in the firebase functionalities or I'm doing something wrong?

AppCheck tokens are not recognised only when using mobile

I'm developing a webapp authentication system using Firebase. When I login and use the webapp from my computer everything works fine but when I use it on mobile appcheck does not work anymore and it gives me the following error in the console:
https://content-firebaseappcheck.googleapis.com/v1/projects/nameoftheproject/apps/1:784721317237:web:5db5892bc06253ab6b173c:exchangeRecaptchaEnterpriseToken?key=myKey
Failed to load resource: the server responded with a status of 403 ()
This is the code I'm using to create initialise appCheck in my webapp:
const appCheck = initializeAppCheck(app, {
provider: new ReCaptchaEnterpriseProvider(config[process.env.REACT_APP_ENV]['recaptcha-key']),
isTokenAutoRefreshEnabled: true
});
export const getAppCheckToken = async () => {
let appCheckTokenResponse;
try {
appCheckTokenResponse = await getToken(appCheck, false);
} catch(err) {
console.log(err);
}
return appCheckTokenResponse.token;
}
So a typical use case for that function is this:
//This is the code from one of my functions, it's just an example to show you how I use appcheck tokens
if (querySnapshot.docs.length === 0) {
headerAPI.headers['X-Firebase-AppCheck'] = await getAppCheckToken();
await axios.post(signupAPI, {
email: email,
username: displayName
}, headerAPI);
await sendEmailVerification(auth.currentUser, {
url: config[process.env.REACT_APP_ENV]['url-used-to-send-mail-auth-signup'],
handleCodeInApp: true
})
props.cookieAlert('Info', 'Cookies', 'Informations here...');
} else {
window.location.href = '/dashboard/home';
}
Now, I can't understand why it doesn't work on mobile...I hope my code is clear enough to let you understand my troubles, thank you in advance.

Microsoft Graph API - Problem to access oneDrive in route '/me/drives'

I'm trying to use Microsoft Graph API to acess oneDrive folders and archives in node.js, the authentication goes fine, and returns the calendar as well, but i have used this:
var graph = require('#microsoft/microsoft-graph-client');
require('isomorphic-fetch');
module.exports = {
getUserDetails: async function(accessToken) {
const client = getAuthenticatedClient(accessToken);
const user = await client.api('/me').get();
return user;
},
// GetEventsSnippet
getEvents: async function(accessToken) {
const client = getAuthenticatedClient(accessToken);
const events = await client
.api('/me/events')
.select('subject,organizer,start,end')
.orderby('createdDateTime DESC')
.get();
return events;
},
getDrives: async function(accessToken) {
const client = getAuthenticatedClient(accessToken);
try{
const drive = await client
.api('/me/drive/root/children')
.get();
console.log(drive);
return drive;
} catch (e) {
console.log(e);
}
}
};
function getAuthenticatedClient(accessToken) {
// Initialize Graph client
const client = graph.Client.init({
// Use the provided access token to authenticate
// requests
authProvider: (done) => {
done(null, accessToken);
}
});
console.log(client);
return client;
}
And it don't return anything... But saying that im unauthenticated
I am following this documentation: https://learn.microsoft.com/en-us/onedrive/developer/rest-api/api/drive_list?view=odsp-graph-online
How can i make this work?

Bot Framework v4 - initiate chat with a user ( proactive messages )

I would like to start a conversation with a user without that he already chatted with the bot.
I'm proceeding bu getting the conversationId when user install the bot app as mentionned here
Here how I catch reference and serviceUrl by using processActivity event
Then I use continueConversation + reference
const {
BotFrameworkAdapter,
} = require('botbuilder');
const adapter = new BotFrameworkAdapter({
appId: "xxxx",
appPassword: "xxxxy"
})
module.exports = async function(context, req) {
console.log(adapter);
try {
adapter.processActivity(req, context.res, async (turnContext) => {
const reference = turnContext.activity.conversation.id
const serviceUrl = turnContext.activity.serviceUrl
await adapter.continueConversation(reference, async (turnContext) => {
try {
await turnContext.sendActivity("this is proacive message");
} catch (e) {
console.log(e)
}
});
});
} catch (e) {
console.log(e)
}
return;
};
I'm getting this error
Error: BotFrameworkAdapter.sendActivity(): missing serviceUrl.
I have checked the turnContext.activity values. I get :
{"type":"event","name":"continueConversation"}" all other values are undefined ( serviceUrl also )
I noticed that turnContext.activityinside adapter.processActivity is not the same as in adapter.continueConversation and have all the serviceUrl and conversationId
How can I edit this code example to be able to send proactive messages to users?
The const reference needs to be ConversationReference not just the Id if you are using it for BotFrameworkAdapter.continueConversation().
A ConversationReference can be retrieved by using:
const reference = TurnContext.getConversationReference(turnContext.activity);
https://learn.microsoft.com/en-us/javascript/api/botbuilder/botframeworkadapter?view=botbuilder-ts-latest#continueconversation-partial-conversationreference----context--turncontext-----promise-void--
https://learn.microsoft.com/en-us/javascript/api/botbuilder-core/turncontext?view=botbuilder-ts-latest#getconversationreference-partial-activity--

Categories