Firestore won't add signup email to new database collection - javascript

When signing up a user, I get no error what so ever, the signup works, but it doesn't create a new DB collection with the signup email.
Furthermore, redirecting the user to /account/dashboard.html doesn't work.
Any ideas? I am very new to all of this, only 4 days in so if you could please explain things a little simpler to me that would be very much appreciated.
// sign up the user
firebase.auth().createUserWithEmailAndPassword(email, password).then(cred => {
return db.collection('users').doc(cred.user.uid).set({
email: "signupForm['signupEmail'].value"
});
}).then(function() {
window.location.replace('/account/dashboard.html');
})
.catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log('Error code: ' + errorCode);
console.log('Error message: ' + errorMessage);
signupButton.style.display = 'flex';
signupError.innerText = errorMessage;
signupError.style.display = 'flex';
signupForm.reset();
});
})
// Trigger button click on enter
var input = document.getElementById("signupPasswordConfirm");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Trigger the button element with a click
document.getElementById("signupButton").click();
}
});
My HTML
<div class="form-content"><label for="signupPassword-2" id="signupError" class="error-message">Error message</label>
<div class="form-wrap extra-space"><input type="text" class="text-field w-input" maxlength="256" name="signupEmail" data-name="signupEmail" placeholder="E-mail" id="signupEmail"></div>
<div class="form-wrap extra-space"><input type="password" class="text-field w-input" maxlength="256" name="signupPassword" data-name="signupPassword" placeholder="Password" id="signupPassword"></div>
<div class="form-wrap extra-space"><input type="password" class="text-field w-input" maxlength="256" name="signupPasswordConfirm" data-name="signupPasswordConfirm" placeholder="Confirm your Password" id="signupPasswordConfirm"></div>
<div class="button-wrap"><a id="signupButton" href="#" class="button w-button">Signup</a>
<h5 class="h5 black centered">Already have an account?</h5>
</div>

Turns out I forgot to declare the DB variable. Also changed the output of email:
// sign up the user
const db = firebase.firestore();
firebase.auth().createUserWithEmailAndPassword(email, password).then(cred => {
return db.collection('users').doc(cred.user.uid).set({
email: signupForm['signupEmail'].value
});

Related

How to I fix an http error code 400? (firebase auth related)

I have a static website where I am trying to configure it to communicate with firebase particularly the authentication bit, but I have 2 errors displaying in the console Console network tab view console: network tab waterfall view
now what is happening exactly is that I made a single html page to handle authentication
this page is called (auth.html)
// Import the functions you need from the SDKs you need
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.8.4/firebase-app.js';
import { getAuth, onAuthStateChanged, signInWithEmailAndPassword, createUserWithEmailAndPassword, signInWithCustomToken, signOut } from "https://www.gstatic.com/firebasejs/9.8.4/firebase-auth.js";
// Your web app's Firebase configuration
// Initialize Firebase
const app = initializeApp({
apiKey: "API key",
authDomain: "firebaseapp.com",
databaseURL: "https://firebaseio.com",
projectId: "fireauth",
storageBucket: "appspot.com",
messagingSenderId: "162620739",
appId: "1:16262739:web:634d6f3357004eced9e"
});
// Above initialization details are incorrect deliberately (they aren't the issue/ focus now)
const auth = getAuth(app);
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
});
signInWithCustomToken()
.then((userCredential) => {
// Signed in
var user = userCredential.user;
// ...
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
// Detect auth state
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const uid = user.uid;
// ...
console.log("Logged in!");
alert("You are logged in!");
} else {
// User is signed out
// ...
console.log("Anonymous mode (signed out)");
}
});
signOut(auth).then(() => {
// Sign-out successful.
console.log("logged out")
}).catch((error) => {
// An error happened.
alert("Network error");
});
<body>
<!--- Login section --->
<div id="login-div" class="container">
<div class="div1">
<form class="login-form"><h1>Login to continue</h1>
<p>Avatar ID</p>
<input type="text" id="email" placeholder="Email" required>
<p>Secret Key</p>
<input type="password" id="password" placeholder="Password" required>
<button type="signInWithEmailAndPassword" disabled>Login</button><br><a onclick="thenewcallout3()" href="#">Reset my secret key</a>
</form>
</div>
</div>
<!--- register section --->
<div id="user-div" class="div2">
<form class="login-form">
<h2>Register to continue</h2><br>
<p>Enter your email address</p>
<input type="email" placeholder="Avatar ID" id="avatarId" required>
<p>Password</p>
<input type="text" placeholder="Secret key"><br><br>
<input type="password" placeholder="Repeat your secret key" id="secretKey" required><br><br>
<p id="up">I accept that my privacy & actions online are my responsibility not StarlinkBw</p><input type="checkbox" required>
<button type="createUserWithEmailAndPassword" disabled>Register</button>
</form></div>
<!---Account reset--->
<div class="fixAcc"><h1>Password reset</h1><input type="email" placeholder="Enter your Avatar ID"><br><br><button disabled>Request new key</button></div>
<!--- Portal --->
<nav class="menu">
<header>Starlink <span>[X]</span></header>
<ol>
<li class="menu-item">
Go back</li>
<!--- views registration form & hides login --->
<li class="menu-item"><a onclick="thenewcallout()" href="#" >Login</a></li>
<li class="menu-item"><a onclick="thenewcallout2()" href="#" >Register</a></li>
<ol class="sub-menu">
<li class="menu-item">
Social networking
</li>
<li class="menu-item">
Self care
</li>
<li class="menu-item">
Entertainment
</li>
<li class="menu-item">
Productivity
</ol>
<li class="menu-item">
Terms & Conditions
</li>
</ol>
</li>
<footer><button aria-label="Toggle Menu">Toggle</button></footer>
</nav>
<script src="../scripts/sl.js"></script>
<script src="../scripts/jl.js"></script>
<script type = 'text/javascript' src="../scripts/status-check.js"></script>
<!--- Firebase --->
<script src="../scripts/sync.js" type="module"></script>
</body>
which is linked to a JavaScript file called ./sync.js.
I managed to initialize firebase successfully (I think) and reports the current user (me in dev mode) is logged out in the console <Console user view> (which is great news) but I am having trouble sending the user data from the static auth.html page to firebase. what is the issue with my sync.js file?
to see the current perfomance of the website in real life, you can visit My website please note all auth triggering buttons are disabled in the actual website so that I can fix this error.
I managed to fix to the problem
thanks to the advice Bravo gave me
I removed a few declaration like signingInWithCustomToken & signout (I am going need signout later though)
signing in using custom token is a little more complicated since it uses the Admin SDK which I failed several times trying to implement it.
I added event listeners to import data from specific input elements fields (most likely which caused the 400 error due to value assignment mismatch)
which turned my auth.html & sync.js to look like the code snippets attached
although Auth works, the system faces issues like (network errors) when ad-blockers are running/ enabled
as for the console there is nothing to report there, it doesnt show any errors anymore
This is the end result after authenticating Auth result within client & firebase updated
// Import the functions you need from the SDKs you need
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.8.4/firebase-app.js';
import { getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword, signOut } from "https://www.gstatic.com/firebasejs/9.8.4/firebase-auth.js";
// Your web app's Firebase configuration
// Initialize Firebase
const firebaseConfig = {
apiKey: "Your API key,
authDomain: "firebaseapp.com",
databaseURL: "firebaseio.com",
projectId: "your project",
storageBucket: "appspot.com",
messagingSenderId: "11739",
appId: "1:162621739:web:634d6f04eced9e"
};
// Again the above configurations are incorrect delibaratetly (but not the main focus)
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
submitData.addEventListener('click', (e) => {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
alert("Account creation success! Welcome " + email);
window.location.replace("https://google.com");
})
.catch((error) => {
const errorMessage = error.message;
// ..
alert(errorMessage);
});
});
submitLogin.addEventListener('click', (f) => {
var avatar = document.getElementById("avatar").value;
var secretKey = document.getElementById("secretKey").value;
signInWithEmailAndPassword(auth, avatar, secretKey)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
alert("You are logged in as: " + avatar);
window.location.replace("https://google.com");
})
.catch((error) => {
const errorCode = error.code;
alert(errorCode);
});
});
<!--- Login section --->
<div class="container">
<form class="login-form"><h1>Login to continue</h1>
<p>Avatar ID</p>
<!--- Avatar & secretKey fields here --->
<input type="text" id="avatar" placeholder="Email" autocomplete="email">
<p>Secret Key</p>
<input type="password" id="secretKey" placeholder="Password" autocomplete="current-password">
<button type="button" id="submitLogin" name="submitLogin">Login</button><br><a onclick="thenewcallout3()" href="#">Reset my secret key</a>
</div>
<!---Register section ---->
<div class="div2">
<div class="login-form">
<h2>Register to continue</h2><br>
<p>Enter your email address</p>
<!----Email & password registration fields here ---->
<input type="email" placeholder="Avatar ID" id="email" autocomplete="email">
<p>Password</p>
<input type="password" placeholder="Secret key"><br><br>
<input type="password" placeholder="Repeat your secret key" id="password" autocomplete="new-password"><br><br>
<p id="up">I accept that my privacy & actions online are my responsibility not StarlinkBw</p><input type="checkbox">
<button id="submitData" name="submitData">Register</button></div>
</div>
Account reset section
<section>
<div class="fixAcc">
<h1>Password reset</h1>
<input placeholder="Enter your Avatar ID" autocomplete="email" id="email-P-Reset"><br>
<br>
<button>Request new key</button>
</div>
</section></form>
I see..., I Had the same problem Today and I realized that the configurations in my code was okay, what I need to do is go to my firebase console on project shortcuts and click on authentication -> go to sign-in Method and on the provider, make sure the email/password provider is enabled, if it's not added click on add provider and select email/password and then enable it

