v0.10.5 added some new permission options

This commit is contained in:
2026-03-20 20:27:44 -04:00
parent f49fd5b885
commit 241d913e0f
11 changed files with 374 additions and 7 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "jama-backend",
"version": "0.10.3",
"version": "0.10.5",
"description": "TeamChat backend server",
"main": "src/index.js",
"scripts": {

View File

@@ -240,6 +240,33 @@ async function seedEventTypes(schema) {
);
}
async function seedUserGroups(schema) {
// Seed three default user groups with their associated DM groups.
// Uses ON CONFLICT DO NOTHING so re-runs on existing installs are safe.
const defaults = ['Coaches', 'Players', 'Parents'];
for (const name of defaults) {
// Skip if a group with this name already exists
const existing = await queryOne(schema,
'SELECT id FROM user_groups WHERE name = $1', [name]
);
if (existing) continue;
// Create the managed DM chat group first
const gr = await queryResult(schema,
"INSERT INTO groups (name, type, is_readonly, is_managed) VALUES ($1, 'private', FALSE, TRUE) RETURNING id",
[name]
);
const dmGroupId = gr.rows[0].id;
// Create the user group linked to the DM group
await exec(schema,
'INSERT INTO user_groups (name, dm_group_id) VALUES ($1, $2) ON CONFLICT (name) DO NOTHING',
[name, dmGroupId]
);
console.log(`[DB:${schema}] Default user group created: ${name}`);
}
}
async function seedAdmin(schema) {
const strip = s => (s || '').replace(/^['"]+|['"]+$/g, '').trim();
const adminEmail = strip(process.env.ADMIN_EMAIL) || 'admin@jama.local';
@@ -317,6 +344,7 @@ async function initDb() {
await seedSettings('public');
await seedEventTypes('public');
await seedAdmin('public');
await seedUserGroups('public');
// Host mode: the public schema is the host's own workspace — always full JAMA-Team plan.
// ON CONFLICT DO UPDATE ensures existing installs get corrected on restart too.
@@ -391,5 +419,5 @@ module.exports = {
tenantMiddleware, resolveSchema, refreshTenantCache,
APP_TYPE, pool,
addUserToPublicGroups, getOrCreateSupportGroup,
seedSettings, seedEventTypes, seedAdmin,
seedSettings, seedEventTypes, seedAdmin, seedUserGroups,
};

View File

@@ -0,0 +1,30 @@
-- Migration 005: User-to-user DM restrictions
--
-- Stores which user groups are blocked from initiating 1-to-1 DMs with
-- users in another group. This is an allowlist-by-omission model:
-- - No rows for a group = no restrictions (can DM anyone)
-- - A row (A, B) = users in group A cannot INITIATE a DM with users in group B
--
-- Enforcement rules:
-- - Restriction is one-way (A→B does not imply B→A)
-- - Least-restrictive-wins: if the initiating user is in any group that is
-- NOT restricted from the target, the DM is allowed
-- - Own group is always exempt (users can DM members of their own groups)
-- - Admins are always exempt from all restrictions
-- - Existing DMs are preserved when a restriction is added
-- - Only 1-to-1 DMs are affected; group chats (3+ people) are always allowed
CREATE TABLE IF NOT EXISTS user_group_dm_restrictions (
restricting_group_id INTEGER NOT NULL REFERENCES user_groups(id) ON DELETE CASCADE,
blocked_group_id INTEGER NOT NULL REFERENCES user_groups(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (restricting_group_id, blocked_group_id),
-- A group cannot restrict itself (own group is always exempt)
CHECK (restricting_group_id != blocked_group_id)
);
CREATE INDEX IF NOT EXISTS idx_dm_restrictions_restricting
ON user_group_dm_restrictions(restricting_group_id);
CREATE INDEX IF NOT EXISTS idx_dm_restrictions_blocked
ON user_group_dm_restrictions(blocked_group_id);

View File

@@ -97,6 +97,46 @@ router.post('/', authMiddleware, async (req, res) => {
// Direct message
if (isDirect && memberIds?.length === 1) {
const otherUserId = memberIds[0], userId = req.user.id;
// U2U restriction check — admins always exempt
if (req.user.role !== 'admin') {
// Get all user groups the initiating user belongs to
const initiatorGroups = await query(req.schema,
'SELECT user_group_id FROM user_group_members WHERE user_id = $1', [userId]
);
const initiatorGroupIds = initiatorGroups.map(r => r.user_group_id);
// Get all user groups the target user belongs to
const targetGroups = await query(req.schema,
'SELECT user_group_id FROM user_group_members WHERE user_id = $1', [otherUserId]
);
const targetGroupIds = targetGroups.map(r => r.user_group_id);
// Least-restrictive-wins: the initiator needs at least ONE group
// that has no restriction against ALL of the target's groups.
// If initiatorGroups is empty, no restrictions apply (user not in any managed group).
if (initiatorGroupIds.length > 0 && targetGroupIds.length > 0) {
// For each initiator group, check if it is restricted from ANY of the target groups
let canDm = false;
for (const igId of initiatorGroupIds) {
const restrictions = await query(req.schema,
'SELECT blocked_group_id FROM user_group_dm_restrictions WHERE restricting_group_id = $1',
[igId]
);
const blockedIds = new Set(restrictions.map(r => r.blocked_group_id));
// This initiator group is unrestricted if none of the target's groups are blocked
const isRestricted = targetGroupIds.some(tgId => blockedIds.has(tgId));
if (!isRestricted) { canDm = true; break; }
}
if (!canDm) {
return res.status(403).json({
error: 'Direct messages with this user are not permitted.',
code: 'DM_RESTRICTED'
});
}
}
}
const existing = await queryOne(req.schema, `
SELECT g.id FROM groups g
JOIN group_members gm1 ON gm1.group_id=g.id AND gm1.user_id=$1

View File

@@ -13,7 +13,7 @@ const router = express.Router();
const {
query, queryOne, queryResult, exec,
runMigrations, ensureSchema,
seedSettings, seedEventTypes, seedAdmin,
seedSettings, seedEventTypes, seedAdmin, seedUserGroups,
refreshTenantCache,
} = require('../models/db');
@@ -123,6 +123,9 @@ router.post('/tenants', async (req, res) => {
// 3. Seed event types
await seedEventTypes(schemaName);
// 3b. Seed default user groups (Coaches, Players, Parents)
await seedUserGroups(schemaName);
// 4. Seed admin user — temporarily override env vars for this tenant
const origEmail = process.env.ADMIN_EMAIL;
const origName = process.env.ADMIN_NAME;

View File

@@ -310,5 +310,44 @@ router.delete('/:id', authMiddleware, teamManagerMiddleware, async (req, res) =>
} catch (e) { res.status(500).json({ error: e.message }); }
});
// ── U2U DM Restrictions ───────────────────────────────────────────────────────
// GET /:id/restrictions — get blocked group IDs for a user group
router.get('/:id/restrictions', authMiddleware, teamManagerMiddleware, async (req, res) => {
try {
const rows = await query(req.schema,
'SELECT blocked_group_id FROM user_group_dm_restrictions WHERE restricting_group_id = $1',
[req.params.id]
);
res.json({ blockedGroupIds: rows.map(r => r.blocked_group_id) });
} catch (e) { res.status(500).json({ error: e.message }); }
});
// PUT /:id/restrictions — replace the full restriction list for a user group
// Body: { blockedGroupIds: [id, id, ...] }
router.put('/:id/restrictions', authMiddleware, teamManagerMiddleware, async (req, res) => {
const { blockedGroupIds = [] } = req.body;
const restrictingId = parseInt(req.params.id);
try {
const ug = await queryOne(req.schema, 'SELECT id FROM user_groups WHERE id = $1', [restrictingId]);
if (!ug) return res.status(404).json({ error: 'User group not found' });
// Clear all existing restrictions for this group then insert new ones
await exec(req.schema,
'DELETE FROM user_group_dm_restrictions WHERE restricting_group_id = $1',
[restrictingId]
);
for (const blockedId of blockedGroupIds) {
if (parseInt(blockedId) === restrictingId) continue; // cannot restrict own group
await exec(req.schema,
'INSERT INTO user_group_dm_restrictions (restricting_group_id, blocked_group_id) VALUES ($1, $2) ON CONFLICT DO NOTHING',
[restrictingId, parseInt(blockedId)]
);
}
res.json({ success: true, blockedGroupIds });
} catch (e) { res.status(500).json({ error: e.message }); }
});
return router;
};

View File

@@ -13,7 +13,7 @@
# ─────────────────────────────────────────────────────────────
set -euo pipefail
VERSION="${1:-0.10.3}"
VERSION="${1:-0.10.5}"
ACTION="${2:-}"
REGISTRY="${REGISTRY:-}"
IMAGE_NAME="jama"

View File

@@ -1,6 +1,6 @@
{
"name": "jama-frontend",
"version": "0.10.3",
"version": "0.10.5",
"private": true,
"scripts": {
"dev": "vite",

View File

@@ -38,9 +38,11 @@ export default function UserProfilePopup({ user: profileUser, anchorEl, onClose,
popup.style.left = `${left}px`;
}, [anchorEl]);
const [dmError, setDmError] = useState('');
const handleDM = async () => {
if (!onDirectMessage) return;
setStarting(true);
setDmError('');
try {
const { group } = await api.createGroup({
type: 'private',
@@ -50,7 +52,11 @@ export default function UserProfilePopup({ user: profileUser, anchorEl, onClose,
onClose();
onDirectMessage(group);
} catch (e) {
console.error('DM error', e);
if (e.message?.includes('DM_RESTRICTED') || e.message?.includes('not permitted')) {
setDmError('Direct messages with this user are not permitted.');
} else {
console.error('DM error', e);
}
} finally {
setStarting(false);
}
@@ -97,7 +103,10 @@ export default function UserProfilePopup({ user: profileUser, anchorEl, onClose,
</p>
)}
{!isSelf && onDirectMessage && (
profileUser.allow_dm === 0 ? (
{dmError && (
<div style={{ fontSize:12, color:'var(--error)', padding:'4px 0', textAlign:'center' }}>{dmError}</div>
)}
{profileUser.allow_dm === 0 ? (
<p style={{
marginTop: 8,
textAlign: 'center',

View File

@@ -266,6 +266,216 @@ function DirectMessagesTab({ allUserGroups, onRefresh, refreshKey }) {
);
}
// ── U2U Restrictions tab ──────────────────────────────────────────────────────
function U2URestrictionsTab({ allUserGroups }) {
const toast = useToast();
const [selectedGroup, setSelectedGroup] = useState(null);
const [blockedIds, setBlockedIds] = useState(new Set());
const [savedBlockedIds, setSavedBlockedIds] = useState(new Set());
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [search, setSearch] = useState('');
const loadRestrictions = async (group) => {
setLoading(true);
try {
const { blockedGroupIds } = await api.getGroupRestrictions(group.id);
const blocked = new Set(blockedGroupIds.map(Number));
setBlockedIds(blocked);
setSavedBlockedIds(blocked);
} catch (e) { toast(e.message, 'error'); }
finally { setLoading(false); }
};
const selectGroup = (g) => {
setSelectedGroup(g);
setSearch('');
loadRestrictions(g);
};
const clearSelection = () => {
setSelectedGroup(null);
setBlockedIds(new Set());
setSavedBlockedIds(new Set());
};
const toggleGroup = (id) => {
setBlockedIds(prev => {
const next = new Set(prev);
next.has(id) ? next.delete(id) : next.add(id);
return next;
});
};
const handleSave = async () => {
setSaving(true);
try {
await api.setGroupRestrictions(selectedGroup.id, [...blockedIds]);
setSavedBlockedIds(new Set(blockedIds));
toast('Restrictions saved', 'success');
} catch (e) { toast(e.message, 'error'); }
finally { setSaving(false); }
};
const isDirty = [...blockedIds].some(id => !savedBlockedIds.has(id)) ||
[...savedBlockedIds].some(id => !blockedIds.has(id));
// Other groups (excluding the selected group itself)
const otherGroups = allUserGroups.filter(g => g.id !== selectedGroup?.id);
const filteredGroups = search.trim()
? otherGroups.filter(g => g.name.toLowerCase().includes(search.toLowerCase()))
: otherGroups;
return (
<div style={{ display:'flex', gap:0, height:'100%', minHeight:0 }}>
{/* Group selector sidebar */}
<div style={{ width:220, flexShrink:0, borderRight:'1px solid var(--border)', overflowY:'auto', padding:'12px 8px' }}>
<div style={{ fontSize:11, fontWeight:700, letterSpacing:'0.8px', textTransform:'uppercase', color:'var(--text-tertiary)', marginBottom:8, paddingLeft:4 }}>
Select Group
</div>
{allUserGroups.map(g => {
const hasRestrictions = g.id === selectedGroup?.id ? blockedIds.size > 0 : false;
return (
<button key={g.id} onClick={() => selectGroup(g)} style={{
display:'block', width:'100%', textAlign:'left', padding:'8px 10px',
borderRadius:'var(--radius)', border:'none',
background: selectedGroup?.id===g.id ? 'var(--primary-light)' : 'transparent',
color: selectedGroup?.id===g.id ? 'var(--primary)' : 'var(--text-primary)',
cursor:'pointer', fontWeight: selectedGroup?.id===g.id ? 600 : 400, fontSize:13, marginBottom:2,
}}>
<div style={{ display:'flex', alignItems:'center', gap:8 }}>
<div style={{ width:26, height:26, borderRadius:6, background:'var(--primary)', display:'flex', alignItems:'center', justifyContent:'center', color:'white', fontSize:9, fontWeight:700, flexShrink:0 }}>UG</div>
<div style={{ flex:1, minWidth:0 }}>
<div style={{ fontSize:13, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{g.name}</div>
<div style={{ fontSize:11, color:'var(--text-tertiary)' }}>{g.member_count} member{g.member_count!==1?'s':''}</div>
</div>
{hasRestrictions && (
<span style={{ width:8, height:8, borderRadius:'50%', background:'var(--warning)', flexShrink:0 }} title="Has restrictions" />
)}
</div>
</button>
);
})}
{allUserGroups.length === 0 && (
<div style={{ fontSize:13, color:'var(--text-tertiary)', padding:'8px 4px' }}>No user groups yet</div>
)}
</div>
{/* Restriction editor */}
<div style={{ flex:1, overflowY:'auto', padding:'16px 24px' }}>
{!selectedGroup ? (
<div style={{ display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center',
height:'100%', color:'var(--text-tertiary)', gap:12, textAlign:'center' }}>
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" opacity="0.4">
<circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/>
</svg>
<div>
<div style={{ fontSize:15, fontWeight:600, marginBottom:4 }}>Select a group</div>
<div style={{ fontSize:13 }}>Choose a user group from the left to configure its DM restrictions.</div>
</div>
</div>
) : (
<div style={{ maxWidth:540 }}>
{/* Header */}
<div style={{ marginBottom:20 }}>
<h3 style={{ fontSize:16, fontWeight:700, margin:'0 0 6px' }}>{selectedGroup.name}</h3>
<p style={{ fontSize:13, color:'var(--text-secondary)', margin:0, lineHeight:1.5 }}>
Members of <strong>{selectedGroup.name}</strong> can initiate 1-to-1 direct messages with members of all <strong>checked</strong> groups.
Unchecking a group blocks initiation existing conversations are preserved.
Admins are always exempt. If a user is in multiple groups, the least restrictive rule applies.
</p>
</div>
{/* Info banner if restrictions exist */}
{blockedIds.size > 0 && (
<div style={{ padding:'10px 14px', background:'#fef3c7', border:'1px solid #fbbf24',
borderRadius:'var(--radius)', fontSize:13, color:'#92400e', marginBottom:16,
display:'flex', alignItems:'center', gap:8 }}>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
<span><strong>{blockedIds.size}</strong> group{blockedIds.size!==1?'s are':' is'} currently blocked from receiving DMs initiated by <strong>{selectedGroup.name}</strong> members.</span>
</div>
)}
{/* Search + group list */}
<div style={{ marginBottom:12 }}>
<label className="settings-section-label" style={{ marginBottom:6, display:'block' }}>
Allowed Groups <span style={{ fontWeight:400, color:'var(--text-tertiary)' }}>({otherGroups.length - blockedIds.size} of {otherGroups.length} allowed)</span>
</label>
<input className="input" placeholder="Search groups…" value={search}
onChange={e => setSearch(e.target.value)} style={{ marginBottom:8 }}
autoComplete="new-password" />
</div>
{loading ? (
<div style={{ padding:32, textAlign:'center' }}><div className="spinner" /></div>
) : (
<div style={{ border:'1px solid var(--border)', borderRadius:'var(--radius)', overflow:'hidden', marginBottom:16 }}>
{filteredGroups.length === 0 ? (
<div style={{ padding:16, textAlign:'center', color:'var(--text-tertiary)', fontSize:13 }}>
{search ? 'No groups match your search.' : 'No other groups exist.'}
</div>
) : (
filteredGroups.map((g, i) => {
const isBlocked = blockedIds.has(g.id);
return (
<label key={g.id} style={{
display:'flex', alignItems:'center', gap:12, padding:'10px 14px',
borderBottom: i < filteredGroups.length-1 ? '1px solid var(--border)' : 'none',
cursor:'pointer', background: isBlocked ? '#fef9f0' : 'transparent',
transition:'background 0.1s',
}}>
<input type="checkbox" checked={!isBlocked}
onChange={() => toggleGroup(g.id)}
style={{ accentColor:'var(--primary)', width:16, height:16, flexShrink:0 }} />
<div style={{ flex:1, minWidth:0 }}>
<div style={{ fontSize:14, fontWeight:500, color: isBlocked ? 'var(--text-tertiary)' : 'var(--text-primary)' }}>
{g.name}
{isBlocked && <span style={{ marginLeft:8, fontSize:11, color:'var(--warning)', fontWeight:600 }}>BLOCKED</span>}
</div>
<div style={{ fontSize:12, color:'var(--text-tertiary)' }}>{g.member_count} member{g.member_count!==1?'s':''}</div>
</div>
</label>
);
})
)}
</div>
)}
{/* Quick actions */}
<div style={{ display:'flex', gap:8, marginBottom:16, flexWrap:'wrap' }}>
<button className="btn btn-secondary btn-sm"
onClick={() => setBlockedIds(new Set())}>
Allow All
</button>
<button className="btn btn-secondary btn-sm"
onClick={() => setBlockedIds(new Set(otherGroups.map(g => g.id)))}>
Block All
</button>
</div>
{/* Save */}
<div style={{ display:'flex', gap:8, alignItems:'center' }}>
<button className="btn btn-primary btn-sm" onClick={handleSave} disabled={saving || !isDirty}>
{saving ? 'Saving…' : 'Save Restrictions'}
</button>
{isDirty && (
<button className="btn btn-secondary btn-sm"
onClick={() => setBlockedIds(new Set(savedBlockedIds))}>
Discard Changes
</button>
)}
{!isDirty && !saving && (
<span style={{ fontSize:12, color:'var(--text-tertiary)' }}>No unsaved changes</span>
)}
</div>
</div>
)}
</div>
</div>
);
}
// ── Main page ─────────────────────────────────────────────────────────────────
export default function GroupManagerPage() {
const [tab, setTab] = useState('all');
@@ -291,6 +501,7 @@ export default function GroupManagerPage() {
<div style={{ display:'flex', gap:8 }}>
<button className={`btn btn-sm ${tab==='all'?'btn-primary':'btn-secondary'}`} onClick={() => setTab('all')}>User Groups</button>
<button className={`btn btn-sm ${tab==='dm'?'btn-primary':'btn-secondary'}`} onClick={() => setTab('dm')}>Multi-Group DMs</button>
<button className={`btn btn-sm ${tab==='u2u'?'btn-primary':'btn-secondary'}`} onClick={() => setTab('u2u')}>U2U Restrictions</button>
</div>
</div>
</div>
@@ -299,6 +510,7 @@ export default function GroupManagerPage() {
<div style={{ flex:1, display:'flex', overflow:'hidden' }}>
{tab==='all' && <AllGroupsTab allUsers={allUsers} onRefresh={onRefresh} />}
{tab==='dm' && <DirectMessagesTab allUserGroups={allUserGroups} onRefresh={onRefresh} refreshKey={refreshKey} />}
{tab==='u2u' && <U2URestrictionsTab allUserGroups={allUserGroups} />}
</div>
</div>
);

View File

@@ -139,11 +139,17 @@ export const api = {
getMultiGroupDms: () => req('GET', '/usergroups/multigroup'),
createMultiGroupDm: (body) => req('POST', '/usergroups/multigroup', body),
deleteMultiGroupDm: (id) => req('DELETE', `/usergroups/multigroup/${id}`),
// U2U Restrictions
getGroupRestrictions: (id) => req('GET', `/usergroups/${id}/restrictions`),
setGroupRestrictions: (id, blockedGroupIds) => req('PUT', `/usergroups/${id}/restrictions`, { blockedGroupIds }),
// Multi-group DMs
getMultiGroupDms: () => req('GET', '/usergroups/multigroup'),
createMultiGroupDm: (body) => req('POST', '/usergroups/multigroup', body),
updateMultiGroupDm: (id, body) => req('PATCH', `/usergroups/multigroup/${id}`, body),
deleteMultiGroupDm: (id) => req('DELETE', `/usergroups/multigroup/${id}`),
// U2U Restrictions
getGroupRestrictions: (id) => req('GET', `/usergroups/${id}/restrictions`),
setGroupRestrictions: (id, blockedGroupIds) => req('PUT', `/usergroups/${id}/restrictions`, { blockedGroupIds }),
uploadLogo: (file) => {
const form = new FormData(); form.append('logo', file);
return req('POST', '/settings/logo', form);