In this post we will create a very simple login system in Node.js & Express with the help of PassportJS. We also need the help of Mongoose to access databases created in MongoDB.
Passport is authentication middleware for Node.js. Extremely flexible and modular, Passport can be unobtrusively dropped in to any Express-based web application. A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter, and more.
We need to have installed:
- Node.js (If you don't have it click here)
- Express (If you don't have it click here)
- MongoDB (If you don't have it click here)
Now, we will create our project:
1 - Open your terminal and headed to the directory where we want to create our project
2 - Write in the terminal: $ express -s LoginApp
The "-s" causes that Express initialize and configure the session variables. if you see "app.js" have 2 new uses (app.use(express.cookieParser('your secret here')); app.use(express.session());
"dependencies": { "express": "3.4.8", "jade": "*", "mongoose": "*", "passport": "*", "passport-local": "*", "passport-local-mongoose": "*" } |
this is the module that will allow us to chat communications
4 - Choose de folder of the proyect in the terminal: $ cd LoginApp
5 - Install dependencies, write in the terminal: $ npm install
Create the DataBase
1 - Headed to the project folder and create a new folder called "Data".
1 - Headed to the project folder and create a new folder called "Data".
2 - Open your terminal and create de new DataBase, write:
$ mongod --dbpath folder_data_url* *change folder_data_url for your folder data url
Warning: You can't close this terminal window.
Create the Model (Database)
1 - Headed to the project folder and create a new folder called "models".
1 - Headed to the project folder and create a new folder called "models".
2- Create a new file called "account.js" and write:
// call the libraries
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
passportLocalMongoose = require('passport-local-mongoose');
// create the object
var Account = new Schema({
nickname: String,
birthdate: Date
});
Account.plugin(passportLocalMongoose);
// export the model
module.exports = mongoose.model('Account', Account);
|
This is the model to keep the data in the database
Create the Server
Open the file "app.js" and write:
1 - Below "var path = require('path');" write:
// ... code var path = require('path'); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var mongoose = require('mongoose'); var app = express();
// ... code
|
2 - Below "app.use(express.session());" write:
// ... code app.use(express.cookieParser('your secret here')); app.use(express.session()); // Inicializate the session variable of Passport app.use(passport.initialize()); app.use(passport.session()); app.use(app.router);
// ... code
|
3 - Below "app.use(express.errorHandler()); }" write:
// ... code
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
// passport config
var Account = require('./models/account');
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());
// mongoose config
mongoose.connect('mongodb://localhost/passport_local_mongoose');
var Account = require('./models/account');
// ... code
|
4 - Create the routes
// ... code
// redirect to index with user information
app.get('/', function (req, res) {
res.render('index', { user : req.user });
});
// Redirect to create a new user
app.get('/register', function(req, res) {
res.render('register', { });
});
// Save the new user with passport and mongoose and redirect to index
app.post('/register', function(req, res) {
Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
if (err) {
return res.render('register', { account : account });
}
passport.authenticate('local')(req, res, function () {
res.redirect('/');
});
});
});
// Redirect to login page
app.get('/login', function(req, res) {
res.render('login', { user : req.user });
});
// Check the login and redirect to index
app.post('/login', passport.authenticate('local'), function(req, res) {
res.redirect('/');
});
// Logout and redirect to index
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
// ... code
|
Create the Views
Open the folder "Views" and:
1 - Open "index.jade" and write:
2 - Create "login.jade" and write:
3 - Create "register.jade" and write:
becareful with the tabulated, jade is very sensitive with them
Run de App
Write in the terminal: $ node app and open your browser in localhost:3000/
I hope you liked it, and if you have any questions feel free to write me:
No comments:
Post a Comment