Advertisement
Guest User

Untitled

a guest
Jul 21st, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.25 KB | None | 0 0
  1.  
  2. import {Router} from 'express';
  3. import models from '../models/index';
  4. import Promise from 'bluebird';
  5. import Helper from './helpers';
  6. import uuid from 'uuid';
  7. import reactCookie from 'react-cookie';
  8. import * as email from './emails';
  9.  
  10. // Initial verison of error handler.
  11. // Helper.errorHandler is slightly modified!
  12. function errorHandler(err, req, res, next) {
  13. console.log('error object:', err);
  14. if (err) { res.send({message: 'errors found!', error: err}) }
  15. }
  16.  
  17. var app = Router();
  18.  
  19. //////////////////////////
  20. // CREATE
  21. //////////////////////////
  22.  
  23. // Create a new Account
  24. app.post('/', function (req, res, next) {
  25. return models.Email
  26. .create({
  27. emailAddress: req.body.email,
  28. isPrimary: true,
  29. // update AccountId if no errors are caught
  30. })
  31. .catch(err => {
  32. Helper.handleCatchError(err, res);
  33. })
  34. .then(email => {
  35. return models.Account.create({
  36. firstName: req.body.firstName,
  37. lastName: req.body.lastName,
  38. phoneNumber: req.body.phoneNumber,
  39. username: req.body.username,
  40. password: req.body.password
  41. })
  42. .catch(err => {
  43. Helper.handleCatchError(err, res);
  44. })
  45. .then(account => {
  46. return models.Email
  47. .update({
  48. AccountId: account.dataValues.id
  49. },
  50. {
  51. where: {
  52. id: email.dataValues.id
  53. }
  54. })
  55. .catch(err => {
  56. Helper.handleCatchError(err, res);
  57. })
  58. .then(updatedEmail => {
  59. return models.Address
  60. .create({
  61. addressLine1: req.body.addressLine1,
  62. addressLine2: req.body.addressLine2,
  63. city: req.body.city,
  64. province: req.body.province,
  65. region: req.body.region,
  66. postalCode: req.body.postalCode,
  67. country: req.body.country,
  68. AccountId: account.dataValues.id,
  69. isShipping: true
  70. })
  71. .catch(err => {
  72. Helper.handleCatchError(err, res);
  73. })
  74. .then(address => {
  75. models.Feed
  76. .create({
  77. AccountId: account.dataValues.id
  78. })
  79. .then(feed => {
  80. req.session.userId = account.dataValues.id;
  81. req.session.email = email.dataValues.emailAddress
  82. req.session.save();
  83. res.send({
  84. userId: req.session.userId,
  85. firstName: account.dataValues.firstName,
  86. lastName: account.dataValues.lastName,
  87. email: req.session.email
  88. })
  89. })
  90. })
  91. })
  92. })
  93. })
  94. })
  95.  
  96. // add new email
  97. app.post('/email/new', function (req, res, next) {
  98. email.createEmail(req, res, next)
  99. })
  100.  
  101. /////////////////////////////////////////////
  102. // Internal use only!
  103. /////////////////////////////////////////////
  104.  
  105. // Create fields in interests table by user id
  106. app.post('/interests/create', function (req, res, next) {
  107. Helper.createInterests(req, res, next);
  108. })
  109.  
  110. //////////////////////////
  111. // READ / FIND
  112. //////////////////////////
  113. // Read/Find one user via :id
  114. app.get('/user/:email/:username', function (req, res, next) {
  115. models.Account
  116. .find({
  117. where: {
  118. id: Number(req.params.id),
  119. username: req.params.username
  120. }
  121. }) // convert req.params.id to integer
  122. .catch(function (err) {
  123. Helper.handleCatchError(err, res);
  124. })
  125. .then(function (account) {
  126. var results = {}
  127. if (account) {
  128. results.account = account.dataValues
  129. models.Address
  130. .find({
  131. where: {
  132. id: Number(req.params.id),
  133. username: req.params.username
  134. }
  135. })
  136. .catch(function (err) {
  137. errorHandler(err.errors, req, res, next);
  138. })
  139. .then(function (address) {
  140. if (address) {
  141. results.address = address.dataValues
  142. res.send(results);
  143. }
  144. })
  145. }
  146. })
  147. })
  148.  
  149. // find all user's email
  150. app.get('/emails/:id', function (req, res, next) {
  151. email.findEmails(req, res, next);
  152. })
  153.  
  154. // find one user by email
  155. app.get('/user/:email', function (req, res, next) {
  156. console.log("attempting to find an email: ");
  157. console.log(req.params);
  158. models.Email
  159. .find({
  160. where: {
  161. emailAddress: req.params.email
  162. },
  163. include: [{
  164. model: models.Account,
  165. required: true
  166. }]
  167. })
  168. .then(email => {
  169. console.log('# # # REQ SESSION # # #');
  170. // Create UUID for sessions
  171. // add to req.session.id
  172. // send to client cookie
  173. // check if UUID already exists from Redis
  174. // req.session.userSessionId = uuid.v4();
  175. req.session.userId = email.dataValues.Account.dataValues.id;
  176. req.session.email = email.dataValues.emailAddress
  177. req.session.save();
  178. reactCookie.setRawCookie(req.headers.cookie);
  179. console.log(req.session);
  180. console.log(req.session.id)
  181. console.log(' ');
  182. console.log('-== ReQ headers ==-');
  183. console.log(' ');
  184. console.log(req.headers)
  185. console.log(' ');console.log(' ');
  186. console.log('--- res cookie ---');
  187. console.log(' ');console.log(' ');
  188. // // console.log (req.session.blah);
  189. // res.setHeader('SetCookie', req.session.id)
  190. // res.setHeader('Set-Cookie', req.session.id.toString())
  191. res.cookie('sessIdResCookie', req.session.id.toString());
  192. console.log(res.cookie);
  193. // console.log(res);
  194. res.send({
  195. sessionId: req.session.id,
  196. userId: req.session.userId,
  197. email: req.session.email
  198. })
  199. })
  200. })
  201.  
  202. // LOGIN : Read/Find one user by id and username or email then check password
  203.  
  204. app.post('/login/', function (req, res, next) {
  205. mdoels.Email
  206. .find({
  207. where: {
  208. emailAddress: req.body.email
  209. }
  210. })
  211. .catch(function (err) {
  212. Helper.handleCatchError(err, res);
  213. })
  214. .then(email => {
  215. models.Account
  216. .find({
  217. where: {
  218. id: email.dataValues.AccountId,
  219. password: req.body.password
  220. }
  221. })
  222. .catch(function (err) {
  223. Helper.handleCatchError(err, res);
  224. })
  225. .then(function (account) {
  226. res.send({
  227. userDetails: {
  228. message: "Logged in as: ",
  229. userId: account.dataValues.id,
  230. firstName: account.dataValues.firstName,
  231. lastName: account.dataValues.lastName,
  232. email: email.dataValues.emailAddress
  233. }
  234. })
  235. })
  236. })
  237. })
  238.  
  239. // LOGOUT
  240. app.post('/logout', function(req, res, next){
  241. return req.session.destroy();
  242. if(req.session){
  243. console.log(req.session)
  244. } else {
  245. console.log("the session has been deleted!");
  246. }
  247. res.json({'msg':'You have been logged out!'});
  248. });
  249.  
  250. //////////////////////////
  251. // UPDATE
  252. //////////////////////////
  253.  
  254. // Update one account's email, phone number, or password all at once
  255. // ### ? ? ? How to update multiple columns at once if one or more inputs are null ? ? ? ###
  256. // The solution below is not optimized
  257. app.post('/update/:id/:username', function (req, res, next) {
  258. console.log({message: 'attempting to update one account with:', body: req.body, params: req.params, trimmedSpace: req.body.email.replace(/\s+/g, '')});
  259. var data = {},
  260. response = {};
  261.  
  262. for (var [key, val] of Object.entries(req.body)) {
  263. if (req.body.hasOwnProperty(key)) {
  264. if (val === null || val.replace(/\s+/g, '') === '') {
  265. data[key] = null;
  266. }
  267. else {
  268. data[key] = val;
  269. }
  270. }
  271. console.log('here is the updated data object: ', data);
  272. }
  273.  
  274. // console.log(typeof Helper);
  275. // console.log(typeof Helper.updateEmail);
  276. if (data.email !== null) {
  277. Helper.updateEmail(res, Number(req.params.id), req.params.username, data)
  278. }
  279. if (data.alias !== null) {
  280. Helper.updateAlias(res, Number(req.params.id), req.params.username, data)
  281. }
  282. if (data.phoneNumber !== null) {
  283. Helper.updatePhoneNumber(res, Number(req.params.id), req.params.username, data)
  284. }
  285. })
  286.  
  287. // update email address name
  288. app.post('/email/update', function (req, res, next) {
  289. email.updateEmail(req, res, next);
  290. })
  291.  
  292. // update primary email
  293. app.post('/email/primary', function (req, res, next) {
  294. email.updatePrimaryEmail(req, res, next);
  295. })
  296.  
  297. // update blog boost status
  298. // * * * PENDING UNTIL PAY IS IMPLEMENTED * * *
  299.  
  300. //////////////////////////
  301. // DELETE
  302. //////////////////////////
  303.  
  304. // Delete One
  305.  
  306. // retrieve a single Account
  307. // router.get('/:id', function(req,res){
  308. // models.Account.find({
  309. // where: {
  310. // id: req.params.id
  311. // }
  312. // }).then(function(account){
  313. // res.json(account);
  314. // });
  315. // });
  316.  
  317.  
  318. // // applying middleware to all routes defined in this router
  319. // router.use(function(req,res,next){
  320. // // do something
  321. // });
  322.  
  323. export default app;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement