44 lines
1.2 KiB
JavaScript
44 lines
1.2 KiB
JavaScript
// Who the request's Saltcorn session user is, for plugin routes.
|
|
//
|
|
// Mirrors upstream isAdmin / loggedIn: on Postgres every tenant shares one
|
|
// session table and deserializeUser returns the stored user verbatim, so a
|
|
// session minted by ANOTHER tenant must count as logged out here (otherwise
|
|
// user #N or the admin of tenant A acts as user #N / admin of tenant B).
|
|
|
|
const { HTTP_STATUS } = require("./httpStatus");
|
|
|
|
// Saltcorn's built-in admin role.
|
|
const ADMIN_ROLE_ID = 1;
|
|
|
|
|
|
// req.user when it belongs to the current tenant, else null.
|
|
const tenantUser = (req) => {
|
|
const db = require("@saltcorn/data/db");
|
|
const u = req && req.user;
|
|
return u && u.tenant === db.getTenantSchema() ? u : null;
|
|
};
|
|
|
|
|
|
const isAdmin = (req) => {
|
|
const u = tenantUser(req);
|
|
return !!u && u.role_id === ADMIN_ROLE_ID;
|
|
};
|
|
|
|
|
|
// Gate for a server-rendered admin page or form POST: true for this tenant's
|
|
// admin, else a plain 403 is sent and false returned.
|
|
const requireAdmin = (req, res) => {
|
|
if (isAdmin(req)) {
|
|
return true;
|
|
}
|
|
res.status(HTTP_STATUS.FORBIDDEN).type("text/plain").send("admin only");
|
|
return false;
|
|
};
|
|
|
|
|
|
module.exports = {
|
|
ADMIN_ROLE_ID,
|
|
tenantUser,
|
|
isAdmin,
|
|
requireAdmin
|
|
};
|