Advertisement
Guest User

Untitled

a guest
Jul 6th, 2018
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.27 KB | None | 0 0
  1. // =======================
  2. // get the packages we need ============
  3. // =======================
  4. var express = require('express');
  5. var bodyParser = require('body-parser');
  6. var morgan = require('morgan');
  7. var mysql = require('mysql');
  8. var fs = require('fs');
  9. var nodemailer = require('nodemailer');
  10. var jwt = require('jsonwebtoken');
  11.  
  12. var config = require('./config');
  13.  
  14. var app = express();
  15.  
  16. // =======================
  17. // configuration =========
  18. // =======================
  19. var port = process.env.PORT || 8080;
  20. app.set('superSecret', config.secret);
  21.  
  22. // use body parser so we can get info from POST and/or URL parameters
  23. app.use(bodyParser.urlencoded({
  24. extended: false
  25. }));
  26. app.use(bodyParser.json());
  27.  
  28. // use morgan to log requests to the console
  29. app.use(morgan('dev'));
  30.  
  31. //Database connection
  32. const mc = mysql.createConnection({
  33. host : config.host,
  34. user : config.user,
  35. password : config.password,
  36. database : config.database
  37. });
  38. mc.connect();
  39.  
  40. // ######### API ROUTES #########
  41.  
  42. // get an instance of the router for api routes
  43. var apiRoutes = express.Router();
  44.  
  45. // ######### PUBLIC API #########
  46.  
  47. // apply the routes to our application with the prefix /api
  48. app.use('/api', apiRoutes);
  49.  
  50. // CORSβ€Š
  51. apiRoutes.use(function (req, res, next) {
  52. res.setHeader('Access-Control-Allow-Origin', '*');
  53. res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  54. res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type, Authorization, Content-Type');
  55. res.setHeader('Access-Control-Allow-Credentials', true);
  56. next();
  57. });
  58.  
  59. // route to show a random message (GET http://localhost:8080/api/)
  60. apiRoutes.get('/', function (req, res) {
  61. res.json({
  62. message: 'Welcome to the RoomManager API!'
  63. });
  64. });
  65.  
  66. /*
  67. * /auth
  68. * username [string]
  69. * password [string]
  70. */
  71. apiRoutes.get('/auth', function (req, res, next) {
  72.  
  73. mc.query('SELECT * FROM utenti WHERE username = "' + req.query.username + '" AND password = "' + req.query.password + '"', function (error, results, fields) {
  74. if (error) throw error;
  75.  
  76. if (results.length == 0) {
  77. res.json({
  78. success: false,
  79. message: 'Autenticazione fallita. Password errata.'
  80. });
  81. } else {
  82.  
  83. // if user is found and password is right
  84. // create a token
  85. var token = jwt.sign(results[0], app.get('superSecret'), {
  86. expiresIn: 1440 // expires in 24 hours
  87. });
  88.  
  89. // return the information including token as JSON
  90. res.json({
  91. success: true,
  92. message: 'Autenticazione effettuata!',
  93. token: token
  94. });
  95. }
  96. });
  97.  
  98. });
  99.  
  100. /*
  101. * /register
  102. *
  103. * name: name of the user [string]
  104. * password: password of the user [string]
  105. * email: email of the user [string]
  106. */
  107. apiRoutes.post("/register", function (req, res) {
  108.  
  109. var userData = {
  110. "username": req.body.username,
  111. "nome": req.body.nome,
  112. "cognome": req.body.cognome,
  113. "email": req.body.email,
  114. "password": req.body.password,
  115. };
  116.  
  117. mc.query("INSERT INTO utenti (`username`, `nome`, `cognome`, `email`, `password`) VALUES ('" + userData.username + "', '" + userData.nome + "', '" + userData.cognome + "', '" + userData.email + "', '" + userData.password + "')", function (error, results, fields) {
  118. if (error) throw error;
  119. res.send(JSON.stringify({"status": 200, "message": null, "response": results}));
  120. });
  121.  
  122. });
  123.  
  124. apiRoutes.get("/aule", function(req, res) {
  125. mc.query('SELECT * FROM aule', function (error, results, fields) {
  126. if (error) throw error;
  127.  
  128. if (results.length == 0) {
  129. res.json({
  130. success: false,
  131. message: 'Aule non trovate'
  132. });
  133. } else {
  134. res.json({
  135. success: true,
  136. message: 'Aule',
  137. aule: results
  138. });
  139. }
  140. });
  141.  
  142. });
  143.  
  144. /*
  145. * /prenotazioni
  146. *
  147. * date: date of the first day of weekend [string]
  148. */
  149. apiRoutes.get("/prenotazioni", function(req, res) {
  150. mc.query('SELECT * FROM prenotazioni ORDER BY id_aula', function (error, results, fields) {
  151. if (error) throw error;
  152.  
  153. if (results.length == 0) {
  154. res.json({
  155. success: false,
  156. message: 'Prenotazioni non trovate'
  157. });
  158. } else {
  159. res.json({
  160. success: true,
  161. message: 'Aule e orari',
  162. prenotazioni: results
  163. });
  164. }
  165. });
  166.  
  167. });
  168.  
  169. // route middleware to verify a token
  170. apiRoutes.use(function (req, res, next) {
  171.  
  172. if (req.method === 'OPTIONS') {
  173. var headers = {};
  174. // IE8 does not allow domains to be specified, just the *
  175. // headers["Access-Control-Allow-Origin"] = req.headers.origin;
  176. headers["Access-Control-Allow-Origin"] = "*";
  177. headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
  178. headers["Access-Control-Allow-Credentials"] = false;
  179. headers["Access-Control-Max-Age"] = '86400'; // 24 hours
  180. headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
  181. res.writeHead(200, headers);
  182. res.end();
  183. } else {
  184.  
  185. // check header or url parameters or post parameters for token
  186. var token = req.body.token || req.query.token || req.headers['x-access-token'];
  187.  
  188. // decode token
  189. if (token) {
  190.  
  191. // verifies secret and checks exp
  192. jwt.verify(token, app.get('superSecret'), function (err, decoded) {
  193. if (err) {
  194. return res.json({
  195. success: false,
  196. message: 'Failed to authenticate token.'
  197. });
  198. } else {
  199. // if everything is good, save to request for use in other routes
  200. req.decoded = decoded;
  201. next();
  202. }
  203. });
  204.  
  205. } else {
  206. // if there is no token
  207. // return an error
  208. return res.status(403).send({
  209. success: false,
  210. message: 'No token provided.'
  211. });
  212. }
  213. }
  214. });
  215.  
  216.  
  217. // ######### API PROTECTED #########
  218.  
  219. /*
  220. * /prenota
  221. * data: date of the day [string]
  222. * orario1: start time [string]
  223. * orario2: finish time [string]
  224. * id_aula: id of the room [integer]
  225. */
  226. apiRoutes.post("/prenota", function (req, res) {
  227.  
  228. var data = req.body.data;
  229. var orario1 = req.body.orario1.substring(0, 2);
  230. var orario2 = req.body.orario2.substring(0, 2);
  231. var id_aula = req.body.id_aula;
  232. var professore = req.body.professore;
  233. var descrizione = req.body.descrizione;
  234.  
  235. mc.query('SELECT * \
  236. FROM prenotazioni \
  237. WHERE giorno="' + data + '" AND id_aula=' + id_aula + ' \
  238. AND ( \
  239. (' + orario1 + ' = SUBSTRING(orario1, 1, 2) AND ' + orario2 + ' = SUBSTRING(orario2, 1, 20)) /* stesso orario */ \
  240. OR (' + orario1 + ' > SUBSTRING(orario1, 1, 2) AND ' + orario1 + ' < SUBSTRING(orario2, 1, 2)) /* ' + orario1 + ' compreso tra orario1 e orario2 */ \
  241. OR (' + orario2 + ' > SUBSTRING(orario1, 1, 2) AND ' + orario2 + ' < SUBSTRING(orario2, 1, 2)) /* ' + orario2 + ' compreso tra orario1 e orario2 */ \
  242. OR (SUBSTRING(orario1, 1, 2) > ' + orario1 + ' AND SUBSTRING(orario1, 1, 2) < ' + orario2 + ') /* orario1 compreso tra ' + orario1 + ' e ' + orario2 + ' */ \
  243. OR (SUBSTRING(orario2, 1, 2) > ' + orario1 + ' AND SUBSTRING(orario2, 1, 2) < ' + orario2 + ') /* orario2 compreso tra ' + orario1 + ' e ' + orario2 + ' */ \
  244. );', function (error, results, fields) {
  245. if (error) throw error;
  246.  
  247. if (results.length == 0) {
  248.  
  249. mc.query("INSERT INTO `prenotazioni` (`id_aula`, `giorno`, `orario1`, `orario2`,`professore`, `descrizione`) VALUES \
  250. (" + id_aula + ", '" + data + "', '" + orario1 + "', '" + orario2 + "', '" + professore + "', '" + descrizione + "')\
  251. ;", function (error, results, fields) {
  252.  
  253. if (error) throw error;
  254.  
  255. if (results)
  256. res.send({
  257. "status": 200,
  258. "message": "Prenotazione effettuata!"
  259. });
  260. else
  261. res.send({
  262. "status": 200,
  263. "message": "Errore durante la prenotazione."
  264. });
  265. });
  266. }
  267. else {
  268. res.send({
  269. "status": 200,
  270. "message": "Questa prenotazione va in conflitto con altre prenotazioni!"
  271. });
  272. }
  273.  
  274. });
  275.  
  276. });
  277.  
  278.  
  279. // =======================
  280. // start the server ======
  281. // =======================
  282. app.listen(port);
  283. console.log('RoomManager http://localhost:' + port);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement