I tried to implement the firebase authentication in my Node + Express application. But can not figure out how to authenticate an user using email and password. It would be helpful if there is a tutorial or example project.
1 Answer
I know this might help someone in need of help like Shams Nahid, there is firebase authentication tutorial that i would recommend for this. Firebase Authentication Tutorial using
To implement user login using firebase, Node js and express, follow these simple steps
Step 1. Follow this documentation about firebase authentication How to use email and password to sign in
Step 2. Create a login.ejs file
<!doctype html>
<html>
<head> <title>Login into your account</title>
<script src="https://www.gstatic.com/firebasejs/6.1.0/firebase-app.js"></script>
<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/6.1.0/firebase-auth.js"</script>
<script src="https://www.gstatic.com/firebasejs/6.1.0/firebase-firestore.js"
</script>
<script src="https://www.gstatic.com/firebasejs/6.1.0/firebase-database.js">
</script>
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-
awesome/4.0.3/css/font-awesome.min.css">
<style>body{padding-top:80px;}</style>
</head>
<body>
<div class="container " >
<div class="col-sm-6 col-sm-offset-3 ">
<h1><span class="fa fa-sign-in"></span> Login</h1>
<!-- LOGIN FORM -->
<fieldset>
<div class="form-group">
<label>Email</label>
<input type="email" id="txtemail" value="" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" id="txtpassword" value="" class="form-
control">
</div>
<button type="submit" id="loginButton" onclick="signInUsers()"class="btn
btn-warning"><a href="/login">Login</a>
</button>
<button type="submit" id="logoutButton" onclick="logout()"class="btn btn-
warning">logout</button>
</fieldset>
<hr>
</div>
</div>
<script src="/js/firebase.js"></script>
</body>
</html>
Step 3. create an authentication script
firebase.js
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "INSERT HERE YOUR API FROM FIREBASE CONSOLE",
authDomain: "INSERT YOUR DOMAIN",
databaseURL: "INSERT YOUR DATABASE URL",
projectId: "INSERT HERE YOUR PROJECT ID",
storageBucket: "canon-4f6d8.appspot.com",
messagingSenderId: "INSERT HERE YOUR MESSAGING ID FROM FIREBASE",
appId: "1YOUR APP ID FROM FIREBASE"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
function signInUsers(){
var email = document.getElementById('txtemail').value;
var pass = document.getElementById('txtpassword').value;
firebase.auth().signInWithEmailAndPassword(email, pass)
.catch(function(error) {
// Handle Errors here.
let errorCode = error.code;
let errorMessage = error.MESSAGE;
console.log(errorCode);
console.log(errorMessage);
});
}
//check if user is logged in or not
function checkIfLogedIn(){
firebase.auth().onAuthStateChanged(function(user) {
if (user) { // if the user is logged in
console.log(user)
var emailv =user.email;
console.log("User is signed in. with email: "+ emailv);
document.getElementById('loginButton').setAttribute('style','display: none;visibility: hidden;');
document.getElementById('logoutButton').setAttribute('style','display: inline-block;visibility: visible;')
} else { // if the user is not logged in
console.log("No user is signed in.");
document.getElementById('loginButton').setAttribute('style','display: none;visibility: visible;');
document.getElementById('logoutButton').setAttribute('style','display: inline-block;visibility: hidden;')
}
});
}
window.onload=function(){
checkIfLogedIn()
}
function logout(){
firebase.auth().signOut();
checkIfLogedIn()
}
Step 3. Create your app.js script that you will be running
app.js file
var express=require('express')
var logger=require('morgan')
var passport = require('passport');
var bodyParser=require('body-parser')
var admin=require('firebase-admin')
var path = require('path');
var serviceAccount=require('./canon-serviceKey.json')
var firebaseAdmin=admin.initializeApp({
credential:admin.credential.cert(serviceAccount),
databaseURL: "INSERT YOUR FIREBASE DB URL"
})
///database reference
var database=firebaseAdmin.database()
//create instance of express app
var app=express()
//we want to serve js and html in ejs
//ejs stands for embedded javascript
app.set('view engine','ejs')
//we also want to send css images and other static files in views folder
//app.use(express.static('views'))
app.use(express.static(path.join(__dirname, '/views/')));
app.set('views',__dirname+'/views/')
//Give the server access to user input
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended:false}))
app.use(logger('dev'))
//create authentication middle ware
function checkLoggedIn(request, resposense, next) {// if user is authenticated in the session, carry on
if (request.isAuthenticated())
return next();// if they aren't redirect them to the index page
resposense.redirect('/');
}
app.get('/',function(request,response){
response.render('login.ejs')
})
app.get('/login', function(request,response){
response.render('profile.ejs')
});
app.get('/logout', function(request,response){
response.render('login.ejs')
});
app.listen(port,function(){
console.log('App running on port'+port)
})
NOTE: Make sure you install the necessary packages first using npm install package-name such as
- express
- morgan
- firebase-admin
- body-parser
After doing the above steps you run your app.js using node app.js and you will be good to go. i hope this helps some one with the same issue about firebase authentication using node js and express