Firebase email verification workflow - javascript

I have a simple input box asking for users emails.
I want them to input something, for me to check it is a string, and then send a verification email to their email address entered.
Then once verified within users mail client and the link is clicked, I want the user to be added to my Firebase users.
At the moment, I am just testing without any email sending via SMTP, just adding data to Firebase. However, no emails I add are being added to my Firebase database.
Current code in the bottom of the body of the HTML, before the other script tags (should this be in the head?):
<script src="https://www.gstatic.com/firebasejs/3.6.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "myapikey",
authDomain: "mydomain.firebaseapp.com",
databaseURL: "https://mydomain.firebaseio.com",
storageBucket: "mydomain.appspot.com",
messagingSenderId: "mymessagesenderid"
};
firebase.initializeApp(config);
</script>
<script src="assets/js/saveEmail.js" type="text/javascript"></script>
Then I have an input box:
<div class="mtb">
<h2 class="signup-title">Sign up for updates on our project</h2>
<p id="signup-success" class="text-success"></p>
<p id="signup-error" class="text-danger"></p>
<form class="signup-form form-inline" id="signup-form" role="form" onsubmit="return signup(this)">
<div id="div">
<input type="email" name="email" class="subscribe-input" placeholder="Enter your e-mail address..." required>
<button class='btn btn-conf btn-yellow' id="signup-button" type="submit">Submit
</button>
</div>
</form>
</div>
And this is saveEmail.js:
var signupForm = document.getElementById('signup-form');
var signupSuccess = document.getElementById('signup-success');
var signupError = document.getElementById('signup-error');
var signupBtn = document.getElementById('signup-button');
var onSignupComplete = function (error) {
signupBtn.disabled = false;
if (error) {
signupError.innerHTML = 'Sorry. Could not signup.';
} else {
signupSuccess.innerHTML = 'Thanks for signing up!';
// hide the form
signupForm.style.display = 'none';
}
};
function signup(formObj) {
// Store emails to firebase
var myFirebaseRef = new Firebase("https://mydomain.firebaseio.com/signups");
myFirebaseRef.push({
email: formObj.email.value,
}, onSignupComplete);
signupBtn.disabled = true;
return false;
}
I know that the signup function is being called as I tried a simple JS alert, which does pop up when the submit button is clicked. However, I am seeing nothing change in my Firebase data dashboard under the /signups section. Also, the URL changes to:
http://localhost:5000/?email=theemailthatwasputintothebox
I modified my rules to:
{"rules":
{".read": true,
".write": true
}
}
So I assume this is not about rules as I have enabled everything for testing purposes.
How can I achieve what I want to achieve (without, and then with the email confirmation part)?
What is going wrong with the existing setup, without email confirmation via SendGrid etc?

I have a simple input box asking for users emails.
I want them to input something, for me to check it is a string, and
then send a verification email to their email address entered.
Then once verified within users mail client and the link is clicked, I want the user to be added to my Firebase users.
I do not think Firebase works that way. Unless the user is registered, you cannot send a verification email to an arbitrary email address. The sendEmailVerification method works on a currentUser.
According to the docs:
You can send an address verification email to a user with the sendEmailVerification method
Now, to your snippet, aren't you simply trying to take a user input and save it to the database? With the recent SDK, you can try this, as per docs
....
var database = firebase.database();
function signup(formObj) {
// Store emails to firebase
database.ref('signups')
.push({
email: formObj.email.value,
})
.then(function(res) {
console.log(res)
// call whatever callback you want here
})
.catch( .... )
}

FYI if you are using Firebase email verification think about testing it during your end-to-end or smoke tests.
Use a service like emaile2e.com to generate random email addresses during a test which you can send and receive from. That way you can verify users during a test programmatically.

Related

Simple Login Form

