Build 2602260214: invites profiles and expiry admin controls

This commit is contained in:
2026-02-26 02:15:21 +13:00
parent 9be0ec75ec
commit f78382c019
14 changed files with 2795 additions and 31 deletions

View File

@@ -0,0 +1,419 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { useRouter } from 'next/navigation'
import AdminShell from '../../ui/AdminShell'
import { authFetch, clearToken, getApiBase, getToken } from '../../lib/auth'
type ProfileOption = {
id: number
name: string
}
type Invite = {
id: number
code: string
label?: string | null
description?: string | null
profile_id?: number | null
profile?: ProfileOption | null
role?: 'user' | 'admin' | null
max_uses?: number | null
use_count: number
remaining_uses?: number | null
enabled: boolean
expires_at?: string | null
is_expired?: boolean
is_usable?: boolean
created_at?: string | null
}
type InviteForm = {
code: string
label: string
description: string
profile_id: string
role: '' | 'user' | 'admin'
max_uses: string
enabled: boolean
expires_at: string
}
const defaultForm = (): InviteForm => ({
code: '',
label: '',
description: '',
profile_id: '',
role: '',
max_uses: '',
enabled: true,
expires_at: '',
})
const formatDate = (value?: string | null) => {
if (!value) return 'Never'
const date = new Date(value)
if (Number.isNaN(date.valueOf())) return value
return date.toLocaleString()
}
export default function AdminInvitesPage() {
const router = useRouter()
const [invites, setInvites] = useState<Invite[]>([])
const [profiles, setProfiles] = useState<ProfileOption[]>([])
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const [status, setStatus] = useState<string | null>(null)
const [editingId, setEditingId] = useState<number | null>(null)
const [form, setForm] = useState<InviteForm>(defaultForm())
const signupBaseUrl = useMemo(() => {
if (typeof window === 'undefined') return '/signup'
return `${window.location.origin}/signup`
}, [])
const handleAuthResponse = (response: Response) => {
if (response.status === 401) {
clearToken()
router.push('/login')
return true
}
if (response.status === 403) {
router.push('/')
return true
}
return false
}
const loadData = async () => {
if (!getToken()) {
router.push('/login')
return
}
setLoading(true)
setError(null)
try {
const baseUrl = getApiBase()
const [inviteRes, profileRes] = await Promise.all([
authFetch(`${baseUrl}/admin/invites`),
authFetch(`${baseUrl}/admin/profiles`),
])
if (!inviteRes.ok) {
if (handleAuthResponse(inviteRes)) return
throw new Error(`Failed to load invites (${inviteRes.status})`)
}
if (!profileRes.ok) {
if (handleAuthResponse(profileRes)) return
throw new Error(`Failed to load profiles (${profileRes.status})`)
}
const [inviteData, profileData] = await Promise.all([inviteRes.json(), profileRes.json()])
setInvites(Array.isArray(inviteData?.invites) ? inviteData.invites : [])
const profileRows = Array.isArray(profileData?.profiles) ? profileData.profiles : []
setProfiles(
profileRows.map((profile: any) => ({
id: Number(profile.id ?? 0),
name: String(profile.name ?? 'Unnamed'),
}))
)
} catch (err) {
console.error(err)
setError('Could not load invites.')
} finally {
setLoading(false)
}
}
useEffect(() => {
void loadData()
}, [])
const resetEditor = () => {
setEditingId(null)
setForm(defaultForm())
}
const editInvite = (invite: Invite) => {
setEditingId(invite.id)
setForm({
code: invite.code ?? '',
label: invite.label ?? '',
description: invite.description ?? '',
profile_id:
typeof invite.profile_id === 'number' && invite.profile_id > 0
? String(invite.profile_id)
: '',
role: (invite.role ?? '') as '' | 'user' | 'admin',
max_uses: typeof invite.max_uses === 'number' ? String(invite.max_uses) : '',
enabled: invite.enabled !== false,
expires_at: invite.expires_at ?? '',
})
setStatus(null)
setError(null)
}
const saveInvite = async (event: React.FormEvent) => {
event.preventDefault()
setSaving(true)
setError(null)
setStatus(null)
try {
const baseUrl = getApiBase()
const payload = {
code: form.code || null,
label: form.label || null,
description: form.description || null,
profile_id: form.profile_id || null,
role: form.role || null,
max_uses: form.max_uses || null,
enabled: form.enabled,
expires_at: form.expires_at || null,
}
const url =
editingId == null ? `${baseUrl}/admin/invites` : `${baseUrl}/admin/invites/${editingId}`
const response = await authFetch(url, {
method: editingId == null ? 'POST' : 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
if (!response.ok) {
if (handleAuthResponse(response)) return
const text = await response.text()
throw new Error(text || 'Save failed')
}
setStatus(editingId == null ? 'Invite created.' : 'Invite updated.')
resetEditor()
await loadData()
} catch (err) {
console.error(err)
setError(err instanceof Error ? err.message : 'Could not save invite.')
} finally {
setSaving(false)
}
}
const deleteInvite = async (invite: Invite) => {
if (!window.confirm(`Delete invite "${invite.code}"?`)) return
setError(null)
setStatus(null)
try {
const baseUrl = getApiBase()
const response = await authFetch(`${baseUrl}/admin/invites/${invite.id}`, {
method: 'DELETE',
})
if (!response.ok) {
if (handleAuthResponse(response)) return
const text = await response.text()
throw new Error(text || 'Delete failed')
}
if (editingId === invite.id) resetEditor()
setStatus(`Deleted invite ${invite.code}.`)
await loadData()
} catch (err) {
console.error(err)
setError(err instanceof Error ? err.message : 'Could not delete invite.')
}
}
const copyInviteLink = async (invite: Invite) => {
const url = `${signupBaseUrl}?code=${encodeURIComponent(invite.code)}`
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(url)
setStatus(`Copied invite link for ${invite.code}.`)
} else {
window.prompt('Copy invite link', url)
}
} catch (err) {
console.error(err)
window.prompt('Copy invite link', url)
}
}
return (
<AdminShell
title="Invites"
subtitle="Create invite-based sign-up links for Magent accounts."
actions={
<div className="admin-inline-actions">
<button type="button" onClick={loadData} disabled={loading}>
{loading ? 'Loading…' : 'Reload'}
</button>
<button type="button" className="ghost-button" onClick={resetEditor}>
New invite
</button>
</div>
}
>
<section className="admin-section">
{error && <div className="error-banner">{error}</div>}
{status && <div className="status-banner">{status}</div>}
<div className="admin-split-grid">
<div className="admin-panel">
<h2>{editingId == null ? 'Create invite' : 'Edit invite'}</h2>
<p className="lede">
Link an invite to a profile to apply account defaults at sign-up.
</p>
<form onSubmit={saveInvite} className="admin-form compact-form">
<div className="admin-fields-grid">
<label>
Code (optional)
<input
value={form.code}
onChange={(e) => setForm((current) => ({ ...current, code: e.target.value }))}
placeholder="Leave blank to auto-generate"
/>
</label>
<label>
Label
<input
value={form.label}
onChange={(e) => setForm((current) => ({ ...current, label: e.target.value }))}
placeholder="Staff invite batch"
/>
</label>
</div>
<label>
Description
<textarea
rows={3}
value={form.description}
onChange={(e) =>
setForm((current) => ({ ...current, description: e.target.value }))
}
placeholder="Optional note shown on the signup page"
/>
</label>
<div className="admin-fields-grid">
<label>
Profile
<select
value={form.profile_id}
onChange={(e) =>
setForm((current) => ({ ...current, profile_id: e.target.value }))
}
>
<option value="">None</option>
{profiles.map((profile) => (
<option key={profile.id} value={profile.id}>
{profile.name}
</option>
))}
</select>
</label>
<label>
Role override
<select
value={form.role}
onChange={(e) =>
setForm((current) => ({
...current,
role: e.target.value as '' | 'user' | 'admin',
}))
}
>
<option value="">Use profile/default</option>
<option value="user">User</option>
<option value="admin">Admin</option>
</select>
</label>
</div>
<div className="admin-fields-grid">
<label>
Max uses
<input
value={form.max_uses}
onChange={(e) =>
setForm((current) => ({ ...current, max_uses: e.target.value }))
}
inputMode="numeric"
placeholder="Blank = unlimited"
/>
</label>
<label>
Invite expiry (ISO datetime)
<input
value={form.expires_at}
onChange={(e) =>
setForm((current) => ({ ...current, expires_at: e.target.value }))
}
placeholder="2026-03-01T12:00:00+00:00"
/>
</label>
</div>
<label className="inline-checkbox">
<input
type="checkbox"
checked={form.enabled}
onChange={(e) =>
setForm((current) => ({ ...current, enabled: e.target.checked }))
}
/>
Invite is enabled
</label>
<div className="admin-inline-actions">
<button type="submit" disabled={saving}>
{saving ? 'Saving…' : editingId == null ? 'Create invite' : 'Save invite'}
</button>
{editingId != null && (
<button type="button" className="ghost-button" onClick={resetEditor}>
Cancel edit
</button>
)}
</div>
</form>
</div>
<div className="admin-panel">
<h2>Existing invites</h2>
<p className="lede">Each invite can be copied as a direct sign-up link.</p>
{loading ? (
<div className="status-banner">Loading invites</div>
) : invites.length === 0 ? (
<div className="status-banner">No invites created yet.</div>
) : (
<div className="admin-list">
{invites.map((invite) => (
<div key={invite.id} className="admin-list-item">
<div className="admin-list-item-main">
<div className="admin-list-item-title-row">
<code className="invite-code">{invite.code}</code>
<span className={`small-pill ${invite.is_usable ? '' : 'is-muted'}`}>
{invite.is_usable ? 'Usable' : 'Unavailable'}
</span>
{invite.profile?.name && <span className="small-pill">{invite.profile.name}</span>}
</div>
{invite.label && <p className="admin-list-item-text">{invite.label}</p>}
{invite.description && (
<p className="admin-list-item-text admin-list-item-text--muted">
{invite.description}
</p>
)}
<div className="admin-meta-row">
<span>Uses: {invite.use_count}{typeof invite.max_uses === 'number' ? ` / ${invite.max_uses}` : ''}</span>
<span>Remaining: {invite.remaining_uses ?? 'Unlimited'}</span>
<span>Expires: {formatDate(invite.expires_at)}</span>
<span>Created: {formatDate(invite.created_at)}</span>
</div>
</div>
<div className="admin-inline-actions">
<button type="button" className="ghost-button" onClick={() => copyInviteLink(invite)}>
Copy link
</button>
<button type="button" className="ghost-button" onClick={() => editInvite(invite)}>
Edit
</button>
<button type="button" onClick={() => deleteInvite(invite)}>
Delete
</button>
</div>
</div>
))}
</div>
)}
</div>
</div>
</section>
</AdminShell>
)
}