Can't figure out how to make a function for creating new users into the database

I am new to working with databases. I've been trying to create a login/register webpage using only HTML, Js and MongoDB in my codes in order to practice. I have successfully made a function for login, yet I've been struggling to create a function for registering using the Fetch API.
I am aware that my register code is used rather for a login function, but I used it as a template for the sign up one.
I'd appreciate it if anyone can help me fix the register function using Fetch() in order to not give me 401 and to be able to add the new user's email and password to my database. Thank you.
const btnAccount = document.querySelector('.account .submit')
btnAccount.addEventListener('click', event => {
event.preventDefault()
const email = emailAccount.value
const pass = passAccount.value
const pass2 = pass2Account.value
if (email && pass && pass2) {
if (pass === pass2) {
// The data i wish to add to my mongoDB users database:
const account = {
strategy: "local",
email : emailAccount.value,
password: passAccount.value
}
fetch('http://localhost:3030/authentication', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(account)
}).then(response => {
return response.json()
}).then(result => {
console.log(result)
document.forms[1].reset();
})
.catch(err => {
// If I got some errors regardings the DB or in the code itself:
console.log('eroare:', err)
alert(`Something's wrong. I can feel it!`)
})
}
else {
// Passwords not the same:
alert('Parolele nu coincid!')
}
}
else {
// Not all fields written:
alert('Completeaza bah campurile...')
}
})
<main>
<form class="account">
<div>
<label for="email">Email:</label>
<input required type="email">
</div>
<div>
<label for="password">Password:</label>
<input required type="password" class="password">
</div>
<div>
<label for="password2">Verify Password:</label>
<input type="password" class="password2">
</div>
<div>
<button class="submit">Create new account</button>
</div>
<div>
I already have an account
</div>
</form>
<button class="fetchItems">Load ITEMS</button>
<div class="output"></div>
</main>

Local storage is missing an ID Token, Please authenticate

