Can't update email from Firebase (auth) - firebase

I got a Firebase auth you can login and logout.
But I want that the currentUser can change the email.
I have a password reset function that send a email with a link and you can reset your password but It didn't work with the email change.
This is the profile page
Here is the code
<template>
<div class="container">
<div class="card">
<div class="card-header">
<h1>Profile</h1>
</div>
<div v-if="!isHidden" class="alert alert-success" role="alert">
<strong>Email sended</strong>
</div>
<div class="card-body">
<form action="#" #submit.prevent="submit" #click="isHidden = !isHidden">
<div class="form-group row mb-0">
<div class="col-md-7 offset-sm-6 offset-md-7 offset-xl-9">
<input type="submit" class="btn btn-primary" #click="resetPassword" value="Reset your password">
</div>
</div>
</form>
<div class="">
<input type="email" class="form-control" v-model="email">
<input type="submit" class="btn btn-primary" #click="resetEmail" value="Reset your email">
</div>
</div>
</div>
</div>
</template>
<script>
import firebase from "firebase";
/* eslint-disable */
export default {
data() {
return {
email: "",
password: "",
isHidden: true
};
},
methods: {
login(e) {
firebase.auth().signInWithEmailAndPassword(this.email, this.password)
.then(user => {
alert('You are logged in as ' + this.email);
this.$router.push('/index');
location.reload();
},
err => {
alert(err.message);
})
e.preventDefault();
},
resetPassword() {
const auth = firebase.auth();
auth.sendPasswordResetEmail(auth.currentUser.email).then(() => {
console.log('Email send');
// Email sent.
}).catch((error) => {
// An error happened.
console.log(error);
});
},
resetEmail() {
const auth = firebase.auth();
auth.updateEmail(this.email).then(() => {
console.log('Email changed');
// Email sent.
}).catch((error) => {
// An error happened.
console.log(error);
});
}
}
};
</script>
When I run this I get this error:
Uncaught TypeError: auth.updateEmail is not a function
at VueComponent.resetEmail (Profile.vue?5a88:64)
at invoker (vue.runtime.esm.js?2b0e:2023)
at HTMLInputElement.fn._withTask.fn._withTask (vue.runtime.esm.js?2b0e:1822)
What do I do wrong because I read the Firebase doc and checkt on Google but I do something wrong.

The updateEmail() method is not a method of the "root" Firebase Auth service but a method of a User.
So you have to do something along the following lines:
const auth = firebase.auth();
auth.currentUser.updateEmail(this.email).then(() => {...});

Related

Unable to add profile info into firebase collection when signing up (vue | firebase)

