From 374eb3420d36040bda7f78434c38cd25a19b93ba Mon Sep 17 00:00:00 2001 From: Diky Arga Date: Thu, 2 Mar 2017 12:40:52 +0700 Subject: [PATCH 1/8] init project with passport local --- app.js | 100 +++++++++++++++++++++++++++ bin/www | 90 ++++++++++++++++++++++++ controllers/bookController.js | 82 ++++++++++++++++++++++ controllers/customerController.js | 82 ++++++++++++++++++++++ controllers/transactionController.js | 82 ++++++++++++++++++++++ models/account.js | 12 ++++ models/book.js | 17 +++++ models/customer.js | 17 +++++ models/transaction.js | 38 ++++++++++ package.json | 28 ++++++++ public/stylesheets/style.css | 8 +++ routes/books.js | 34 +++++++++ routes/customers.js | 34 +++++++++ routes/dashboard/index.js | 8 +++ routes/index.js | 44 ++++++++++++ routes/transactions.js | 34 +++++++++ routes/users.js | 9 +++ views/auth/login.ejs | 18 +++++ views/auth/register.ejs | 1 + views/error.ejs | 3 + views/index.ejs | 11 +++ 21 files changed, 752 insertions(+) create mode 100644 app.js create mode 100755 bin/www create mode 100644 controllers/bookController.js create mode 100644 controllers/customerController.js create mode 100644 controllers/transactionController.js create mode 100644 models/account.js create mode 100644 models/book.js create mode 100644 models/customer.js create mode 100644 models/transaction.js create mode 100644 package.json create mode 100644 public/stylesheets/style.css create mode 100644 routes/books.js create mode 100644 routes/customers.js create mode 100644 routes/dashboard/index.js create mode 100644 routes/index.js create mode 100644 routes/transactions.js create mode 100644 routes/users.js create mode 100644 views/auth/login.ejs create mode 100644 views/auth/register.ejs create mode 100644 views/error.ejs create mode 100644 views/index.ejs diff --git a/app.js b/app.js new file mode 100644 index 0000000..fba6f3c --- /dev/null +++ b/app.js @@ -0,0 +1,100 @@ +var express = require('express'); +var path = require('path'); +var favicon = require('serve-favicon'); +var http = require('http'); +var logger = require('morgan'); +var cookieParser = require('cookie-parser'); +var session = require('express-session') +var bodyParser = require('body-parser'); +// Mongoose +var mongoose = require('mongoose') +mongoose.Promise = global.Promise; +mongoose.connect('mongodb://localhost/library') + +var app = express(); + +// passport + +let passport = require('passport') +var LocalStrategy = require('passport-local').Strategy; + + + +// Import Mongoose Models + + + +app.use(passport.initialize()); +app.use(passport.session()); + +// passport config +var Account = require('./models/account'); +passport.use(new LocalStrategy(Account.authenticate())); +passport.serializeUser(Account.serializeUser()); +passport.deserializeUser(Account.deserializeUser()); +app.use(cookieParser('sssshhhh')); +app.use(session({ + cookieName: 'session', + secret: 'sssshhhh', + duration: 30 * 60 * 1000, + activeDuration: 5 * 60 * 1000, + httpOnly: true, + secure: true, + ephemeral: true, + resave: true, + saveUninitialized: true +})); + + +app.use(function(req, res, next){ + res.locals.session = req.session; + next(); +}); + +var index = require('./routes/index'); +var users = require('./routes/users'); +var books = require('./routes/books'); +var customers = require('./routes/customers'); +var transactions = require('./routes/transactions'); +var dashboard = require('./routes/dashboard'); + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'ejs'); + +// uncomment after placing your favicon in /public +//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); +app.use(logger('dev')); +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ extended: false })); + + + +app.use(express.static(path.join(__dirname, 'public'))); + +app.use('/', index); +app.use('/users', users); +app.use('/books', books); +app.use('/customers', customers); +app.use('/transactions', transactions); +app.use('/dashboard', dashboard); + +// catch 404 and forward to error handler +app.use(function(req, res, next) { + var err = new Error('Not Found'); + err.status = 404; + next(err); +}); + +// error handler +app.use(function(err, req, res, next) { + // set locals, only providing error in development + res.locals.message = err.message; + res.locals.error = req.app.get('env') === 'development' ? err : {}; + + // render the error page + res.status(err.status || 500); + res.render('error'); +}); + +module.exports = app; diff --git a/bin/www b/bin/www new file mode 100755 index 0000000..1efba33 --- /dev/null +++ b/bin/www @@ -0,0 +1,90 @@ +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var app = require('../app'); +var debug = require('debug')('mongodb-crud:server'); +var http = require('http'); + +/** + * Get port from environment and store in Express. + */ + +var port = normalizePort(process.env.PORT || '3000'); +app.set('port', port); + +/** + * Create HTTP server. + */ + +var server = http.createServer(app); + +/** + * Listen on provided port, on all network interfaces. + */ + +server.listen(port); +server.on('error', onError); +server.on('listening', onListening); + +/** + * Normalize a port into a number, string, or false. + */ + +function normalizePort(val) { + var port = parseInt(val, 10); + + if (isNaN(port)) { + // named pipe + return val; + } + + if (port >= 0) { + // port number + return port; + } + + return false; +} + +/** + * Event listener for HTTP server "error" event. + */ + +function onError(error) { + if (error.syscall !== 'listen') { + throw error; + } + + var bind = typeof port === 'string' + ? 'Pipe ' + port + : 'Port ' + port; + + // handle specific listen errors with friendly messages + switch (error.code) { + case 'EACCES': + console.error(bind + ' requires elevated privileges'); + process.exit(1); + break; + case 'EADDRINUSE': + console.error(bind + ' is already in use'); + process.exit(1); + break; + default: + throw error; + } +} + +/** + * Event listener for HTTP server "listening" event. + */ + +function onListening() { + var addr = server.address(); + var bind = typeof addr === 'string' + ? 'pipe ' + addr + : 'port ' + addr.port; + debug('Listening on ' + bind); +} diff --git a/controllers/bookController.js b/controllers/bookController.js new file mode 100644 index 0000000..a64fef1 --- /dev/null +++ b/controllers/bookController.js @@ -0,0 +1,82 @@ +let Book = require('../models/book') + +let faker = require('faker') + +module.exports = { + index: function(req, res, next){ + Book.find({}, function(err, books){ + if (err) { + res.send(err) + } else { + res.json(books) + } + }) + }, + create: function(req, res, next){ + let book = new Book({ + isbn: req.body.isbn, + title: req.body.title, + author: req.body.author, + category: req.body.category, + stock: req.body.stock + }) + + book.save(function(err){ + if(err){ + res.send(err) + } else { + res.send('Book saved') + } + }) + }, + show: function(req, res, next){ + Book.findById(req.params.id, function(err, book){ + if (err) { + console.log(err); + } else { + res.json(book) + } + }) + }, + destroy: function(req, res, next){ + // Using find and remove + Book.findByIdAndRemove(req.params.id, function(err){ + if(err) throw err + res.json('Book Deleted') + }) + }, + test: function(req, res, next){ + res.send('tested') + }, + update: function(req, res, next){ + Book.findById(req.params.id, function(err, book){ + if(err) throw err + book.category = req.body.category + + book.save(function(err){ + if(err) throw err + res.json('Book updated') + }) + }) + }, + generate: function(req, res, next){ + for (let i = 0; i < req.params.amount; i++) { + let book = new Book({ + isbn: faker.internet.mac(), + title: faker.lorem.words(), + author: faker.name.findName(), + category: faker.commerce.department(), + stock: faker.random.number() + }) + + book.save(function(err){ + if(err){ + console.log(err); + } else { + console.log('Book created'); + } + }) + + } + } +} diff --git a/controllers/customerController.js b/controllers/customerController.js new file mode 100644 index 0000000..955c814 --- /dev/null +++ b/controllers/customerController.js @@ -0,0 +1,82 @@ +let Customer = require('../models/customer') + +let faker = require('faker') + +module.exports = { + index: function(req, res, next){ + Customer.find({}, function(err, customers){ + if (err) { + res.send(err) + } else { + res.json(customers) + } + }) + }, + create: function(req, res, next){ + let customer = new Customer({ + name: req.body.name, + memberid: req.body.memberid, + address: req.body.address, + zipcode: req.body.zipcode, + phone: req.body.phone + }) + + customer.save(function(err){ + if(err){ + res.send(err) + } else { + res.send('Customer saved') + } + }) + }, + show: function(req, res, next){ + Customer.findById(req.params.id, function(err, customer){ + if (err) { + console.log(err); + } else { + res.json(customer) + } + }) + }, + destroy: function(req, res, next){ + // Using find and remove + Customer.findByIdAndRemove(req.params.id, function(err){ + if(err) throw err + res.json('Customer Deleted') + }) + }, + test: function(req, res, next){ + res.send('tested') + }, + update: function(req, res, next){ + Customer.findById(req.params.id, function(err, customer){ + if(err) throw err + customer.category = req.body.category + + customer.save(function(err){ + if(err) throw err + res.json('Customer updated') + }) + }) + }, + generate: function(req, res, next){ + for (let i = 0; i < req.params.amount; i++) { + let customer = new Customer({ + name: faker.name.findName(), + memberid: faker.system.semver(), + address: faker.address.streetAddress(), + zipcode: faker.address.zipCode(), + phone: faker.phone.phoneNumber() + }) + + customer.save(function(err){ + if(err){ + console.log(err); + } else { + console.log('Customer created'); + } + }) + + } + } +} diff --git a/controllers/transactionController.js b/controllers/transactionController.js new file mode 100644 index 0000000..3a2267f --- /dev/null +++ b/controllers/transactionController.js @@ -0,0 +1,82 @@ +let Transaction = require('../models/transaction') +let faker = require('faker') + + +module.exports = { + index: function(req, res, next){ + Transaction.find({}).populate('booklist').then((transactions) => { + res.json(transactions) + }) + }, + create: function(req, res, next){ + let transaction = new Transaction({ + memberid: req.body.memberid, + days: req.body.days, + out_date: req.body.out_date, + due_date: req.body.due_date, + in_date: req.body.in_date, + fine: req.body.fine, + booklist: req.body.booklist + }) + + transaction.save(function(err){ + if(err){ + res.send(err) + } else { + res.send('Transaction saved') + } + }) + }, + show: function(req, res, next){ + Transaction.findById(req.params.id, function(err, transaction){ + if (err) { + console.log(err); + } else { + res.json(transaction) + } + }) + }, + destroy: function(req, res, next){ + // Using find and remove + Transaction.findByIdAndRemove(req.params.id, function(err){ + if(err) throw err + res.json('Transaction Deleted') + }) + }, + test: function(req, res, next){ + res.send('tested') + }, + update: function(req, res, next){ + Transaction.findById(req.params.id, function(err, transaction){ + if(err) throw err + transaction.category = req.body.category + + transaction.save(function(err){ + if(err) throw err + res.json('Transaction updated') + }) + }) + }, + generate: function(req, res, next){ + for (let i = 0; i < req.params.amount; i++) { + let transaction = new Transaction({ + memberid: req.body.memberid, + days: req.body.days, + out_date: req.body.out_date, + due_date: req.body.due_date, + in_date: req.body.in_date, + fine: req.body.fine, + booklist: req.body.booklist + }) + + transaction.save(function(err){ + if(err){ + console.log(err); + } else { + console.log('Transaction created'); + } + }) + + } + } +} diff --git a/models/account.js b/models/account.js new file mode 100644 index 0000000..0561f4a --- /dev/null +++ b/models/account.js @@ -0,0 +1,12 @@ +var mongoose = require('mongoose'), + Schema = mongoose.Schema, + passportLocalMongoose = require('passport-local-mongoose'); + +var Account = new Schema({ + username: String, + password: String +}); + +Account.plugin(passportLocalMongoose); + +module.exports = mongoose.model('Account', Account); diff --git a/models/book.js b/models/book.js new file mode 100644 index 0000000..9873c08 --- /dev/null +++ b/models/book.js @@ -0,0 +1,17 @@ +// load +let mongoose = require('mongoose') + +// define book schema +let BookSchema = new mongoose.Schema({ + isbn: String, + title: String, + author: String, + category: String, + stock: Number +}, { + timestamps: true +}) + +// Export mongoose model + +module.exports = mongoose.model('Book', BookSchema) diff --git a/models/customer.js b/models/customer.js new file mode 100644 index 0000000..ce40c85 --- /dev/null +++ b/models/customer.js @@ -0,0 +1,17 @@ +// load +let mongoose = require('mongoose') + +// define book schema +let CustomerSchema = new mongoose.Schema({ + name: String, + memberid: String, + address: String, + zipcode: String, + phone: String, +}, { + timestamps: true +}) + +// Export mongoose model + +module.exports = mongoose.model('Customer', CustomerSchema) diff --git a/models/transaction.js b/models/transaction.js new file mode 100644 index 0000000..c2a28bc --- /dev/null +++ b/models/transaction.js @@ -0,0 +1,38 @@ +// load +let mongoose = require('mongoose') +mongoose.Promise = global.Promise +let Schema = mongoose.Schema + +let Book = require('./book') +// define book schema + +let transactionSchema = Schema({ + memberid: String, + days: Number, + out_date: Date, + due_date: Date, + in_date: Date, + fine: Number, + booklist: [{ + type: Schema.Types.ObjectId, ref: 'Book' + }] +}, { + timestamps: true +}) + +// let TransactionSchema = new mongoose.Schema({ +// memberid: String, +// days: Number, +// out_date: Date, +// due_date: Date, +// in_date: Date, +// fine: Number, +// booklist: [{ +// type: this.Types.ObjectId, ref: 'Book' +// }] +// }, { +// timestamps: true +// }) + +// Export mongoose model +module.exports = mongoose.model('Transaction', transactionSchema) diff --git a/package.json b/package.json new file mode 100644 index 0000000..7ab3bb5 --- /dev/null +++ b/package.json @@ -0,0 +1,28 @@ +{ + "name": "mongodb-crud", + "version": "0.0.0", + "private": true, + "scripts": { + "start": "node ./bin/www", + "dev": "nodemon ./bin/www" + }, + "dependencies": { + "body-parser": "~1.16.0", + "cookie-parser": "~1.4.3", + "debug": "~2.6.0", + "ejs": "~2.5.5", + "express": "~4.14.1", + "express-session": "^1.15.1", + "faker": "^4.1.0", + "mongodb": "^2.2.24", + "mongoose": "^4.8.5", + "morgan": "~1.7.0", + "passport": "^0.3.2", + "passport-local": "^1.0.0", + "passport-local-mongoose": "^4.0.0", + "serve-favicon": "~2.3.2" + }, + "devDependencies": { + "nodemon": "^1.11.0" + } +} diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css new file mode 100644 index 0000000..9453385 --- /dev/null +++ b/public/stylesheets/style.css @@ -0,0 +1,8 @@ +body { + padding: 50px; + font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; +} + +a { + color: #00B7FF; +} diff --git a/routes/books.js b/routes/books.js new file mode 100644 index 0000000..2490154 --- /dev/null +++ b/routes/books.js @@ -0,0 +1,34 @@ +var express = require('express'); +var router = express.Router(); + +let bookController = require('../controllers/bookController') + + +/* GET home page. */ +router.get('/', bookController.index); + +// sample : {{host}}/books/58b6882ea1bd12533ff15315 +router.get('/:id', bookController.show) + +// sample : {{host}}/books/create +/* +isbn:986-343-3214-2414-2 +title:Gowes to campus +author:Diky Arga +category:health +stock:7 +*/ +router.post('/create', bookController.create) + +// Update sample : {{host}}/books/update/58b6882ea1bd12533ff15315 +router.put('/update/:id', bookController.update) + +// Update sample : {{host}}/books/destroy/58b6882ea1bd12533ff15315 +router.delete('/destroy/:id', bookController.destroy) + +router.get('/test', bookController.test) + +// Generateor sample {{host}}/books/generate/100 +router.get('/generate/:amount', bookController.generate) + +module.exports = router; diff --git a/routes/customers.js b/routes/customers.js new file mode 100644 index 0000000..bc81216 --- /dev/null +++ b/routes/customers.js @@ -0,0 +1,34 @@ +var express = require('express'); +var router = express.Router(); + +let customerController = require('../controllers/customerController') + + +/* GET home page. */ +router.get('/', customerController.index); + +// sample : {{host}}/customers/58b6882ea1bd12533ff15315 +router.get('/:id', customerController.show) + +// sample : {{host}}/customers/create +/* +name:Diky Arga +memberid:xxx +address:Semarang, Indonesia +zipcode:51372 +phone:08728732183621 +*/ +router.post('/create', customerController.create) + +// Update sample : {{host}}/customers/update/58b6882ea1bd12533ff15315 +router.put('/update/:id', customerController.update) + +// Update sample : {{host}}/customers/destroy/58b6882ea1bd12533ff15315 +router.delete('/destroy/:id', customerController.destroy) + +router.get('/test', customerController.test) + +// Generateor sample {{host}}/customers/generate/100 +router.get('/generate/:amount', customerController.generate) + +module.exports = router; diff --git a/routes/dashboard/index.js b/routes/dashboard/index.js new file mode 100644 index 0000000..3af08d2 --- /dev/null +++ b/routes/dashboard/index.js @@ -0,0 +1,8 @@ +var express = require('express'); +var router = express.Router(); + +router.get('/', function(req, res, next){ + res.json(req.session) +}) + +module.exports = router; diff --git a/routes/index.js b/routes/index.js new file mode 100644 index 0000000..2402f7e --- /dev/null +++ b/routes/index.js @@ -0,0 +1,44 @@ +var express = require('express'); +var router = express.Router(); + +var passport = require('passport'); +var Account = require('../models/account'); + +router.post('/register', function(req, res, next){ + Account.register(new Account({ + username : req.body.username + }), req.body.password, function(err, account) { + console.log('account : ', account); + if (err) { + return res.render('auth/register', { account : account }); + } + passport.authenticate('local')(req, res, function () { + res.redirect('/'); + }); + }); +}) + +router.get('/login', function(req, res, next){ + res.render('auth/login') +}) + +router.post('/login', passport.authenticate('local'), function(req, res, next){ + res.redirect('/dashboard'); +}) + +router.get('/logout', function(req, res) { + req.logout(); + res.redirect('/'); + }); + +router.get('/ping', function(req, res, next){ + res.send("pong!", 200); +}) + +/* GET home page. */ +router.get('/', function(req, res, next) { + res.json(req.session.passport.user) + // res.render('index', { title: 'Express', username: req.username }); +}); + +module.exports = router; diff --git a/routes/transactions.js b/routes/transactions.js new file mode 100644 index 0000000..e1758cc --- /dev/null +++ b/routes/transactions.js @@ -0,0 +1,34 @@ +var express = require('express'); +var router = express.Router(); + +let transactionController = require('../controllers/transactionController') + + +/* GET home page. */ +router.get('/', transactionController.index); + +// sample : {{host}}/transactions/58b6882ea1bd12533ff15315 +router.get('/:id', transactionController.show) + +// sample : {{host}}/transactions/create +/* +isbn:986-343-3214-2414-2 +title:Gowes to campus +author:Diky Arga +category:health +stock:7 +*/ +router.post('/create', transactionController.create) + +// Update sample : {{host}}/transactions/update/58b6882ea1bd12533ff15315 +router.put('/update/:id', transactionController.update) + +// Update sample : {{host}}/transactions/destroy/58b6882ea1bd12533ff15315 +router.delete('/destroy/:id', transactionController.destroy) + +router.get('/test', transactionController.test) + +// Generateor sample {{host}}/transactions/generate/100 +router.get('/generate/:amount', transactionController.generate) + +module.exports = router; diff --git a/routes/users.js b/routes/users.js new file mode 100644 index 0000000..623e430 --- /dev/null +++ b/routes/users.js @@ -0,0 +1,9 @@ +var express = require('express'); +var router = express.Router(); + +/* GET users listing. */ +router.get('/', function(req, res, next) { + res.send('respond with a resource'); +}); + +module.exports = router; diff --git a/views/auth/login.ejs b/views/auth/login.ejs new file mode 100644 index 0000000..7fcf07d --- /dev/null +++ b/views/auth/login.ejs @@ -0,0 +1,18 @@ + + +
+
+ + +
+
+
+ + +
+
+ +
+
+ + diff --git a/views/auth/register.ejs b/views/auth/register.ejs new file mode 100644 index 0000000..d8a46a4 --- /dev/null +++ b/views/auth/register.ejs @@ -0,0 +1 @@ +register here diff --git a/views/error.ejs b/views/error.ejs new file mode 100644 index 0000000..7cf94ed --- /dev/null +++ b/views/error.ejs @@ -0,0 +1,3 @@ +