View File

@@ -0,0 +1,335 @@
'use client'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import AdminShell from '../../ui/AdminShell'
import { authFetch, clearToken, getApiBase, getToken } from '../../lib/auth'
type Profile = {
id: number
name: string
description?: string | null
role: 'user' | 'admin'
auto_search_enabled: boolean
account_expires_days?: number | null
is_active: boolean
assigned_users?: number
assigned_invites?: number
}
type ProfileForm = {
name: string
description: string
role: 'user' | 'admin'
auto_search_enabled: boolean
account_expires_days: string
is_active: boolean
}
const defaultForm = (): ProfileForm => ({
name: '',
description: '',
role: 'user',
auto_search_enabled: true,
account_expires_days: '',
is_active: true,
})
export default function AdminProfilesPage() {
const router = useRouter()
const [profiles, setProfiles] = useState<Profile[]>([])
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const [status, setStatus] = useState<string | null>(null)
const [editingId, setEditingId] = useState<number | null>(null)
const [form, setForm] = useState<ProfileForm>(defaultForm())
const handleAuthResponse = (response: Response) => {
if (response.status === 401) {
clearToken()
router.push('/login')
return true
}
if (response.status === 403) {
router.push('/')
return true
}
return false
}
const loadProfiles = async () => {
if (!getToken()) {
router.push('/login')
return
}
setLoading(true)
setError(null)
try {
const baseUrl = getApiBase()
const response = await authFetch(`${baseUrl}/admin/profiles`)
if (!response.ok) {
if (handleAuthResponse(response)) return
throw new Error(`Failed to load profiles (${response.status})`)
}
const data = await response.json()
setProfiles(Array.isArray(data?.profiles) ? data.profiles : [])
} catch (err) {
console.error(err)
setError('Could not load profiles.')
} finally {
setLoading(false)
}
}
useEffect(() => {
void loadProfiles()
}, [])
const resetEditor = () => {
setEditingId(null)
setForm(defaultForm())
}
const editProfile = (profile: Profile) => {
setEditingId(profile.id)
setForm({
name: profile.name ?? '',
description: profile.description ?? '',
role: profile.role ?? 'user',
auto_search_enabled: Boolean(profile.auto_search_enabled),
account_expires_days:
typeof profile.account_expires_days === 'number' ? String(profile.account_expires_days) : '',
is_active: profile.is_active !== false,
})
setStatus(null)
setError(null)
}
const saveProfile = async (event: React.FormEvent) => {
event.preventDefault()
setSaving(true)
setError(null)
setStatus(null)
try {
const baseUrl = getApiBase()
const payload = {
name: form.name,
description: form.description || null,
role: form.role,
auto_search_enabled: form.auto_search_enabled,
account_expires_days: form.account_expires_days || null,
is_active: form.is_active,
}
const url =
editingId == null
? `${baseUrl}/admin/profiles`
: `${baseUrl}/admin/profiles/${editingId}`
const response = await authFetch(url, {
method: editingId == null ? 'POST' : 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
if (!response.ok) {
if (handleAuthResponse(response)) return
const text = await response.text()
throw new Error(text || 'Save failed')
}
setStatus(editingId == null ? 'Profile created.' : 'Profile updated.')
resetEditor()
await loadProfiles()
} catch (err) {
console.error(err)
setError(err instanceof Error ? err.message : 'Could not save profile.')
} finally {
setSaving(false)
}
}
const deleteProfile = async (profile: Profile) => {
if (!window.confirm(`Delete profile "${profile.name}"?`)) return
setError(null)
setStatus(null)
try {
const baseUrl = getApiBase()
const response = await authFetch(`${baseUrl}/admin/profiles/${profile.id}`, {
method: 'DELETE',
})
if (!response.ok) {
if (handleAuthResponse(response)) return
const text = await response.text()
throw new Error(text || 'Delete failed')
}
if (editingId === profile.id) resetEditor()
setStatus(`Deleted profile "${profile.name}".`)
await loadProfiles()
} catch (err) {
console.error(err)
setError(err instanceof Error ? err.message : 'Could not delete profile.')
}
}
return (
<AdminShell
title="Profiles"
subtitle="Reusable account templates for invite-based sign-up."
actions={
<div className="admin-inline-actions">
<button type="button" onClick={loadProfiles} disabled={loading}>
{loading ? 'Loading…' : 'Reload'}
</button>
<button type="button" className="ghost-button" onClick={resetEditor}>
New profile
</button>
</div>
}
>
<section className="admin-section">
{error && <div className="error-banner">{error}</div>}
{status && <div className="status-banner">{status}</div>}
<div className="admin-split-grid">
<div className="admin-panel">
<h2>{editingId == null ? 'Create profile' : 'Edit profile'}</h2>
<p className="lede">
Profiles define defaults applied when a user signs up using an invite.
</p>
<form onSubmit={saveProfile} className="admin-form compact-form">
<label>
Profile name
<input
value={form.name}
onChange={(e) => setForm((current) => ({ ...current, name: e.target.value }))}
placeholder="Standard users"
required
/>
</label>
<label>
Description
<textarea
rows={3}
value={form.description}
onChange={(e) =>
setForm((current) => ({ ...current, description: e.target.value }))
}
placeholder="Default invite settings for normal users"
/>
</label>
<div className="admin-fields-grid">
<label>
Role
<select
value={form.role}
onChange={(e) =>
setForm((current) => ({
...current,
role: e.target.value as 'user' | 'admin',
}))
}
>
<option value="user">User</option>
<option value="admin">Admin</option>
</select>
</label>
<label>
Account expiry (days)
<input
value={form.account_expires_days}
onChange={(e) =>
setForm((current) => ({
...current,
account_expires_days: e.target.value,
}))
}
inputMode="numeric"
placeholder="Blank = no expiry"
/>
</label>
</div>
<label className="inline-checkbox">
<input
type="checkbox"
checked={form.auto_search_enabled}
onChange={(e) =>
setForm((current) => ({
...current,
auto_search_enabled: e.target.checked,
}))
}
/>
Allow auto search/download by default
</label>
<label className="inline-checkbox">
<input
type="checkbox"
checked={form.is_active}
onChange={(e) =>
setForm((current) => ({ ...current, is_active: e.target.checked }))
}
/>
Profile is active
</label>
<div className="admin-inline-actions">
<button type="submit" disabled={saving}>
{saving ? 'Saving…' : editingId == null ? 'Create profile' : 'Save profile'}
</button>
{editingId != null && (
<button type="button" className="ghost-button" onClick={resetEditor}>
Cancel edit
</button>
)}
</div>
</form>
</div>
<div className="admin-panel">
<h2>Existing profiles</h2>
<p className="lede">Assign these to invites so sign-up accounts get consistent defaults.</p>
{loading ? (
<div className="status-banner">Loading profiles</div>
) : profiles.length === 0 ? (
<div className="status-banner">No profiles created yet.</div>
) : (
<div className="admin-list">
{profiles.map((profile) => (
<div key={profile.id} className="admin-list-item">
<div className="admin-list-item-main">
<div className="admin-list-item-title-row">
<strong>{profile.name}</strong>
<span className={`small-pill ${profile.is_active ? '' : 'is-muted'}`}>
{profile.is_active ? 'Active' : 'Disabled'}
</span>
<span className="small-pill">{profile.role}</span>
</div>
{profile.description && (
<p className="admin-list-item-text">{profile.description}</p>
)}
<div className="admin-meta-row">
<span>Auto search: {profile.auto_search_enabled ? 'On' : 'Off'}</span>
<span>
Account expiry:{' '}
{typeof profile.account_expires_days === 'number'
? `${profile.account_expires_days} days`
: 'Never'}
</span>
<span>Users: {profile.assigned_users ?? 0}</span>
<span>Invites: {profile.assigned_invites ?? 0}</span>
</div>
</div>
<div className="admin-inline-actions">
<button type="button" className="ghost-button" onClick={() => editProfile(profile)}>
Edit
</button>
<button type="button" onClick={() => deleteProfile(profile)}>
Delete
</button>
</div>
</div>
))}
</div>
)}
</div>
</div>
</section>
</AdminShell>
)
}

View File

@@ -3895,3 +3895,237 @@ button:hover:not(:disabled) {
border-radius: 14px;
}
}
.admin-inline-actions {
display: inline-flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
.admin-split-grid {
display: grid;
grid-template-columns: minmax(300px, 420px) minmax(0, 1fr);
gap: 14px;
align-items: start;
}
.admin-panel {
border: 1px solid rgba(255, 255, 255, 0.06);
background: rgba(255, 255, 255, 0.02);
border-radius: 10px;
padding: 14px;
}
.admin-panel h2 {
margin: 0 0 6px;
font-size: 1rem;
}
.admin-panel .lede {
margin: 0 0 12px;
}
.compact-form {
gap: 12px;
}
.compact-form textarea {
min-height: 84px;
resize: vertical;
}
.admin-fields-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
.inline-checkbox {
display: flex;
align-items: center;
gap: 8px;
}
.inline-checkbox input[type='checkbox'] {
width: 16px;
height: 16px;
}
.admin-list {
display: grid;
gap: 10px;
}
.admin-list-item {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 12px;
align-items: start;
border: 1px solid rgba(255, 255, 255, 0.06);
background: rgba(255, 255, 255, 0.015);
border-radius: 10px;
padding: 10px 12px;
}
.admin-list-item-main {
min-width: 0;
display: grid;
gap: 6px;
}
.admin-list-item-title-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.admin-list-item-text {
margin: 0;
color: #d0d6df;
line-height: 1.35;
}
.admin-list-item-text--muted {
color: #9ea7b6;
}
.admin-meta-row {
display: flex;
flex-wrap: wrap;
gap: 10px;
color: #9ea7b6;
font-size: 0.83rem;
}
.small-pill {
display: inline-flex;
align-items: center;
padding: 2px 8px;
border-radius: 999px;
border: 1px solid rgba(255, 255, 255, 0.09);
background: rgba(255, 255, 255, 0.03);
font-size: 0.72rem;
color: #d0d6df;
}
.small-pill.is-muted {
color: #9ea7b6;
border-color: rgba(255, 255, 255, 0.06);
background: rgba(255, 255, 255, 0.015);
}
.invite-code {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono',
'Courier New', monospace;
padding: 3px 8px;
border-radius: 8px;
border: 1px solid rgba(111, 149, 198, 0.2);
background: rgba(111, 149, 198, 0.07);
color: #c8d7ec;
}
.invite-lookup-row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 8px;
align-items: center;
}
.invite-summary {
display: grid;
gap: 8px;
border: 1px solid rgba(111, 149, 198, 0.18);
background: rgba(111, 149, 198, 0.06);
border-radius: 10px;
padding: 10px 12px;
}
.invite-summary.is-disabled {
border-color: rgba(255, 255, 255, 0.08);
background: rgba(255, 255, 255, 0.03);
}
.invite-summary p {
margin: 0;
}
.invite-summary-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.user-bulk-toolbar--stacked {
align-items: stretch;
}
.user-bulk-groups {
display: grid;
gap: 10px;
width: 100%;
}
.user-bulk-group {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: flex-end;
}
.user-bulk-group > label {
display: grid;
gap: 6px;
min-width: 220px;
flex: 1 1 220px;
}
.user-bulk-label {
font-size: 0.78rem;
color: #9ea7b6;
}
.user-bulk-group input,
.user-bulk-group select {
width: 100%;
}
.user-detail-actions--stacked {
display: grid;
gap: 8px;
margin-top: 10px;
}
.user-detail-actions--stacked > label {
display: grid;
gap: 6px;
}
@media (max-width: 980px) {
.admin-split-grid {
grid-template-columns: 1fr;
}
.admin-fields-grid {
grid-template-columns: 1fr;
}
.admin-list-item {
grid-template-columns: 1fr;
}
.invite-lookup-row {
grid-template-columns: 1fr;
}
.user-bulk-group {
align-items: stretch;
}
.user-bulk-group > label {
min-width: 100%;
flex-basis: 100%;
}
}

View File

@@ -85,6 +85,9 @@ export default function LoginPage() {
>
Sign in with Magent account
</button>
<a className="ghost-button" href="/signup">
Have an invite? Create a Magent account
</a>
</form>
</main>
)

View File

@@ -0,0 +1,223 @@
'use client'
import { Suspense, useEffect, useMemo, useState } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import BrandingLogo from '../ui/BrandingLogo'
import { clearToken, getApiBase, setToken } from '../lib/auth'
type InviteInfo = {
code: string
label?: string | null
description?: string | null
enabled: boolean
is_expired?: boolean
is_usable?: boolean
expires_at?: string | null
max_uses?: number | null
use_count?: number | null
remaining_uses?: number | null
profile?: {
id: number
name: string
description?: string | null
} | null
}
const formatDate = (value?: string | null) => {
if (!value) return 'Never'
const date = new Date(value)
if (Number.isNaN(date.valueOf())) return value
return date.toLocaleString()
}
function SignupPageContent() {
const router = useRouter()
const searchParams = useSearchParams()
const [inviteCode, setInviteCode] = useState(searchParams.get('code') ?? '')
const [invite, setInvite] = useState<InviteInfo | null>(null)
const [inviteLoading, setInviteLoading] = useState(false)
const [loading, setLoading] = useState(false)
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [error, setError] = useState<string | null>(null)
const [status, setStatus] = useState<string | null>(null)
const canSubmit = useMemo(() => {
return Boolean(invite?.is_usable && username.trim() && password && !loading)
}, [invite, username, password, loading])
const lookupInvite = async (code: string) => {
const trimmed = code.trim()
if (!trimmed) {
setInvite(null)
return
}
setInviteLoading(true)
setError(null)
setStatus(null)
try {
const baseUrl = getApiBase()
const response = await fetch(`${baseUrl}/auth/invites/${encodeURIComponent(trimmed)}`)
if (!response.ok) {
const text = await response.text()
throw new Error(text || 'Invite not found')
}
const data = await response.json()
setInvite(data?.invite ?? null)
setStatus('Invite loaded.')
} catch (err) {
console.error(err)
setInvite(null)
setError('Invite code not found or unavailable.')
} finally {
setInviteLoading(false)
}
}
useEffect(() => {
const initialCode = searchParams.get('code') ?? ''
if (initialCode) {
setInviteCode(initialCode)
void lookupInvite(initialCode)
}
}, [searchParams])
const submit = async (event: React.FormEvent) => {
event.preventDefault()
if (password !== confirmPassword) {
setError('Passwords do not match.')
return
}
if (!inviteCode.trim()) {
setError('Invite code is required.')
return
}
if (!invite?.is_usable) {
setError('Invite is not usable. Refresh invite details or ask an admin for a new code.')
return
}
setLoading(true)
setError(null)
setStatus(null)
try {
clearToken()
const baseUrl = getApiBase()
const response = await fetch(`${baseUrl}/auth/signup`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
invite_code: inviteCode,
username: username.trim(),
password,
}),
})
if (!response.ok) {
const text = await response.text()
throw new Error(text || 'Sign-up failed')
}
const data = await response.json()
if (data?.access_token) {
setToken(data.access_token)
window.location.href = '/'
return
}
throw new Error('Sign-up did not return a token')
} catch (err) {
console.error(err)
setError(err instanceof Error ? err.message : 'Unable to create account.')
} finally {
setLoading(false)
}
}
return (
<main className="card auth-card">
<BrandingLogo className="brand-logo brand-logo--login" />
<h1>Create account</h1>
<p className="lede">Use an invite code from your admin to create a Magent account.</p>
<form onSubmit={submit} className="auth-form">
<label>
Invite code
<div className="invite-lookup-row">
<input
value={inviteCode}
onChange={(e) => setInviteCode(e.target.value)}
placeholder="Paste your invite code"
autoCapitalize="characters"
/>
<button
type="button"
className="ghost-button"
disabled={inviteLoading}
onClick={() => void lookupInvite(inviteCode)}
>
{inviteLoading ? 'Checking…' : 'Check invite'}
</button>
</div>
</label>
{invite && (
<div className={`invite-summary ${invite.is_usable ? '' : 'is-disabled'}`}>
<div className="invite-summary-row">
<strong>{invite.label || invite.code}</strong>
<span className={`small-pill ${invite.is_usable ? '' : 'is-muted'}`}>
{invite.is_usable ? 'Usable' : 'Unavailable'}
</span>
</div>
{invite.description && <p>{invite.description}</p>}
<div className="admin-meta-row">
<span>Code: {invite.code}</span>
<span>Expires: {formatDate(invite.expires_at)}</span>
<span>Remaining uses: {invite.remaining_uses ?? 'Unlimited'}</span>
<span>Profile: {invite.profile?.name || 'None'}</span>
</div>
</div>
)}
<label>
Username
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
autoComplete="username"
/>
</label>
<label>
Password
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoComplete="new-password"
/>
</label>
<label>
Confirm password
<input
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
autoComplete="new-password"
/>
</label>
{error && <div className="error-banner">{error}</div>}
{status && <div className="status-banner">{status}</div>}
<div className="auth-actions">
<button type="submit" disabled={!canSubmit}>
{loading ? 'Creating account…' : 'Create account'}
</button>
</div>
<button type="button" className="ghost-button" disabled={loading} onClick={() => router.push('/login')}>
Back to sign in
</button>
</form>
</main>
)
}
export default function SignupPage() {
return (
<Suspense fallback={<main className="card auth-card">Loading sign-up</main>}>
<SignupPageContent />
</Suspense>
)
}

