SlideShare a Scribd company logo
Node JS crash course
Login,Registration and HashPassword | 8:15 pm
Abdul Rahman
Masri Attal
@abed_attal
● Mongoose
● Model & Validations
● Controllers
● Routes
Recap of last week
var mongoose = require('mongoose');
//Define a schema
var Schema = mongoose.Schema;
var SomeModelSchema = new Schema({
a_string: String,
a_date: Date
});
var SomeModel = mongoose.model('SomeModel', SomeModelSchema );
const express = require('express'); //import express
const router = express.Router()
const teaController = require('../controllers/tea');
router.post('/tea', teaController.newTea);
module.exports = router
Express and Routes
// newTea function for post tea route
const newTea = (req, res, next) => {
res.json({message: "POST new tea"}); //dummyfuncti
};
module.exports = {newTea};
route.js
/controllers/tea.js
const express = require ('express');
const routes = require('./routes/tea');
const app = express();
app.use(express.json());
app.use('/', routes); //to use the routes
const listener = app.listen(process.env.PORT || 3000,
() => { console.log('Your app is listening on port ' +
listener.address().port) })
server.js
module.exports = (app) => {
const brands = require('../controllers/brand.controller.js');
// Create a new brand
app.post('/brands', brands.create);
// Retrieve all brands
app.get('/brands', brands.findAll);
Creating CRUD REST
Basic GET & POST
// Retrieve a single brand with brandId
app.get('/brands/:brandId', brands.findOne);
// Update a brand with brandId
app.put('/brands/:brandId', brands.update);
// Delete a brand with brandId
app.delete('/brands/:brandId', brands.delete);
}
Creating CRUD REST
API by ID : GET & UPDATE & DELETE
// Retrieve a single brand with brandId
app.get('/brands/:brandId', brands.findOne);
// Update a brand with brandId
app.put('/brands/:brandId', brands.update);
// Delete a brand with brandId
app.delete('/brands/:brandId', brands.delete);
}
Creating CRUD REST
API by ID : GET & UPDATE & DELETE
The first step of login/register is creating a model defining the schema for
user.
Then, we'll need to register the model with Mongoose so that we can use it
throughout our application.
We should add more validations
Creating the User Schema in Mongoose
var mongoose = require('mongoose');
var UserSchema = new mongoose.Schema({
name: String,
email: String,
password: String,
}, {timestamps: true});
mongoose.model('User', UserSchema);
● We use POST to send the user registration info
● We should obviously not to save the password as it is in the body.
That’s why we encrypt it
● We might check if the user email already registered.
● We can use “bcrypt” package to do so with function bcrypt.hash()
● We can also use genSalt(10) to add more complexity to the hash
Registration and setting User passwords
app.post('/register, auth.register);
● We also use POST to send the data of login information so it checks in
the database without passing them in the URL
● First we check if the user exist so if not we throw error
● Then we check the hashed version of our password using
bcrypt.compare() so if matched we login.
Login
app.post('/login, auth.login);

More Related Content

What's hot

Automated Slow Query Analysis: Dex the Index Robot
Automated Slow Query Analysis: Dex the Index RobotAutomated Slow Query Analysis: Dex the Index Robot
Automated Slow Query Analysis: Dex the Index Robot
MongoDB
 
CONFidence 2014: Kiss, Zagon, Sseller: Scaling security
CONFidence 2014: Kiss, Zagon, Sseller: Scaling securityCONFidence 2014: Kiss, Zagon, Sseller: Scaling security
CONFidence 2014: Kiss, Zagon, Sseller: Scaling security
PROIDEA
 
iOS: Web Services and XML parsing
iOS: Web Services and XML parsingiOS: Web Services and XML parsing
iOS: Web Services and XML parsing
Jussi Pohjolainen
 
Ajax with DWR
Ajax with DWRAjax with DWR
Ajax with DWR
gouthamrv
 

What's hot (20)

Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.
 
Automated Slow Query Analysis: Dex the Index Robot
Automated Slow Query Analysis: Dex the Index RobotAutomated Slow Query Analysis: Dex the Index Robot
Automated Slow Query Analysis: Dex the Index Robot
 
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
 
Connecting to a REST API in iOS
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOS
 
Web Services with Objective-C
Web Services with Objective-CWeb Services with Objective-C
Web Services with Objective-C
 
Log MongoDB slow query
Log MongoDB slow queryLog MongoDB slow query
Log MongoDB slow query
 
Scala with mongodb
Scala with mongodbScala with mongodb
Scala with mongodb
 
Rapid prototyping using azure functions - A walk on the wild side
Rapid prototyping using azure functions - A walk on the wild sideRapid prototyping using azure functions - A walk on the wild side
Rapid prototyping using azure functions - A walk on the wild side
 
Ajax Introduction
Ajax IntroductionAjax Introduction
Ajax Introduction
 
Using Webservice in iOS
Using Webservice  in iOS Using Webservice  in iOS
Using Webservice in iOS
 
Mule: JSON to Object
Mule: JSON to ObjectMule: JSON to Object
Mule: JSON to Object
 
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorialsMongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
 
CONFidence 2014: Kiss, Zagon, Sseller: Scaling security
CONFidence 2014: Kiss, Zagon, Sseller: Scaling securityCONFidence 2014: Kiss, Zagon, Sseller: Scaling security
CONFidence 2014: Kiss, Zagon, Sseller: Scaling security
 
Sekilas PHP + mongoDB
Sekilas PHP + mongoDBSekilas PHP + mongoDB
Sekilas PHP + mongoDB
 
iOS: Web Services and XML parsing
iOS: Web Services and XML parsingiOS: Web Services and XML parsing
iOS: Web Services and XML parsing
 
Json
Json Json
Json
 
Ajax with DWR
Ajax with DWRAjax with DWR
Ajax with DWR
 
JSON Processing and mule
JSON Processing and muleJSON Processing and mule
JSON Processing and mule
 
Mule json transformers
Mule json transformersMule json transformers
Mule json transformers
 

Similar to Node js crash course session 6

09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Igor Bronovskyy
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Implement Search Screen Using Knockoutjs
Implement Search Screen Using KnockoutjsImplement Search Screen Using Knockoutjs
Implement Search Screen Using Knockoutjs
Neeraj Kaushik
 

Similar to Node js crash course session 6 (20)

Spring MVC 3 Restful
Spring MVC 3 RestfulSpring MVC 3 Restful
Spring MVC 3 Restful
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
 
Angular 1 + es6
Angular 1 + es6Angular 1 + es6
Angular 1 + es6
 
2016 W3C Conference #4 : ANGULAR + ES6
2016 W3C Conference #4 : ANGULAR + ES62016 W3C Conference #4 : ANGULAR + ES6
2016 W3C Conference #4 : ANGULAR + ES6
 
[W3C HTML5 2016] Angular + ES6
[W3C HTML5 2016] Angular + ES6[W3C HTML5 2016] Angular + ES6
[W3C HTML5 2016] Angular + ES6
 
Testing in JavaScript
Testing in JavaScriptTesting in JavaScript
Testing in JavaScript
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Designing CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsDesigning CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIs
 
Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedure
 
EWD 3 Training Course Part 43: Using JSON Web Tokens with QEWD REST Services
EWD 3 Training Course Part 43: Using JSON Web Tokens with QEWD REST ServicesEWD 3 Training Course Part 43: Using JSON Web Tokens with QEWD REST Services
EWD 3 Training Course Part 43: Using JSON Web Tokens with QEWD REST Services
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplication
 
AngularJS for Java Developers
AngularJS for Java DevelopersAngularJS for Java Developers
AngularJS for Java Developers
 
Passport js authentication in nodejs how to implement facebook login feature ...
Passport js authentication in nodejs how to implement facebook login feature ...Passport js authentication in nodejs how to implement facebook login feature ...
Passport js authentication in nodejs how to implement facebook login feature ...
 
Introduction to angular js
Introduction to angular jsIntroduction to angular js
Introduction to angular js
 
Implement Search Screen Using Knockoutjs
Implement Search Screen Using KnockoutjsImplement Search Screen Using Knockoutjs
Implement Search Screen Using Knockoutjs
 

Recently uploaded

Recently uploaded (20)

Studiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareStudiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting software
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysis
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 

Node js crash course session 6

  • 1. Node JS crash course Login,Registration and HashPassword | 8:15 pm Abdul Rahman Masri Attal @abed_attal
  • 2. ● Mongoose ● Model & Validations ● Controllers ● Routes Recap of last week var mongoose = require('mongoose'); //Define a schema var Schema = mongoose.Schema; var SomeModelSchema = new Schema({ a_string: String, a_date: Date }); var SomeModel = mongoose.model('SomeModel', SomeModelSchema );
  • 3. const express = require('express'); //import express const router = express.Router() const teaController = require('../controllers/tea'); router.post('/tea', teaController.newTea); module.exports = router Express and Routes // newTea function for post tea route const newTea = (req, res, next) => { res.json({message: "POST new tea"}); //dummyfuncti }; module.exports = {newTea}; route.js /controllers/tea.js const express = require ('express'); const routes = require('./routes/tea'); const app = express(); app.use(express.json()); app.use('/', routes); //to use the routes const listener = app.listen(process.env.PORT || 3000, () => { console.log('Your app is listening on port ' + listener.address().port) }) server.js
  • 4. module.exports = (app) => { const brands = require('../controllers/brand.controller.js'); // Create a new brand app.post('/brands', brands.create); // Retrieve all brands app.get('/brands', brands.findAll); Creating CRUD REST Basic GET & POST
  • 5. // Retrieve a single brand with brandId app.get('/brands/:brandId', brands.findOne); // Update a brand with brandId app.put('/brands/:brandId', brands.update); // Delete a brand with brandId app.delete('/brands/:brandId', brands.delete); } Creating CRUD REST API by ID : GET & UPDATE & DELETE
  • 6. // Retrieve a single brand with brandId app.get('/brands/:brandId', brands.findOne); // Update a brand with brandId app.put('/brands/:brandId', brands.update); // Delete a brand with brandId app.delete('/brands/:brandId', brands.delete); } Creating CRUD REST API by ID : GET & UPDATE & DELETE
  • 7. The first step of login/register is creating a model defining the schema for user. Then, we'll need to register the model with Mongoose so that we can use it throughout our application. We should add more validations Creating the User Schema in Mongoose var mongoose = require('mongoose'); var UserSchema = new mongoose.Schema({ name: String, email: String, password: String, }, {timestamps: true}); mongoose.model('User', UserSchema);
  • 8. ● We use POST to send the user registration info ● We should obviously not to save the password as it is in the body. That’s why we encrypt it ● We might check if the user email already registered. ● We can use “bcrypt” package to do so with function bcrypt.hash() ● We can also use genSalt(10) to add more complexity to the hash Registration and setting User passwords app.post('/register, auth.register);
  • 9. ● We also use POST to send the data of login information so it checks in the database without passing them in the URL ● First we check if the user exist so if not we throw error ● Then we check the hashed version of our password using bcrypt.compare() so if matched we login. Login app.post('/login, auth.login);