· 4 years ago · Jan 27, 2021, 10:46 AM
1FILE: controller/session.js
2const moment = require('moment');
3const bcrypt = require('bcryptjs');
4
5const pusher = require('../config/pusher');
6
7const Session = require('../models/Session');
8const Table = require('../models/Table');
9const Restaurant = require('../models/Restaurant');
10
11const today = moment().startOf('day');
12
13// @desc Start a session
14// @route POST /api/session/Start
15// @access Public
16// CHANGES: from frontend we need allowMultiple value to be passed here!
17exports.Start_Session = async (req, res, next) => {
18 try {
19 console.log(req.body);
20 const { restaurant, table, allowMultiple } = req.body;
21 const table_1 = await Table.findById(table);
22 const r = await Restaurant.findById(restaurant);
23 if (!r.Open_Now || !r.Authenticated) {
24 return res.status(404).json({
25 success: false,
26 msg: 'Restaurant Closed',
27 });
28 }
29 if (table_1.status === 'disabled') {
30 return res.status(400).json({
31 success: false,
32 msg: 'This QR code is disabled.',
33 });
34 }
35 const sess = await Session.findOne({
36 table: table,
37 active: true,
38 });
39 console.log(`allowMultiple: ${allowMultiple} `);
40 // for Single Session ONLY, ie if allowMultiple=false (for multiple, table.status always 'active')
41 if (!allowMultiple && sess && table_1.status === 'active') {
42 console.log(1);
43 return res.status(401).json({
44 success: false,
45 msg: 'The table is Engaged',
46 flag: -1,
47 join: sess._id, //Prompt User to Join Session by providing the Session Password
48 tableNo: table_1.tableNo,
49 Restaurant_Name: r.Name, // Prompt to set Session Password
50 verify: sess.verify,
51 Short_Address: r.Short_Address,
52 });
53 }
54
55 console.log(2);
56
57 const session = await Session.create(req.body);
58 const t = await Table.findById(table);
59 return res.status(200).json({
60 success: true,
61 data: session,
62 tableNo: t.tableNo,
63 Restaurant_Name: r.Name,
64 Short_Address: r.Short_Address, // Prompt to set Session Password
65 });
66 } catch (error) {
67 console.log(error);
68 return res.status(500).json({
69 success: false,
70 error: error,
71 });
72 }
73};
74
75// @desc Set nickname and password for a newly created session
76// @route POST /api/session/set_password/:session_id
77// @access Public
78// NOTE: as in v2, we want nickname to be unique!
79exports.Set_Session_Password = async (req, res, next) => {
80 try {
81 const { password, verify, allowMultiple } = req.body;
82 const { session_id } = req.params;
83 const salt = await bcrypt.genSalt(10);
84
85 // in case of multiple sessions, we want all nicknames to be unique!
86 if (allowMultiple) {
87 const _session = await Session.findOne({
88 verify,
89 allowMultiple: true,
90 isEnded: false,
91 });
92 // User with same nickname exists for an active session
93 // Current user should change his nickname
94 if (_session) {
95 return res.status(404).json({
96 success: false,
97 msg: `${verify} nickname is already in use! Please enter your ${verify} <lastname>`,
98 });
99 }
100 }
101
102 const encrypted_password = await bcrypt.hash(password, salt);
103
104 const session = await Session.findByIdAndUpdate(
105 session_id,
106 {
107 password: encrypted_password,
108 authentication_requested: true,
109 verify: verify,
110 Date_Ref: Date.now(),
111 },
112 {
113 new: true,
114 runValidators: true,
115 }
116 );
117 console.log(1);
118 if (!session) {
119 return res.status(404).json({
120 success: false,
121 msg: 'There seems to be some error',
122 });
123 }
124 const s = await Session.findById(session_id).populate('table');
125 pusher.trigger('session_request', s.restaurant, s);
126 return res.status(200).json({
127 success: true,
128 data: session,
129 });
130 } catch (error) {
131 return res.status(500).json({
132 success: false,
133 error: error,
134 });
135 }
136};
137
138// NOTE: Only called for single session!
139// @desc For single sessions, user wants to join his missed session via session_id and password
140// @route POST /api/session/Join_session/:session_id
141// @access Public
142exports.Join_Session = async (req, res, next) => {
143 try {
144 const { password } = req.body;
145 const { session_id } = req.params;
146 const session = await Session.findById(session_id);
147 if (!session) {
148 return res.status(404).json({
149 success: false,
150 msg: 'There seems to be some error',
151 });
152 }
153 if (!session.active) {
154 return res.status(404).json({
155 success: false,
156 msg: 'Session Already Closed!',
157 });
158 }
159 const compare = await bcrypt.compare(password, session.password);
160 if (!compare) {
161 return res
162 .status(400)
163 .json({ success: false, msg: 'Incorrect Credentials' });
164 }
165 return res.status(200).json({
166 success: true,
167 data: session,
168 });
169 } catch (error) {
170 return res.status(500).json({
171 success: false,
172 error: error,
173 });
174 }
175};
176
177// NOTE: Only called for multiple session!
178// @desc For multiple sessions, user wants to join his missed session via credentials
179// @route POST /api/session/JoinMultipleSession
180// @access Public
181exports.Join_Multiple_Session = async (req, res, next) => {
182 try {
183 // verify ~ nickname
184 const { verify, password } = req.body;
185 const session = await Session.findOne({
186 verify: verify,
187 allowMultiple: true,
188 isEnded: false,
189 });
190
191 // No session found with given nickname
192 if (!session) {
193 return res.status(404).json({
194 success: false,
195 msg: 'There seems to be some error',
196 });
197 }
198 console.log('A');
199 // Session found via nickname, but vendor closed the session
200 // User needs to create a new session
201 if (!session.active) {
202 return res.status(404).json({
203 success: false,
204 msg: 'Session Already Closed!. You need to create a new session',
205 });
206 }
207 console.log('B');
208
209 // validating user entered pwd with pwd stored in session
210 const isMatch = await bcrypt.compare(password, session.password);
211
212 // incorrect password entered by user
213 if (!isMatch) {
214 return res
215 .status(400)
216 .json({ success: false, msg: 'Incorrect Credentials' });
217 }
218
219 // Success!
220 // Session is active
221 // Credentials matched
222 // Let user enter his session
223 return res.status(200).json({
224 success: true,
225 data: session,
226 });
227 } catch (error) {
228 return res.status(500).json({
229 success: false,
230 error: error,
231 });
232 }
233};
234
235// @desc For single/multiple sessions, vendor approves the session
236// @route PUT /api/session/Authenticate_Session/:session_id/:table_id
237// @access Private
238exports.Authenticate_Session = async (req, res, next) => {
239 try {
240 const table_1 = await Table.findById(req.params.table_id);
241 if (!table_1.allowMultiple && table_1.status === 'active') {
242 console.log(2);
243 return res.status(200).json({
244 success: false,
245 msg: 'Dine-In has already begun on this Table',
246 });
247 }
248 var IndiaDate = new Date().toLocaleString('en-us', {
249 timeZone: 'Asia/Kolkata',
250 });
251 const table = await Table.findByIdAndUpdate(
252 req.params.table_id,
253 {
254 status: 'active',
255 },
256 {
257 new: true,
258 runValidators: true,
259 }
260 );
261
262 if (!table) {
263 console.log(1);
264 return res.status(404).json({
265 success: false,
266 msg: 'There seems to be some error --table',
267 });
268 }
269 console.log(new Date(IndiaDate).toLocaleString());
270 const session = await Session.findByIdAndUpdate(
271 req.params.session_id,
272 {
273 active: true,
274 authenticatedBy: req.user._id,
275 Start: new Date(IndiaDate).toLocaleString(),
276 verified: true,
277 },
278 {
279 new: true,
280 runValidators: true,
281 }
282 );
283 console.log(2);
284 if (!session) {
285 return res.status(404).json({
286 success: false,
287 msg: 'There seems to be some error',
288 });
289 }
290 pusher.trigger('confirm_session', `${session.restaurant}`, session);
291 return res.status(200).json({
292 success: true,
293 data: session,
294 });
295 } catch (error) {
296 console.log(error);
297 return res.status(500).json({
298 success: false,
299 error: error,
300 });
301 }
302};
303
304// NOTE: Needs to be changes!!!
305// @desc Inactive Session list of specific restaurant
306// @route GET /api/session/Sessions_list
307// @access Private
308exports.Session_List = async (req, res, next) => {
309 try {
310 const sessions = await Session.find({
311 restaurant: req.user.restaurant,
312 authentication_requested: true,
313 active: false,
314 verified: false,
315 }).populate('table');
316 console.log(sessions);
317 return res.status(200).json({
318 success: true,
319 data: sessions,
320 });
321 } catch (error) {
322 return res.status(500).json({
323 success: false,
324 error: error,
325 });
326 }
327};
328
329// @desc Deleting a session before approving
330// @route DELETE /api/session/Delete_Session/:session_id
331// @access Public
332exports.Delete_Session = async (req, res, next) => {
333 try {
334 const session = await Session.findByIdAndDelete(req.params.session_id);
335 if (!session) {
336 return res.status(400).json({
337 success: false,
338 msg: 'No such session exists',
339 });
340 }
341 return res.status(200).json({
342 success: true,
343 msg: 'Deleted Session',
344 });
345 } catch (error) {
346 return res.status(500).json({
347 success: false,
348 error: error,
349 });
350 }
351};
352
353// NOTE: Close Session when generating Final Bill
354// @desc daily session
355// @route GET /api/session/Daily_Active_Sessions
356// @access Private
357exports.Get_Daily_Sessions = async (req, res, next) => {
358 try {
359 const s_list = await Session.find({
360 Date_Ref: {
361 $gte: today.toDate(),
362 $lte: moment(today).endOf('day').toDate(),
363 },
364 verified: true,
365 active: true,
366 });
367 if (!s_list) {
368 return res.status(404).json({
369 success: false,
370 msg: 'Sessions Yet not started for the Day',
371 });
372 }
373 return res.status(200).json({
374 success: true,
375 data: s_list,
376 });
377 } catch (error) {
378 return res.status(500).json({
379 success: false,
380 error: error,
381 });
382 }
383};
384
385// @desc Status of a session
386// @route GET /api/session/check_status/:session_id
387// @access Public
388exports.Check_Status = async (req, res, next) => {
389 try {
390 const session = await Session.findById(req.params.session_id);
391 if (!session) {
392 return res.status(404).json({
393 success: false,
394 msg: 'There seems to be some error',
395 });
396 }
397
398 return res.status(200).json({
399 success: true,
400 data: session,
401 });
402 } catch (error) {
403 return res.status(500).json({
404 success: false,
405 error: error,
406 });
407 }
408};
409
410/* -------------------------------------------------------------------------- */
411/* NOTE USED */
412/* -------------------------------------------------------------------------- */
413
414exports.Remove_Spam_Sessions = async (req, res, next) => {
415 try {
416 const session = await Session.deleteMany({
417 authentication_requested: false,
418 restaurant: req.body.restaurant,
419 });
420 return res.status(200).json({
421 success: true,
422 msg: 'Deleted Session',
423 });
424 } catch (error) {
425 return res.status(500).json({
426 success: false,
427 error: error,
428 });
429 }
430};
431
432//To be Executed at the End of the Day to Remove any spam unverified Session Requests
433exports.Remove_unverified = async (req, res, next) => {
434 try {
435 const session = await Session.deleteMany({
436 verified: false,
437 restaurant: req.body.restaurant,
438 });
439 } catch (error) {
440 return res.status(500).json({
441 success: false,
442 error: error,
443 });
444 }
445};
446