I'm getting these two errors
TypeError: firebase__WEBPACK_IMPORTED_MODULE_2__.default.firestore(...).collections is not a function
Cannot read property 'user' of undefined
when trying to add user profile data into firebase collections 'profiles' when signing up. Please help.
This is the template section of my 'EditProfile' page.
<template>
<div class="edit-profile">
<section>
<div class="column">
<div class="header" style="font-weight:bold">
Profile Settings
</div>
<div>
<input
type="text"
class="form-control"
placeholder="Full name"
v-model="profile.name"
/>
<input
type="phone"
class="form-control"
placeholder="Phone"
v-model="profile.phone"
/>
<input
type="text"
class="form-control"
placeholder="Billing Address"
v-model="profile.address"
/>
<input
type="text"
class="form-control"
placeholder="Postcode"
v-model="profile.postcode"
/>
<button
#click="updateProfile"
>
Save changes
</button>
</div>
</div>
</section>
</div>
</template>
Here is my script for the above EditProfile page.I haven't really added the code for edit profile bcuz I'm still unaware on how to do that
<script>
import firebase from "firebase";
require("firebase/auth");
export default {
name: "EditProfile",
data() {
return {
profile: {
fullName: null,
phone: null,
address: null,
postcode: null,
},
};
},
methods: {
updateProfile() {},
},
};
</script>
Here is the template for 'RegisterCustomer' page. Here I will be signing up new users.
<template>
<div class="row">
<transition type="text/x-template" id="register-customer">
<div class="modal-mask">
<div class="modal-wrapper">
<div>
<div class="modal-body">
<slot name="body">
<div class="row">
<div class="col-sm-4 off-set">
<form>
<div #click="$emit('close')">
<span class="close">✖</span>
</div>
<h3>Sign up</h3>
<br />
<div class="form-group">
<input
type="text"
class="form-control"
placeholder="fullName"
v-model="fullName"
/>
</div>
<div class="form-group">
<input
type="email"
class="form-control"
placeholder="Email"
v-model="email"
/>
</div>
<div class="form-group">
<input
type="password"
class="form-control"
placeholder="Password"
v-model="password"
#keyup.enter="
onSubmit();
$emit('close');
"
/>
</div>
<div class="modal-footer">
<slot name="footer">
<button
class="btn btn-primary"
type="button"
#click.prevent="onSubmit"
#click="$emit('close')"
>
Sign up
</button>
</slot>
</div>
</form>
</div>
</div>
</slot>
</div>
</div>
</div>
</div></transition
>
</div>
</template>
This is my sign up code in my RegisterCustomer page. I want to add user info into my profiles collection. For now I want to pass the fullName data into my profiles collection.
<script>
import firebase from "firebase";
import "firebase/auth";
export default {
name: "RegisterCustomer",
data: () => ({
fullName: "",
email: "",
password: "",
}),
methods: {
async onSubmit() {
try {
var { user } = await firebase
.auth()
.createUserWithEmailAndPassword(this.email, this.password)
.then(() => {
firebase
.firestore()
.collection("profiles")
.doc(user.uid)
.update({
fullName: this.fullName,
});
console.log("Document successfully written.");
})
.then(() => {
alert("Registration successful.");
console.log(user.uid);
})
.catch((error) => {
console.log(error.message);
});
// this.$router.push("/customer");
} catch (error) {
console.log("error occured", error.message);
alert(error.message);
}
},
},
};
</script>
You need to import the Firebase services you are importing along with the core Firebase App as shown:
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
If you don't import Firestore that way, it'll result in similar issue. Although it was a typo in your case, it's "collection".
The second error Cannot read property 'user' of undefined, is probably because you are trying to get user property from a Promise. Try refactoring your code like this:
async onSubmit() {
try {
const { user } = await firebase.auth().createUserWithEmailAndPassword(this.email, this.password)
await firebase.firestore().collection("profiles")
.doc(user.uid)
.update({
fullName: this.fullName,
});
console.log("Document successfully written.");
alert("Registration successful.");
console.log(user.uid);
} catch (error) {
console.log("error occured", error.message);
alert(error.message);
}
},
I figured out the answer. All I had to do was change .update() to .set() when creating the profiles collection in RegisterCustomer.
Here is the script for RegisterCustomer. Hope someone finds this useful.
<script>
import firebase from "firebase";
import "firebase/auth";
import "firebase/firestore";
export default {
name: "RegisterCustomer",
data: () => ({
fullName: null,
email: null,
password: null,
address: null,
postcode: null,
}),
methods: {
async onSubmit() {
try {
firebase
.auth()
.createUserWithEmailAndPassword(this.email, this.password)
.then((cred) => {
return firebase
.firestore()
.collection("profiles")
.doc(cred.user.uid)
.set({
email: this.email,
fullName: this.fullName,
address: this.address,
postcode: this.postcode,
})
.then(() => {
console.log("Document successfully written.");
});
})
.then(() => {
alert("Registration successful.");
})
.catch((error) => {
console.log(error.message);
});
this.$router.push("/customer");
} catch (error) {
console.log("Error", error.message);
alert(error.message);
}
},
},
};
</script>

The email address is badly formatted firebase vue.js

Getting an error "The email address is badly formatted." when trying to use Vue.js with firebase to create a login page.
Here's my code:
<template>
<div class = "sign-up">
<p> Let's create a new account</p>
<input type="email" v-model="email" placeholder="Email"> <br>
<input type="password" v-model="password" placeholder="Password"> <br>
<button v-on:click="signUp">Sign Up</button>
<br>
</div>
</template>
<script>
import firebase from 'firebase'
export default {
name:'Signup',
data: function() {
return {
email: '',
password: '',
}
},
methods: {
signUp: function() {
firebase.auth().createUserWithEmailAndPassword(this.email, this.password).then(
function (user) {
alert('Your account has been created')
},
function(error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
}
}
}
</script>
I did make sure that I have enabled the authentication part at the firebase console .
Don't know why still get this error
Help please
Thank God I solved it.
The problem is solved by adding
firebase.initializeApp(config);
right after
import firebase from 'firebase'
since I have already initialize Firebase in other files
the problem might be caused by javascript loading asynchronously .
This works well. I tired to solve your ones. I have brought official firebase auth sample. Your user was not defined and while importing you must have use {} to prevent .auth() error.
<template>
<div class = "sign-up">
<p> Let's create a new account</p>
<input type="email" v-model="email" placeholder="Email">
<input type="password" v-model="password" placeholder="Password">
<button v-on:click="signUp">Sign Up</button>
</div>
</template>
<script>
import {fb} from '../firebase';
export default {
name:'Signup',
data() {
return {
email: "",
password: "",
}
},
methods: {
signUp: function() {
fb.auth().createUserWithEmailAndPassword(this.email, this.password)
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
}
}
}
</script>

How to upload image in angular2? in post method

html
<div class="form-group ">
<input type="file" [(ngModel)]="model.files" name="files" #files="ngModel" class="form-control" id="files" multiple="">
</div>
<div class="form-group ">
<label for="productname">Name</label>
<input type="text" class="form-control" id="productname" required minlength="5" pattern="^[a-zA-Z0-9/,-. ]*$" maxlength="30" [(ngModel)]="model.productname" name="productname" #productname="ngModel">
</div>
<div class="form-group ">
<label for="sales">Sales price/rate</label>
<input type="text" class="form-control" id="sales" pattern="[0-9]+" required minlength="0" maxlength="10" [(ngModel)]="model.sales" name="sales" #sales="ngModel">
</div>
<button type="submit" class="btn btn-success " (click)="save(productname,sales,files);onChangeroot(root)">Submit</button>
component.ts
export class NewProductComponent {
productservice:ProductsService
selectedFile = null;
onfileSelected(event){
console.log(event);
this.selectedFile =<File>event.target.files[0];
}
save1(productname,sales,files)
{
let obj = {
'pro_name':productname.value,
'sales':sales.value,
'image':files.value
}
var json = JSON.stringify(obj)
console.log(json)
const fd = new FormData();
fd.append('image', this.selectedFile , this.selectedFile.name );
this.http.post('http://127.0.0.1:8000/product/images/',fd)
this.service.save_user1(json).subscribe(response => console.log('Inserted Successfully'),
error => console.log(error));
}
}
service.ts
export class ProductsService {
save_user1(exp_data:any): Observable<any[]>{
console.log("console",exp_data)
let headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers });
console.log("options",options)
return this.http.post("http://127.0.0.1:8000/product/", exp_data, options)
.map(response => response.json())
.catch(error => Observable.throw(error.statusText));
};
}
After selecting image in console event is working while submitting the form except that image all other data are so successfully stored in database.
I am tried in this way but not able to post image,.so please help me how to do that ?
I think your service method need to be change. Usually we have to send file as multipart form data. My working copy is :
let formData: FormData = new FormData();
formData.append('file', this.imageFile);
this.http.post(this.url , formData) .subscribe(
(result) => {
console.log(result);
},
(error) => {
console.error(error);
}
);

