Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Didit Suryadi #2

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
facebookClientID='
facebookClientSecret=
fabookCallbackURL='http://localhost:3000/auth/facebook/callback'

twitterConsumerKey=
twitterConsumerSecret=
twittercallbackURL=

googleClientID=
googleClientSecret=
googleCallbackURL=

githubClientID=
githubClientSecret=
githubCallbackURL=

SECRET=

17 changes: 17 additions & 0 deletions .env.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
facebookClientID=
facebookClientSecret=
facebookCallbackURL=http://localhost:3000/auth/facebook/callback

twitterConsumerKey=
twitterConsumerSecret=
twittercallbackURL=http://localhost:3000/auth/twitter/callback

googleClientID=
googleClientSecret=
googlecallbackURL=http://localhost:3000/auth/google/callback

githubClientID=
githubClientSecret=
githubCallbackURL=http://localhost:3000/auth/github/callback

secret=rahasia
64 changes: 64 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
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 mongoose = require('mongoose')
var index = require('./routes/index');
var users = require('./routes/users');
var passport = require('passport')
var session = require('express-session')
var app = express();

mongoose.connect('mongodb://localhost/otentikasi', function (err) {
if (err) throw err
console.log('database connected using mongoose')
})

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// Passport --------
app.use(session({
secret: 'rahasialoh',
key: 'sid',
resave: false,
saveUninitialized: true
}))

app.use(passport.initialize())
app.use(passport.session())
require('./config/passport')(passport)
//-----------------//
// 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(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;
90 changes: 90 additions & 0 deletions bin/www
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#!/usr/bin/env node

/**
* Module dependencies.
*/

var app = require('../app');
var debug = require('debug')('api-oauth-thirdparty-1: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);
}
146 changes: 146 additions & 0 deletions config/passport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
`use strict`
const LocalStrategy = require('passport-local').Strategy;
const FacebookStrategy = require('passport-facebook').Strategy;
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const TwitterStrategy = require('passport-twitter').Strategy;
const GitHubStrategy = require('passport-github').Strategy;
const User = require('../models/user')
const hash = require('password-hash')
require('dotenv').config()


module.exports = function (passport) {

passport.serializeUser(function(user, callback){
callback(null, user)
})

passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user)
})
})

//------------------------LocalStrategy----------------------------------------------
passport.use('didit-login', new LocalStrategy(function(usernameInput, password, cb){

User.findOne({ 'local.username': usernameInput }, function(err, data){
if (!data) {
cb(null, false)
}else{
if (hash.verify(password, data.local.password)) {
cb(null, data)
}else{
cb(null, false)
}
}

})

}))
//-------------------------END-------------------------------------------------------

//------------------------Twitter STrategy----------------------------------------------
passport.use(new TwitterStrategy({
consumerKey: process.env.twitterConsumerKey,
consumerSecret: process.env.twitterConsumerSecret,
callbackURL: process.env.twitterCallbackURL
},
function (token, tokenSecret, profile, done) {
process.nextTick(function () {
User.findOne({ 'twitter.id': profile.id }, function (err, user) {
if (err) return done(err)
if (user) { return done(null, user) } else {
User.create({
'twitter.id' : profile.id,
'twitter.token' : token,
'twitter.username' : profile.username,
'twitter.name' : profile.displayName
}, function(err,data){
if(err) throw err;
return done(null, data)
})
}
})
})
}
))

//------------------------Facebook Strategy----------------------------------------------
passport.use(new FacebookStrategy({
clientID: process.env.facebookClientID,
clientSecret: process.env.facebookClientSecret,
callbackURL: process.env.facebookCallbackURL,
profileFields: ['id', 'emails', 'displayName']
},
function (token, refreshToken, profile, done) {
process.nextTick(function () {
User.findOne({ 'facebook.id': profile.id }, function (err, user) {
if (err) return done(err)
if (user) { return done(null, user) } else {
User.create({
'facebook.id' : profile.id,
'facebook.token' : token,
'facebook.name' : profile.displayName,
'facebook.email' : profile.emails[0].value
}, function(err,data){
if(err) throw err;
return done(null, data)
})
}
})
})
}
))

//------------------------GoogleStrategy----------------------------------------------
passport.use(new GoogleStrategy({
clientID: process.env.googleClientID,
clientSecret: process.env.googleClientSecret,
callbackURL: process.env.googleCallbackURL
},
function (token, refreshToken, profile, done) {
process.nextTick(function () {
User.findOne({ 'google.id': profile.id }, function (err, user) {
if (err) return done(err)
if (user) { return done(null, user) } else {
User.create({
'google.id' : profile.id,
'google.token' : token,
'google.email' : profile.emails[0].value,
'google.name' : profile.displayName
}, function(err,data){
if(err) throw err;
return done(null, data)
})
}
})
})
}
))
//------------------------github Strategy----------------------------------------------
passport.use(new GitHubStrategy({
clientID: process.env.githubClientID,
clientSecret: process.env.githubClientSecret,
callbackURL: process.env.githubCallbackURL
},
function(token, refreshToken, profile, done) {
process.nextTick(function () {
User.findOne({ githubId: profile.id }, function (err, user) {
if (err) return done(err)
if (user) { return done(null, user) } else {
User.create({
'github.id' : profile.id,
'github.token' : token,
'github.username' : profile.username,
'github.name' : profile.displayName
}, function(err,data){
if(err) throw err;
return done(null, data)
})
}
})
})
}
))
}
34 changes: 34 additions & 0 deletions controllers/userController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
var User = require('../models/user')
var hash = require('password-hash')
var jwt = require('jsonwebtoken')
require('dotenv').config()

module.exports = {
login: function(req, res, next) {
var token = jwt.sign({ username: req.body.username }, process.env.SECRET, { expiresIn: '1d' });
res.send({ token: token })
},

register: function(req, res, next) {
User.create({
'local.username': req.body.username,
'local.password': hash.generate(req.body.password),
'local.email': req.body.email
}, function(err,data){
if(err) throw err;
res.json(data)
})
},

verify: function(req, res, next){
if (req.headers.token == 'null') {
res.json("you don't have access")
}else{
if (jwt.verify(req.headers.token, process.env.SECRET)) {
next()
}else {
res.json("token was expried")
}
}
}
}
Loading