Error: auth.sendSignInLinkToEmail is not a function - javascript

const firebase = require("firebase-admin");
const auth=firebase.auth();
// create user in firebase data
var actionCodeSettings = {
// URL you want to redirect back to. The domain (www.example.com) for this
// URL must be in the authorized domains list in the Firebase Console.
url: 'https://www.example.com/finishSignUp?cartId=1234',
// This must be true.
handleCodeInApp: true,
dynamicLinkDomain: 'example.page.link'
};
// [END auth_email_link_actioncode_settings]
app.get("/firebase/api/createUser",function(req,resp){
auth.sendSignInLinkToEmail("sagar#gmail.com",actionCodeSettings)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
console.log("user created :"+user);
resp.send("--"+userCredential);
// ...
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
// ..
});
});
It gives me an error. the setting I already enable in firebase.
What is issue here?
This function was written in the firebase cloud function.

Sending emails and SMS messages to a user with Firebase Authentication is only possible with the client-side SDKs.
You're using the Admin SDK, which does not have this functionality, as it would be too prone to abuse.
So you will have to implement this functionality in the client-side application code, using the regular client-side/Web SDK for Firebase Authentication.

Related

Firebase Google Authentication Says: Access blocked: This app’s request is invalid

I have linked my domain in the firebase authentication, and I have allowed access for auth too.
If you would like to try it, here is the link
https://colesprojects.ml/signin/
signInWithPopup(auth, provider)
.then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
alert(user.displayName);
// ...
}).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
alert(errorMessage);
});
});
Here is my code if I am doing something wrong.
Looking at the error, it seems to me you didn't add your domain to your Authorized redirect URIs.
Go to the GCP console Credentials configuration, in the OAuth 2.0 Client IDs section select your app and add your redirect url to the Authorized redirect URIs section at the bottom (here your redirect URI would be https://colesprojects.ml/__/auth/handler as stated in the error).

Firebase Auth setCustomClaims() not working

I am facing a problem with setting custom claims for Firebase Authentication service's token. I am using Cloud function to set the custom claims for Hasura. The cloud function executes upon new user create event to set the custom claims. Here's my code running in cloud function
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.processSignup = functions.auth.user().onCreate(user => {
// create custom claims for hasura
const hasuraClaims = {
"x-hasura-default-role": "user",
"x-hasura-allowed-roles": ["user"],
"x-hasura-user-id": user.uid
}
// attach claims to user auth object
return admin.auth().setCustomUserClaims(user.uid, hasuraClaims)
.then(_ => {
functions.logger.info('SUCCESS: Custom claims attached');
})
.catch(err => {
console.log('ERROR: ', err);
})
})
In my frontend web page, I am running the following code to get the idToken
// subscribe to user state change
firebase.auth().onAuthStateChanged(async user => {
console.log('Firebase auth state changed');
if (user) {
// User is signed in.
window.User = user;
let idToken = await user.getIdTokenResult();
console.log('idToken: ', idToken);
}
})
I don't know what I'm doing wrong, but the token doesn't contain the custom claims that I've set in my Cloud function processSignup(). I know that the function executed without error because I can check my function logs and find the info entry SUCCESS: Custom claims attached.
Can anyone please help me solve this problem?
Updating claims does not trigger an onAuthStateChanged (the auth state of being logged in or not has not changed, but the users' claims have) and tokens are minted and then used for ~1h.
You are calling getIdTokenResult but not forcing a refresh, try:
let idToken = await user.getIdTokenResult(true);
which will force a new token to be fetched from the server and will (hopefully) include your custom claims.

Firebase google sign in pop up window flashes and never signing in using Vuejs?

I have used google sign in popup method in vuejs. In live google sign in pop up window flashes and never signed in. But everything works fine in local.
Here is firebase google sign in & sign up method code:
const database = firebase.initializeApp(config);
const firestore = database.firestore();
var provider = new firebase.auth.GoogleAuthProvider();
database.signIn = async (email, password) => {
try {
await firebase.auth().signInWithPopup(provider).then((result) => {
// This gives you a Google Access Token. You can use it to access Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
console.log("user",user.displayName);
console.log('result google',result.user);
// ...
store.commit("setCurrentUser", result.user);
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
return true;
} catch (error) {
return error;
}
}
Tried by changing chrome pop up, cookies setting nothing works. Any help much appreciated please...
If it's working locally, you should make sure your hosting domain is registered with Google OAuth.
In Firebase console:
Develop -> Authentication -> Sign-in method -> Authorized domains
And add your domain to the list. It may take some time to verify.
If that doesn't work, try logging error.message for more information.
After updating firebase it works fine. npm i firebase#latest..

How to remove captcha verification from Firebase phone auth using javascript?

I am using firebase phone auth for the very first time and I see captcha verification is must proceed with the process, as per firebase official documentation. Though it serves a good purpose, but sometimes it becomes very bad for the user experience when it starts asking about the road signs, bridges and all. Is there a way to directly skip to the verification code right after getting user's number? As per the documentation, the code is mentioned below. Thanks.
var phoneNumber = getPhoneNumberFromUserInput();
var appVerifier = window.recaptchaVerifier;
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function (confirmationResult) {
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
window.confirmationResult = confirmationResult;
}).catch(function (error) {
// Error; SMS not sent
// ...
});
var code = getCodeFromUserInput();
confirmationResult.confirm(code).then(function (result) {
// User signed in successfully.
var user = result.user;
// ...
}).catch(function (error) {
// User couldn't sign in (bad verification code?)
// ...
});
Go to Firebase console -->to your project-->project overview settings-->project settings --> App check -->overview (Register your app for SafetyNet).
Then your app will stop redirecting to web for captcha verification
method 1:
firebase.auth().settings.appVerificationDisabledForTesting = true;
Firebase docs
https://firebase.google.com/docs/auth/web/phone-auth?authuser=0#web-v8_6
// Turn off phone auth app verification.
firebase.auth().settings.appVerificationDisabledForTesting = true;
var phoneNumber = "+16505554567";
var testVerificationCode = "123456";
// This will render a fake reCAPTCHA as appVerificationDisabledForTesting is true.
// This will resolve after rendering without app verification.
var appVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
// signInWithPhoneNumber will call appVerifier.verify() which will resolve with a fake
// reCAPTCHA response.
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function (confirmationResult) {
// confirmationResult can resolve with the fictional testVerificationCode above.
return confirmationResult.confirm(testVerificationCode)
}).catch(function (error) {
// Error; SMS not sent
// ...
});
method 2:
https://firebase.google.com/docs/auth/web/phone-auth#use-invisible-recaptcha
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
'size': 'invisible',
'callback': (response) => {
// reCAPTCHA solved, allow signInWithPhoneNumber.
onSignInSubmit();
}
});
I had the same problem while integrating iOS SDK.
If google has same architecture and classes of the firebase SDK across languages, this solution might work for you.
Auth.auth().settings?.isAppVerificationDisabledForTesting = true
firebase.initializeApp(firebaseConfig);
// Create a Recaptcha verifier instance globally
// Calls submitPhoneNumberAuth() when the captcha is verified
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
"recaptcha-container",
{
size: "invisible",
callback: function(response) {
submitPhoneNumberAuth();
}
}
);
use size: "normal" to size: "invisible"
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
"recaptcha-container",
{
size: "invisible",
callback: function(response) {
submitPhoneNumberAuth();
}
}
);
Firebase provides two properties for captcha size
Normal - which is visible and captcha code visible to the user and manually perform the captcha process.
Invisible - which is invisible to the user, automated captcha process, and code will auto render in DOM.
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
"recaptcha-container", {
size: "invisible"
}
);
For more details, refer to this Official Link
Use isAppVerificationDisabledForTesting = TRUE in auth settings as the below given snippet:
Auth.auth().settings.isAppVerificationDisabledForTesting = TRUE
Please check the below official information for more details:
JavaScript - https://firebase.google.com/docs/reference/js/firebase.auth.AuthSettings
SDK reference - https://firebase.google.com/docs/auth/ios/phone-auth#integration-testing
Actually you can't. But, some of the devices it does not work. Instead, setup Safety and enable API key. Then back to your project setting in Firebase and copy and paste SHA-25 from Android Gradle to there if it does not exist. In this manner, in app browser redirecting will be no more irritating to you...
According To Google Official Docs 2 things are There :
Add Sha-256 Key to Firebase
Enable SafetyNet : https://console.cloud.google.com/apis/library/androidcheck.googleapis.com
To use phone number authentication, Firebase must be able to verify that phone number sign-in requests are coming from your app. There are two ways Firebase Authentication accomplishes this:
SafetyNet: If a user has a device with Google Play Services installed, and Firebase Authentication can verify the device as legitimate with Android SafetyNet, phone number sign-in can proceed.
To enable SafetyNet for use with Firebase Authentication:
In the Google Cloud Console, enable the Android DeviceCheck API for your project. The default Firebase API Key will be used, and needs to be allowed to access the DeviceCheck API.
If you haven't yet specified your app's SHA-256 fingerprint, do so from the Settings Page of the Firebase console. Refer to Authenticating Your Client for details on how to get your app's SHA-256 fingerprint.
For More Details : https://firebase.google.com/docs/auth/android/phone-auth

Firebase Auth check if new user on Facebook login

I am creating a web app using Firebase auth to authenticate my users and a MongoDB database to store some relevant user information specific to my site. I am trying to add Facebook as another means of authentication.
Logging in with Facebook is working, but what I want to do is intercept the user generation/authentication with Firebase to check if Firebase is creating a new user on a first-time Facebook login. This way if a new user is being created in Firebase I can also create a new user in my mongo database (essentially handling a signup). My facebook login function looks like this:
handleFacebookLogin() {
firebase.auth().signInWithPopup(provider).then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
// check if new user here
// handleNewFacebookUser()
this.props.update(user);
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
var email = error.email;
var credential = error.credential;
});
}
I couldn't find anything that allowed me to check if a new user was being generated in the Firebase docs. It seems to silently handle new Firebase auth user generation when logging in through Facebook for the first time. If there is no built-in way for Firebase to handle this I will just check if the user exists in my database, but I wanted to be sure there wasn't a simpler alternative.
You can detect if a user is new or existing as follows:
firebase.auth().signInWithPopup(provider)
.then(function(result) {
console.log(result.additionalUserInfo.isNewUser);
})
.catch(function(error) {
// Handle error.
});
For more on this refer to the documentation.

Categories

Resources