Firebase - no displayName for user - firebase

I can add users in Firebase console -> Auth but I can't do anything more than setting an email and password for them.
Could I in some way set for them displayName?

I guess if you just want to update users profile:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
user.updateProfile({
displayName: "Random Name"
}).then(function() {
// Update successful.
}, function(error) {
// An error happened.
});
} else {
// No user is signed in.
}
});
Additionally: https://firebase.google.com/docs/auth/web/manage-users

When you create a user you create it only with email and password but you can and the displayName in the promise, then inside the .then() method you call the updateProfile method and you are ready, right down is the code:
onSubmit(formData) {
if(formData.valid) {
console.log(formData.value);
this.af.auth.createUserWithEmailAndPassword(
formData.value.email,
formData.value.password
).then(
(success) => {
console.log(success);
success.updateProfile({
displayName: "Example User",
photoURL: "https://example.com/jane-q-user/profile.jpg"
}).catch(
(err) => {
this.error = err;
});
this.router.navigate(['/login'])
}).catch(
(err) => {
this.error = err;
})
}
}
Note that in my example the displayName is set to "Example User", in the real app you just add the parameter as in my case it should be -> displayName:formData.value.name

Related

Firebase set method not adding data to an existing Collection

I am using VUEX and Firebase to create a register form with three fields NAME, EMAIL, PASSWORD. First i am using createUserWithEmailAndPassword method to add the user but I also want to ad the name filed data to an Existing Blank collection, here I am using set method. But it is not adding the name field data in the collection.
methods: {
onSignUp() {
firebase
.auth()
.createUserWithEmailAndPassword(this.email, this.password)
.then(user => {
console.log(user);
console.log(user.user.uid);
firebase.database.collection("profiles").doc(user.user.id).set({
name: this.name
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
this.$store.dispatch('signUserUp', user);
})
.catch(error => {
this.$store.dispatch('signUserError', error)
});
}
}
data(){
return {
name: "",
email: "",
password: "",
}
}
After submitting the form it's adding a new user and I can also see the uid in the console but some how its not updating the name field in the database.
You should use firebase.firestore() and not firebase.database (See this doc) and therefore adapt your code as follows:
onSignUp() {
firebase
.auth()
.createUserWithEmailAndPassword(this.email, this.password)
.then(user => {
console.log(user);
console.log(user.user.uid);
return firebase.firestore().collection("profiles").doc(user.user.id).set({
name: this.name
});
})
.then(() => {
console.log("Document successfully written!");
this.$store.dispatch('signUserUp', user);
})
.catch(error => {
this.$store.dispatch('signUserError', error)
});
}
}
You should also check that your security rules for the profiles collection are correctly set. Normally (authenticated) users should only be able to write a document with their own userid as document id.

Send email when user is created on firestore using Cloud Functions

I'm trying to send the email verification link after the user is created on my flutter app, but the email isn't sent and in my Cloud Functions Log I'm receiving the message when I deploy:
{"#type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{"code":9,"message":"FAILED_PRECONDITION"},"authenticationInfo":{"principalEmail":"*************"},"requestMetadata":{"callerIp":"186.216.140.62","callerSuppliedUserAgent":"FirebaseCLI/6.5.0,gzip(gfe),gzip(gfe)","requestAttributes":{"time":"2019-03-29T23:21:10.130Z","auth":{}},"destinationAttributes":{}},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.UpdateFunction","authorizationInfo":[{"permission":"cloudfunctions.functions.update","granted":true,"resourceAttributes":{}},{"resource":"projects/pppppp-9800a/locations/us-central1/functions/sendVerificationEmail","permission":"cloudfunctions.functions.update","granted":true,"resourceAttributes":{}}],"resourceName":"projects/pppppp-9800a/locations/us-central1/functions/sendVerificationEmail","request":{"#type":"type.googleapis.com/google.cloud.functions.v1.UpdateFunctionRequest","function":{"labels":{"deployment-tool":"cli-firebase"},"eventTrigger":{"eventType":"providers/cloud.firestore/eventTypes/document.create","resource":"projects/pppppp-9800a/databases/(default)/documents/users/{userId}","service":"firestore.googleapis.com"},"sourceUploadUrl":"https://storage.googleapis.com/gcf-upload-us-central1-dc1829cf-3a07-4951-be81-1a15f892ed8d/8ea3f162-c860-4846-9064-04a855efca2f.zip?GoogleAccessId=service-73683634264#gcf-admin-robot.iam.gserviceaccount.com&Expires=1553903464&Signature=******************","name":"projects/pppppp-9800a/locations/us-central1/functions/sendVerificationEmail"}}}
My code:
exports.sendVerificationEmail = functions.firestore.document('users/{userId}').onCreate((snap, context) => {
const user = snap.data();
console.log("----------------------");
console.log("user created: " + user.uidColumn);
admin.auth().generateEmailVerificationLink(user.email).then((link) => {
console.log("**********" + link);
sendVerificationEmail(user.emailColumn, link);
return 0;
}).catch(e => {
console.log(e);
})
return 0;
});
function sendVerificationEmail(email, link) {
var smtpConfig = {
host: 'smtp.gmail.com',
port: 465,
secure: true, // use SSL
auth: {
user: 'myappemail#gmail.com',
pass: 'password'
}
};
var transporter = nodemailer.createTransport(smtpConfig);
var mailOptions = {
from: "qeaapp#gmail.com", // sender address
to: email, // list of receivers
subject: "Email verification", // Subject line
text: "Email verification, press here to verify your email: " + link,
html: "<b>Hello there,<br> click here to verify</b>" // html body
};
transporter.sendMail(mailOptions, function (error, response) {
if (error) {
console.log(error);
} else {
console.log("Message sent: " + response.message);
}
return 0;
});
return 0;
}
When I the the command firebase deploy I get the message functions: failed to update function sendVerificationEmail
HTTP Error: 400, Change of function trigger type or event provider is not allowed
I'm new in JS and I don't know what these erros mean
Delete your first function called sendVerificationEmail, then redeploy. It looks like you maybe initially deployed it as something other than a Firestore trigger.

Link Multiple Auth Providers to an Account react-native

I'm new with react-native-firebase
I want to link the user after login with facebook provider and google provider
I tried all solutions on the internet but any of them worked.
this is my code
const loginUser = await firebase.auth().signInAndRetrieveDataWithEmailAndPassword('test#gmail.com','password888').then(async function(userRecord) {
console.log("Successfully sign in user:", userRecord.user._user);
let user = firebase.auth().currentUser;
console.log('current user ',user)
let linkAndRetrieveDataWithCredential=firebase.auth().currentUser.linkAndRetrieveDataWithCredential(firebase.auth.FacebookAuthProvider.PROVIDER_ID).then(async u=>{
console.log('linkAndRetrieveDataWithCredential u',u)
}).catch(async (e)=>{
console.log('linkAndRetrieveDataWithCredential error',e)
})
console.log('linkAndRetrieveDataWithCredential error',linkAndRetrieveDataWithCredential)
/**/
await firebase.auth().fetchSignInMethodsForEmail('sss#sss.sss')
.then(async providers => {
console.log('login index providers',providers)
}).catch(function(error){
console.log('login index providers error',error)
})
}).catch(async function(error){
console.log('login error',error,error.email)
if(error.code=='auth/user-not-found'){
}else if(error.code=='auth/wrong-password'){
errorMsg=`${L('password')} ${L('notValid')}`
}
if(errorMsg){
if (Platform.OS === 'android') {
ToastAndroid.show(
errorMsg,
ToastAndroid.LONG
)
} else {
Alert.alert(
'',
errorMsg,
[{ text: L('close'), style: 'cancel' }]
)
}
}
console.log("Error sign in user:", error.code);
})
linkAndRetrieveDataWithCredential needs an AuthCredential, in my app I use react-native-fbsdk to get the credential(You’ll need to follow their setup instructions).
This function will prompt the user to log into his facebook account and return an AccessToken, then you get the credential from firebase and finally linkAndRetrieveDataWithCredential.
linkToFacebook = () => {
LoginManager.logInWithReadPermissions(['public_profile', 'email'])
.then((result) => {
if (result.isCancelled) {
return Promise.reject(new Error('The user cancelled the request'))
}
// Retrieve the access token
return AccessToken.getCurrentAccessToken()
})
.then((data) => {
// Create a new Firebase credential with the token
const credential = firebase.auth.FacebookAuthProvider.credential(data.accessToken)
// Link using the credential
return firebase.auth().currentUser.linkAndRetrieveDataWithCredential(credential)
})
.catch((error) => {
const { code, message } = error
window.alert(message)
})
}

Prevent Firebase auth from remembering Google account?

So I'm using Firebase-UI to authenticate and sign in users, I need to use the account chooser in order for them to sign in to a different Google account (not using the account chooser results in it auto-signing them in), however, I want to either prevent it from displaying + saving accounts, or remove them on sign out.
And this is the Firebase-UI web I'm using: Firebase UI web
This isn't a huge issue when the application is running on a user's machine, however, it will also be running on a public machine with many users signing in an out, and we can't have them saved as an easy one-click sign in. The biggest security issue is the fact that I can also log into their emails once they've authenticated with Google. We want it to forget them once they sign out.
My sign-in flow:
<script type="text/javascript">
// FirebaseUI config.
var uiConfig = {
callbacks: {
signInSuccess: function (user, credential, redirectUrl) {
var userSignIn = {
displayName: user.displayName,
email: user.email,
emailVerified: user.emailVerified,
photoURL: user.photoURL,
uid: user.uid,
phoneNumber: user.phoneNumber
};
/* POST signed in user to Login Controller*/
var csrfToken = $('input[name="csrfToken"]').attr('value');
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Csrf-Token', csrfToken);
}
});
$.ajax({
url: '/signedIn',
type: 'POST',
data: JSON.stringify(userSignIn),
contentType: 'application/json',
error: function(err) {
console.log(err);
}
});
return true;
}
},
signInSuccessUrl: '/Dashboard',
signInOptions: [{
provider: firebase.auth.GoogleAuthProvider.PROVIDER_ID,
scopes: ['https://www.googleapis.com/auth/calendar']
}],
// Terms of service url.
tosUrl: '/Terms'
};
// Initialize the FirebaseUI Widget using FirestoreDB.
var ui = new firebaseui.auth.AuthUI(firebase.auth());
// The start method will wait until the DOM is loaded.
ui.start('#firebaseui-auth-container', uiConfig);
</script>
Sign-out flow:
initApp = function () {
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
// User is signed in.
if (window.location.pathname === "/Login" || window.location.pathname === "/") {
window.location.href = '/Dashboard';
}
$('#sign-out').show();
} else {
// User is signed out.
$('#sign-out').hide();
disableLinks();
switch(window.location.pathname){
case "/Login":
case "/Terms":
case "/Help":
break;
default:
window.location.href = '/Login';
}
}
}, function (error) {
console.log(error);
});
};
window.addEventListener('load', function () {
initApp();
document.getElementById('sign-out').addEventListener('click', function () {
firebase.auth().signOut().then(function() {
sessionStorage.clear();
localStorage.clear();
window.location = "/Logout";
}).catch(function(error) {
console.log(error);
});
});
});
On sign out from Firebase Auth, redirect to Google single sign out URL:
firebase.auth().signOut()
.then(function() {
window.location.assign('https://accounts.google.com/Logout');
})
.catch(function(error) {
console.log(error);
});

How do I update currentUser after Accounts.createUser() and Accounts.loginWithPassword()?

I am trying to create my own UI for signing up/logging in users:
'submit .signin': function(event){
var user = {'email':event.target.email.value, 'password' :event.target.password.value}
Accounts.createUser(user, function(err) {
if (err){
console.log(err);
} else
console.log('success!');
});
Meteor.loginWithPassword(user['email'], user['password'], function(error){
if(error){
console.log(error)
}
else{
console.log('success')
}
});
}
My question is once this code logs in the user, how do I set the currentUser the way loginButtons automatically does after you sign in. Thanks!
You don't have to call login after user is created.
To modify user data you can use http://docs.meteor.com/#/full/accounts_oncreateuser
See examples here: https://github.com/juliancwirko/meteor-s-id

Resources