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

REST API Basic #1

Open
wants to merge 23 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 .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
SECRETKEY=secret
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules/
.env
32 changes: 31 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,31 @@
# rest-api-auth
# rest-api-auth

# REST API

## List of basic routes:

Please register first to access all api except signup.

| Routes | HTTP | Description |
| ----- | ----- | ----- |
| https://simple-rest-api-crud.herokuapp.com/api/users | GET | Get all the users |
| https://simple-rest-api-crud.herokuapp.com/api/users/:id | GET | Get a single user |
| https://simple-rest-api-crud.herokuapp.com/api/users | POST | Create a user |
| https://simple-rest-api-crud.herokuapp.com/api/users/:id | DELETE | Delete a user |
| https://simple-rest-api-crud.herokuapp.com/api/users/:id | PUT | Update a user with new info |
| https://simple-rest-api-crud.herokuapp.com/api/signin | POST | Login to the app |
| https://simple-rest-api-crud.herokuapp.com/api/signup | POST | Register to the app |

# 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
You can access this app with this url:
https://simple-rest-api-crud.herokuapp.com/ | https://git.heroku.com/simple-rest-api-crud.git
13 changes: 13 additions & 0 deletions config/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"development": {
"username": "arahito",
"password": "arahito",
"database": "seninapibasic",
"host": "127.0.0.1",
"port": "5432",
"dialect": "postgres"
},
"production": {
"use_env_variable": "DATABASE_URL"
}
}
163 changes: 163 additions & 0 deletions controllers/userController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
const db = require('../models')
const bCrypt = require('bcrypt');
let methods = {}
const saltRounds = 10;
const jwt = require('jsonwebtoken')
require('dotenv').config()
const Sequelize = require('sequelize')
let helperDecodeToken = require('../helpers/decode_token')

methods.getAll = (req, res) => {
if (req.body.role === 'admin') {
db.User.findAll()
.then(response => {
console.log('Get all data users success');
res.json(response)
})
.catch(err => {
res.json({err})
})
} else {
res.send('You are not authorized')
}
} // getAll

methods.getById = (req, res) => {
let decoded = helperDecodeToken.decode_token(req.headers.token)
console.log('oooooo');
console.log(decoded);
if (req.body.role === 'admin' || req.body.role === 'user') {
db.User.findById(decoded.id)
.then(response => {
console.log('Get data user by id success');
res.json(response)
})
.catch(err => {
res.json({err})
})
} else {
res.send('You are not authorized')
}
} //getById

methods.insertOne = (req, res) => {
let pwd = req.body.password
let salt = bCrypt.genSaltSync(saltRounds)
let generateHash = bCrypt.hashSync(pwd, salt)

if (req.body.role === 'admin') {
db.User.create({
name: req.body.name,
username: req.body.username,
password: generateHash,
email: req.body.email
})
.then(response => {
console.log('Insert data user success');
res.json(response)
})
.catch(Sequelize.ValidationError, function (err) {
// respond with validation errors
res.send(err.message);
})
} else {
res.send('You are not authorized')
}
} // insertOne

methods.updateById = (req, res) => {
let pwd = req.body.password
let salt = bCrypt.genSaltSync(saltRounds)
let generateHash = bCrypt.hashSync(pwd, salt)

db.User.update({
name: req.body.name,
username: req.body.username,
password: generateHash,
email: req.body.email
}, {
where: {
id: req.params.id
}
})
.then(response => {
console.log('Update data user success');
res.json(response)
})
.catch(Sequelize.ValidationError, function (err) {
// respond with validation errors
res.send(err.message);
})
} // updateById

methods.deleteById = (req, res) => {
if (req.body.role === 'admin') {
db.User.destroy({
where: {
id: req.params.id
}
})
.then(response => {
console.log('Delete data user success');
res.json(response)
})
} else {
res.send('You are not authorized')
}
} //deleteById

methods.signup = (req, res) => {
let pwd = req.body.password
let salt = bCrypt.genSaltSync(saltRounds)
let generateHash = bCrypt.hashSync(pwd, salt)
db.User.create({
name: req.body.name,
username: req.body.username,
password: generateHash,
email: req.body.email
})
.then(response => {
console.log(response);
console.log('Signup data user success');
res.json(response)
})
.catch(Sequelize.ValidationError, function (err) {
// respond with validation errors
res.send(err.message);
})
} //signup

methods.signin = (req, res) => {
db.User.findOne({
where: {
username: req.body.username
}
})
.then(response => {

let pwdHash = req.body.password
console.log('Tesss');
console.log(bCrypt.compareSync(pwdHash, response.password));
if (bCrypt.compareSync(pwdHash, response.password)) {
let data = Object.assign({}, response.toJSON())
console.log(data);
delete data.password

let token = jwt.sign(data, process.env.SECRETKEY, {
expiresIn: '1h'
})
res.json({
message: 'Login is Successful',
token,
username: data.username,
role: data.role
})
} else {
res.json({
message: 'Your password is not match'
})
}
})
} //signin

module.exports = methods
18 changes: 18 additions & 0 deletions helpers/check_token.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const methods = {}
const jwt = require('jsonwebtoken')
require('dotenv').config()

methods.check_token = (req, res, next) => {
let token = req.headers.token
console.log('ini file dotenv '+process.env.SECRETKEY);
jwt.verify(token, process.env.SECRETKEY, (err, decoded) => {
if(decoded){
req.body.role = decoded.role
next()
} else {
res.json({err})
}
})
}

module.exports = methods
14 changes: 14 additions & 0 deletions helpers/decode_token.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
let methods = {}
const jwt = require('jsonwebtoken')
require('dotenv').config()

methods.decode_token = (token) => {
try {
var decoded = jwt.verify(token, process.env.SECRETKEY);
return decoded
} catch(err) {
return 'Error'
}
}

module.exports = methods
39 changes: 39 additions & 0 deletions migrations/20170522072949-create-user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
username: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
role: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Users');
}
};
36 changes: 36 additions & 0 deletions models/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';

var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];
var db = {};

if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function(file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});

Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
Loading