Getting Local storage is missing an ID Token, Please authenticate. My end goal is to get the user signed up through AWS Cognito and then add a row in my DynamoDB table. I am able to get the user in the user pool but not able to add the details to DynamoDB. Unable to figure out the error any help will be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Javascript SDK-->
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.410.0.min.js"></script>
<script src="https://rawgit.com/aws/amazon-cognito-identity-js/master/dist/aws-cognito-sdk.min.js"></script>
<script src="https://rawgit.com/aws/amazon-cognito-identity-js/master/dist/amazon-cognito-identity.min.js"></script>
</head>
<body>
<fieldset >
<h1 class="h3 mb-3 font-weight-normal" id="titleheader">Register an Account</h1>
<form>
<input type="email" class="form-control" id="emailInputRegister" placeholder="Email" pattern=".*" required><br><br>
<input type="password" class="form-control" id="passwordInputRegister" placeholder="Password" pattern=".*" required><br><br>
<input type="personalname" class="form-control" id="personalnameRegister" placeholder="First Name" pattern=".*" required><br><br>
<input type="personalname2" class="form-control" id="personalnameRegister2" placeholder="Last Name" pattern=".*" required><br><br>
<input type="text" class="form-control" id="organizationRegister" placeholder="Organization" pattern=".*" required><br><br>
<input type="text" class="form-control" id="jobTitleRegister" placeholder="JobTitle" pattern=".*" required><br><br>
<input type="tel" class="form-control" id="phone" placeholder="Cell Phone Number" pattern=".*" required><br><br>
<button id="mainbutton" class="btn btn-lg btn-primary btn-block" type="button" onclick="registerButton()" >Sign Up</button>
</form>
</fieldset >
<script>
var username;
var password;
var firstname;
var lastname;
var jobtitle;
var organization;
var phonenumber;
var poolData;
function registerButton() {
username = document.getElementById("emailInputRegister").value;
password = document.getElementById("passwordInputRegister").value;
firstname = document.getElementById("personalnameRegister").value;
lastname = document.getElementById("personalnameRegister2").value;
organization = document.getElementById("organizationRegister").value;
jobtitle = document.getElementById("jobTitleRegister").value;
phonenumber = document.getElementById("phone").value;
poolData = {
UserPoolId :<userPoolId>,
'
ClientId : <client id>
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var attributeList = [];
var dataEmail = {
Name : 'email',
Value : username, //get from form field
};
var dataFirstName = {
Name : 'name',
Value : firstname, //get from form field
};
/*var dataLastName ={
Name : 'family name',
Value : lastname,
};
var dataPhoneNumber ={
Name : 'family name',
Value : lastname,
};*/
var attributeEmail = new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail);
var attributePersonalName = new AmazonCognitoIdentity.CognitoUserAttribute(dataFirstName);
attributeList.push(attributeEmail);
attributeList.push(attributePersonalName);
var temp;
userPool.signUp(username, password, attributeList, null, function(err, result){
if (err) {
alert(err.message || JSON.stringify(err));
return;
}
cognitoUser = result.user;
console.log('user name is ' + cognitoUser.getUsername());
//var cognitoUser = userPool.getCurrentUser();
//console.log('cognitoUser =',cognitoUser);
//change elements of page
//document.getElementById("titleheader").innerHTML = "Check your email for a verification link";
//});
//var userPool1 = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data);
//console.log('userPool',userPool1);
//var cognitoUser = userPool1.getCurrentUser();
//console.log("temp is ", cognitoUser);
if (cognitoUser != null) {
cognitoUser.getSession(function(err, session) {
if (err) {
console.log(err);
return;
}
console.log('session validity: ' + session.isValid());
console.log('session token: ' + session.getIdToken().getJwtToken());
AWS.config.region = 'us-east-1';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId : <Identity_Pool>,
Logins : {
// Change the key below according to the specific region your user pool is in.
'cognito-idp.us-east-1.amazonaws.com/${Identity_Pool}' : session.getIdToken().getJwtToken()
}
});
AWS.config.credentials.get(function(err) {
if (!err) {
var id = AWS.config.credentials.identityId;
console.log('Cognito Identity ID '+ id);
// Instantiate aws sdk service objects now that the credentials have been updated
var docClient = new AWS.DynamoDB.DocumentClient({ region: AWS.config.region });
var params = {
TableName: 'TestTable',
Item:{emailId:username, }
};
docClient.put(params, function(err, data) {
if (err)
console.error(err);
else
console.log(data);
});
}
});
});
} else {
console.log(err);
return;
}
});
}
</script>
</body>
</html>
You can use an API for Dynamodb operations with docClient.put()

Required attribute is not working in registration form

