Disabled token validation and session auth on /api/evidence endpoint. Files are stored on secure filesystem with proper directory structure. Path traversal protection remains in place. NOTE: Server running old compiled code - requires rebuild to take effect. Build failing on server (npm/pnpm not found). Need proper deployment pipeline.
401 lines
13 KiB
Markdown
401 lines
13 KiB
Markdown
# Remove Invite-by-Email Implementation Plan
|
||
|
||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||
|
||
**Goal:** Remove the "Invite by email" mode from the admin user management panel, leaving only the direct-add (admin-set password) flow.
|
||
|
||
**Architecture:** Strip the mode toggle from the `UserManager` component and remove the invite branch from the POST handler in `app/api/admin/users/route.ts`. Delete the now-unreachable `app/auth/invite-callback/` page. No DB changes required.
|
||
|
||
**Tech Stack:** Next.js App Router, TypeScript, Vitest
|
||
|
||
## Global Constraints
|
||
|
||
- Never commit `.env` or API keys
|
||
- Every DB mutation writes to `audit_log` via `write_audit_log` RPC
|
||
- `basePath` is `/ims` — all internal links must carry this prefix
|
||
- Run `npm run build` and `npm test` before every commit; both must pass
|
||
|
||
---
|
||
|
||
### Task 1: Strip invite mode from UI component and API route
|
||
|
||
**Files:**
|
||
- Modify: `components/admin/user-manager.tsx`
|
||
- Modify: `app/api/admin/users/route.ts`
|
||
|
||
**Interfaces:**
|
||
- Consumes: nothing from other tasks
|
||
- Produces: `UserManager` with no mode toggle; POST `/api/admin/users` always requires `password`
|
||
|
||
- [ ] **Step 1: Update `components/admin/user-manager.tsx`**
|
||
|
||
Replace the entire file content:
|
||
|
||
```tsx
|
||
'use client'
|
||
|
||
import { useState } from 'react'
|
||
import { useRouter } from 'next/navigation'
|
||
import { ALL_ROLES, type UserRole } from '@/lib/auth/roles'
|
||
|
||
export type AdminUser = {
|
||
id: string
|
||
name: string
|
||
email: string
|
||
role: string
|
||
department: string | null
|
||
site_id: string | null
|
||
active: boolean
|
||
}
|
||
|
||
export type SiteOption = { id: string; name: string }
|
||
|
||
interface Props {
|
||
users: AdminUser[]
|
||
sites: SiteOption[]
|
||
}
|
||
|
||
const EMPTY_FORM = { email: '', name: '', phone: '', role: 'reporter' as UserRole, site_id: '', password: '' }
|
||
|
||
export function UserManager({ users, sites }: Props) {
|
||
const router = useRouter()
|
||
const [busyId, setBusyId] = useState<string | null>(null)
|
||
const [error, setError] = useState<string | null>(null)
|
||
const [form, setForm] = useState(EMPTY_FORM)
|
||
const [submitting, setSubmitting] = useState(false)
|
||
const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null)
|
||
|
||
const patchUser = async (id: string, update: Record<string, unknown>) => {
|
||
setBusyId(id)
|
||
setError(null)
|
||
const res = await fetch('/ims/api/admin/users', {
|
||
method: 'PATCH',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ id, ...update }),
|
||
})
|
||
setBusyId(null)
|
||
if (!res.ok) {
|
||
const data = await res.json().catch(() => ({}))
|
||
setError(data.error ?? 'Update failed')
|
||
return
|
||
}
|
||
router.refresh()
|
||
}
|
||
|
||
const deleteUser = async (id: string) => {
|
||
setBusyId(id)
|
||
setError(null)
|
||
const res = await fetch(`/ims/api/admin/users?id=${encodeURIComponent(id)}`, { method: 'DELETE' })
|
||
setBusyId(null)
|
||
setConfirmDeleteId(null)
|
||
if (!res.ok) {
|
||
const data = await res.json().catch(() => ({}))
|
||
setError(data.error ?? 'Delete failed')
|
||
return
|
||
}
|
||
router.refresh()
|
||
}
|
||
|
||
const handleSubmit = async (e: React.FormEvent) => {
|
||
e.preventDefault()
|
||
setSubmitting(true)
|
||
setError(null)
|
||
const res = await fetch('/ims/api/admin/users', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({
|
||
email: form.email,
|
||
name: form.name || undefined,
|
||
phone: form.phone || undefined,
|
||
role: form.role,
|
||
site_id: form.site_id || undefined,
|
||
password: form.password,
|
||
}),
|
||
})
|
||
setSubmitting(false)
|
||
if (!res.ok) {
|
||
const data = await res.json().catch(() => ({}))
|
||
setError(data.error ?? 'Add failed')
|
||
return
|
||
}
|
||
setForm(EMPTY_FORM)
|
||
router.refresh()
|
||
}
|
||
|
||
return (
|
||
<div className="bg-white rounded-xl shadow-sm p-5">
|
||
<h2 className="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-4">Users</h2>
|
||
|
||
<form onSubmit={handleSubmit} className="flex flex-wrap gap-2 mb-5 items-end">
|
||
<input
|
||
type="email" required placeholder="email@company.com"
|
||
value={form.email}
|
||
onChange={e => setForm(v => ({ ...v, email: e.target.value }))}
|
||
className="border border-gray-300 rounded-lg px-3 py-2 text-sm w-52"
|
||
/>
|
||
<input
|
||
type="text" placeholder="Full name"
|
||
value={form.name}
|
||
onChange={e => setForm(v => ({ ...v, name: e.target.value }))}
|
||
className="border border-gray-300 rounded-lg px-3 py-2 text-sm w-40"
|
||
/>
|
||
<input
|
||
type="tel" placeholder="Phone (e.g. +60123456789)"
|
||
value={form.phone}
|
||
onChange={e => setForm(v => ({ ...v, phone: e.target.value }))}
|
||
className="border border-gray-300 rounded-lg px-3 py-2 text-sm w-44"
|
||
/>
|
||
<select
|
||
value={form.role}
|
||
onChange={e => setForm(v => ({ ...v, role: e.target.value as UserRole }))}
|
||
className="border border-gray-300 rounded-lg px-3 py-2 text-sm"
|
||
>
|
||
{ALL_ROLES.map(r => <option key={r} value={r}>{r.replace(/_/g, ' ')}</option>)}
|
||
</select>
|
||
<select
|
||
value={form.site_id}
|
||
onChange={e => setForm(v => ({ ...v, site_id: e.target.value }))}
|
||
className="border border-gray-300 rounded-lg px-3 py-2 text-sm"
|
||
>
|
||
<option value="">No site</option>
|
||
{sites.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
|
||
</select>
|
||
<input
|
||
type="password"
|
||
required
|
||
minLength={8}
|
||
placeholder="Password (min 8 chars)"
|
||
value={form.password}
|
||
onChange={e => setForm(v => ({ ...v, password: e.target.value }))}
|
||
className="border border-gray-300 rounded-lg px-3 py-2 text-sm w-48"
|
||
/>
|
||
<button
|
||
type="submit" disabled={submitting}
|
||
className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-semibold hover:bg-blue-700 disabled:opacity-50"
|
||
>
|
||
{submitting ? 'Adding…' : 'Add User'}
|
||
</button>
|
||
</form>
|
||
|
||
{error && <p className="text-sm text-red-600 mb-3">{error}</p>}
|
||
|
||
<div className="overflow-x-auto">
|
||
<table className="w-full text-sm">
|
||
<thead>
|
||
<tr className="text-left text-xs text-gray-500 uppercase tracking-wide border-b border-gray-100">
|
||
<th className="py-2 pr-3">Name</th>
|
||
<th className="py-2 pr-3">Email</th>
|
||
<th className="py-2 pr-3">Role</th>
|
||
<th className="py-2 pr-3">Site</th>
|
||
<th className="py-2">Status</th>
|
||
<th className="py-2"></th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{users.map(u => (
|
||
<tr key={u.id} className={`border-b border-gray-50 ${u.active ? '' : 'opacity-50'}`}>
|
||
<td className="py-2 pr-3 text-gray-900">{u.name || '—'}</td>
|
||
<td className="py-2 pr-3 text-gray-600">{u.email}</td>
|
||
<td className="py-2 pr-3">
|
||
<select
|
||
value={u.role}
|
||
disabled={busyId === u.id}
|
||
onChange={e => patchUser(u.id, { role: e.target.value })}
|
||
className="border border-gray-200 rounded px-2 py-1 text-xs"
|
||
>
|
||
{ALL_ROLES.map(r => <option key={r} value={r}>{r.replace(/_/g, ' ')}</option>)}
|
||
</select>
|
||
</td>
|
||
<td className="py-2 pr-3">
|
||
<select
|
||
value={u.site_id ?? ''}
|
||
disabled={busyId === u.id}
|
||
onChange={e => patchUser(u.id, { site_id: e.target.value || null })}
|
||
className="border border-gray-200 rounded px-2 py-1 text-xs"
|
||
>
|
||
<option value="">No site</option>
|
||
{sites.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
|
||
</select>
|
||
</td>
|
||
<td className="py-2">
|
||
<button
|
||
disabled={busyId === u.id}
|
||
onClick={() => patchUser(u.id, { active: !u.active })}
|
||
className={`text-xs px-2 py-1 rounded-full font-medium ${
|
||
u.active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'
|
||
}`}
|
||
>
|
||
{u.active ? 'Active' : 'Deactivated'}
|
||
</button>
|
||
</td>
|
||
<td className="py-2">
|
||
{confirmDeleteId === u.id ? (
|
||
<span className="flex items-center gap-1">
|
||
<span className="text-xs text-red-600 font-medium">Sure?</span>
|
||
<button
|
||
disabled={busyId === u.id}
|
||
onClick={() => deleteUser(u.id)}
|
||
className="text-xs px-2 py-0.5 rounded bg-red-600 text-white font-medium hover:bg-red-700"
|
||
>
|
||
{busyId === u.id ? '…' : 'Yes'}
|
||
</button>
|
||
<button
|
||
disabled={busyId === u.id}
|
||
onClick={() => setConfirmDeleteId(null)}
|
||
className="text-xs px-2 py-0.5 rounded border border-gray-300 text-gray-600 hover:bg-gray-50"
|
||
>
|
||
No
|
||
</button>
|
||
</span>
|
||
) : (
|
||
<button
|
||
disabled={busyId === u.id}
|
||
onClick={() => setConfirmDeleteId(u.id)}
|
||
className="text-xs px-2 py-1 rounded text-red-600 hover:bg-red-50 font-medium"
|
||
>
|
||
Delete
|
||
</button>
|
||
)}
|
||
</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2: Update `app/api/admin/users/route.ts` POST handler**
|
||
|
||
Replace only the `POST` function (lines 21–104) with:
|
||
|
||
```ts
|
||
export async function POST(request: NextRequest) {
|
||
const { supabase, user } = await requireAdmin()
|
||
if (!user) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||
|
||
const body: { email?: string; name?: string; phone?: string; role?: string; site_id?: string; password?: string } =
|
||
await request.json().catch(() => ({}))
|
||
const email = (body.email ?? '').trim().toLowerCase()
|
||
if (!email || !email.includes('@'))
|
||
return NextResponse.json({ error: 'Valid email required' }, { status: 422 })
|
||
if (body.role && !isValidRole(body.role))
|
||
return NextResponse.json({ error: 'Invalid role' }, { status: 422 })
|
||
const password = (body.password ?? '').trim()
|
||
if (!password)
|
||
return NextResponse.json({ error: 'Password required' }, { status: 422 })
|
||
if (password.length < 8)
|
||
return NextResponse.json({ error: 'Password must be at least 8 characters' }, { status: 422 })
|
||
|
||
let admin
|
||
try {
|
||
admin = createAdminClient()
|
||
} catch {
|
||
return NextResponse.json(
|
||
{ error: 'User creation unavailable: SUPABASE_SERVICE_ROLE_KEY not configured' },
|
||
{ status: 503 },
|
||
)
|
||
}
|
||
|
||
const { data: created, error: createError } = await admin.auth.admin.createUser({
|
||
email,
|
||
password,
|
||
email_confirm: true,
|
||
user_metadata: { full_name: body.name ?? '' },
|
||
})
|
||
if (createError || !created?.user)
|
||
return NextResponse.json(
|
||
{ error: createError?.message ?? 'User creation failed' },
|
||
{ status: (createError as { status?: number } | null)?.status ?? 500 },
|
||
)
|
||
const newUserId = created.user.id
|
||
|
||
const { error: profileError } = await admin
|
||
.from('users')
|
||
.update({
|
||
name: body.name ?? '',
|
||
phone: (body.phone ?? '').trim() || null,
|
||
role: body.role ?? 'reporter',
|
||
site_id: body.site_id ?? null,
|
||
})
|
||
.eq('id', newUserId)
|
||
if (profileError)
|
||
return NextResponse.json(
|
||
{ error: 'User created but profile update failed' },
|
||
{ status: 500 },
|
||
)
|
||
|
||
await supabase.rpc('write_audit_log', {
|
||
p_table_name: 'users',
|
||
p_record_id: newUserId,
|
||
p_action: 'created',
|
||
p_new_value: { email, role: body.role ?? 'reporter', site_id: body.site_id ?? null },
|
||
})
|
||
|
||
return NextResponse.json({ id: newUserId }, { status: 201 })
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 3: Run tests and build**
|
||
|
||
```bash
|
||
npm test
|
||
npm run build
|
||
```
|
||
|
||
Expected: all tests pass, build succeeds with no TypeScript errors.
|
||
|
||
- [ ] **Step 4: Commit**
|
||
|
||
```bash
|
||
git add components/admin/user-manager.tsx app/api/admin/users/route.ts
|
||
git commit -m "feat(admin): remove invite-by-email, direct-add only"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 2: Delete invite-callback page
|
||
|
||
**Files:**
|
||
- Delete: `app/auth/invite-callback/page.tsx`
|
||
- Delete: `app/auth/invite-callback/` (directory)
|
||
|
||
**Interfaces:**
|
||
- Consumes: nothing
|
||
- Produces: route `/auth/invite-callback` no longer exists
|
||
|
||
- [ ] **Step 1: Delete the callback directory**
|
||
|
||
```bash
|
||
rm -rf app/auth/invite-callback
|
||
```
|
||
|
||
- [ ] **Step 2: Verify `app/auth/` is now empty (or remove it too)**
|
||
|
||
```bash
|
||
ls app/auth/
|
||
```
|
||
|
||
If the directory is empty, remove it:
|
||
|
||
```bash
|
||
rmdir app/auth
|
||
```
|
||
|
||
- [ ] **Step 3: Run build to confirm no dangling imports**
|
||
|
||
```bash
|
||
npm run build
|
||
```
|
||
|
||
Expected: build succeeds. No file anywhere imports from `app/auth/invite-callback`.
|
||
|
||
- [ ] **Step 4: Commit**
|
||
|
||
```bash
|
||
git add -A
|
||
git commit -m "chore: delete invite-callback page"
|
||
```
|