From a30e4b28cd122d608b15ddbd3ffe603c068a41fb Mon Sep 17 00:00:00 2001 From: adamsaparudin Date: Thu, 2 Mar 2017 19:59:13 +0700 Subject: [PATCH] SELESAI --- .env | 0 app.js | 62 +++++++++++++++++ authentication.js | 127 +++++++++++++++++++++++++++++++++++ bin/www | 90 +++++++++++++++++++++++++ controllers/login.js | 17 +++++ db/mongo.js | 10 +++ models/user.js | 13 ++++ package.json | 28 ++++++++ public/stylesheets/style.css | 8 +++ routes/index.js | 9 +++ routes/login.js | 60 +++++++++++++++++ routes/users.js | 9 +++ views/error.jade | 6 ++ views/index.jade | 5 ++ views/layout.jade | 7 ++ 15 files changed, 451 insertions(+) create mode 100644 .env create mode 100644 app.js create mode 100644 authentication.js create mode 100755 bin/www create mode 100644 controllers/login.js create mode 100644 db/mongo.js create mode 100644 models/user.js create mode 100644 package.json create mode 100644 public/stylesheets/style.css create mode 100644 routes/index.js create mode 100644 routes/login.js create mode 100644 routes/users.js create mode 100644 views/error.jade create mode 100644 views/index.jade create mode 100644 views/layout.jade diff --git a/.env b/.env new file mode 100644 index 0000000..e69de29 diff --git a/app.js b/app.js new file mode 100644 index 0000000..5fb5a49 --- /dev/null +++ b/app.js @@ -0,0 +1,62 @@ +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'); +const passport = require('passport'); +const jwt = require('jsonwebtoken'); +const session = require('express-session'); + +var index = require('./routes/index'); +var users = require('./routes/users'); +var login = require('./routes/login') + +var app = express(); + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'jade'); + +// 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(cookieParser()); +app.use(session({ + secret: 'keyboard cat', + resave: false, + saveUninitialized: true, + cookie: { secure: true } +})) +app.use(express.static(path.join(__dirname, 'public'))); +app.use(passport.initialize()); + +let token = jwt.sign({foo: 'bar'}, 'This shit is token secret') + +app.use('/', index); +app.use('/users', users); +app.use('/login', login) + +// 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/authentication.js b/authentication.js new file mode 100644 index 0000000..be621b6 --- /dev/null +++ b/authentication.js @@ -0,0 +1,127 @@ +const passport = require('passport'); +const LocalStrategy = require('passport-local').Strategy +const FacebookStrategy = require('passport-facebook').Strategy +const TwitterStrategy = require('passport-twitter').Strategy +var GoogleStrategy = require('passport-google-oauth20').Strategy +var GitHubStrategy = require('passport-github').Strategy; + +const jwt = require('jsonwebtoken'); + +let User = require('./models/user'); + + + +passport.use(new LocalStrategy( + function(username, password, done) { + User.findOne({username: username}, function(err, user) { + if(err) {done(err)} + if(!user) {done("User not found")} + if(password !== user.password) { + done("Wrong password") + } + let token = jwt.sign({user: user}, 'ThisShitisFuckingToken') + done(null, user) + }) + } +)) + +passport.use(new FacebookStrategy({ + clientID: '190233801464815', + clientSecret: '2fed281ec8d8b6aba6a06b9d771a4c60', + callbackURL: "http://localhost:3000/login/facebook", + }, + function(accessToken, refreshToken, profile, cb) { + // console.log(profile); + User.findOne({ username: profile.displayName }, function (err, user) { + if(err) { + cb(err) + } + if(user) { + cb(null, "User already have access") + } + User.create({username: profile.displayName}, function(err) { + if(err) { + cb(err) + } + cb(null, "Success create user") + }) + }); + } +)) + +passport.use(new TwitterStrategy({ + consumerKey: 'J4ZwEVtil3OJeDAGfJaPiBfue', + consumerSecret: 'LymPrw6MzHq0gK5Q1eWxa6NCUF18I6pGrVrqFKUlSOSIWcOCXE', + callbackURL: "http://localhost:3000/login/twitter" + }, + function(accessToken, refreshToken, profile, cb) { + console.log(profile); + User.findOne({ username: profile.username }, function (err, user) { + if(err) { + cb(err) + } + if(user) { + cb(null, "User already have access") + } + User.create({username: profile.username}, function(err) { + if(err) { + cb(err) + } + cb(null, "Success create user") + }) + }); + } +)); + +passport.use(new GoogleStrategy({ + clientID: '117416411129-hkhd9phcp59vnvdfba6vv7dq17fbv459.apps.googleusercontent.com', + clientSecret: 'Pf4134WeGZZG9Qm4Phq6kw6C', + callbackURL: "http://localhost:3000/login/google/callback" + }, + function(accessToken, refreshToken, profile, cb) { + console.log(profile); + User.findOne({ username: profile.emails.value }, function (err, user) { + if(err) { + cb(err) + } + if(user) { + cb(null, "User already have access") + } + User.create({username: profile.emails.value}, function(err) { + if(err) { + cb(err) + } + cb(null, "Success create user") + }) + }); + } +)); + +passport.use(new GitHubStrategy({ + clientID: 'f67835b8b07f702a952e', + clientSecret: '13064e087deca7771a2261afd42617ef0e411eb3', + callbackURL: "http://localhost:3000/login/github/callback" + }, + function(accessToken, refreshToken, profile, cb) { + User.findOne({ username: profile.blog }, function (err, user) { + if(err) { + cb(err) + } + if(user) { + cb(null, "User already have access") + } + User.create({username: profile.blog }, function(err) { + if(err) { + cb(err) + } + cb(null, "Success create user") + }) + }); + } +)); + + + +passport.serializeUser(function(user, cb) { + cb(null, user); +}); 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/controllers/login.js b/controllers/login.js new file mode 100644 index 0000000..750fc65 --- /dev/null +++ b/controllers/login.js @@ -0,0 +1,17 @@ +let User = require('../models/user') + + +register = function(req, res, next) { + let dataInput = new User({ + username: req.body.username, + password: req.body.password + }) + dataInput.save(function(err) { + if(err) res.send(err) + else { + res.send("Data has been created") + } + }) +} + +module.exports = {register: register} diff --git a/db/mongo.js b/db/mongo.js new file mode 100644 index 0000000..82d98c5 --- /dev/null +++ b/db/mongo.js @@ -0,0 +1,10 @@ +var mongoose = require('mongoose'); +var mongoDB = 'mongodb://127.0.0.1/oauth_party_db'; +mongoose.Promise = global.Promise; +mongoose.connect(mongoDB); +var db = mongoose.connection; + +//Bind connection to error event (to get notification of connection errors) +db.on('error', console.error.bind(console, 'MongoDB connection error:')); + +module.exports = db diff --git a/models/user.js b/models/user.js new file mode 100644 index 0000000..f0feb19 --- /dev/null +++ b/models/user.js @@ -0,0 +1,13 @@ +const mongoose = require('mongoose'); +const db = require('../db/mongo'); + +let userSchema = new mongoose.Schema({ + username: {type: String, unique: true}, + password: String, +}, { + timestamps: true +}) + +let User = mongoose.model('User', userSchema) + +module.exports = User diff --git a/package.json b/package.json new file mode 100644 index 0000000..3861721 --- /dev/null +++ b/package.json @@ -0,0 +1,28 @@ +{ + "name": "api-oauth-thirdparty", + "version": "0.0.0", + "private": true, + "scripts": { + "start": "node ./bin/www" + }, + "dependencies": { + "body-parser": "~1.16.0", + "cookie-parser": "~1.4.3", + "debug": "~2.6.0", + "express": "~4.14.1", + "express-session": "^1.15.1", + "github": "^9.1.0", + "jade": "~1.11.0", + "jsonwebtoken": "^7.3.0", + "mongoose": "^4.8.5", + "morgan": "~1.7.0", + "passport": "^0.3.2", + "passport-facebook": "^2.1.1", + "passport-github": "^1.1.0", + "passport-google-oauth": "^1.0.0", + "passport-google-oauth20": "^1.0.0", + "passport-local": "^1.0.0", + "passport-twitter": "^1.0.4", + "serve-favicon": "~2.3.2" + } +} 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/index.js b/routes/index.js new file mode 100644 index 0000000..ecca96a --- /dev/null +++ b/routes/index.js @@ -0,0 +1,9 @@ +var express = require('express'); +var router = express.Router(); + +/* GET home page. */ +router.get('/', function(req, res, next) { + res.render('index', { title: 'Express' }); +}); + +module.exports = router; diff --git a/routes/login.js b/routes/login.js new file mode 100644 index 0000000..21c0382 --- /dev/null +++ b/routes/login.js @@ -0,0 +1,60 @@ +let express = require('express'); +const passport = require('passport'); +let router = express.Router(); +let userController = require('../controllers/login') +require('../authentication.js') + +/* GET home page. */ +router.get('/', function(req, res, next) { + res.send('Login you little prick') +}); + +router.post('/', passport.authenticate('local'), function(req, res, next){ + res.send("Logged In ") +}) + +router.post('/register', userController.register) + +router.get('/facebook', + passport.authenticate('facebook', { failureRedirect: '/login' }), + function(req, res) { + // Successful authentication, redirect home. + res.send('Login facebook success'); +}); + +router.get('/twitter', + passport.authenticate('twitter', { failureRedirect: '/login' }), + function(req, res) { + // Successful authentication, redirect home. + res.send('Login twitter success'); +}) + +router.get('/google', + passport.authenticate('google', { scope: + [ 'https://www.googleapis.com/auth/plus.login', + , 'https://www.googleapis.com/auth/plus.profile.emails.read' ] }, + { failureRedirect: '/login' }), + function(req, res) { + // Successful authentication, redirect home. + res.send('Login google success'); +}) + +router.get('/google/callback', + passport.authenticate('google', { failureRedirect: '/login/google' }), + function(req, res) { + // Successful authentication, redirect home. + res.send('success') + }); + +router.get('/github', + passport.authenticate('github')); + +router.get('/github/callback', +passport.authenticate('github', { failureRedirect: '/login/github' }), +function(req, res) { + // Successful authentication, redirect home. + res.send('success') +}); + + +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.jade b/views/error.jade new file mode 100644 index 0000000..51ec12c --- /dev/null +++ b/views/error.jade @@ -0,0 +1,6 @@ +extends layout + +block content + h1= message + h2= error.status + pre #{error.stack} diff --git a/views/index.jade b/views/index.jade new file mode 100644 index 0000000..3d63b9a --- /dev/null +++ b/views/index.jade @@ -0,0 +1,5 @@ +extends layout + +block content + h1= title + p Welcome to #{title} diff --git a/views/layout.jade b/views/layout.jade new file mode 100644 index 0000000..15af079 --- /dev/null +++ b/views/layout.jade @@ -0,0 +1,7 @@ +doctype html +html + head + title= title + link(rel='stylesheet', href='/stylesheets/style.css') + body + block content