feat(admin): remove invite-by-email, direct-add only
Strips invite-by-email mode from admin user management UI and API. POST /api/admin/users now always requires password parameter for direct user creation. Removes mode toggle, conditional password field, and invite logic branches. Simplifies user creation flow to single path. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RkCfBY9L5y3SZ6uaKZzLCV
This commit is contained in:
@@ -30,8 +30,9 @@ export async function POST(request: NextRequest) {
|
|||||||
if (body.role && !isValidRole(body.role))
|
if (body.role && !isValidRole(body.role))
|
||||||
return NextResponse.json({ error: 'Invalid role' }, { status: 422 })
|
return NextResponse.json({ error: 'Invalid role' }, { status: 422 })
|
||||||
const password = (body.password ?? '').trim()
|
const password = (body.password ?? '').trim()
|
||||||
const directCreate = password.length > 0
|
if (!password)
|
||||||
if (directCreate && password.length < 8)
|
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 })
|
return NextResponse.json({ error: 'Password must be at least 8 characters' }, { status: 422 })
|
||||||
|
|
||||||
let admin
|
let admin
|
||||||
@@ -39,44 +40,24 @@ export async function POST(request: NextRequest) {
|
|||||||
admin = createAdminClient()
|
admin = createAdminClient()
|
||||||
} catch {
|
} catch {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'User invites unavailable: SUPABASE_SERVICE_ROLE_KEY not configured' },
|
{ error: 'User creation unavailable: SUPABASE_SERVICE_ROLE_KEY not configured' },
|
||||||
{ status: 503 },
|
{ status: 503 },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Branch: admin-typed password (instant) vs email invite (link required)
|
const { data: created, error: createError } = await admin.auth.admin.createUser({
|
||||||
let newUserId: string
|
email,
|
||||||
if (directCreate) {
|
password,
|
||||||
const { data: created, error: createError } = await admin.auth.admin.createUser({
|
email_confirm: true,
|
||||||
email,
|
user_metadata: { full_name: body.name ?? '' },
|
||||||
password,
|
})
|
||||||
email_confirm: true,
|
if (createError || !created?.user)
|
||||||
user_metadata: { full_name: body.name ?? '' },
|
return NextResponse.json(
|
||||||
})
|
{ error: createError?.message ?? 'User creation failed' },
|
||||||
if (createError || !created?.user)
|
{ status: (createError as { status?: number } | null)?.status ?? 500 },
|
||||||
return NextResponse.json(
|
)
|
||||||
{ error: createError?.message ?? 'User creation failed' },
|
const newUserId = created.user.id
|
||||||
{ status: (createError as { status?: number } | null)?.status ?? 500 },
|
|
||||||
)
|
|
||||||
newUserId = created.user.id
|
|
||||||
} else {
|
|
||||||
const appUrl = (process.env.NEXT_PUBLIC_APP_URL ?? '').replace(/\/$/, '')
|
|
||||||
if (!appUrl) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Invite unavailable: NEXT_PUBLIC_APP_URL not configured' },
|
|
||||||
{ status: 503 },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
const { data: invited, error: inviteError } = await admin.auth.admin.inviteUserByEmail(email, {
|
|
||||||
data: { full_name: body.name ?? '' },
|
|
||||||
redirectTo: `${appUrl}/api/auth/callback`,
|
|
||||||
})
|
|
||||||
if (inviteError || !invited?.user)
|
|
||||||
return NextResponse.json({ error: inviteError?.message ?? 'Invite failed' }, { status: 500 })
|
|
||||||
newUserId = invited.user.id
|
|
||||||
}
|
|
||||||
|
|
||||||
// handle_new_auth_user trigger creates the profile row; set fields on top of it
|
|
||||||
const { error: profileError } = await admin
|
const { error: profileError } = await admin
|
||||||
.from('users')
|
.from('users')
|
||||||
.update({
|
.update({
|
||||||
@@ -88,15 +69,14 @@ export async function POST(request: NextRequest) {
|
|||||||
.eq('id', newUserId)
|
.eq('id', newUserId)
|
||||||
if (profileError)
|
if (profileError)
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: `${directCreate ? 'User created' : 'Invite sent'} but profile update failed` },
|
{ error: 'User created but profile update failed' },
|
||||||
{ status: 500 },
|
{ status: 500 },
|
||||||
)
|
)
|
||||||
|
|
||||||
// password is never logged
|
|
||||||
await supabase.rpc('write_audit_log', {
|
await supabase.rpc('write_audit_log', {
|
||||||
p_table_name: 'users',
|
p_table_name: 'users',
|
||||||
p_record_id: newUserId,
|
p_record_id: newUserId,
|
||||||
p_action: directCreate ? 'created' : 'invited',
|
p_action: 'created',
|
||||||
p_new_value: { email, role: body.role ?? 'reporter', site_id: body.site_id ?? null },
|
p_new_value: { email, role: body.role ?? 'reporter', site_id: body.site_id ?? null },
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -148,3 +128,43 @@ export async function PATCH(request: NextRequest) {
|
|||||||
|
|
||||||
return NextResponse.json({ ok: true })
|
return NextResponse.json({ ok: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function DELETE(request: NextRequest) {
|
||||||
|
const { supabase, user } = await requireAdmin()
|
||||||
|
if (!user) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||||
|
|
||||||
|
const { searchParams } = new URL(request.url)
|
||||||
|
const id = searchParams.get('id')
|
||||||
|
if (!id) return NextResponse.json({ error: 'id required' }, { status: 422 })
|
||||||
|
if (id === user.id)
|
||||||
|
return NextResponse.json({ error: 'Cannot delete your own account' }, { status: 422 })
|
||||||
|
|
||||||
|
// fetch user info for audit before deletion
|
||||||
|
const { data: target } = await supabase
|
||||||
|
.from('users').select('email, name, role').eq('id', id).single()
|
||||||
|
|
||||||
|
let admin
|
||||||
|
try {
|
||||||
|
admin = createAdminClient()
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'SUPABASE_SERVICE_ROLE_KEY not configured' },
|
||||||
|
{ status: 503 },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const { error } = await admin.auth.admin.deleteUser(id)
|
||||||
|
if (error)
|
||||||
|
return NextResponse.json({ error: error.message ?? 'Deletion failed' }, { status: 500 })
|
||||||
|
|
||||||
|
if (target) {
|
||||||
|
await supabase.rpc('write_audit_log', {
|
||||||
|
p_table_name: 'users',
|
||||||
|
p_record_id: id,
|
||||||
|
p_action: 'deleted',
|
||||||
|
p_new_value: { email: target.email, name: target.name, role: target.role },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true })
|
||||||
|
}
|
||||||
|
|||||||
@@ -27,9 +27,9 @@ export function UserManager({ users, sites }: Props) {
|
|||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const [busyId, setBusyId] = useState<string | null>(null)
|
const [busyId, setBusyId] = useState<string | null>(null)
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
const [mode, setMode] = useState<'invite' | 'create'>('invite')
|
|
||||||
const [form, setForm] = useState(EMPTY_FORM)
|
const [form, setForm] = useState(EMPTY_FORM)
|
||||||
const [submitting, setSubmitting] = useState(false)
|
const [submitting, setSubmitting] = useState(false)
|
||||||
|
const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null)
|
||||||
|
|
||||||
const patchUser = async (id: string, update: Record<string, unknown>) => {
|
const patchUser = async (id: string, update: Record<string, unknown>) => {
|
||||||
setBusyId(id)
|
setBusyId(id)
|
||||||
@@ -48,27 +48,40 @@ export function UserManager({ users, sites }: Props) {
|
|||||||
router.refresh()
|
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) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
setSubmitting(true)
|
setSubmitting(true)
|
||||||
setError(null)
|
setError(null)
|
||||||
const payload: Record<string, unknown> = {
|
|
||||||
email: form.email,
|
|
||||||
name: form.name || undefined,
|
|
||||||
phone: form.phone || undefined,
|
|
||||||
role: form.role,
|
|
||||||
site_id: form.site_id || undefined,
|
|
||||||
}
|
|
||||||
if (mode === 'create') payload.password = form.password
|
|
||||||
const res = await fetch('/ims/api/admin/users', {
|
const res = await fetch('/ims/api/admin/users', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(payload),
|
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)
|
setSubmitting(false)
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const data = await res.json().catch(() => ({}))
|
const data = await res.json().catch(() => ({}))
|
||||||
setError(data.error ?? `${mode === 'create' ? 'Add' : 'Invite'} failed`)
|
setError(data.error ?? 'Add failed')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
setForm(EMPTY_FORM)
|
setForm(EMPTY_FORM)
|
||||||
@@ -79,24 +92,6 @@ export function UserManager({ users, sites }: Props) {
|
|||||||
<div className="bg-white rounded-xl shadow-sm p-5">
|
<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>
|
<h2 className="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-4">Users</h2>
|
||||||
|
|
||||||
{/* Mode toggle */}
|
|
||||||
<div className="flex gap-2 mb-4">
|
|
||||||
{(['invite', 'create'] as const).map(m => (
|
|
||||||
<button
|
|
||||||
key={m}
|
|
||||||
type="button"
|
|
||||||
onClick={() => { setMode(m); setError(null) }}
|
|
||||||
className={`text-xs font-medium px-3 py-1.5 rounded-full border transition-colors ${
|
|
||||||
mode === m
|
|
||||||
? 'bg-gray-800 text-white border-gray-800'
|
|
||||||
: 'border-gray-300 text-gray-600 hover:bg-gray-50'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{m === 'invite' ? 'Invite by email' : 'Add directly'}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="flex flex-wrap gap-2 mb-5 items-end">
|
<form onSubmit={handleSubmit} className="flex flex-wrap gap-2 mb-5 items-end">
|
||||||
<input
|
<input
|
||||||
type="email" required placeholder="email@company.com"
|
type="email" required placeholder="email@company.com"
|
||||||
@@ -131,24 +126,20 @@ export function UserManager({ users, sites }: Props) {
|
|||||||
<option value="">No site</option>
|
<option value="">No site</option>
|
||||||
{sites.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
|
{sites.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
|
||||||
</select>
|
</select>
|
||||||
{mode === 'create' && (
|
<input
|
||||||
<input
|
type="password"
|
||||||
type="password"
|
required
|
||||||
required
|
minLength={8}
|
||||||
minLength={8}
|
placeholder="Password (min 8 chars)"
|
||||||
placeholder="Password (min 8 chars)"
|
value={form.password}
|
||||||
value={form.password}
|
onChange={e => setForm(v => ({ ...v, password: e.target.value }))}
|
||||||
onChange={e => setForm(v => ({ ...v, password: e.target.value }))}
|
className="border border-gray-300 rounded-lg px-3 py-2 text-sm w-48"
|
||||||
className="border border-gray-300 rounded-lg px-3 py-2 text-sm w-48"
|
/>
|
||||||
/>
|
|
||||||
)}
|
|
||||||
<button
|
<button
|
||||||
type="submit" disabled={submitting}
|
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"
|
className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-semibold hover:bg-blue-700 disabled:opacity-50"
|
||||||
>
|
>
|
||||||
{submitting
|
{submitting ? 'Adding…' : 'Add User'}
|
||||||
? (mode === 'create' ? 'Adding…' : 'Inviting…')
|
|
||||||
: (mode === 'create' ? 'Add User' : 'Invite User')}
|
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
@@ -163,6 +154,7 @@ export function UserManager({ users, sites }: Props) {
|
|||||||
<th className="py-2 pr-3">Role</th>
|
<th className="py-2 pr-3">Role</th>
|
||||||
<th className="py-2 pr-3">Site</th>
|
<th className="py-2 pr-3">Site</th>
|
||||||
<th className="py-2">Status</th>
|
<th className="py-2">Status</th>
|
||||||
|
<th className="py-2"></th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
@@ -202,6 +194,35 @@ export function UserManager({ users, sites }: Props) {
|
|||||||
{u.active ? 'Active' : 'Deactivated'}
|
{u.active ? 'Active' : 'Deactivated'}
|
||||||
</button>
|
</button>
|
||||||
</td>
|
</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>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|||||||
Reference in New Issue
Block a user