<%= message %>

+

<%= error.status %>

+
<%= error.stack %>
diff --git a/views/index.ejs b/views/index.ejs new file mode 100644 index 0000000..8ee1f3e --- /dev/null +++ b/views/index.ejs @@ -0,0 +1,11 @@ + + + + <%= title %> + + + +

<%= title %>

+

Welcome to <%= username %>

+ + From 2dc3645960afaf01fa91409929606135f73b129f Mon Sep 17 00:00:00 2001 From: Diky Arga Date: Thu, 2 Mar 2017 12:52:18 +0700 Subject: [PATCH 2/8] add login, register and dashboard view --- routes/dashboard/index.js | 9 ++++++- routes/index.js | 53 +++++++++++++++++++++++++-------------- views/auth/register.ejs | 20 ++++++++++++++- views/dashboard/index.ejs | 4 +++ views/index.ejs | 4 ++- 5 files changed, 68 insertions(+), 22 deletions(-) create mode 100644 views/dashboard/index.ejs diff --git a/routes/dashboard/index.js b/routes/dashboard/index.js index 3af08d2..459e3e7 100644 --- a/routes/dashboard/index.js +++ b/routes/dashboard/index.js @@ -2,7 +2,14 @@ var express = require('express'); var router = express.Router(); router.get('/', function(req, res, next){ - res.json(req.session) + // res.json(req.session) + console.log(req.session); + if(req.session.passport){ + res.render('dashboard/index', {username: req.session.passport.user}) + + } else { + res.redirect('/login') + } }) module.exports = router; diff --git a/routes/index.js b/routes/index.js index 2402f7e..8492019 100644 --- a/routes/index.js +++ b/routes/index.js @@ -4,41 +4,56 @@ var router = express.Router(); var passport = require('passport'); var Account = require('../models/account'); -router.post('/register', function(req, res, next){ - Account.register(new Account({ - username : req.body.username - }), req.body.password, function(err, account) { - console.log('account : ', account); +router.get('/register', function(req, res, next) { + res.render('auth/register') +}) + +router.post('/register', function(req, res, next) { + Account.register(new Account({ + username: req.body.username + }), req.body.password, function(err, account) { + console.log('account : ', account); if (err) { - return res.render('auth/register', { account : account }); + return res.render('auth/register', { + account: account + }); } - passport.authenticate('local')(req, res, function () { - res.redirect('/'); + passport.authenticate('local')(req, res, function() { + res.redirect('/dashboard'); }); }); }) -router.get('/login', function(req, res, next){ - res.render('auth/login') +router.get('/login', function(req, res, next) { + res.render('auth/login') }) -router.post('/login', passport.authenticate('local'), function(req, res, next){ - res.redirect('/dashboard'); +router.post('/login', passport.authenticate('local'), function(req, res, next) { + res.redirect('/dashboard'); }) router.get('/logout', function(req, res) { - req.logout(); - res.redirect('/'); - }); + req.session.destroy(function(err) { + if (err) { + console.log(err); + } else { + req.logout(); + res.redirect('/'); + } + }) +}); -router.get('/ping', function(req, res, next){ - res.send("pong!", 200); +router.get('/ping', function(req, res, next) { + res.send("pong!", 200); }) /* GET home page. */ router.get('/', function(req, res, next) { - res.json(req.session.passport.user) - // res.render('index', { title: 'Express', username: req.username }); + // res.json(req.session.passport.user) + res.render('index', { + title: 'Express', + username: req.username + }); }); module.exports = router; diff --git a/views/auth/register.ejs b/views/auth/register.ejs index d8a46a4..78c95f8 100644 --- a/views/auth/register.ejs +++ b/views/auth/register.ejs @@ -1 +1,19 @@ -register here + + +

Register

+
+
+ + +
+
+
+ + +
+
+ +
+
+ + diff --git a/views/dashboard/index.ejs b/views/dashboard/index.ejs new file mode 100644 index 0000000..764d938 --- /dev/null +++ b/views/dashboard/index.ejs @@ -0,0 +1,4 @@ +welcome to dashboar <%= username %> +
+ +Log out diff --git a/views/index.ejs b/views/index.ejs index 8ee1f3e..c773142 100644 --- a/views/index.ejs +++ b/views/index.ejs @@ -6,6 +6,8 @@

<%= title %>

-

Welcome to <%= username %>

+

Welcome to <%= title %>

+ Login + Register From a1363a2214290fc5e46b9e786bfbbcf2fa4d10fe Mon Sep 17 00:00:00 2001 From: Diky Arga Date: Thu, 2 Mar 2017 14:16:09 +0700 Subject: [PATCH 3/8] refactor many thing --- app.js | 142 +++++++++++++++++++++++++++------- config/oauth.js | 9 +++ controllers/authController.js | 0 models/account.js | 12 --- models/user.js | 42 ++++++++++ package.json | 4 +- routes/dashboard/index.js | 8 +- routes/index.js | 43 +++++----- views/auth/login.ejs | 4 +- views/auth/register.ejs | 4 +- views/index.ejs | 1 + 11 files changed, 202 insertions(+), 67 deletions(-) create mode 100644 config/oauth.js create mode 100644 controllers/authController.js delete mode 100644 models/account.js create mode 100644 models/user.js diff --git a/app.js b/app.js index fba6f3c..03d184b 100644 --- a/app.js +++ b/app.js @@ -6,6 +6,7 @@ var logger = require('morgan'); var cookieParser = require('cookie-parser'); var session = require('express-session') var bodyParser = require('body-parser'); +var flash = require('connect-flash'); // Mongoose var mongoose = require('mongoose') mongoose.Promise = global.Promise; @@ -16,41 +17,122 @@ var app = express(); // passport let passport = require('passport') -var LocalStrategy = require('passport-local').Strategy; - +var LocalStrategy = require('passport-local').Strategy; +var FacebookStrategy = require('passport-facebook').Strategy; +var oauthConfig = require('./config/oauth.js'); // Import Mongoose Models +// passport config +var User = require('./models/user'); + +passport.use('local-signup', new LocalStrategy({ + usernameField: 'email', + passwordField: 'password', + passReqToCallback: true +}, function(req, email, password, done) { + process.nextTick(function() { + User.findOne({ + 'local.email': email + }, function(err, user) { + if (err) { + return done(err) + } + if (user) { + return done(null, false, req.flash('signupMessage', 'That email is already taken.')); + } else { + var newUser = new User(); + + // set the user's local credentials + newUser.local.email = email; + newUser.local.password = newUser.generateHash(password); + + // save the user + newUser.save(function(err) { + if (err) + throw err; + return done(null, newUser); + }); + } + }) + }) +})); -app.use(passport.initialize()); -app.use(passport.session()); +passport.use('local-login', new LocalStrategy({ + usernameField : 'email', + passwordField : 'password', + passReqToCallback : true +}, function(req, email, password, done){ + User.findOne({ + 'local.email': email + }, function(err, user){ + if (err) { + return done(err) + } + + if (!user) { + return done(null, false, req.flash('loginMessage', 'Gak ada user')) + } + + if(!user.validPassword(password)){ + return done(null, false, req.flash('loginMessage', 'Password salah')) + } + + return done(null, user) + }) +})) + +passport.use(new FacebookStrategy({ + clientID: oauthConfig.facebook.clientID, + clientSecret: oauthConfig.facebook.clientSecret, + callbackURL: oauthConfig.facebook.callbackURL + }, + function(accessToken, refreshToken, profile, done) { + process.nextTick(function() { + return done(null, profile); + }); + } +)); + +app.use(bodyParser()); -// passport config -var Account = require('./models/account'); -passport.use(new LocalStrategy(Account.authenticate())); -passport.serializeUser(Account.serializeUser()); -passport.deserializeUser(Account.deserializeUser()); app.use(cookieParser('sssshhhh')); app.use(session({ - cookieName: 'session', - secret: 'sssshhhh', - duration: 30 * 60 * 1000, - activeDuration: 5 * 60 * 1000, - httpOnly: true, - secure: true, - ephemeral: true, - resave: true, - saveUninitialized: true + cookieName: 'session', + secret: 'sssshhhh', + duration: 30 * 60 * 1000, + activeDuration: 5 * 60 * 1000, + httpOnly: true, + secure: true, + ephemeral: true, + resave: true, + saveUninitialized: true })); -app.use(function(req, res, next){ +app.use(passport.initialize()); +app.use(passport.session()); // persistent login sessions +app.use(flash()); + +app.use(function(req, res, next) { res.locals.session = req.session; next(); }); +// used to serialize the user for the session +passport.serializeUser(function(user, done) { + done(null, user.id); +}); + +// used to deserialize the user +passport.deserializeUser(function(id, done) { + User.findById(id, function(err, user) { + done(err, user); + }); +}); + var index = require('./routes/index'); var users = require('./routes/users'); var books = require('./routes/books'); @@ -66,7 +148,9 @@ app.set('view engine', 'ejs'); //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); -app.use(bodyParser.urlencoded({ extended: false })); +app.use(bodyParser.urlencoded({ + extended: false +})); @@ -81,20 +165,20 @@ app.use('/dashboard', dashboard); // catch 404 and forward to error handler app.use(function(req, res, next) { - var err = new Error('Not Found'); - err.status = 404; - next(err); + var err = new Error('Not Found'); + err.status = 404; + next(err); }); // error handler app.use(function(err, req, res, next) { - // set locals, only providing error in development - res.locals.message = err.message; - res.locals.error = req.app.get('env') === 'development' ? err : {}; + // set locals, only providing error in development + res.locals.message = err.message; + res.locals.error = req.app.get('env') === 'development' ? err : {}; - // render the error page - res.status(err.status || 500); - res.render('error'); + // render the error page + res.status(err.status || 500); + res.render('error'); }); module.exports = app; diff --git a/config/oauth.js b/config/oauth.js new file mode 100644 index 0000000..39bad26 --- /dev/null +++ b/config/oauth.js @@ -0,0 +1,9 @@ +var ids = { + facebook: { + clientID: '860625337409184', + clientSecret: '1bece61f1b4d55afd80a04f25c54007a', + callbackURL: 'http://localhost:3000/auth/facebook/callback' + } +}; + +module.exports = ids; diff --git a/controllers/authController.js b/controllers/authController.js new file mode 100644 index 0000000..e69de29 diff --git a/models/account.js b/models/account.js deleted file mode 100644 index 0561f4a..0000000 --- a/models/account.js +++ /dev/null @@ -1,12 +0,0 @@ -var mongoose = require('mongoose'), - Schema = mongoose.Schema, - passportLocalMongoose = require('passport-local-mongoose'); - -var Account = new Schema({ - username: String, - password: String -}); - -Account.plugin(passportLocalMongoose); - -module.exports = mongoose.model('Account', Account); diff --git a/models/user.js b/models/user.js new file mode 100644 index 0000000..5867254 --- /dev/null +++ b/models/user.js @@ -0,0 +1,42 @@ +var mongoose = require('mongoose') + +var bcrypt = require('bcrypt-nodejs'); + +var userSchema = mongoose.Schema({ + local : { + email : String, + password : String, + }, + facebook : { + id : String, + token : String, + email : String, + name : String + }, + twitter : { + id : String, + token : String, + displayName : String, + username : String + }, + google : { + id : String, + token : String, + email : String, + name : String + } + +}); + +// generating a hash +userSchema.methods.generateHash = function(password) { + return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); +}; + +// checking if password is valid +userSchema.methods.validPassword = function(password) { + return bcrypt.compareSync(password, this.local.password); +}; + +// create the model for users and expose it to our app +module.exports = mongoose.model('User', userSchema); diff --git a/package.json b/package.json index 7ab3bb5..0f96c0a 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,9 @@ "dev": "nodemon ./bin/www" }, "dependencies": { + "bcrypt-nodejs": "0.0.3", "body-parser": "~1.16.0", + "connect-flash": "^0.1.1", "cookie-parser": "~1.4.3", "debug": "~2.6.0", "ejs": "~2.5.5", @@ -18,8 +20,8 @@ "mongoose": "^4.8.5", "morgan": "~1.7.0", "passport": "^0.3.2", + "passport-facebook": "^2.1.1", "passport-local": "^1.0.0", - "passport-local-mongoose": "^4.0.0", "serve-favicon": "~2.3.2" }, "devDependencies": { diff --git a/routes/dashboard/index.js b/routes/dashboard/index.js index 459e3e7..83ffb6c 100644 --- a/routes/dashboard/index.js +++ b/routes/dashboard/index.js @@ -3,13 +3,17 @@ var router = express.Router(); router.get('/', function(req, res, next){ // res.json(req.session) - console.log(req.session); + console.log(req.user.local.email); if(req.session.passport){ - res.render('dashboard/index', {username: req.session.passport.user}) + res.render('dashboard/index', {username: req.user.local.email}) } else { res.redirect('/login') } }) +router.get('/facebook', function(req, res, next){ + res.send('welcome from FB') +}) + module.exports = router; diff --git a/routes/index.js b/routes/index.js index 8492019..1b663b4 100644 --- a/routes/index.js +++ b/routes/index.js @@ -2,35 +2,24 @@ var express = require('express'); var router = express.Router(); var passport = require('passport'); -var Account = require('../models/account'); router.get('/register', function(req, res, next) { res.render('auth/register') }) -router.post('/register', function(req, res, next) { - Account.register(new Account({ - username: req.body.username - }), req.body.password, function(err, account) { - console.log('account : ', account); - if (err) { - return res.render('auth/register', { - account: account - }); - } - passport.authenticate('local')(req, res, function() { - res.redirect('/dashboard'); - }); - }); -}) +router.post('/register', passport.authenticate('local-signup', { + successRedirect : '/dashboard', + failureRedirect : '/register' +})) router.get('/login', function(req, res, next) { res.render('auth/login') }) -router.post('/login', passport.authenticate('local'), function(req, res, next) { - res.redirect('/dashboard'); -}) +router.post('/login', passport.authenticate('local-login', { + successRedirect: '/dashboard', + failureRedirect: '/login' +})) router.get('/logout', function(req, res) { req.session.destroy(function(err) { @@ -56,4 +45,20 @@ router.get('/', function(req, res, next) { }); }); + +router.get('/auth/facebook', + passport.authenticate('facebook'), + function(req, res) { + + }); + +router.get('/auth/facebook/callback', + passport.authenticate('facebook', { + failureRedirect: '/' + }), + function(req, res) { + console.log(profile); + res.redirect('/dashboard/facebook'); + }); + module.exports = router; diff --git a/views/auth/login.ejs b/views/auth/login.ejs index 7fcf07d..4ac2641 100644 --- a/views/auth/login.ejs +++ b/views/auth/login.ejs @@ -2,8 +2,8 @@
- - + +
diff --git a/views/auth/register.ejs b/views/auth/register.ejs index 78c95f8..ea1626c 100644 --- a/views/auth/register.ejs +++ b/views/auth/register.ejs @@ -3,8 +3,8 @@

Register

- - + +
diff --git a/views/index.ejs b/views/index.ejs index c773142..1c262eb 100644 --- a/views/index.ejs +++ b/views/index.ejs @@ -8,6 +8,7 @@

<%= title %>

Welcome to <%= title %>

Login + Login via FaceBook Register From 4a4f1800b7ad2017279f6dbc3e2ff3cba3c404a7 Mon Sep 17 00:00:00 2001 From: Diky Arga Date: Thu, 2 Mar 2017 14:24:12 +0700 Subject: [PATCH 4/8] update dashboard view --- routes/dashboard/index.js | 6 +++--- routes/index.js | 2 -- views/dashboard/index.ejs | 9 +++++++++ 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/routes/dashboard/index.js b/routes/dashboard/index.js index 83ffb6c..883d588 100644 --- a/routes/dashboard/index.js +++ b/routes/dashboard/index.js @@ -3,9 +3,9 @@ var router = express.Router(); router.get('/', function(req, res, next){ // res.json(req.session) - console.log(req.user.local.email); - if(req.session.passport){ - res.render('dashboard/index', {username: req.user.local.email}) + if(req.user){ + console.log(req.user.local.email); + res.render('dashboard/index', {username: req.user.local.email, user: req.user}) } else { res.redirect('/login') diff --git a/routes/index.js b/routes/index.js index 1b663b4..745375b 100644 --- a/routes/index.js +++ b/routes/index.js @@ -41,7 +41,6 @@ router.get('/', function(req, res, next) { // res.json(req.session.passport.user) res.render('index', { title: 'Express', - username: req.username }); }); @@ -57,7 +56,6 @@ router.get('/auth/facebook/callback', failureRedirect: '/' }), function(req, res) { - console.log(profile); res.redirect('/dashboard/facebook'); }); diff --git a/views/dashboard/index.ejs b/views/dashboard/index.ejs index 764d938..a4d4037 100644 --- a/views/dashboard/index.ejs +++ b/views/dashboard/index.ejs @@ -1,4 +1,13 @@ welcome to dashboar <%= username %>
+

local

+id : <%= user._id %> +
+email : <%= user.local.email %> +
+pass : <%= user.local.password %> +
+
+
Log out From 0105bebf8c1ab873312c8b866101a368fad6870b Mon Sep 17 00:00:00 2001 From: Diky Arga Date: Thu, 2 Mar 2017 14:42:08 +0700 Subject: [PATCH 5/8] add FB oauth --- app.js | 32 +++++++++++++++++++++++++++++--- routes/index.js | 18 +++++++----------- 2 files changed, 36 insertions(+), 14 deletions(-) diff --git a/app.js b/app.js index 03d184b..9b0c409 100644 --- a/app.js +++ b/app.js @@ -91,7 +91,35 @@ passport.use(new FacebookStrategy({ }, function(accessToken, refreshToken, profile, done) { process.nextTick(function() { - return done(null, profile); + User.findOne({ + 'facebook.id' : profile.id + }, function(err, user){ + if (err) { + return done(err) + } + if(user){ + return done(null, user) + } else { + + console.log('dfsjfdsahfsdfk ds', profile); + var newUser = new User() + + newUser.facebook.id = profile.id + newUser.facebook.token = accessToken + newUser.facebook.email = profile.emails + newUser.facebook.name = profile.displayName + + newUser.save(function(err){ + if (err) { + throw err + } + + return done(null, newUser) + }) + + } + }) + // return done(null, profile); }); } )); @@ -152,8 +180,6 @@ app.use(bodyParser.urlencoded({ extended: false })); - - app.use(express.static(path.join(__dirname, 'public'))); app.use('/', index); diff --git a/routes/index.js b/routes/index.js index 745375b..db27d51 100644 --- a/routes/index.js +++ b/routes/index.js @@ -45,18 +45,14 @@ router.get('/', function(req, res, next) { }); -router.get('/auth/facebook', - passport.authenticate('facebook'), - function(req, res) { - - }); +router.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' })); router.get('/auth/facebook/callback', - passport.authenticate('facebook', { - failureRedirect: '/' - }), - function(req, res) { - res.redirect('/dashboard/facebook'); - }); + passport.authenticate('facebook', { + successRedirect : '/dashboard', + failureRedirect : '/' + })); + + module.exports = router; From 5c919ddf7079a40c584f70c7955a7a648ddc28fd Mon Sep 17 00:00:00 2001 From: Diky Arga Date: Thu, 2 Mar 2017 15:08:24 +0700 Subject: [PATCH 6/8] add Twitter Oauth --- app.js | 37 +++++++++++++++++++++++++++++++++++++ config/oauth.js | 16 +++++++++++----- package.json | 1 + routes/index.js | 25 ++++++++++++++++--------- views/index.ejs | 4 ++++ 5 files changed, 69 insertions(+), 14 deletions(-) diff --git a/app.js b/app.js index 9b0c409..41e4ee0 100644 --- a/app.js +++ b/app.js @@ -19,6 +19,7 @@ var app = express(); let passport = require('passport') var LocalStrategy = require('passport-local').Strategy; var FacebookStrategy = require('passport-facebook').Strategy; +var TwitterStrategy = require('passport-twitter').Strategy var oauthConfig = require('./config/oauth.js'); @@ -124,6 +125,42 @@ passport.use(new FacebookStrategy({ } )); +passport.use(new TwitterStrategy({ + consumerKey: oauthConfig.twitter.consumerKey, + consumerSecret: oauthConfig.twitter.consumerSecret, + callbackURL: oauthConfig.twitter.callbackURL +}, function(token, tokenSecret, profile, done){ + console.log('dffssaf', profile); + process.nextTick(function(){ + + User.findOne({ + 'twitter.id': profile.id + }, function(err, user){ + if (err) { + return done(err) + } + + if(user){ + return done(err, user) + } else { + let newUser = new User() + newUser.twitter.id = profile.id + newUser.twitter.token = token + newUser.twitter.username = profile.username + newUser.twitter.displayName = profile.displayName + + newUser.save(function(err){ + if (err) { + throw err + } + + return done(null, newUser) + }) + } + }) + }) +})) + app.use(bodyParser()); app.use(cookieParser('sssshhhh')); diff --git a/config/oauth.js b/config/oauth.js index 39bad26..14e839c 100644 --- a/config/oauth.js +++ b/config/oauth.js @@ -1,9 +1,15 @@ var ids = { - facebook: { - clientID: '860625337409184', - clientSecret: '1bece61f1b4d55afd80a04f25c54007a', - callbackURL: 'http://localhost:3000/auth/facebook/callback' - } + facebook: { + clientID: '860625337409184', + clientSecret: '1bece61f1b4d55afd80a04f25c54007a', + callbackURL: 'http://localhost:3000/auth/facebook/callback' + }, + twitter: { + consumerKey: 'wUmYq3Dj5tbUhHgCvMJHnGJSg', + consumerSecret: 'tKHu0nmrKZeNHDNbsVSDLWxvamswkfHQibcXpY6cl0kfRrJdoP', + callbackURL: 'http://localhost:3000/auth/twitter/callback' + }, + }; module.exports = ids; diff --git a/package.json b/package.json index 0f96c0a..9e58880 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,7 @@ "passport": "^0.3.2", "passport-facebook": "^2.1.1", "passport-local": "^1.0.0", + "passport-twitter": "^1.0.4", "serve-favicon": "~2.3.2" }, "devDependencies": { diff --git a/routes/index.js b/routes/index.js index db27d51..c0ed1a3 100644 --- a/routes/index.js +++ b/routes/index.js @@ -8,8 +8,8 @@ router.get('/register', function(req, res, next) { }) router.post('/register', passport.authenticate('local-signup', { - successRedirect : '/dashboard', - failureRedirect : '/register' + successRedirect: '/dashboard', + failureRedirect: '/register' })) router.get('/login', function(req, res, next) { @@ -17,8 +17,8 @@ router.get('/login', function(req, res, next) { }) router.post('/login', passport.authenticate('local-login', { - successRedirect: '/dashboard', - failureRedirect: '/login' + successRedirect: '/dashboard', + failureRedirect: '/login' })) router.get('/logout', function(req, res) { @@ -45,14 +45,21 @@ router.get('/', function(req, res, next) { }); -router.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' })); +router.get('/auth/facebook', passport.authenticate('facebook', { + scope: 'email' +})); router.get('/auth/facebook/callback', - passport.authenticate('facebook', { - successRedirect : '/dashboard', - failureRedirect : '/' - })); + passport.authenticate('facebook', { + successRedirect: '/dashboard', + failureRedirect: '/' + })); +router.get('/auth/twitter', passport.authenticate('twitter')) +router.get('/auth/twitter/callback', passport.authenticate('twitter', { + successRedirect: '/dashboard', + failureRedirect: '/' +})) module.exports = router; diff --git a/views/index.ejs b/views/index.ejs index 1c262eb..71cecf2 100644 --- a/views/index.ejs +++ b/views/index.ejs @@ -8,7 +8,11 @@

<%= title %>

Welcome to <%= title %>

Login +
Login via FaceBook +
+ Login via Twitter +
Register From de908db2c38376eef2054f808062dc0266e13c42 Mon Sep 17 00:00:00 2001 From: Diky Arga Date: Thu, 2 Mar 2017 15:33:54 +0700 Subject: [PATCH 7/8] add Google+ OAuth --- app.js | 42 +++++++++++++++++++++++++++++++++++++++--- config/oauth.js | 6 ++++++ package.json | 1 + routes/index.js | 7 +++++++ views/index.ejs | 2 ++ 5 files changed, 55 insertions(+), 3 deletions(-) diff --git a/app.js b/app.js index 41e4ee0..335d876 100644 --- a/app.js +++ b/app.js @@ -20,6 +20,7 @@ let passport = require('passport') var LocalStrategy = require('passport-local').Strategy; var FacebookStrategy = require('passport-facebook').Strategy; var TwitterStrategy = require('passport-twitter').Strategy +var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; var oauthConfig = require('./config/oauth.js'); @@ -102,7 +103,6 @@ passport.use(new FacebookStrategy({ return done(null, user) } else { - console.log('dfsjfdsahfsdfk ds', profile); var newUser = new User() newUser.facebook.id = profile.id @@ -130,9 +130,7 @@ passport.use(new TwitterStrategy({ consumerSecret: oauthConfig.twitter.consumerSecret, callbackURL: oauthConfig.twitter.callbackURL }, function(token, tokenSecret, profile, done){ - console.log('dffssaf', profile); process.nextTick(function(){ - User.findOne({ 'twitter.id': profile.id }, function(err, user){ @@ -161,6 +159,44 @@ passport.use(new TwitterStrategy({ }) })) +passport.use(new GoogleStrategy({ + + clientID : oauthConfig.google.clientID, + clientSecret : oauthConfig.google.clientSecret, + callbackURL : oauthConfig.google.callbackURL, + +}, function(token, refreshToken, profile, done){ + process.nextTick(function(){ + console.log('profile', profile); + User.findOne({ + 'google.id': profile.id + }, function(err, user){ + if (err) { + return done(err) + } + + if (user) { + return done(user) + } else { + let newUser = new User() + + newUser.google.id = profile.id + newUser.google.name = profile.displayName + newUser.google.email = profile.emails[0].value + newUser.google.token = token + + newUser.save(function(err){ + if (err) { + throw err + } + + return done(null, newUser) + }) + } + }) + }) +})) + app.use(bodyParser()); app.use(cookieParser('sssshhhh')); diff --git a/config/oauth.js b/config/oauth.js index 14e839c..61af98a 100644 --- a/config/oauth.js +++ b/config/oauth.js @@ -9,6 +9,12 @@ var ids = { consumerSecret: 'tKHu0nmrKZeNHDNbsVSDLWxvamswkfHQibcXpY6cl0kfRrJdoP', callbackURL: 'http://localhost:3000/auth/twitter/callback' }, + google: { + clientID: '494087991614-lofh08kr6qets0b7s9gqj0hg4hvidk3l.apps.googleusercontent.com', + clientSecret: 'ee-6W8MoeaoXNDdnEwjICg7z', + callbackURL: 'http://localhost:3000/auth/google/callback' + } + }; diff --git a/package.json b/package.json index 9e58880..3fbb205 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "morgan": "~1.7.0", "passport": "^0.3.2", "passport-facebook": "^2.1.1", + "passport-google-oauth": "^1.0.0", "passport-local": "^1.0.0", "passport-twitter": "^1.0.4", "serve-favicon": "~2.3.2" diff --git a/routes/index.js b/routes/index.js index c0ed1a3..00302cc 100644 --- a/routes/index.js +++ b/routes/index.js @@ -62,4 +62,11 @@ router.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/' })) +router.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] })); + +router.get('/auth/google/callback', + passport.authenticate('google', { + successRedirect : '/dashboard', + failureRedirect : '/' + })); module.exports = router; diff --git a/views/index.ejs b/views/index.ejs index 71cecf2..1e4925f 100644 --- a/views/index.ejs +++ b/views/index.ejs @@ -13,6 +13,8 @@
Login via Twitter
+ Login via Google +
Register From 2dd44d4a03669923e01987adecb45082c8b7107d Mon Sep 17 00:00:00 2001 From: Diky Arga Date: Thu, 2 Mar 2017 15:44:18 +0700 Subject: [PATCH 8/8] move key to dotenv --- .env.example | 11 +++++++++++ .gitignore | 3 +++ app.js | 2 +- config/oauth.js | 18 +++++++++--------- package.json | 1 + 5 files changed, 25 insertions(+), 10 deletions(-) create mode 100644 .env.example diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..9920ce8 --- /dev/null +++ b/.env.example @@ -0,0 +1,11 @@ +FACEBOOK_CLIENTID = +FACEBOOK_CLIENTSECRET = +FACEBOOK_CALLBACK = http://localhost:3000/auth/facebook/callback + +TWITTER_CONSUMERKEY = +TWITTER_CONSUMERSECRET = +TWITTER_CALLBACKURL = http://localhost:3000/auth/twitter/callback + +GOOGLE_CLIENTID = +GOOGLE.CLIENTSECRET = +GOOGLE.CALLBACKURL = http://localhost:3000/auth/google/callback diff --git a/.gitignore b/.gitignore index 5148e52..64ec195 100644 --- a/.gitignore +++ b/.gitignore @@ -32,6 +32,9 @@ jspm_packages # Optional npm cache directory .npm +# ENV + +.env # Optional REPL history .node_repl_history diff --git a/app.js b/app.js index 335d876..9381350 100644 --- a/app.js +++ b/app.js @@ -11,7 +11,7 @@ var flash = require('connect-flash'); var mongoose = require('mongoose') mongoose.Promise = global.Promise; mongoose.connect('mongodb://localhost/library') - +require('dotenv').config() var app = express(); // passport diff --git a/config/oauth.js b/config/oauth.js index 61af98a..9ce6bcc 100644 --- a/config/oauth.js +++ b/config/oauth.js @@ -1,18 +1,18 @@ var ids = { facebook: { - clientID: '860625337409184', - clientSecret: '1bece61f1b4d55afd80a04f25c54007a', - callbackURL: 'http://localhost:3000/auth/facebook/callback' + clientID: process.env.FACEBOOK_CLIENTID, + clientSecret: process.env.FACEBOOK_CLIENTSECRET, + callbackURL: process.env.FACEBOOK_CALLBACK }, twitter: { - consumerKey: 'wUmYq3Dj5tbUhHgCvMJHnGJSg', - consumerSecret: 'tKHu0nmrKZeNHDNbsVSDLWxvamswkfHQibcXpY6cl0kfRrJdoP', - callbackURL: 'http://localhost:3000/auth/twitter/callback' + consumerKey: process.env.TWITTER_CONSUMERKEY, + consumerSecret: process.env.TWITTER_CONSUMERSECRET, + callbackURL: process.env.TWITTER_CALLBACKURL }, google: { - clientID: '494087991614-lofh08kr6qets0b7s9gqj0hg4hvidk3l.apps.googleusercontent.com', - clientSecret: 'ee-6W8MoeaoXNDdnEwjICg7z', - callbackURL: 'http://localhost:3000/auth/google/callback' + clientID: process.env.GOOGLE_CLIENTID, + clientSecret: process.env.GOOGLE_CLIENTSECRET, + callbackURL: process.env.GOOGLE_CALLBACKURL } diff --git a/package.json b/package.json index 3fbb205..37f9785 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "connect-flash": "^0.1.1", "cookie-parser": "~1.4.3", "debug": "~2.6.0", + "dotenv": "^4.0.0", "ejs": "~2.5.5", "express": "~4.14.1", "express-session": "^1.15.1",