// dashboard.js // Copyright (C) 2021 Digital Telepresence, LLC // License: Apache-2.0 'use strict'; const DTP_COMPONENT_NAME = 'dashboard'; const express = require('express'); const { SiteController, SiteError } = require('../../lib/site-lib'); class DashboardController extends SiteController { constructor (dtp) { super(dtp, DTP_COMPONENT_NAME); } async start ( ) { const { dtp } = this; const { limiter: limiterService, session: sessionService } = dtp.services; const authRequired = sessionService.authCheckMiddleware({ requireLogin: true }); const router = express.Router(); dtp.app.use('/dashboard', router); router.use(async (req, res, next) => { res.locals.currentView = DTP_COMPONENT_NAME; return next(); }); router.param('linkId', this.populateLinkId.bind(this)); router.get('/link/:linkId', limiterService.create(limiterService.config.dashboard.getLinkView), authRequired, this.getLinkView.bind(this), ); router.get('/', limiterService.create(limiterService.config.dashboard.getDashboardView), authRequired, this.getDashboardView.bind(this), ); } async populateLinkId (req, res, next, linkId) { const { link: linkService } = this.dtp.services; try { res.locals.link = await linkService.getById(linkId); if (!res.locals.link) { return next(new SiteError(404, 'Link not found')); } return next(); } catch (error) { this.log.error('failed to populate linkId', { linkId, error }); return next(error); } } async getLinkView (req, res, next) { const { dashboard: dashboardService, link: linkService } = this.dtp.services; try { res.locals.linkVisitStats = await dashboardService.getLinkVisitStats(res.locals.link); res.locals.linkCountryStats = await dashboardService.getLinkCountryStats(res.locals.link); res.locals.linkCityStats = await dashboardService.getLinkCityStats(res.locals.link); res.locals.userLinks = await linkService.getForUser(req.user); res.render('dashboard/link-analyzer'); } catch (error) { this.log.error('failed to display dashboard', { userId: req.user._id, error }); return next(error); } } async getDashboardView (req, res, next) { const { dashboard: dashboardService, link: linkService } = this.dtp.services; try { res.locals.profileVisitStats = await dashboardService.getResourceVisitStats('User', req.user._id); res.locals.linkVisitStats = await dashboardService.getUserVisitStats(req.user); res.locals.userLinks = await linkService.getForUser(req.user); res.locals.linkCountryStats = await dashboardService.getUserCountryStats(req.user); res.locals.linkCityStats = await dashboardService.getUserCityStats(req.user); res.render('dashboard/view'); } catch (error) { this.log.error('failed to display dashboard', { userId: req.user._id, error }); return next(error); } } } module.exports = async (dtp) => { let controller = new DashboardController(dtp); return controller; };