· 10 years ago · Jul 20, 2016, 11:18 PM
1
2import {Router} from 'express';
3import models from '../models/index';
4import Promise from 'bluebird';
5import Helper from './helpers';
6import uuid from 'uuid';
7import reactCookie from 'react-cookie';
8import * as email from './emails';
9
10// Initial verison of error handler.
11// Helper.errorHandler is slightly modified!
12function errorHandler(err, req, res, next) {
13 console.log('error object:', err);
14 if (err) { res.send({message: 'errors found!', error: err}) }
15}
16
17var app = Router();
18
19//////////////////////////
20// CREATE
21//////////////////////////
22
23// Create a new Account
24app.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
97app.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
106app.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
114app.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
150app.get('/emails/:id', function (req, res, next) {
151 email.findEmails(req, res, next);
152})
153
154// find one user by email
155app.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
204app.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//////////////////////////
240// UPDATE
241//////////////////////////
242
243// Update one account's email, phone number, or password all at once
244// ### ? ? ? How to update multiple columns at once if one or more inputs are null ? ? ? ###
245// The solution below is not optimized
246app.post('/update/:id/:username', function (req, res, next) {
247 console.log({message: 'attempting to update one account with:', body: req.body, params: req.params, trimmedSpace: req.body.email.replace(/\s+/g, '')});
248 var data = {},
249 response = {};
250
251 for (var [key, val] of Object.entries(req.body)) {
252 if (req.body.hasOwnProperty(key)) {
253 if (val === null || val.replace(/\s+/g, '') === '') {
254 data[key] = null;
255 }
256 else {
257 data[key] = val;
258 }
259 }
260 console.log('here is the updated data object: ', data);
261 }
262
263 // console.log(typeof Helper);
264 // console.log(typeof Helper.updateEmail);
265 if (data.email !== null) {
266 Helper.updateEmail(res, Number(req.params.id), req.params.username, data)
267 }
268 if (data.alias !== null) {
269 Helper.updateAlias(res, Number(req.params.id), req.params.username, data)
270 }
271 if (data.phoneNumber !== null) {
272 Helper.updatePhoneNumber(res, Number(req.params.id), req.params.username, data)
273 }
274})
275
276// update email address name
277app.post('/email/update', function (req, res, next) {
278 email.updateEmail(req, res, next);
279})
280
281// update primary email
282app.post('/email/primary', function (req, res, next) {
283 email.updatePrimaryEmail(req, res, next);
284})
285
286// update blog boost status
287// * * * PENDING UNTIL PAY IS IMPLEMENTED * * *
288
289//////////////////////////
290// DELETE
291//////////////////////////
292
293// Delete One
294
295// retrieve a single Account
296// router.get('/:id', function(req,res){
297// models.Account.find({
298// where: {
299// id: req.params.id
300// }
301// }).then(function(account){
302// res.json(account);
303// });
304// });
305
306
307// // applying middleware to all routes defined in this router
308// router.use(function(req,res,next){
309// // do something
310// });
311
312export default app;