Reviewed-on: #1 Co-authored-by: ChrisChrome <chris@chrischro.me> Co-committed-by: ChrisChrome <chris@chrischro.me>
40 lines
1.7 KiB
JavaScript
40 lines
1.7 KiB
JavaScript
const { ROLES, ORG_ROLES } = require('./auth');
|
|
|
|
// Creates a new default personal organization for a freshly-created user and makes them an Admin
|
|
// member of it. Used both at registration (routes/auth.js) and when a platform admin creates a user
|
|
// directly (routes/admin.js), so every user always has at least one organization to create places in.
|
|
function createDefaultOrg(db, userId, username, callback) {
|
|
db.run(`INSERT INTO organizations (name, ownerId) VALUES (?, ?)`, [`Personal (${username})`, userId], function (err) {
|
|
if (err) return callback(err);
|
|
|
|
const orgId = this.lastID;
|
|
db.run(`INSERT INTO organization_members (orgId, userId, role, invitedBy) VALUES (?, ?, ?, ?)`, [orgId, userId, ORG_ROLES.ADMIN, userId], (err) => {
|
|
if (err) return callback(err);
|
|
callback(null, orgId);
|
|
});
|
|
});
|
|
}
|
|
|
|
// Looks up the caller's effective role within an organization: their actual membership role if
|
|
// they're a member, or an Admin-level "bypass" if they're not a member but hold a platform-wide
|
|
// elevated/admin/superadmin role (mirroring the old per-place ownership bypass). Calls back with
|
|
// `{ role, isMember, bypass }`, or `{ role: null }` if the user has no access at all.
|
|
function getEffectiveOrgRole(db, orgId, user, callback) {
|
|
db.get(`SELECT role FROM organization_members WHERE orgId = ? AND userId = ?`, [orgId, user.id], (err, member) => {
|
|
if (err) return callback(err);
|
|
|
|
if (member) {
|
|
return callback(null, { role: member.role, isMember: true, bypass: false });
|
|
}
|
|
|
|
if (user.role >= ROLES.ELEVATED) {
|
|
return callback(null, { role: ORG_ROLES.ADMIN, isMember: false, bypass: true });
|
|
}
|
|
|
|
callback(null, { role: null, isMember: false, bypass: false });
|
|
});
|
|
}
|
|
|
|
module.exports = { createDefaultOrg, getEffectiveOrgRole };
|
|
|