DTP Base provides a scalable and secure Node.js application development harness ready for production service.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

97 lines
2.4 KiB

// admin/user.js
// Copyright (C) 2024 Digital Telepresence, LLC
// All Rights Reserved
'use strict';
import express from 'express';
import { SiteController, SiteError } from '../../../lib/site-lib.js';
export default class UserAdminController extends SiteController {
static get name ( ) { return 'UserAdminController'; }
static get slug ( ) { return 'admin'; }
constructor (dtp) {
super(dtp, UserAdminController);
}
async start ( ) {
const router = express.Router();
router.param('userId', this.populateUserId.bind(this));
router.post(
'/:userId',
this.postUserUpdate.bind(this),
);
router.get(
'/:userId',
this.getUserView.bind(this),
);
router.get(
'/',
this.getDashboard.bind(this),
);
return router;
}
async populateUserId (req, res, next, userId) {
const { user: userService } = this.dtp.services;
try {
res.locals.userAccount = await userService.getUserAccount(userId);
if (!res.locals.userAccount) {
throw new SiteError(404, 'User not found');
}
return next();
} catch (error) {
this.log.error('failed to populate user account', { userId, error });
return next(error);
}
}
async postUserUpdate (req, res, next) {
const { user: userService } = this.dtp.services;
try {
switch (req.body.action) {
case 'update':
await userService.updateForAdmin(res.locals.userAccount, req.body);
break;
case 'ban':
if (res.locals.userAccount._id.equals(req.user._id)) {
throw new SiteError(400, "You can't ban yourself");
}
await userService.banUser(res.locals.userAccount);
break;
}
res.redirect(`/admin/user`);
} catch (error) {
this.log.error('failed to update user', { error });
return next(error);
}
}
async getUserView (req, res) {
res.render('admin/user/view');
}
async getDashboard (req, res, next) {
const { user: userService } = this.dtp.services;
try {
res.locals.currentView = 'admin';
res.locals.adminView = 'user';
res.locals.latestSignups = await userService.getLatestSignups(10);
res.render('admin/user/dashboard');
} catch (error) {
this.error.log('failed to present the admin dashboard', { error });
return next(error);
}
}
}