users0.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. var knex = require('../db/db.js');
  2. var express = require('express');
  3. var app = new express.Router();
  4. var CryptoJS = require('crypto-js');
  5. var auth = require('../helpers/auth');
  6. var ErrorHandler = require('./error-handler.js');
  7. // /////////////////////////////////////////////////////////////////////
  8. var included = {
  9. email: 3,
  10. id: 99,
  11. // password : 2,
  12. role: 5,
  13. token: 4,
  14. username: 1
  15. };
  16. function present(user) {
  17. var res = {};
  18. for (var key in user) {
  19. if (included[key]) {
  20. res[key] = user[key];
  21. }
  22. }
  23. return res;
  24. }
  25. // /////////////////////////////////////////////////////////////////////
  26. function getUser(token) {
  27. return knex.table('users').select('*').
  28. where({ token }).
  29. then((data) => {
  30. var [user] = data;
  31. if (user === null) {
  32. throw Error('Not a valid token!');
  33. } else {
  34. return user;
  35. }
  36. });
  37. }
  38. function middleware(req, res, next) {
  39. var token = req.get('Token');
  40. if (!token || token.length < 5) {
  41. next();
  42. return true;
  43. }
  44. getUser(token).then((user) => {
  45. req.sessionUser = user;
  46. next();
  47. }).
  48. catch(() => {
  49. console.log('Session Users errors');
  50. next();
  51. });
  52. return true;
  53. }
  54. // /////////////////////////////////////////////////////////////////////
  55. app.post('/role', (req, res) => {
  56. if (!auth.isAdmin(req)) {
  57. return res.sendStatus(403);
  58. }
  59. if (!req.body.role || !req.body.id) {
  60. return res.sendStatus(404);
  61. }
  62. return knex.table('users').
  63. where({ id: req.body.id }).
  64. update({ role: req.body.role }).
  65. then((updated) => {
  66. const updates = updated;
  67. if (updates !== 1) {
  68. res.sendStatus(409);
  69. const err = { status: 409 };
  70. throw err;
  71. }
  72. }).
  73. then(() => res.send({ msg: 'OK' }));
  74. });
  75. app.post('/register', (req, res) => {
  76. if (!auth.isAdmin(req)) {
  77. return res.sendStatus(403);
  78. }
  79. var theuser = {};
  80. return knex.table('users').select('*').
  81. where({ username: req.body.username }).
  82. then((data) => {
  83. var [ndata] = data;
  84. if (typeof ndata !== 'undefined' || ndata) {
  85. res.status(409);
  86. res.send(ErrorHandler.
  87. createError('Please choose another username or login!'));
  88. throw Error('Username exists');
  89. }
  90. }).
  91. then(() => {
  92. // create salt and hash
  93. console.log(req.body);
  94. var hashFn = CryptoJS.SHA256;
  95. var salt = CryptoJS.lib.WordArray.random(128 / 8).toString();
  96. var hash = hashFn(salt + req.body.password + salt).toString();
  97. var user = {
  98. email: req.body.email,
  99. name: req.body.name,
  100. password: hash,
  101. phone: req.body.phone,
  102. salt,
  103. username: req.body.username
  104. };
  105. theuser = user;
  106. return knex.table('users').insert(user);
  107. }).
  108. // register
  109. then(() => res.send(present(theuser)));
  110. });
  111. function checkUpdateToken(user) {
  112. var hashFn = CryptoJS.SHA256;
  113. var Token = user.token;
  114. var month = new Date().getMonth();
  115. if (month > 9) {
  116. month -= 10;
  117. }
  118. if (!user.token || parseInt(user.token[user.token.length - 1], 10) !== month) {
  119. // generate token
  120. Token = hashFn(Math.random().toString() + user.salt).toString() + month;
  121. }
  122. return Token;
  123. }
  124. function checkGenerateToken(user, password) {
  125. var hashFn = CryptoJS.SHA256;
  126. var hash = hashFn(user.salt + password + user.salt).toString();
  127. if (hash === user.password) {
  128. var Token = checkUpdateToken(user);
  129. return knex.table('users').where({ id: user.id }).
  130. update('token', Token).
  131. then(() => Token);
  132. }
  133. return Promise.reject(new Error('incorrect password'));
  134. }
  135. app.post('/login', (req, res) => {
  136. if (!req.body.username || !req.body.password) {
  137. res.status(400);
  138. res.send('Missing creds');
  139. return;
  140. }
  141. var theuser = {};
  142. knex.table('users').select('*').
  143. where({ username: req.body.username }).
  144. then((users) => {
  145. var [user] = users;
  146. theuser = user;
  147. if (!user) {
  148. throw Error({ 'msg': 'No username' });
  149. }
  150. return checkGenerateToken(user, req.body.password).
  151. then((token) => {
  152. theuser.token = token;
  153. return res.send(present(theuser));
  154. });
  155. }).
  156. catch(() => {
  157. res.status(403);
  158. res.send('Bad creds');
  159. });
  160. });
  161. app.get('/me', (req, res) => {
  162. var token = req.get('Token');
  163. if (!token) {
  164. res.status(400);
  165. res.send('Need a token...');
  166. return;
  167. }
  168. knex.table('users').select('*').
  169. where({ token }).
  170. then((users) => {
  171. var [user] = users;
  172. if (user === null) {
  173. res.status(400);
  174. res.send(ErrorHandler.createError('Invalid token!'));
  175. } else {
  176. res.send(present(user));
  177. }
  178. });
  179. });
  180. app.get('/', (req, res) => {
  181. if (!auth.isAdmin(req)) {
  182. res.sendStatus(403);
  183. return false;
  184. }
  185. return knex.table('users').select('*').
  186. then((users) => res.send(users));
  187. });
  188. app.get('/logout', (req, res) => {
  189. knex.table('users').select('*').
  190. where({ token: req.get('Token') }).
  191. then((users) => {
  192. var [user] = users;
  193. if (user === null) {
  194. res.status(400);
  195. res.send(ErrorHandler.createError('Invalid token!'));
  196. } else {
  197. return knex.table('users').where({ id: user.id }).
  198. update('Token', null);
  199. }
  200. return false;
  201. }).
  202. then((data) => res.send(data));
  203. });
  204. module.exports = {
  205. App: app,
  206. GetUser: getUser,
  207. Middleware: middleware
  208. };