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

Finish #5

Open
wants to merge 2 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
15 changes: 15 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//FB
App_ID_FB = 292655984487826
FB_Secret = 6ad5027d98301df265b8306ae4fad298
Code_Token = b6886757945f93b11a69d8f5ddbcf72c

//Twitter
Consumer_Key = Cbyphqmiw7WyXIasys0IR8uIc
Application_Secret = L45wsjg1KTheDEvQ1ziOzejskZkUjARa0ltUSkQDLQ4j9095kS
User_Token = 211415643-HjOVzGJhmISapZOXPyhpszLZ7KBPfFROMsoP51SG
User_Secret = zdp2NHVoRWOKjr6qOCDlpXKPhKiCtNuPGwLBq7D7DoKT6

//Google
Callback = http://localhost:3000/login/google/callback
ID_Client = 272185450173-gu2ve3a4kdr50qjpc213bact4d19ldh0.apps.googleusercontent.com
Client_Secret = lE0q5kU_ZTAvoRcq2i1rpmMa
83 changes: 82 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,82 @@
# api-oauth-thirdparty
##**Sehati API**
#### REST API with OAuth by 3rd Party

##**REST API with OAuth**
#### List of passport-local routes:

**Route** | **HTTP** | **Description**
-------------|----------------|------------------------
/login | GET | Print: Login page
/login/local | GET | Print: Login
/login/local | POST | req.body (username & password)
/login/exit | GET | Print: Logout

#### List of passport-facebook routes:

**Route** | **HTTP** | **Description**
-------------------------|---------------|------------------------
/login/facebook | GET | Print: Login page on FB
/login/facebook/callback | GET | Print: Callback
/login/facebook | POST | Print: Page on FB
/login/facebook/exit | GET | Print: Logout

#### List of passport-twitter routes:

**Route** | **HTTP** | **Description**
-------------------------|---------------|------------------------
/login/twitter | GET | Print: Login page on Twitter
/login/twitter/callback | GET | Print: Callback
/login/twitter | POST | Print: Page on Twitter
/login/twitter/exit | GET | Print: Logout

#### List of passport-google routes:

**Route** | **HTTP** | **Description**
-------------------------|---------------|------------------------
/login/google | GET | Print: Login page on Google
/login/google/callback | GET | Print: Callback
/login/google | POST | Print: Page on Google
/login/google/exit | GET | Print: Logout


### **USAGE**
#### With only npm:

> npm init <br>
> npm install express <br>
> npm install nodemon <br>
> npm run dev <br>
> npm install jsonwebtoken <br>
> npm install password-hash <br>
> npm install --save dotenv <br>
> npm install mongoose <br>
> npm install passport passport-local <br>
> npm install passport-facebook <br>
> npm install passport-twitter <br>
> npm install express-session <br>
> npm install passport-google-oauth20

#### Mongoose (db):

> sudo service mongod start <br>
> connection @robomongo <br>
> mongo <br>
> use user <br>
> create file connection: db.js

##### **IMPORTANT**
Using passport local:
//Must first position in app.use
app.use(passport.initialize());

Correct Structure:
> 1. passport.session <br>
> 2. cookieParser <br>
> 3. session <br>
> 4. app.router

##### Special for CRUD using Token in headers (postman):
P.s. Token will get when sign in as Admin

Access the website via http://localhost:3000 or API via http://localhost:3000/login <br>
Debugger encode & decode via https://jwt.io/
55 changes: 55 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
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');
require('./auth/passportLocal')

var FacebookStrategy = require('passport-facebook').Strategy
require('./auth/passportFb')

var TwitterStrategy = require('passport-twitter').Strategy;
require('./auth/passportTwitter')

var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
require('./auth/passportGoogle')

var index = require('./routes/index');
var users = require('./routes/users');
var passports = require('./routes/passports')

require('./db')

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(favicon(path.join(__dirname, 'public', 'favicon.ico')));

app.use(passport.initialize());
app.use(session({
resave: false,
saveUninitialized: true,
secret: 'secret'
}));
app.use(passport.session());

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);
app.use('/login', passports);

module.exports = app;
33 changes: 33 additions & 0 deletions auth/passportFb.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
var passport = require('passport')
var FacebookStrategy = require('passport-facebook').Strategy
var user = require('../models/user')
require('dotenv').config()

passport.use(new FacebookStrategy({
clientID: process.env.App_ID_FB,
clientSecret: process.env.FB_Secret,
callbackURL: "http://localhost:3000/login/facebook/callback"
},

function(accessToken, refreshToken, profile, cb) {
// console.log(profile);
user.find ({ username: profile.displayName }, function(err, user) {
if (err) {
return cb(err);
}
if(user) {
cb(null, user);
} else {
user.create({username: profile.displayName}, function(err) {
if(err) {
return cb(err)
} else {
cb(null, user);
}
})
}
});
}
));

module.exports = FacebookStrategy
31 changes: 31 additions & 0 deletions auth/passportGoogle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth20').Strategy;
var user = require('../models/user')
require('dotenv').config()

passport.use(new GoogleStrategy({
consumerKey: process.env.ID_Client,
consumerSecret: process.env.Client_Secret,
clientID: process.env.ID_Client,
clientSecret: process.env.Client_Secret,
callbackURL: "http://localhost:3000/login/google/callback"
},
function(accessToken, refreshToken, profile, cb) {
user.find ({ googleId: profile.id }, function(err, user) {
if (err) {
return cb(err);
}
if(user) {
cb(null, user);
} else {
user.create({ googleId: profile.id }, function(err) {
if(err) {
return cb(err)
} else {
cb(null, user);
}
})
}
});
}
));
30 changes: 30 additions & 0 deletions auth/passportLocal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
var passport = require('passport');
var Strategy = require('passport-local').Strategy;
let user = require('../models/user')
// var passwordHash = require('password-hash');

passport.use('Isumi-Strategy', new Strategy(
function(username, password, cb) {
user.findOne({
username: username
}, function (err, user) {
return cb(null, user);
});

//Password Local Statis, example:
// if (username == 'isumi' && password == '123') {
// cb(null, {username: 'isumi'});
// } else {
// cb('Username and password not match!')
// }
}
))

passport.serializeUser(function(user, cb) {
cb(null, user);
});

passport.deserializeUser(function(id, cb) {
if (err) { return cb(err); }
cb(null, user);
});
30 changes: 30 additions & 0 deletions auth/passportTwitter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
var passport = require('passport')
var TwitterStrategy = require('passport-twitter').Strategy;
var user = require('../models/user')
// var user = require('./auth/passportTwitter')
require('dotenv').config()

passport.use(new TwitterStrategy({
consumerKey: process.env.Consumer_Key,
consumerSecret: process.env.Application_Secret,
callbackURL: "http://localhost:3000/login/twitter/callback"
},
function(token, tokenSecret, profile, cb) {
user.find ({ twitterId: profile.id }, function(err, user) {
if (err) {
return cb(err);
}
if(user) {
cb(null, user);
} else {
user.create({ twitterId: profile.id }, function(err) {
if(err) {
return cb(err)
} else {
cb(null, user);
}
})
}
});
}
));
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: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);
}
Loading