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

Auth Passport Fix #3

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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
30 changes: 29 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,29 @@
# auth-passport
# REST API Authentication

Demo app with Authentication REST API

## REST API

List of user routes :

| Route | HTTP | Description |
| -------------- | ------ | ---------------------------------------------------------- |
| /api/signup | POST | Sign up with new user info |
| /api/signin | POST | Sign in while get an access token based on credentials |
| /api/users | GET | Get All the user info (admin only) |
| /api/users/:id | GET | Get a single user (admin and authenticated user) |
| /api/users | POST | Create a user (admin only) |
| /api/users/:id | DELETE | Delete a user (admin only) |
| /api/users/:id | PUT | Update a user with new info (admin and authenticated user) |


## Usage

With only npm:
> npm install

> npm start

> npm run dev

Access the website via http://localhost:3000 or API via http://localhost:3000/api
48 changes: 48 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
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');
var Strategy = require('passport-local').Strategy;


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

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


app.use('/', 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')('rest-api-basic: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);
}
23 changes: 23 additions & 0 deletions config/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"development": {
"username": "dyankastutara",
"password": "12345",
"database": "db_restful_api_basic",
"host": "127.0.0.1",
"dialect": "postgres"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
118 changes: 118 additions & 0 deletions controllers/usersController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
const models = require('../models');
const passHash = require('password-hash');
const jwt = require('jsonwebtoken');


var methode = {}


methode.signup = (req, res, next)=>{
models.User.findOne({
where : {
username : req.body.username
}
})
.then ((query)=>{
if(!query){
models.User.create({
firstname : req.body.firstname,
lastname : req.body.lastname,
dateofbirth : req.body.dateofbirth,
gender : req.body.gender,
username : req.body.username,
password : passHash.generate(req.body.password),
access : req.body.access || 'user'
})
.then(()=>{
res.send('User added')
})
}else{
res.send('Username already exists')
}
})
};

methode.signin = (username, password, callback)=>{
models.User.findOne({
where :{
username : username
}
})
.then((query)=>{
if(passHash.verify(password, query.password)){
var myToken = jwt.sign({username : query.username, access : query.access}, 'secret', {expiresIn : '1h'});
callback(null,{token : myToken})
}else{
callback(null,"gagal")
}
})
}



methode.getAllData = function(req, res, next) {
models.User.findAll({})
.then((query)=>{
res.send(query)
})
};

methode.getDataById = function(req, res, next) {
models.User.findOne({
where : {
id : req.params.id
}
})
.then((query)=>{
res.send(query)
})
} ;

methode.insert = (req, res, next)=>{
models.User.create({
firstname : req.body.firstname,
lastname : req.body.lastname,
dateofbirth : req.body.dateofbirth,
gender : req.body.gender,
username : req.body.username,
password : passHash.generate(req.body.password),
access : req.body.access || 'user'
})
.then((query)=>{
res.send(query)
})
};

methode.delete = (req, res, next)=>{
models.User.destroy({
where :{
id : req.params.id
}
})
.then(()=>{
res.send("Data Deleted with id : "+req.params.id)
})
};

methode.updates = (req, res, next)=>{
models.User.update({
firstname : req.body.firstname,
lastname : req.body.lastname,
dateofbirth : req.body.dateofbirth,
gender : req.body.gender,
username : req.body.username,
password : passHash.generate(req.body.password),
access : req.body.access,
updatedAt : new Date()
},{
where : {
id : req.params.id
}
})
.then((query)=>{
res.send(query)
})
};


module.exports = methode
33 changes: 33 additions & 0 deletions helper/jwthelper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
var jwt = require('jsonwebtoken');
var methode ={}

methode.check_token = (req, res, next) =>{
jwt.verify(req.headers.token, 'secret', (err, decoded) =>{
console.log(decoded)
if(decoded){
if(decoded.access === 'admin'){
next();
}else{
res.send('You can not access')
}
}else{
res.send('tes')
}
})
}

methode.check_token_global = (req, res, next) =>{
jwt.verify(req.headers.token, 'secret', (err, decoded) =>{
if(decoded){
if(decoded.access === 'admin' || decoded.access === 'user' ){
next();
}else{
res.send('You can not access')
}
}else{
res.send('tes')
}
})
}

module.exports = methode
36 changes: 36 additions & 0 deletions migrations/20170425041834-create-user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
firstname: {
type: Sequelize.STRING
},
lastname: {
type: Sequelize.STRING
},
dateofbirth: {
type: Sequelize.DATE
},
gender: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Users');
}
};
Loading