I am trying to implement a simple login form using JavaScript and HTML. When I submit the form, I want to check the username and password against a list of valid credentials.
If the credentials are valid, I want to redirect the user to the home page. Otherwise, I want to show an error message. I have written the following code, but it is not working as expected. Can someone please help me debug this issue?
<form id="login-form">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
<script>
const form = document.getElementById('login-form');
const username = document.getElementById('username');
const password = document.getElementById('password');
form.addEventListener('submit', function(event) {
event.preventDefault();
const validCredentials = [
{ username: 'user1', password: 'pass1' },
{ username: 'user2', password: 'pass2' }
];
for (const credential of validCredentials) {
if (credential.username === username.value && credential.password === password.value) {
window.location.href = '/home';
} else {
alert('Invalid username or password');
}
}
});
</script>
I am implement a simple login form using JavaScript and HTML.
The expected outcome of the code is that when the user enters a valid username and password and clicks the submit button, they will be redirected to the home page. If the username and password are invalid, an error message should be displayed.
First of all, don't do this if you want to use this code for real users and production web app. It's not a good approach to hardcore users or passwords in a JavaScript script. If you are using this code for learning purposes, it's okay!
Secondly, the code has two meaningful problems. The alert inside the else block is running after every iteration of the for loop. You have to add a return statement to stop the loop and exists the function. Place the alert after the for loop, because the intention of the alert (I guess) is: if you don't find any coincidence, show to the user that the username and password are invalid.
for (const credential of validCredentials) {
if (credential.username === username.value && credential.password === password.value) {
return window.location.href = '/home';
}
} //end of the loop
alert('Invalid username or password');
}); //end of the callback function
});
On the other hand, in window.location.href = '/home', the string is a malformed URI. You have to send user to a completed URI like, https://google.com/ or http:/yoursite.com/home

Unable to retrieve data for displaying in the browser

