feat: org admin can create chapter (tenant) admins

Add POST /org/tenants/:id/admins so org admins can provision the first
login for a chapter's admin team. New chapter admins can then sign in at
/login with email + password.

- OrgService.createTenantAdmin — validates chapter belongs to org, hashes
  password, creates Admin record
- OrgController POST tenants/:id/admins endpoint
- BFF route /api/org/tenants/[id]/admins
- Add Admin form on /org/tenants/[id] page (email, password, role select)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-20 17:21:50 +05:30
parent b26a635283
commit 6bff55db64
4 changed files with 116 additions and 1 deletions
@@ -32,6 +32,15 @@ export class OrgController {
return this.orgService.getTenant(admin.organizationId, id);
}
@Post('tenants/:id/admins')
createTenantAdmin(
@CurrentOrgAdmin() admin: OrgAdminJwtPayload,
@Param('id') id: string,
@Body() body: { email: string; password: string; role?: string },
) {
return this.orgService.createTenantAdmin(admin.organizationId, id, body.email, body.password, body.role);
}
@Get('rules')
getRules(@CurrentOrgAdmin() admin: OrgAdminJwtPayload) {
return this.orgService.getRules(admin.organizationId);
+22
View File
@@ -162,4 +162,26 @@ export class OrgService {
if (!rule) throw new NotFoundException('Rule not found');
await this.prisma.orgRule.delete({ where: { id: ruleId } });
}
async createTenantAdmin(
organizationId: string,
tenantId: string,
email: string,
password: string,
role?: string,
) {
const tenant = await this.prisma.tenant.findFirst({ where: { id: tenantId, organizationId } });
if (!tenant) throw new NotFoundException('Chapter not found or does not belong to this org');
const existing = await this.prisma.admin.findUnique({
where: { tenantId_email: { tenantId, email } },
});
if (existing) throw new ConflictException('An admin with this email already exists for this chapter');
const passwordHash = await bcrypt.hash(password, 10);
return this.prisma.admin.create({
data: { tenantId, email, passwordHash, ...(role ? { role: role as any } : {}) },
select: { id: true, email: true, role: true, createdAt: true },
});
}
}
@@ -0,0 +1,21 @@
import { getApiBaseUrl, jsonResponse } from '../../../../../_lib/api';
export const dynamic = 'force-dynamic';
async function getOrgToken(): Promise<string | undefined> {
const { cookies } = await import('next/headers');
return (await cookies()).get('tower_org_token')?.value;
}
export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }): Promise<Response> {
const { id } = await params;
const token = await getOrgToken();
const body = await req.json().catch(() => ({}));
const res = await fetch(`${getApiBaseUrl()}/org/tenants/${id}/admins`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
body: JSON.stringify(body),
cache: 'no-store',
});
return jsonResponse(await res.json(), res.status);
}
+64 -1
View File
@@ -9,6 +9,10 @@ export default function OrgTenantDetailPage({ params }: { params: Promise<{ id:
const { orgAdmin, loading } = useOrgAdmin();
const router = useRouter();
const [tenant, setTenant] = useState<any>(null);
const [showAdminForm, setShowAdminForm] = useState(false);
const [adminForm, setAdminForm] = useState({ email: '', password: '', role: 'ADMIN' });
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
useEffect(() => {
if (loading) return;
@@ -19,6 +23,31 @@ export default function OrgTenantDetailPage({ params }: { params: Promise<{ id:
.catch(() => {});
}, [orgAdmin, loading, router, id]);
async function handleCreateAdmin(e: React.FormEvent) {
e.preventDefault();
setError('');
setSaving(true);
try {
const res = await fetch(`/api/org/tenants/${id}/admins`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(adminForm),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(Array.isArray(err.message) ? err.message.join(', ') : (err.message ?? 'Failed'));
}
setShowAdminForm(false);
setAdminForm({ email: '', password: '', role: 'ADMIN' });
const updated = await fetch(`/api/org/tenants/${id}`).then((r) => r.ok ? r.json() : null);
if (updated) setTenant(updated);
} catch (err) {
setError(err instanceof Error ? err.message : 'Error');
} finally {
setSaving(false);
}
}
if (loading || !orgAdmin) return <p className="text-gray-500">Loading...</p>;
if (!tenant) return <p className="text-gray-400">Chapter not found.</p>;
@@ -44,9 +73,43 @@ export default function OrgTenantDetailPage({ params }: { params: Promise<{ id:
</div>
<div className="bg-white rounded-xl border overflow-hidden">
<div className="px-5 py-4 border-b">
<div className="px-5 py-4 border-b flex items-center justify-between">
<h2 className="font-semibold">Chapter Admins</h2>
<button
onClick={() => setShowAdminForm(!showAdminForm)}
className="bg-blue-600 text-white rounded-lg px-3 py-1.5 text-sm font-medium hover:bg-blue-700"
>
Add Admin
</button>
</div>
{showAdminForm && (
<form onSubmit={(e) => void handleCreateAdmin(e)} className="p-5 border-b flex flex-col gap-3">
<div className="grid grid-cols-3 gap-3">
<div>
<label className="block text-xs font-medium mb-1">Email</label>
<input type="email" value={adminForm.email} onChange={(e) => setAdminForm({ ...adminForm, email: e.target.value })} className="w-full border rounded-lg px-3 py-2 text-sm" required />
</div>
<div>
<label className="block text-xs font-medium mb-1">Password</label>
<input type="password" value={adminForm.password} onChange={(e) => setAdminForm({ ...adminForm, password: e.target.value })} className="w-full border rounded-lg px-3 py-2 text-sm" required />
</div>
<div>
<label className="block text-xs font-medium mb-1">Role</label>
<select value={adminForm.role} onChange={(e) => setAdminForm({ ...adminForm, role: e.target.value })} className="w-full border rounded-lg px-3 py-2 text-sm">
<option value="OWNER">OWNER</option>
<option value="ADMIN">ADMIN</option>
<option value="VIEWER">VIEWER</option>
</select>
</div>
</div>
{error && <p className="text-red-600 text-sm">{error}</p>}
<div className="flex gap-2">
<button type="submit" disabled={saving} className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-medium hover:bg-blue-700 disabled:opacity-50">{saving ? 'Saving...' : 'Create'}</button>
<button type="button" onClick={() => { setShowAdminForm(false); setError(''); }} className="border rounded-lg px-4 py-2 text-sm hover:bg-gray-50">Cancel</button>
</div>
</form>
)}
<table className="w-full text-sm">
<thead className="bg-gray-50 text-left">
<tr>