View File

@@ -27,6 +27,8 @@ const NAV_GROUPS = [
items: [
{ href: '/admin/site', label: 'Site' },
{ href: '/users', label: 'Users' },
{ href: '/admin/profiles', label: 'Profiles' },
{ href: '/admin/invites', label: 'Invites' },
{ href: '/admin/logs', label: 'Activity log' },
{ href: '/admin/maintenance', label: 'Maintenance' },
],

View File

@@ -26,6 +26,15 @@ type AdminUser = {
is_blocked?: boolean
auto_search_enabled?: boolean
jellyseerr_user_id?: number | null
profile_id?: number | null
expires_at?: string | null
is_expired?: boolean
}
type UserProfileOption = {
id: number
name: string
is_active?: boolean
}
const formatDateTime = (value?: string | null) => {
@@ -35,6 +44,22 @@ const formatDateTime = (value?: string | null) => {
return date.toLocaleString()
}
const toLocalDateTimeInput = (value?: string | null) => {
if (!value) return ''
const date = new Date(value)
if (Number.isNaN(date.valueOf())) return ''
const offsetMs = date.getTimezoneOffset() * 60_000
const local = new Date(date.getTime() - offsetMs)
return local.toISOString().slice(0, 16)
}
const fromLocalDateTimeInput = (value: string) => {
if (!value.trim()) return null
const date = new Date(value)
if (Number.isNaN(date.valueOf())) return null
return date.toISOString()
}
const normalizeStats = (stats: any): UserStats => ({
total: Number(stats?.total ?? 0),
ready: Number(stats?.ready ?? 0),
@@ -55,6 +80,36 @@ export default function UserDetailPage() {
const [stats, setStats] = useState<UserStats | null>(null)
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(true)
const [profiles, setProfiles] = useState<UserProfileOption[]>([])
const [profileSelection, setProfileSelection] = useState('')
const [expiryInput, setExpiryInput] = useState('')
const [savingProfile, setSavingProfile] = useState(false)
const [savingExpiry, setSavingExpiry] = useState(false)
const [actionStatus, setActionStatus] = useState<string | null>(null)
const loadProfiles = async () => {
try {
const baseUrl = getApiBase()
const response = await authFetch(`${baseUrl}/admin/profiles`)
if (!response.ok) {
return
}
const data = await response.json()
if (!Array.isArray(data?.profiles)) {
setProfiles([])
return
}
setProfiles(
data.profiles.map((profile: any) => ({
id: Number(profile.id ?? 0),
name: String(profile.name ?? 'Unnamed profile'),
is_active: Boolean(profile.is_active ?? true),
}))
)
} catch (err) {
console.error(err)
}
}
const loadUser = async () => {
if (!idParam) return
@@ -80,8 +135,15 @@ export default function UserDetailPage() {
throw new Error('Could not load user.')
}
const data = await response.json()
setUser(data?.user ?? null)
const nextUser = data?.user ?? null
setUser(nextUser)
setStats(normalizeStats(data?.stats))
setProfileSelection(
nextUser?.profile_id == null || Number.isNaN(Number(nextUser?.profile_id))
? ''
: String(nextUser.profile_id)
)
setExpiryInput(toLocalDateTimeInput(nextUser?.expires_at))
setError(null)
} catch (err) {
console.error(err)
@@ -94,6 +156,7 @@ export default function UserDetailPage() {
const toggleUserBlock = async (blocked: boolean) => {
if (!user) return
try {
setActionStatus(null)
const baseUrl = getApiBase()
const response = await authFetch(
`${baseUrl}/admin/users/${encodeURIComponent(user.username)}/${blocked ? 'block' : 'unblock'}`,
@@ -103,6 +166,7 @@ export default function UserDetailPage() {
throw new Error('Update failed')
}
await loadUser()
setActionStatus(blocked ? 'User blocked.' : 'User unblocked.')
} catch (err) {
console.error(err)
setError('Could not update user access.')
@@ -112,6 +176,7 @@ export default function UserDetailPage() {
const updateUserRole = async (role: string) => {
if (!user) return
try {
setActionStatus(null)
const baseUrl = getApiBase()
const response = await authFetch(
`${baseUrl}/admin/users/${encodeURIComponent(user.username)}/role`,
@@ -125,6 +190,7 @@ export default function UserDetailPage() {
throw new Error('Update failed')
}
await loadUser()
setActionStatus(`Role updated to ${role}.`)
} catch (err) {
console.error(err)
setError('Could not update user role.')
@@ -134,6 +200,7 @@ export default function UserDetailPage() {
const updateAutoSearchEnabled = async (enabled: boolean) => {
if (!user) return
try {
setActionStatus(null)
const baseUrl = getApiBase()
const response = await authFetch(
`${baseUrl}/admin/users/${encodeURIComponent(user.username)}/auto-search`,
@@ -147,18 +214,114 @@ export default function UserDetailPage() {
throw new Error('Update failed')
}
await loadUser()
setActionStatus(`Auto search/download ${enabled ? 'enabled' : 'disabled'}.`)
} catch (err) {
console.error(err)
setError('Could not update auto search access.')
}
}
const applyProfileToUser = async (profileOverride?: string | null) => {
if (!user) return
const profileValue = profileOverride ?? profileSelection
setSavingProfile(true)
setError(null)
setActionStatus(null)
try {
const baseUrl = getApiBase()
const response = await authFetch(
`${baseUrl}/admin/users/${encodeURIComponent(user.username)}/profile`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ profile_id: profileValue || null }),
}
)
if (!response.ok) {
const text = await response.text()
throw new Error(text || 'Profile update failed')
}
await loadUser()
setActionStatus(profileValue ? 'Profile applied to user.' : 'Profile assignment cleared.')
} catch (err) {
console.error(err)
setError('Could not update user profile.')
} finally {
setSavingProfile(false)
}
}
const saveUserExpiry = async () => {
if (!user) return
const expiresAt = fromLocalDateTimeInput(expiryInput)
if (expiryInput.trim() && !expiresAt) {
setError('Invalid expiry date/time.')
return
}
setSavingExpiry(true)
setError(null)
setActionStatus(null)
try {
const baseUrl = getApiBase()
const response = await authFetch(
`${baseUrl}/admin/users/${encodeURIComponent(user.username)}/expiry`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ expires_at: expiresAt }),
}
)
if (!response.ok) {
const text = await response.text()
throw new Error(text || 'Expiry update failed')
}
await loadUser()
setActionStatus(expiresAt ? 'User expiry updated.' : 'User expiry cleared.')
} catch (err) {
console.error(err)
setError('Could not update user expiry.')
} finally {
setSavingExpiry(false)
}
}
const clearUserExpiry = async () => {
if (!user) return
setSavingExpiry(true)
setError(null)
setActionStatus(null)
try {
const baseUrl = getApiBase()
const response = await authFetch(
`${baseUrl}/admin/users/${encodeURIComponent(user.username)}/expiry`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clear: true }),
}
)
if (!response.ok) {
const text = await response.text()
throw new Error(text || 'Expiry clear failed')
}
setExpiryInput('')
await loadUser()
setActionStatus('User expiry cleared.')
} catch (err) {
console.error(err)
setError('Could not clear user expiry.')
} finally {
setSavingExpiry(false)
}
}
useEffect(() => {
if (!getToken()) {
router.push('/login')
return
}
void loadUser()
void loadProfiles()
}, [router, idParam])
if (loading) {
@@ -177,6 +340,7 @@ export default function UserDetailPage() {
>
<section className="admin-section">
{error && <div className="error-banner">{error}</div>}
{actionStatus && <div className="status-banner">{actionStatus}</div>}
{!user ? (
<div className="status-banner">No user data found.</div>
) : (
@@ -196,6 +360,10 @@ export default function UserDetailPage() {
</span>
<span className="user-detail-chip">Role: {user.role}</span>
<span className="user-detail-chip">Login type: {user.auth_provider || 'local'}</span>
<span className="user-detail-chip">Profile: {user.profile_id ?? 'None'}</span>
<span className={`user-detail-chip ${user.is_expired ? 'is-blocked' : ''}`}>
Expiry: {user.expires_at ? formatDateTime(user.expires_at) : 'Never'}
</span>
<span className="user-detail-chip">Last login: {formatDateTime(user.last_login_at)}</span>
</div>
</div>
@@ -227,6 +395,63 @@ export default function UserDetailPage() {
{user.is_blocked ? 'Allow access' : 'Block access'}
</button>
</div>
<div className="user-detail-actions user-detail-actions--stacked">
<label className="admin-select">
<span>Assigned profile</span>
<select
value={profileSelection}
onChange={(event) => setProfileSelection(event.target.value)}
disabled={savingProfile}
>
<option value="">None</option>
{profiles.map((profile) => (
<option key={profile.id} value={profile.id}>
{profile.name}{profile.is_active === false ? ' (disabled)' : ''}
</option>
))}
</select>
</label>
<div className="admin-inline-actions">
<button type="button" onClick={() => void applyProfileToUser()} disabled={savingProfile}>
{savingProfile ? 'Applying...' : 'Apply profile defaults'}
</button>
<button
type="button"
className="ghost-button"
onClick={() => {
setProfileSelection('')
void applyProfileToUser('')
}}
disabled={savingProfile}
>
Clear profile
</button>
</div>
</div>
<div className="user-detail-actions user-detail-actions--stacked">
<label>
<span className="user-bulk-label">Account expiry</span>
<input
type="datetime-local"
value={expiryInput}
onChange={(event) => setExpiryInput(event.target.value)}
disabled={savingExpiry}
/>
</label>
<div className="admin-inline-actions">
<button type="button" onClick={saveUserExpiry} disabled={savingExpiry}>
{savingExpiry ? 'Saving...' : 'Save expiry'}
</button>
<button
type="button"
className="ghost-button"
onClick={clearUserExpiry}
disabled={savingExpiry}
>
Clear expiry
</button>
</div>
</div>
{user.role === 'admin' && (
<div className="user-detail-helper">
Admins always have auto search/download access.

View File

@@ -14,9 +14,18 @@ type AdminUser = {
lastLoginAt?: string | null
isBlocked?: boolean
autoSearchEnabled?: boolean
profileId?: number | null
expiresAt?: string | null
isExpired?: boolean
stats?: UserStats
}
type UserProfileOption = {
id: number
name: string
isActive?: boolean
}
type UserStats = {
total: number
ready: number
@@ -43,6 +52,13 @@ const formatLastRequest = (value?: string | null) => {
return date.toLocaleString()
}
const formatExpiry = (value?: string | null) => {
if (!value) return 'Never'
const date = new Date(value)
if (Number.isNaN(date.valueOf())) return value
return date.toLocaleString()
}
const emptyStats: UserStats = {
total: 0,
ready: 0,
@@ -76,6 +92,35 @@ export default function UsersPage() {
const [jellyseerrSyncBusy, setJellyseerrSyncBusy] = useState(false)
const [jellyseerrResyncBusy, setJellyseerrResyncBusy] = useState(false)
const [bulkAutoSearchBusy, setBulkAutoSearchBusy] = useState(false)
const [profiles, setProfiles] = useState<UserProfileOption[]>([])
const [bulkProfileId, setBulkProfileId] = useState('')
const [bulkProfileBusy, setBulkProfileBusy] = useState(false)
const [bulkExpiryDays, setBulkExpiryDays] = useState('')
const [bulkExpiryBusy, setBulkExpiryBusy] = useState(false)
const loadProfiles = async () => {
try {
const baseUrl = getApiBase()
const response = await authFetch(`${baseUrl}/admin/profiles`)
if (!response.ok) {
return
}
const data = await response.json()
if (!Array.isArray(data?.profiles)) {
setProfiles([])
return
}
setProfiles(
data.profiles.map((profile: any) => ({
id: Number(profile.id ?? 0),
name: String(profile.name ?? 'Unnamed profile'),
isActive: Boolean(profile.is_active ?? true),
}))
)
} catch (err) {
console.error(err)
}
}
const loadUsers = async () => {
try {
@@ -103,6 +148,12 @@ export default function UsersPage() {
lastLoginAt: user.last_login_at ?? null,
isBlocked: Boolean(user.is_blocked),
autoSearchEnabled: Boolean(user.auto_search_enabled ?? true),
profileId:
user.profile_id == null || Number.isNaN(Number(user.profile_id))
? null
: Number(user.profile_id),
expiresAt: user.expires_at ?? null,
isExpired: Boolean(user.is_expired),
id: Number(user.id ?? 0),
stats: normalizeStats(user.stats ?? emptyStats),
}))
@@ -238,12 +289,110 @@ export default function UsersPage() {
}
}
const bulkApplyProfile = async () => {
setBulkProfileBusy(true)
setJellyseerrSyncStatus(null)
setError(null)
try {
const baseUrl = getApiBase()
const response = await authFetch(`${baseUrl}/admin/users/profile/bulk`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
profile_id: bulkProfileId || null,
scope: 'non-admin-users',
}),
})
if (!response.ok) {
const text = await response.text()
throw new Error(text || 'Bulk profile update failed')
}
const data = await response.json()
setJellyseerrSyncStatus(
bulkProfileId
? `Applied profile ${bulkProfileId} to ${data?.updated ?? 0} non-admin users.`
: `Cleared profile assignment for ${data?.updated ?? 0} non-admin users.`
)
await loadUsers()
} catch (err) {
console.error(err)
setError('Could not apply profile to all users.')
} finally {
setBulkProfileBusy(false)
}
}
const bulkSetExpiryDays = async () => {
if (!bulkExpiryDays.trim()) {
setError('Enter expiry days before applying bulk expiry.')
return
}
setBulkExpiryBusy(true)
setJellyseerrSyncStatus(null)
setError(null)
try {
const baseUrl = getApiBase()
const response = await authFetch(`${baseUrl}/admin/users/expiry/bulk`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
days: bulkExpiryDays,
scope: 'non-admin-users',
}),
})
if (!response.ok) {
const text = await response.text()
throw new Error(text || 'Bulk expiry update failed')
}
const data = await response.json()
setJellyseerrSyncStatus(
`Set expiry for ${data?.updated ?? 0} non-admin users (${bulkExpiryDays} days).`
)
await loadUsers()
} catch (err) {
console.error(err)
setError('Could not set expiry for all users.')
} finally {
setBulkExpiryBusy(false)
}
}
const bulkClearExpiry = async () => {
setBulkExpiryBusy(true)
setJellyseerrSyncStatus(null)
setError(null)
try {
const baseUrl = getApiBase()
const response = await authFetch(`${baseUrl}/admin/users/expiry/bulk`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
clear: true,
scope: 'non-admin-users',
}),
})
if (!response.ok) {
const text = await response.text()
throw new Error(text || 'Bulk expiry clear failed')
}
const data = await response.json()
setJellyseerrSyncStatus(`Cleared expiry for ${data?.updated ?? 0} non-admin users.`)
await loadUsers()
} catch (err) {
console.error(err)
setError('Could not clear expiry for all users.')
} finally {
setBulkExpiryBusy(false)
}
}
useEffect(() => {
if (!getToken()) {
router.push('/login')
return
}
void loadUsers()
void loadProfiles()
}, [router])
if (loading) {
@@ -274,11 +423,11 @@ export default function UsersPage() {
<section className="admin-section">
{error && <div className="error-banner">{error}</div>}
{jellyseerrSyncStatus && <div className="status-banner">{jellyseerrSyncStatus}</div>}
<div className="user-bulk-toolbar">
<div className="user-bulk-summary">
<strong>Auto search/download</strong>
<span>
{autoSearchEnabledCount} of {nonAdminUsers.length} non-admin users enabled
<div className="user-bulk-toolbar">
<div className="user-bulk-summary">
<strong>Auto search/download</strong>
<span>
{autoSearchEnabledCount} of {nonAdminUsers.length} non-admin users enabled
</span>
</div>
<div className="user-bulk-actions">
@@ -299,6 +448,57 @@ export default function UsersPage() {
</button>
</div>
</div>
<div className="user-bulk-toolbar user-bulk-toolbar--stacked">
<div className="user-bulk-summary">
<strong>Profiles and expiry</strong>
<span>Apply invite profile defaults and account expiry to all non-admin users.</span>
</div>
<div className="user-bulk-groups">
<div className="user-bulk-group">
<label className="admin-select">
<span>Profile</span>
<select
value={bulkProfileId}
onChange={(e) => setBulkProfileId(e.target.value)}
disabled={bulkProfileBusy}
>
<option value="">None / clear assignment</option>
{profiles.map((profile) => (
<option key={profile.id} value={profile.id}>
{profile.name}{profile.isActive === false ? ' (disabled)' : ''}
</option>
))}
</select>
</label>
<button type="button" onClick={bulkApplyProfile} disabled={bulkProfileBusy}>
{bulkProfileBusy ? 'Applying...' : 'Apply profile to all users'}
</button>
</div>
<div className="user-bulk-group">
<label>
<span className="user-bulk-label">Expiry days</span>
<input
value={bulkExpiryDays}
onChange={(e) => setBulkExpiryDays(e.target.value)}
inputMode="numeric"
placeholder="e.g. 30"
disabled={bulkExpiryBusy}
/>
</label>
<button type="button" onClick={bulkSetExpiryDays} disabled={bulkExpiryBusy}>
{bulkExpiryBusy ? 'Working...' : 'Set expiry for all users'}
</button>
<button
type="button"
className="ghost-button"
onClick={bulkClearExpiry}
disabled={bulkExpiryBusy}
>
{bulkExpiryBusy ? 'Working...' : 'Clear expiry for all users'}
</button>
</div>
</div>
</div>
{users.length === 0 ? (
<div className="status-banner">No users found yet.</div>
) : (
@@ -322,6 +522,14 @@ export default function UsersPage() {
<span className={`user-grid-pill ${user.autoSearchEnabled === false ? 'is-disabled' : ''}`}>
Auto search {user.autoSearchEnabled === false ? 'Off' : 'On'}
</span>
<span className={`user-grid-pill ${user.isExpired ? 'is-blocked' : ''}`}>
{user.expiresAt
? `Expiry ${user.isExpired ? 'expired' : formatExpiry(user.expiresAt)}`
: 'Expiry Never'}
</span>
<span className="user-grid-pill">
Profile {user.profileId ?? 'None'}
</span>
</div>
<div className="user-grid-stats">
<div>