I have a web app where I can login using Firebase. I know the details are stored in the Firebase database. I want the username value to be displayed on the browser in a certain field. Here are the screenshots.
This is the firebase data. In this picture, see the username karthik babu.
I want that username to be displayed on the area in the picture below:
So, instead of the username, I need the actual username value to be displayed.
Here is the code I tried:
var provider = new firebase.auth.GoogleAuthProvider();
provider.addScope('https://www.googleapis.com/auth/plus.login');
firebase.auth().signInWithPopup(provider).then(function(user) {
var token = user.credential.accessToken;
var user = user.user;
var usersRef = firebase.database().ref("WoofyDesktop/UserList");
if (user) {
usersRef.child(user.uid).set({
useremail: user.email,
useruid: user.uid,
username: user.displayName
});
firebase retrieve code i tried:
var rootRef = firebase.database().ref().child("UserList");
rootRef.on("child_added", snap => {
var username = snap.child("username").val();
$("username").append("<div><a><label>" + username + "</label></a></div>");
console.log(username);
});
html code for username..
<div>
<a href="#" class="user">
<label for="username" id="username" >username</label>
</a></div>
Any suggestions on how or what I should change for displaying the required data?
Edit: Tried the updated query as in the answer by aks79 and this is what I am getting. Any insights?
You cannot embed another label inside a label tag
Limitations of label tag...
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label
use a different tag like div instead
try using it like
HTML Code
<div class="user" id="username"></div>
and the jquery as
$("#username").append("<a href='javascript:void(0)'><label>" + username + "</label></a>");

Meteor How to create a Invite system

I want to make a small invite system (User send an email to the friend with an ivitation code --> friend clicks on the public website everyone can go --> puts his invitation code in the text field and meteor searches for this code if it can find the code all is fine and he can continue but when meteor cant find the code he is one random internet user and he shouldnt can continue
So I need something which compares the inputted value with the data in the collection
this is my js file maybe some good things are already inside of it ;)
Template.Invite.onCreated(function() {
this.subscribe('invites');
});
Template.Invite.events({
'submit .Invite'(event) {
event.preventDefault();
var Invite = event.target.Invite.value;
}
});
Template.Invite.helpers({
results: function(){
return Invites.find({
code: Session.get('Invite'),
if (Invite = Invite)
{
FlowRouter.go('/');
}
});
}
});
my publish part in the main.js
Meteor.publish("invites", function() {
return Invites.find();
})
and the not important html
<template name="Invite">
<form class="Invite" >
<input type="text" name="Invite" placeholder="Invite Code" />
<input type="submit" value="Bestätigen" />
</form>
</template>
the insert in the Invite Collection works already but not the find and the compare
Thank you for your time and help ;)
I've created an invitation system a few times and this is how I did it.
When the user sends an invitation, you create a new document in the Invitation collection like this:
import { Random } from 'meteor/random';
const code = Random.hexString(16);
invitation = {
'code': code,
'sentTo': 'user#website.com',
'accepted': false,
}
Then when a user tries to sign up you need to call a method that grabs their invitation code and compares it to the code in the database
Meteor.methods({
'acceptInvitation'(code) {
check(code, String);
// find invitation in database
let invitation = Invitations.findOne({ 'code': code});
//check if invitation exists and if it hasn't already been accepted
if(invitation && invitation.accepted == false) {
//update invitation to now be accepted
Invitations.update(
{ '_id': invitation._id},
{ $set: { accepted: true }
);
return true;
} else {
throw new Meteor.Error('invalid', 'Your invitation code is not valid');
}
}
});
To make your invitation system even better, when you are sending the invitation email you can pass the invitation code as a parameter in the URL. Then when the user clicks the invitation link you can grab the code from the URL and automatically put it in the registration form for them. This prevents them making mistakes when they copy/paste it!

Retrieving AND Displaying saved data from local storage inanother web page

I am doing a school project on creating a web site. I have managed to save user data into local storage upon signing up for an account. I want to retrieve and display the saved user data from local storage into an edit profile page, such that when I load the edit profile page, there would be some data already shown in the page.
For example in social media accounts whenever we want to edit our profile, our current information would be shown, and we just edit our info from that page. How do I achieve this?
Here are my codes:
<script>
var currentUser=null;
document.addEventListener("DOMContentLoaded",loadUserData);
function loadUserData() {
currentUser = localStorage.getItem("currentUser");
if(currentUser!=null) {
currentUser = JSON.parse(currentUser);
console.log(currentUser.username);
console.log(currentUser.name);
console.log(currentUser.password);
console.log(currentUser.email);
}
}
</script>
I know the console.log only shows the data in console, but I need the data to be shown in the text box instead when users go to the edit profile page.
Is the following script correct to display a username in the username text box?It didn't work for me though.
<p>
<label for="newusername">Change Username:</label>
<input type="text" name="username" onload="valueAsPlaceHolder();"
id="username" required="required"/>
<!--<script>
function valueAsPlaceHolder() {
var changeUsernameInput = document.getElementById("username");
localStorage["username"] = changeUsernameInput.value;
var changeUsernameSetting = localStorage["username"];
if (changeUsernameSetting == null) {
changeUsernameInput.value = "";
}
else {
changeUsernameInput.value = changeUsernameSetting;
}
}
</script-->
</p>
You should have to modify the loadUserData function like below. I have set example for username you can follow for all fields like name, email and password.
function loadUserData() {
currentUser = localStorage.getItem("currentUser");
if(currentUser!=null) {
currentUser = JSON.parse(currentUser);
document.getElementById('username').value = currentUser.username;
}
}

Facebook Accountkit JAVASCRIPT Implementation

I am trying to implement the facebook accountkit using javascript. I followed the documentation on https://developers.facebook.com/docs/accountkit/web/integrating.
AccountKit login form
Enter country code (e.g. +1):
<input type="text" id="country_code" />
Enter phone number without spaces (e.g. 444555666):
<input type="text" id="phone_num"/>
<button onclick="phone_btn_onclick();">Login via SMS</button>
Enter email address
<input type="text" id="email"/>
<button onclick="email_btn_onclick();">Login via Email</button>
Below is the javascript code on my app
<script src="https://sdk.accountkit.com/en_US/sdk.js"></script>
<script>
// initialize Account Kit with CSRF protection
AccountKit_OnInteractive = function(){
AccountKit.init(
{
appId:'facebook_app_id',
state:"csrf",
version:"accountkit_version"
}
);
};
// login callback
function loginCallback(response) {
console.log(response);
if (response.status === "PARTIALLY_AUTHENTICATED") {
document.getElementById("code").value = response.code;
document.getElementById("csrf_nonce").value = response.state;
document.getElementById("my_form").submit();
}
else if (response.status === "NOT_AUTHENTICATED") {
// handle authentication failure
}
else if (response.status === "BAD_PARAMS") {
// handle bad parameters
}
}
// phone form submission handler
function phone_btn_onclick() {
var country_code = document.getElementById("country_code").value;
var ph_num = document.getElementById("phone_num").value;
AccountKit.login('PHONE',
{countryCode: country_code, phoneNumber: ph_num}, // will use default values if this is not specified
loginCallback);
}
// email form submission handler
function email_btn_onclick() {
var email_address = document.getElementById("email").value;
AccountKit.login('EMAIL', {emailAddress: email_address}, loginCallback);
}
</script>
After setting the required values for appId, state and version. I tried filling the form but I was redirecting to account kit page saying
we are sorry, something went wrong, try again
Any help in the implementation will be highly appreciated. Thanks in advance
The problem has been resolved. On account kit page on facebook developer site, I pointed the server url on web login settings to all occurrence of the domain i.e http://domain.com, http://www.domain.com including https if available. This resolved the problem. THANKS ALL.

Categories

Resources