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.
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">Login
</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
Related
I am new to node js and creating a simple application to query data stored in database(MySql) .So what i am doing is, I have created a database named stock and i am querying it using index.html to show it at get.html but after executing the get request i am not able to get the result.
Here is my app.js
const express=require('express');
const app=express();
const port= 5050;
const bodyParser=require("body-parser");
app.use(bodyParser.urlencoded({extended:false}));
app.get('/',(req,res)=>res.sendFile(__dirname + '/index.html'));
app.post('/get',function(req,res){
const mysql=require('mysql');
const con=mysql.createConnection({
host:"localhost",
user:"root",
password:"abc123",
database:"abc",
});
con.connect(function(err){
if(err) throw err;
console.log("Connected");
let sqlQuery='SELECT * FROM stock';
con.query(sqlQuery,(err,rows)=>{
if(err) throw err;
console.log('Data Received:-');
console.log(rows);
});
});
});
app.listen(port);
My Index.html:-
<!DOCTYPE html>
<html>
<head>
<title>My node js app</title>
</head>
<body>
<form action="/get" method="get">
<h1>Welcome to Stock manipulation</h1><br></br>
Select option<select>
<option value=0>Get</option></select>
<input type="submit" id="query" value="get Result">
</body>
</html>
And my get.html
<!DOCTYPE html>
<html>
<head>
<title>Get</title>
</head>
<body>
</body>
</html>
And here is the data stored at database
[ RowDataPacket { id: 1, type: 'BSE' },
RowDataPacket { id: 2, type: 'NSE' } ]
The error i am getting after Submitting the request is
What is your nodejs server saying? In your routes you typically want to return some data. for example in your case your /get route res.send(data). that way your front end can show the data received. Also looks like you need to change your form to be a post not a get (Edit: As Nikos M. mentioned).
If you are new to http requests I recommend downloading Postman to get used to testing your routes requests.
change
<form action="/get" method="get">
to
<form action="/get" method="post">
as you have defined the /get route (app.post('/get',function(req,res){/*..*/}))
to accept only post requests
Also in your /get route handler you should output something. Right now you do not output anything, only log to the node.js console
I'm making a very simple authenticated website for learning giving users the ability to create an account log in and view content.
The issue is not seeing the registered users on the home page (as a test) after a successful post registration. After the post, I am redirecting the user back to the home page and the get route runs a postgres function using node-postgres module to retrieve all of the users in the database and returns them. That doesn't seem to be firing. Yet, when I run the same function in my database, I do see the new user.
What's weird is that when I hit enter on the home route in the browser afterwards, the new user does pop up. So I'm really not sure if this is a caching thing or not understanding promises correctly (I've just started getting into this) or something else.
I have tried using callbacks instead of promises as shown on here: https://node-postgres.com/features/queries to see if it makes a difference. Other than that, I've added log statements to see if the promise actually resolves or rejects. But it seems to always resolve so I'm really unsure what's going on here.
<!-- register.ejs -->
<%- include('partials/header') %>
<div class="container mt-5">
<h1>Register</h1>
<div class="row">
<div class="col-sm-8">
<div class="card">
<div class="card-body">
<!-- Makes POST request to /register route -->
<form action="/register" method="POST">
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password">
</div>
<button type="submit" class="btn btn-dark">Register</button>
</form>
</div>
</div>
</div>
</div>
</div>
<%- include('partials/header') %>
\\index.js (in ./db)
const {
Pool
} = require('pg');
const pool = new Pool({
database: 'secrets'
});
module.exports = {
query: (text, params, callback) => {
return pool.query(text, params, callback)
}
};
//jshint esversion:6
/* Imports
* ================================================================================ */
const express = require('express');
const bodyParser = require('body-parser');
const db = require('./db');
const util = require('util');
/* App setup
* ================================================================================ */
const app = express();
app.disable('etag');
const port = 3000;
app.use(express.static(util.format("%s/%s", __dirname, 'public')));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
/* Routes
* ================================================================================ */
// Get request
app.get("/", function (req, res, next) {
db.query('SELECT * FROM dbo.usp_SelectUsers()')
.then(function(dbResult) {
console.log(dbResult.rows);
res.send(dbResult.rows);
}, (reason) => {
console.log("Not fulfilled :(");
}).catch(_err => next(_err));
});
// Post request for registration
app.post("/register", function (req, res, next) {
const queryText = 'SELECT dbo.usp_CreateUser($1, $2)';
const queryValues = [req.body.username, req.body.password];
db.query(queryText, queryValues)
.then(res.redirect("/"))
.catch(err => next(err))
});
CREATE OR REPLACE FUNCTION dbo.usp_SelectUsers()
RETURNS TABLE (User_ID INTEGER, User_Name VARCHAR(100)) AS
$func$
BEGIN
RETURN QUERY
SELECT u.User_ID
,u.User_Name
FROM dbo.User u
;
END
$func$ LANGUAGE plpgsql;
Expected result is to see new users in database and displayed on home page ("/") after successful post without having to refresh the page again.
I have updated my registration code to use async / await as follows and this fixed everything for me. I realized that the issue I was having previously is that the post did not fully complete before the database call to retrieve the the list of users were made (ie: database did not yet have the new user when calling dbo.usp_SelectUsers).
app.post("/register", async (req, res, next) => {
try {
const queryText = 'SELECT dbo.usp_CreateUser($1, $2)';
const queryValues = [req.body.username, req.body.password];
const results = await db.query(queryText, queryValues);
res.redirect("/login");
} catch (err) {
throw err;
}
});
As a side note, I have read that async / await is also much better to use nowadays and this fix added onto the pluses. Please see the following article for reference:
https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9
I am trying to write a login page . i got the html page with the login box
im enter email and password than submit to server , on server i got route who get the data check on db if doc exists , if its exists should redirect to main page
the problem is the data i send from form to server always undefined i check here on other ppl questions and i didnt find any good result for this
html login page :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="/css/style.css" />
<title>{{PageTitle}}</title>
</head>
<body>
{{> header}}
<div class="login-box">
<div class="form">
<form action="/get_user" method="post" class="login-form">
<input type="email" name="Email" placeholder="Email"/>
<input type="password" name="Password" placeholder="Password"/>
<button type="submit">login</button>
</form>
</div>
</div>
{{> footer}}
</body>
server code :
const _ = require('lodash');
const express = require('express');
const bodyParser = require('body-parser');
const {mongoose} = require('./db/mongoose');
const hbs = require('hbs');
var {User} = require('./models/user');
var app = express();
app.set('view engine', 'hbs');
const port = process.env.PORT;
hbs.registerPartials(__dirname + '/../views/partials');
app.user(bodyParser.json());
app.use(express.static(__dirname + '/../public'));
app.use(express.static(__dirname + '/../public/images'));
app.use(express.static(__dirname + '/../public/fonts'));
app.listen(port, () => {
console.log(`Started on port ${port}`);
});
app.get('/', (req, res) => {
res.render('login.hbs', {
PageTitle: 'Log In',
ConnectUser: 'Guest'
});
});
app.post('/get_user', (req, res) => {
var body = _.pick(req.body, ['Email , 'Password']);
User.findOne({
Email: body.Email,
Password: body.Password
}).then((user) => {
console.log(body.Email + ' ' + body.Password);
if(!user) {
return res.status(404).send();
}
var fullName = user.First_Name + ' ' + user.Last_Name;
res.redirect('/mainPage', {ConnectUser: fullName});
}).catch((e) => {
res.status(400).send();
});
});
i did few checks and when i call /get_user req.body->var body -> user r empty
the data arnt pass from form to server im also check this route on postman and its work find when i write the body by myself the only problem i can think is the data i send from form arnt send as json and the body parser send only in json format so maybe i need to change the line
app.use(bodyParser.json());
if any 1 can put in the right direction ill appraise that ty.
When using an html form with method post, the data is posted to the server withContent-Type: application/x-www-form-urlencoded instead of JSON.
Json bodyparser will not do anything with that, as its not using JSON format to send the data. See MDN guide under post method.
In your server code, below app.use(bodyParser.json()) add the following:
app.use(bodyParser.urlencoded({extended: true}));
This will add the data onto the request body the way you expect.
Try playing with the form enc-type attribute and see how to configure the bodyparser to get the values you need based on the enc-type.
application/x-www-form-urlencoded
multipart/form-data
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/enctype
I am new to node js. i am trying to learn node js. My question is how can we create dynamic webpages using node js?
PHP
<html>
<body>
<?php .......... ?>
</body>
Like in php we can do this way. How can we do in node js.
First off you would start by installing the nodejs framework expressJS
sudo npm install express
For instance, let's say you want to create a form.
<html>
<body>
<head>
This is a simple form
</head>
<body>
<form action="/" method="POST">
<label for="firstName">First Name:</label>
<input name="firstName">
<br>
<label for="lastName">Last Name:</label>
<input name="lastName">
<br>
<button type="submit">send</button>
This what the server side part would look like
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false});
// Set EJS View Engine**
app.set('view engine','ejs');
// Set HTML engine**
app.engine('html', require('ejs').renderFile);
//set directory
app.set('views', __dirname + '/views');
//static folder
app.use(express.static('staticfolder'));
app.get('/form', function(req, res) {
//open form.html from the views directory
res.render('form');
});
app.post('/', urlencodedParser, function(req, res) {
//retrieve first and lastname
var firstName = req.body.firstName;
var lastName = req.body.lastName;
//open submitted.html after the user has submitted the form
res.render('submitted', {output: req.body.firstName});
});
app.listen(3000);
Page that will be displayed when user submits the form. It is called submitted.html in this case
<html>
<body>
<p> you have submitted the form </p>
<!--firstname entered by user-->
<p> your first name is <%= output %></p>
</body>
</html>
You need a template to dynamically change its content.
Step 1: Create a server with Express Node.JS Framework.
Step 2: Use EJS(Embedded JavaScript) to create a template.
Follow the instructions bellow:
https://shockoe.com/ideas/development/creating-dynamic-web-pages-ejs/
Eh, my third question about API and still cannot manage to work it the way I want... Anyways, I have two files: app.js and index.html.
My index.html is simple form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Steam</title>
</head>
<body>
<form>
Steam User ID: <br>
<input type="text" name="steamid"><br>
<input type="submit" value="PoĊĦalji">
</form>
</body>
</html>
Form is getting Steam User ID and submit button, to submit this form.
My app.js:
//Express
var express = require('express');
var server = express();
//SteamWebAPI
var SteamWebAPI = require('steamwebapi').SteamWebAPI;
SteamWebAPI.setAPIKey('7DB297EBF0D0FC352539B4AF9C7C850B');
//Render - Form
server.get('/user_id', function(req, res) {
app.render('form', function(err, html) {
if(err)
return res.send(err);
else
return res.send(html)
});
});
//Route - Form
server.post('/user_info', function(req, res) {
var _userID = req.body.userId;
//Variable - SteamWebAPI
SteamWebAPI.getRecentlyPlayedGames(_userID, 5, function(req, res) {
return res.json(response.response.games);
});
});
// Localhost
server.listen(3000, function() {
console.log('Server: 3000');
});
Someone correct me if I'm wrong:
-after i require express and steamwebapi, i'm getting informations (in this case steam id) from form,
- then this variable _userID is equal to req.body.userId; and i dont know why...anyways...error im getting is: **ReferenceError: app is not defined
**
Can someone help me with this? Is this Node too hard? Like, It's simple. User enter id in form, server getting form? and returning in json format? What I'm doing wrong???
PS: Doing simple way, when I enter Steam ID, I get in console.log game: CS:GO for example...Is there way to display as icon? Obviously I cannot in console so I need to use angular, ember, or what? Thx folks
Just add this before using app variable:
var app = express();