I have a register form which works with Vue and local storage, when I submit the form blank or leave out an input the data is going to the local storage the same and not showing the HTML validation which is used by adding required attribute. Is there any way I can fix this problem by showing the HTML validation if the form has inputs which are empty or if the email do not have an at-sign inserted.
Form:
<form id="signup" method="post" v-on:submit.prevent>
<br>
<h1>Registration</h1>
<label for ="studentsorparents">Student or parents:</label>
<input type="text" id="studentsorparents" v-model="studentsorparents" required ="required">
<br><br>
<label for ="username">username:</label>
<input type="text" id="username" v-model="username" required ="required" v-text="null">
<br><br>
<label for="email">email: </label>
<input type="email" id="email" v-model='email' required ="required">
<br><br>
<label for="password">password: </label>
<input type="password" id="password" v-model='password' required ="required">
<br><br>
<button v-on:click='onSubmit' onclick="passuseremail()" >Register</button>
</form>
JS:
var signupApp = new Vue({
el: '#signup',
data: {
studentsorparents: '',
username: '',
email: '',
password: '',
},
methods: {
onSubmit: function () {
// check if the email already exists
var users = '';
var studentParent = this.studentsorparents;
var newUser = this.username;
var newEmail = this.email;
if (localStorage.getItem('users')) { // 'users' is an array of objects
users = JSON.parse(localStorage.getItem('users'));
}
if (users) {
if (users.some(function (user) {
return user.username === newUser
})) {
alert('Account already exits');
return;
}
if (users) {
if (users.some(function (user) {
return user.email === newEmail
})) {
alert('Account already exits');
return;
} else {
alert('Account created');
window.location.href = 'user-profile.html' + '#' + newUser;
}
}
users.push({
'studentsorparents': studentParent,
'username': newUser,
'email': newEmail,
'password': this.password
});
localStorage.setItem('users', JSON.stringify(users));
} else {
users = [{
'studentparents': studentParent,
'username': newUser,
'email': newEmail,
'password': this.password
}];
localStorage.setItem('users', JSON.stringify(users));
}
}
}
});
function passuseremail()
{
var username = document.getElementById('username').value;
localStorage.setItem("user-check", username);
var studentsorparents=document.getElementById('studentsorparents').value;
localStorage.setItem("students-parents-check", studentsorparents)
var email=document.getElementById('email').value;
localStorage.setItem("email-check", email)
return false
}
You need to add button type='submit' to the submit button else it will behave like just any other button.
<button v-on:click='onSubmit' onclick="passuseremail()" type="submit">Register</button>
It then only act as submit button else it will just trigger the button eventlisteners attached.
You have spaces after required attributes in your inputs:
required ="required"
It's incorrect and it will not work; just write it like this:
<input type=email id=email v-model=email required>
You can validate email like this:
const email_re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/;
if (email_re.test( email.value )) {
/* email is valid */
} else {
/* email is not valid */
}
You can add a class to the button like jsValidateRegister.
And the add the code
First declare a variable
isPageValid = true
Then in add the following code for validation so the isPageValid is set to false inside the passuseremail();
$(".jsValidateRegister").click(function ()
{
passuseremail();
});
In the onSubmit: function () check
isPageValid === true

Angular AWS Cognito Force Change password

I am creating a Cognito user from the AWS Console. I am asked to change the password at first login. I want to prompt up a new page or hide a div in the login page to allow the user to pass the new password . Could you please help me how to prompt the new password page with the below code
login.tml
<div class="login">
<div>
<form class="login-form"
[formGroup]="loginForm"
(ngSubmit)="onLogin()" >
<div >
<div fxFlexFill>
<mat-form-field >
<input
type="email"
matInput
placeholder="Your email"
formControlName="email">
<mat-error>Invalid or missing email.</mat-error>
</mat-form-field>
</div>
</div>
<div >
<div >
<mat-form-field >
<input
type="password"
matInput
placeholder="password"
formControlName="password">
<mat-error>Missing password.</mat-error>
</mat-form-field>
</div>
</div>
Login.ts
export class Login implements OnInit {
constructor(private example:ExampleService,
private _router: Router) {
}
onLogin() {
const email=this.loginForm.get('email').value
const password=this.loginForm.get('password').value
this.example.LogIn(email, password).subscribe((data) => {
this._router.navigate(['/home']);
}, (err)=> {
});
}
ExampleService.ts
LogIn(email, password) {
return Observable.create(observ => {
cognitoUser.authenticateUser(authenticationDetails, {
newPasswordRequired: function(userAttributes, requiredAttributes) {
//How do I prompt a new password page from here and collect the form
value
and pass the value on below password paramaters
const email1={
email:email
};
cognitoUser.completeNewPasswordChallenge(password, email1, this)
},
onSuccess: function (result) {
observ.next(result);
observ.complete();
},
onFailure: function(err) {
console.log(err);
observ.error(err);
},
});
});
}
don't know how do I verify the user is a first time user or not. If It is a first-time user how do I show a new page within a call back function(newPasswordRequired: function()).

Categories