From 19d3350f90eda7baf9a98bbef0be6a7a0117565f Mon Sep 17 00:00:00 2001 From: Stefan Sterz Date: Tue, 23 Feb 2016 17:47:54 +0100 Subject: [PATCH] add auth and login and register routes --- nodejs/routes/index.js | 58 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 48 insertions(+), 10 deletions(-) diff --git a/nodejs/routes/index.js b/nodejs/routes/index.js index 15ca046..cf66f36 100644 --- a/nodejs/routes/index.js +++ b/nodejs/routes/index.js @@ -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;