@opengis/admin
Version:
This project Softpro Admin
55 lines (40 loc) • 2.21 kB
JavaScript
import { pgClients } from '@opengis/fastify-table/utils.js';
import { getAdminAccess } from '../../../../utils.js';
import accessGroup from './access.group.js';
export default async function accessGroupPost({
pg = pgClients.client, params = {}, session = {}, body = {},
}) {
const { id } = params;
const { user } = session?.passport || {};
if (!user) return { status: 403, message: 'access restricted' }
// restrict access - admin only
const check = await getAdminAccess({ id, user });
if (check) return check;
const { users = [], routes = [] } = body;
if (!routes?.length) {
// return { message: 'not enough params: users / routes', status: 400 };
await pg.query(`delete from admin.role_access where role_id=$1`, [id]);
if (!users?.length) {
return { message: { id, routes }, status: 200 };
}
}
if (routes?.length) {
const { routesDB = [] } = await pg.query('select array_agg(route_id) as "routesDB" from admin.routes where enabled')
.then((res1) => res1.rows?.[0] || {});
await pg.query(`delete from admin.role_access where role_id=$1;`, [id]);
const q = `insert into admin.role_access(role_id,route_id,actions) values ($1,$2,$3)`;
await Promise.all(routes.filter(el => routesDB.includes(el.path) && el.actions).map(el => pg.query(q, [id, el.path, el.actions])))
const { rows } = await pg.query(`select a.route_id as path, b.actions as actions from admin.routes a
left join admin.role_access b on a.route_id=b.route_id
where b.role_id=$1`, [id]);
if (!users?.length) {
return { message: { id, routes: rows }, status: 200 };
}
}
const q = `delete from admin.user_roles where role_id='${id.replace(/'/g, "''")}';
insert into admin.user_roles(role_id,user_uid,access_granted)
values ${users.filter((el) => el?.id).map((el) => `('${id.replace(/'/g, "''")}','${el.id.replace(/'/g, "''")}','${user?.uid?.replace(/'/g, "''")}')`)}`;
await pg.query(q);
const res = await accessGroup({ pg, params, session });
return res;
}