Vue.js with Firebase email must be valid string

I'm following a tutorial of Vue.js with Firebase.
I'm novice to this and trying to make user account to firebase with Vue.js and I'm getting this error.
Uncaught O {code: "auth/argument-error", message: "createUserWithEmailAndPassword failed: First argument "email" must be a valid string."}
I've already enabled sign-in-method in firebase. Here is my code.
<template>
<div class="signup">
<p>Let's create a new account</p>
<input type="text" v-model="email" placeholder="Email" /><br/>
<input type="password" v-model="password" placeholder="Password" /><br/>
<button v-on:click="signUp">Sign up</button>
<span>or go back to <router-link to="/login">login</router-link>.</span>
</div>
</template>
<script>
import firebase from 'firebase'
export default {
name: 'signup',
data () {
return {
email: '',
password: ''
}
},
methods: {
signUp: () => {
firebase.auth().createUserWithEmailAndPassword(this.email, this.password).then(
(user) => {
alert('Your account has been created!')
},
(err) => {
alert('Opps!' + err.message)
}
);
}
}
}
</script>
When I console.log the email and password in signUp method, I found both the email and password are undefined.
The Problem was arrow functions. Changed ()=> {} to function() {} and now it works. Thanks to #EricGuan's comment.

why i get a "?" in my angular2 url when i use a http post rest api

hello i'm new in Angular , i'm trying to send to my backend(Symfony2.8) a Subject , Email and Message . when i route the the localhost:4200/contact , i get no error , no excption and the nothing happend , the URL becomes localhost:4200/contact? . here is my component,service and html file: (BTW i used this method to add and object to the database and it works normally)
export class ContactComponent {
contactForm: any;
constructor(private formBuilder: FormBuilder, public router: Router ,private cService: ContactService) {
this.contactForm = this.formBuilder.group({
'subject': ['', Validators.required],
'email' : ['', Validators.required],
'msg': ['', Validators.required],
});
}
sendMessage()
{
// console.log(this.contactForm.value.subject,this.contactForm.value.email,this.contactForm.value.msg);
this.cService.sendMsg(this.contactForm.value.subject,this.contactForm.value.email,
this.contactForm.value.msg)
.subscribe(
response => {
alert("Thanks for contacting us");
},
error => {
alert(error);
}
);
export class ContactService {
url:string = '/web/contactus';
constructor (private http: Http) {
}
sendMsg(subject: string,email: string, msg: string): Observable<any> {
let body = JSON.stringify({
subject,
email,
msg
} || null);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
console.log(body);
return this.http.post(this.url, body, options)
.map(res => res.json().data)
.do(data => console.log(JSON.parse(JSON.stringify(data || null ))))
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || { };
}
<form [formGroup]="contactForm" (submit)="sendMessage()">
<div class="form-group">
<label >Subject</label>
<input class="form-control" formControlName="subject" placeholder="Subject"/>
<span *ngIf="!contactForm.controls.subject.valid">required</span>
</div><!-- /.form-group -->
<div class="form-group">
<label>E-mail</label>
<input class="form-control" formControlName="email" placeholder="Email"/>
<span *ngIf="!contactForm.controls.email.valid">required</span>
</div><!-- /.form-group -->
<div class="form-group">
<label >Message</label>
<textarea class="form-control" formControlName="msg" rows="6"></textarea>
<span *ngIf="!contactForm.controls.msg.valid">required</span>
</div><!-- /.form-group -->
<button class="btn btn-primary pull-right" type="submit" [disabled]="!contactForm.valid">Post Message</button>
</form>
Looks like it is throwing some exception. In console click on the preserve log and then try the same. You may see some exceptions

Resources