rainbox.email/src/controllers/backend/AccountBackendController.ts

66 lines
2.6 KiB
TypeScript

import Controller from "swaf/Controller";
import BackendController from "swaf/helpers/BackendController";
import {RequireAdminMiddleware, RequireAuthMiddleware} from "swaf/auth/AuthComponent";
import {Request, Response} from "express";
import User from "swaf/auth/models/User";
import {NotFoundHttpError} from "swaf/HttpError";
import Validator from "swaf/db/Validator";
import UserPasswordComponent from "swaf/auth/password/UserPasswordComponent";
import UserNameComponent from "swaf/auth/models/UserNameComponent";
export default class AccountBackendController extends Controller {
public constructor() {
super();
BackendController.registerMenuElement({
getLink: async () => Controller.route('backend-list-users'),
getDisplayString: async () => 'Users',
getDisplayIcon: async () => 'user',
});
}
public getRoutesPrefix(): string {
return '/backend/users';
}
public routes(): void {
this.get('/', this.getListUsers, 'backend-list-users', RequireAuthMiddleware, RequireAdminMiddleware);
this.get('/:user_id/change-password', this.getChangeUserPassword, 'backend-change-user-password', RequireAuthMiddleware, RequireAdminMiddleware);
this.post('/:user_id/change-password', this.postChangeUserPassword, 'backend-change-user-password', RequireAuthMiddleware, RequireAdminMiddleware);
}
protected async getListUsers(req: Request, res: Response): Promise<void> {
res.render('backend/users', {
accounts: await User.select()
.with('mainEmail')
.get(),
});
}
protected async getChangeUserPassword(req: Request, res: Response): Promise<void> {
const user = await User.getById(req.params.user_id);
if (!user) throw new NotFoundHttpError('user', req.url);
res.render('backend/users-change-password', {
user: user,
});
}
protected async postChangeUserPassword(req: Request, res: Response): Promise<void> {
const user = await User.getById(req.params.user_id);
if (!user) throw new NotFoundHttpError('user', req.url);
await Validator.validate({
'new_password': new Validator().defined(),
'new_password_confirmation': new Validator().sameAs('new_password', req.body.new_password),
}, req.body);
await user.as(UserPasswordComponent).setPassword(req.body.new_password, 'new_password');
await user.save();
req.flash('success', `New password set for ${user.as(UserNameComponent).name}`);
res.redirect(Controller.route('backend-list-users'));
}
}