@opengis/fastify-table
Version:
core-plugins
52 lines (51 loc) • 2.37 kB
JavaScript
import { pgClients, getAdminAccess } from "../../../../utils.js";
import accessGroup from "./access.group.js";
export default async function accessGroupPost({ pg = pgClients.client, params, user = {}, body = {}, unittest, }, reply) {
const { id } = params;
if (!user?.uid) {
return reply.status(401).send("unauthorized");
}
// restrict access - admin only
const check = await getAdminAccess({ id, user });
if (check?.message && check?.status && !unittest) {
return reply.status(check?.status).send(check?.message);
}
const { users = [], routes = [] } = body;
if (!routes?.length) {
await pg.query("delete from admin.role_access where role_id=$1", [id]);
if (!users?.length) {
return reply.status(200).send({ id, routes });
}
}
if (routes?.length) {
const routesDB = await pg
.query('select array_agg(route_id) as "routesDB" from admin.routes where enabled')
.then((el) => el.rows?.[0]?.routesDB || []);
await pg.query("delete from admin.role_access where role_id=$1;", [id]);
await Promise.all(routes
.filter((el) => !routesDB?.includes(el.path))
.map((el) => pg.query("insert into admin.routes(route_id) values($1)", [el.path])));
await Promise.all(routes
.filter((el) => /*routesDB?.includes?.(el.path) && */ el.actions)
.map((el) => pg.query("insert into admin.role_access(role_id,route_id,actions) values ($1,$2,$3)", [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 reply.status(200).send({ id, routes: rows });
}
}
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,
user,
unittest,
}, reply);
return res;
}