const express = require("express"); const DBUtils = require('../../Utils/DBUtil'); const Config = require('../../Config/Config'); const AuthUtil = require('../../Utils/AuthUtil'); // Logger const Logger = require('../../Utils/Logger'); const TAG = '[FrameViewerRouter]' const router = express.Router(); router.use((req, res, next) => { Logger.debug(TAG, 'Auth middleware'); const token = req.get('token'); Logger.debug(TAG, `Params ${JSON.stringify(req.params)}`) const frameId = req.params.frameId; if (!token) { res.status(403).json({ message: 'Invalid access token' }); } else { next(); } }); router.get('/frame/:frameId', (req, res) => { Logger.debug(TAG, 'GET: /frame/:frameId'); const token = req.get('token'); const frameId = req.params.frameId; DBUtils.Models.Frame.findOne({ _id: frameId }, (err, doc) => { if (err) { res.status(400).json({ message: err.message }); return; } else if (!doc) { res.status(400).json({ message: 'Unable to find a Frame with id: ' + frameId }); return; } if(doc.viewerKeys.indexOf(token) == -1){ res.status(403).json({ message: 'Frame Viewer has no access to frame with id of: ' + frameId }); return; } const frame = doc.toObject(); /// lets get all images ids... DBUtils.Models.Photo.find({ frame_id: frameId }) .populate('user') .exec((err, docs) => { if (err) { res.status(400).json({ message: err.message }); return; } frame.photos = docs.map((p) => { return { photo_id: p._id, user: p.user, timestamp: p.timestamp }; }) res.json(frame); }) }); }); router.get('/frame/:frameId/photo/:photoId', (req, res) => { Logger.debug(TAG, 'GET: /frame/:frameId/photo/:photoId'); const token = req.get('token'); const photoId = req.params.photoId; const frameId = req.params.frameId; DBUtils.Models.Frame.findOne({ _id: frameId }, (err, frame) => { if (err) { res.status(500).json({ message: 'DB error' }) return; } if (frame) { if (frame.viewerKeys.indexOf(token) != -1) { req.frame = frame; DBUtils.Models.Photo.findOne({ _id: photoId }, (err, doc) => { if (err) { res.status(400).json({ message: err.message }); return; } if (doc) res.contentType(doc.contentType).send(doc.photo); else res.status(400).json({ message: 'Photo not found' }); }); } else { res.status(403).json({ message: 'Frame Viewer has no access to frame with id of: ' + frameId }); } }else{ res.status(404).json({ message: 'Unable to find frame with id of ' + frameId }); } }); }); module.exports = router;