Skip to content
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 @@
SECRET_KEY=acmilan
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.DS_Store
node_modules
36 changes: 35 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,35 @@
# rest-api-auth
# Database Hacktiv8 Students
Database hacktiv8 students with basic REST API

## rest-api-crud
List of basic routes:

| **Route** | **HTTP** | **Description** |
|-----------|----------|---------------------------------------|
| / | GET | Print "Welcome to Hacktiv8 database!" |

List of user routes:

| **Route** | **HTTP** | **Description** |
|--------------------|----------|------------------------------------------------------------|
| /api/users | GET | Get all the users info (admin only) |
| /api/users/:id | GET | Get a single user info (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) |

List of user signin and signup:

| **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 |

## Usage
With only npm:
```
npm install
npm start
```
Access the website via http://localhost:3000 or API via http://localhost:3000/api/users.
Access the website via https://raynor-rest-auth.herokuapp.com
36 changes: 36 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
var express = require('express');
var bodyParser = require('body-parser');

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

var app = express();

// uncomment after placing your favicon in /public
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/', index);
app.use('/api/users', users);
app.use('/api', sign);

// 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) {
// 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-crud: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);
}
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": "postgres",
"password": "jack1899",
"database": "hacktiv8",
"host": "127.0.0.1",
"port": "5432",
"dialect": "postgres"
},
"production": {
"use_env_variable": "DATABASE_URL"
}
}
111 changes: 111 additions & 0 deletions controllers/users_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
require('dotenv').config();
const db = require('../models');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
let secret = process.env.SECRET_KEY;

function getAllUsers(req, res) {
db.Students.findAll({
order: "id ASC"
})
.then(student => res.send(student))
.catch(err => res.send(err.message));
}

function getSingleUser(req, res) {
let id = req.params.id;
db.Students.findById(id)
.then(student => res.send(student))
.catch(err => res.send(err.message));
}

function createUser(req, res) {
let hash = bcrypt.hashSync(req.body.password, 8);

db.Students.create({
name : req.body.name,
gender : req.body.gender,
age : req.body.age,
address : req.body.address,
email : req.body.email,
username : req.body.username,
password : hash,
role : req.body.role
})
.then(() => res.send(`Create user success!!`))
.catch(err => res.send(err.message));
}

function deleteUser(req, res) {
db.Students.destroy({
where : {
id : req.params.id
}
})
.then(() => res.send('Delete user success!!'))
.catch(err => res.send(err.message));
}

function updateUser(req, res) {
let hash = bcrypt.hashSync(req.body.password, 8);

db.Students.findById(req.params.id)
.then(student => {
db.Students.update({
name : req.body.name || student.name,
gender : req.body.gender || student.gender,
age : req.body.age || student.age,
address : req.body.address || student.address,
email : req.body.email || student.email,
username : req.body.username || student.username,
password : hash || student.password,
role : req.body.role || student.role
}, {
where: {
id: req.params.id
}
})
res.send(`Update user success!!`);
})
.catch(err => res.send(err.message));
}

function signUp(req, res) {
let hash = bcrypt.hashSync(req.body.password, 8);

db.Students.create({
name : req.body.name,
gender : req.body.gender,
age : req.body.age,
address : req.body.address,
email : req.body.email,
username : req.body.username,
password : hash,
role : req.body.role
})
.then(() => res.send(`Create user success!!`))
.catch(err => res.send(err.message));
}

function signIn(req, res) {
db.Students.find({
where: {
username : req.body.username
}
})
.then(user => {
bcrypt.compare(req.body.password, user.password, function(err, result) {
if(result) {
let token = jwt.sign({role: user.role, id: user.id}, secret);
res.send(token);
} else {
res.send("Wrong password..")
}
})
})
.catch(err => res.send(err.message));
}

module.exports = {
getAllUsers, getSingleUser, createUser, deleteUser, updateUser, signUp, signIn
};
39 changes: 39 additions & 0 deletions helpers/util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
require('dotenv').config();
let sec = process.env.SECRET_KEY;
var jwt = require('jsonwebtoken');

function admin(req, res, next) {
let token = req.headers.token

if(token) {
jwt.verify(token, process.env.SECRET_KEY, (err, decoded) => {
if(decoded.role == 'admin') {
next()
} else {
res.send('This route for admin only')
}
})
} else {
res.send('Please login first!')
}
}

function auth(req, res, next) {
let token = req.headers.token

if(token) {
jwt.verify(token, sec, (err, decoded) => {
if(decoded.role == 'admin' || decoded.id == req.params.id) {
next()
} else {
res.send('This route for admin and authenticated user only')
}
})
} else {
res.send('Please login first!')
}
}

module.exports = {
admin, auth
};
39 changes: 39 additions & 0 deletions migrations/20170522054555-create-students.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('Students', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
gender: {
type: Sequelize.STRING
},
age: {
type: Sequelize.INTEGER
},
address: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Students');
}
};
Loading