From 66ffabd31f2df3446f7f133ce733866b0c901639 Mon Sep 17 00:00:00 2001 From: pisanggoreng <7ofpentacles@gmail.com> Date: Mon, 20 Mar 2017 00:19:07 +0700 Subject: [PATCH] clear --- .gitignore0 | 2 + app.js | 77 ++++++++++++++++++ bin/www | 90 +++++++++++++++++++++ cara-pakai-passport-facebook.js | 32 ++++++++ helper/hash.js | 23 ++++++ models/userSchema.js | 11 +++ package.json | 22 +++++ passport/passport.js | 0 public/stylesheets/style.css | 8 ++ query.js | 15 ++++ routes/index.js | 137 ++++++++++++++++++++++++++++++++ routes/users.js | 9 +++ views/error.ejs | 3 + views/index.ejs | 11 +++ 14 files changed, 440 insertions(+) create mode 100644 .gitignore0 create mode 100644 app.js create mode 100755 bin/www create mode 100644 cara-pakai-passport-facebook.js create mode 100644 helper/hash.js create mode 100644 models/userSchema.js create mode 100644 package.json create mode 100644 passport/passport.js create mode 100644 public/stylesheets/style.css create mode 100644 query.js create mode 100644 routes/index.js create mode 100644 routes/users.js create mode 100644 views/error.ejs create mode 100644 views/index.ejs diff --git a/.gitignore0 b/.gitignore0 new file mode 100644 index 0000000..9daa824 --- /dev/null +++ b/.gitignore0 @@ -0,0 +1,2 @@ +.DS_Store +node_modules diff --git a/app.js b/app.js new file mode 100644 index 0000000..c857abd --- /dev/null +++ b/app.js @@ -0,0 +1,77 @@ +var express = require('express'); +var path = require('path'); +var favicon = require('serve-favicon'); +var logger = require('morgan'); +var cookieParser = require('cookie-parser'); +var bodyParser = require('body-parser'); +var session = require('express-session') + + +var passport = require('passport'); +var Strategy = require('passport-local') + .Strategy; + +var index = require('./routes/index'); +var users = require('./routes/users'); + +var app = express(); + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'ejs'); + +// uncomment after placing your favicon in /public + +app.use(passport.initialize()); +app.use(passport.session()); + +app.use(session({ + cookieName: 'session', + secret: 'eg[isfd-8yF9-7w2315df{}+Ijsli;;to8', + duration: 30 * 60 * 1000, + activeDuration: 5 * 60 * 1000, + httpOnly: true, + secure: true, + ephemeral: true, + resave: true, + saveUninitialized: true +})) +// penambahan untuk session +app.use(function (req, res, next) { + res.set('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'); + next(); +}); + +app.use(logger('dev')); +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ + extended: false +})); +app.use(cookieParser()); +app.use(express.static(path.join(__dirname, 'public'))); + + +app.use('/', index); +app.use('/users', users); + + + +// 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..e87e94d --- /dev/null +++ b/bin/www @@ -0,0 +1,90 @@ +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var app = require('../app'); +var debug = require('debug')('api-oauth-thirdparty: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/cara-pakai-passport-facebook.js b/cara-pakai-passport-facebook.js new file mode 100644 index 0000000..c90f4e9 --- /dev/null +++ b/cara-pakai-passport-facebook.js @@ -0,0 +1,32 @@ +// FACEBOOK +var passport = require('passport'); +var FacebookStrategy = require('passport-facebook') + .Strategy; + +passport.use(new FacebookStrategy({ + clientID: "1420197958030285", + clientSecret: "2722281df2b0f30eb6267b2d71e1e701", + // harus sama dengan URL di facebook developer + callbackURL: "http://localhost:3000/auth/facebook/callback" + }, + function (accessToken, refreshToken, profile, cb) { + return cb(null, profile); + } +)); + +router.get('/auth/facebook', + passport.authenticate('facebook', { + failureRedirect: '/error' + }), + function (req, res) { + // Successful authentication, redirect home. + // memang kosong, & harus ada agar bisa redirect ke halaman selanjutnya + }); + +router.get('/auth/facebook/callback', passport.authenticate('facebook', { + failureRedirect: '/error' + }), + function (req, res) { + // Successful authentication, redirect home. + res.send(res.req.user); + }); diff --git a/helper/hash.js b/helper/hash.js new file mode 100644 index 0000000..fa43a77 --- /dev/null +++ b/helper/hash.js @@ -0,0 +1,23 @@ +module.exports = function (req, res, next) { + let crypto = require('crypto'); + let mongoose = require('mongoose'); + // mongoose.connect('mongodb://localhost/AOuth'); + + let salt = ""; + let hashPassword = ""; + // generate random namber untuk diisi ke variabel salt + let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + for (var i = 0; i < 5; i++) { + salt += possible.charAt(Math.floor(Math.random() * possible.length)); + } + // hash hasil generate salt dengan password yang di inputkan + // lalu simpan hasil nya ke variabel hash + hashPassword = crypto.createHmac('sha256', salt) + .update(req.body.hashPassword) + .digest('hex'); + + req.hash = {} + req.hash.salt = salt + req.hash.hashPassword = hashPassword + next() +} diff --git a/models/userSchema.js b/models/userSchema.js new file mode 100644 index 0000000..e1ea975 --- /dev/null +++ b/models/userSchema.js @@ -0,0 +1,11 @@ +let mongoose = require("mongoose"); + +let user = mongoose.Schema({ + userName: String, + hashPassword: String, + salt: String, + dataId: Number +}) + +let User = mongoose.model('user', user) +module.exports = User; diff --git a/package.json b/package.json new file mode 100644 index 0000000..d1cc7a8 --- /dev/null +++ b/package.json @@ -0,0 +1,22 @@ +{ + "name": "api-oauth-thirdparty", + "version": "0.0.0", + "private": true, + "scripts": { + "start": "node ./bin/www", + "dev": "nodemon ./bin/www" + }, + "dependencies": { + "body-parser": "~1.15.2", + "cookie-parser": "~1.4.3", + "debug": "~2.2.0", + "ejs": "~2.5.2", + "express": "~4.14.0", + "mongodb": "^2.2.24", + "morgan": "~1.7.0", + "nodemon": "^1.11.0", + "passport": "^0.3.2", + "passport-local": "^1.0.0", + "serve-favicon": "~2.3.0" + } +} diff --git a/passport/passport.js b/passport/passport.js new file mode 100644 index 0000000..e69de29 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/query.js b/query.js new file mode 100644 index 0000000..e8cc031 --- /dev/null +++ b/query.js @@ -0,0 +1,15 @@ +var mongoose = require('mongoose'); +mongoose.connect('mongodb://localhost/AOuth'); + +let User = require("./models/userSchema"); + +passport.use(new LocalStrategy( + function(username, password, done) { + User.findOne({ username: username }, function (err, user) { + if (err) { return done(err); } + if (!user) { return done(null, false); } + if (!user.verifyPassword(password)) { return done(null, false); } + return done(null, user); + }); + } +)); diff --git a/routes/index.js b/routes/index.js new file mode 100644 index 0000000..5430a64 --- /dev/null +++ b/routes/index.js @@ -0,0 +1,137 @@ +// req express component +var express = require('express'); +var router = express.Router(); + +// req mongoose component +var mongoose = require('mongoose'); +mongoose.connect('mongodb://localhost/AOuth'); + +var passport = require('passport'); +var Strategy = require('passport-local') + .Strategy; + +// inisiasi models class setiap table +let User = require("../models/userSchema"); +// require crypto untuk hash + +let hash = require("../helper/hash"); + +/* GET home page. */ +router.get('/', function (req, res) { + User.find() + .then(function (result) { + res.send(result); + }); +}); + +// http://localhost:3000/user/new +router.post('/user/new', hash, function (req, res, next) { + User.find() + .then(function (result) { + let dataUser = new User({ + dataId: result.length + 1, + userName: req.body.userName, + hashPassword: req.hash.hashPassword, + salt: req.hash.salt, + }); + + dataUser.save(function (err, respond) { + if (err) return console.error(err); + res.send(respond) + }); + }); +}); + +passport.use(new Strategy( + function (username, password, cb) { + if (username == 'endy' && password == "bukabuka") { + cb(null, 'user'); + } + })); + +passport.serializeUser(function (user, cb) { + cb(null, user); +}); + +router.post('/user/login', + passport.authenticate('local', { + failureRedirect: '/login' + }), + function (req, res) { + res.send('oke coy'); + }); + +// FACEBOOK +var passport = require('passport'); +var FacebookStrategy = require('passport-facebook') + .Strategy; + +passport.use(new FacebookStrategy({ + clientID: "1420197958030285", + clientSecret: "2722281df2b0f30eb6267b2d71e1e701", + // harus sama dengan URL di facebook developer + callbackURL: "http://localhost:3000/auth/facebook/callback" + }, + function (accessToken, refreshToken, profile, cb) { + return cb(null, profile); + } +)); + +router.get('/auth/facebook', + passport.authenticate('facebook', { + failureRedirect: '/error' + }), + function (req, res) { + // Successful authentication, redirect home. + // memang kosong, & harus ada agar bisa redirect ke halaman selanjutnya + }); + +router.get('/auth/facebook/callback', passport.authenticate('facebook', { + failureRedirect: '/error' + }), + function (req, res) { + // Successful authentication, redirect home. + // tampilkan data user dari facebook + // req.user sudah bawaan default dari sana + res.send(res.req.user); + }); + +// TWITTER +// http://localhost:3000/auth/twitter +// +var session = require('express-session') +var TwitterStrategy = require('passport-twitter') + .Strategy + +passport.use(new TwitterStrategy({ + consumerKey: "2WzYNinTeyeDU0J1bN4vaHF4T", + consumerSecret: "ScljJYetgKUN3p0NpTaGjKgLrAFzNLLMxgo1AVHfbJko1JcXnT", + callbackURL: "http://localhost:3000/auth/twitter/callback" + }, + function (token, tokenSecret, profile, cb) { + return cb(null, profile); + } +)); + +// router.get('/auth/twitter', +// passport.authenticate('twitter')); + +router.get('/auth/twitter', + passport.authenticate('twitter', { + failureRedirect: '/error' + }), + function (req, res) { + // Successful authentication, redirect home. + // memang kosong, & harus ada agar bisa redirect ke halaman selanjutnya + }); + +router.get('/auth/twitter/callback', + passport.authenticate('twitter', { + failureRedirect: '/login' + }), + function (req, res) { + // Successful authentication, redirect home. + res.send(res.req.user); + }); + +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/error.ejs b/views/error.ejs new file mode 100644 index 0000000..7cf94ed --- /dev/null +++ b/views/error.ejs @@ -0,0 +1,3 @@ +
<%= error.stack %>diff --git a/views/index.ejs b/views/index.ejs new file mode 100644 index 0000000..7b7a1d6 --- /dev/null +++ b/views/index.ejs @@ -0,0 +1,11 @@ + + + +
Welcome to <%= title %>
+ +