add auth and login and register routes

This commit is contained in:
Shannon Sterz 2016-02-23 17:47:54 +01:00
parent 11ec0315b9
commit 19d3350f90

View file

@ -1,11 +1,21 @@
var express = require('express');
var router = express.Router();
var jwt = require('express-jwt');
var passport = require('passport');
var arcom = new require('../ar-com');
var RCDB = new require('../models/rc_db');
var rc_db = new RCDB();
var config = require('../config');
var models = new require('../models');
var auth = jwt({secret: config.crypto_secret, userProperty: 'payload'});
var router = express.Router();
// Database models
var rc_db = new models.RCDB();
var users = new models.Users();
// Arduino communications
var arduino = new arcom.Arduino();
var rc = new arcom.RC(arduino);
// Get arduino ready
arduino.setup();
/* GET home page. */
@ -13,7 +23,12 @@ router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/getRCs', function (req, res, next) {
router.post('/sendRC', auth, function (req, res, next){
rc.send(req.body.code);
res.send(req.body);
});
router.get('/getRCs', auth, function (req, res, next) {
rc_db.findAll(function (error, results, fields) {
if(error){ console.log(error); return(next); }
res.json(results);
@ -21,14 +36,37 @@ router.get('/getRCs', function (req, res, next) {
});
router.post('/register', function (req, res, next){
rc.send(req.body.code);
res.send(req.body);
});
router.get('/irTest', function (req, res) {
router.get('/irTest', auth, function (req, res) {
arduino.write(new Buffer('X0' + String.fromCharCode(4) + String.fromCharCode(12) + String.fromCharCode(0)+String.fromCharCode(0)+String.fromCharCode(2689 / 256) + String.fromCharCode(2689 % 256),'ascii'));
res.send('switch light');
});
// Authentication
router.post('/register', auth, function(req, res, next){
if(!req.body.username || !req.body.password){
return res.status(400).json({message: 'Please fill out all fields.'});
}
users.add(req.body.username, req.body.password, function (error, result){
if(error){ return next(error); }
return res.send('success');
});
});
router.post('/login', function(req, res, next){
if(!req.body.username || !req.body.password){
return res.status(400).json({message: 'Please fill out all fields'});
}
passport.authenticate('local', function(error, result, info){
if(error){ return next(error); }
if(result){
return res.json({token: users.generateJWT(result.id, result.name)});
} else {
return res.status(401).json(info);
}
})(req, res, next);
});
module.exports = router;