feat: add company selection to user dialog, require email password link on user creation, password validation with confirmation, and company grouping with search
Some checks failed
Staging Build / build (push) Failing after 25s

This commit is contained in:
DanielS
2026-06-25 01:09:19 +02:00
parent 69c8e8e5c1
commit 4cd6d86f33
5 changed files with 373 additions and 119 deletions

View File

@@ -8,6 +8,8 @@ import { Suspense } from 'react'
export const dynamic = 'force-dynamic'
export default async function AdminUsersPage() {
const companies = await getCompanies()
return (
<div className="flex-1 space-y-8 p-8 pt-6">
<div className="flex items-center justify-between space-y-2">
@@ -21,7 +23,7 @@ export default async function AdminUsersPage() {
</p>
</div>
<div className="flex items-center space-x-2">
<UserDialog />
<UserDialog companies={companies} />
</div>
</div>
<Suspense fallback={<div className="h-40 w-full animate-pulse bg-white/5 rounded-xl" />}>

View File

@@ -1,6 +1,4 @@
'use client'
import { useState } from 'react'
import { useState, useRef, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
@@ -25,36 +23,53 @@ import {
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { createUser } from '@/lib/actions/users'
import { Plus } from 'lucide-react'
import { Plus, Building2 } from 'lucide-react'
const userSchema = z.object({
email: z.string().email('Ungültige E-Mail-Adresse'),
password: z.string().min(6, 'Passwort muss mindestens 6 Zeichen lang sein').optional().or(z.literal('')),
role: z.enum(['admin', 'partner']),
company_id: z.string().optional().or(z.literal('')),
})
type UserFormValues = z.infer<typeof userSchema>
export function UserDialog() {
interface UserDialogProps {
companies: { id: string; name: string }[]
}
export function UserDialog({ companies }: UserDialogProps) {
const [open, setOpen] = useState(false)
const [dropdownOpen, setDropdownOpen] = useState(false)
const [search, setSearch] = useState('')
const dropdownRef = useRef<HTMLDivElement>(null)
const router = useRouter()
useEffect(() => {
function handleClickOutside(e: MouseEvent) {
if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
setDropdownOpen(false)
setSearch('')
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [])
const form = useForm<UserFormValues>({
resolver: zodResolver(userSchema) as any,
defaultValues: {
email: '',
password: '',
role: 'partner',
company_id: '',
},
})
async function onSubmit(values: UserFormValues) {
try {
// If password is empty string, omit it
const payload = {
email: values.email,
role: values.role,
...(values.password ? { password: values.password } : {})
company_id: values.company_id || undefined,
}
await createUser(payload)
setOpen(false)
@@ -66,7 +81,14 @@ export function UserDialog() {
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<Dialog open={open} onOpenChange={(val) => {
setOpen(val)
if (!val) {
form.reset()
setDropdownOpen(false)
setSearch('')
}
}}>
<DialogTrigger asChild>
<Button className="bg-primary hover:bg-primary/90">
<Plus className="mr-2 h-4 w-4" /> Benutzer neu anlegen
@@ -76,7 +98,7 @@ export function UserDialog() {
<DialogHeader>
<DialogTitle>Neuen Benutzer anlegen</DialogTitle>
<DialogDescription className="text-slate-300">
Geben Sie die E-Mail, die Rolle und optional ein Passwort für den neuen Benutzer ein.
Geben Sie die E-Mail, die Rolle und optional die Firma für den neuen Benutzer ein. Nach der Erstellung erhält der Benutzer eine E-Mail zum Festlegen seines Passworts.
</DialogDescription>
</DialogHeader>
@@ -116,16 +138,80 @@ export function UserDialog() {
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel className="text-white">Passwort (optional)</FormLabel>
name="company_id"
render={({ field }) => {
const selectedCompany = companies.find((c) => c.id === field.value)
return (
<FormItem className="flex flex-col">
<FormLabel className="text-white">Firma (optional)</FormLabel>
<FormControl>
<Input type="password" placeholder="Passwort leer lassen für Zufall" className="bg-white/5 border-white/10 text-white" {...field} />
<div className="relative" ref={dropdownRef}>
<div className="flex items-center gap-2">
<Building2 className="w-4 h-4 text-slate-500 shrink-0" />
<button
type="button"
onClick={() => {
setDropdownOpen(!dropdownOpen)
setSearch('')
}}
className="w-full text-left text-sm bg-white/5 border border-white/10 rounded-md px-3 py-2 text-slate-300 hover:bg-white/10 cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 max-w-full truncate"
>
{selectedCompany ? selectedCompany.name : 'Keine Firma'}
</button>
</div>
{dropdownOpen && (
<div className="absolute z-50 mt-1 left-0 w-full bg-slate-900 border border-white/10 rounded-lg shadow-xl overflow-hidden">
<div className="p-2 border-b border-white/10">
<input
type="text"
placeholder="Firma suchen..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="w-full text-xs bg-white/5 border border-white/10 rounded px-2 py-1.5 text-slate-200 placeholder-slate-500 focus:outline-none focus:ring-1 focus:ring-primary/50"
autoFocus
/>
</div>
<div className="max-h-40 overflow-y-auto">
<button
type="button"
onClick={() => {
field.onChange('')
setDropdownOpen(false)
setSearch('')
}}
className={`w-full text-left text-xs px-3 py-2 hover:bg-white/10 transition-colors ${
!field.value ? 'text-primary font-semibold' : 'text-slate-300'
}`}
>
Keine Firma
</button>
{companies
.filter((c) => c.name.toLowerCase().includes(search.toLowerCase()))
.map((c) => (
<button
key={c.id}
type="button"
onClick={() => {
field.onChange(c.id)
setDropdownOpen(false)
setSearch('')
}}
className={`w-full text-left text-xs px-3 py-2 hover:bg-white/10 transition-colors ${
field.value === c.id ? 'text-primary font-semibold' : 'text-slate-300'
}`}
>
{c.name}
</button>
))}
</div>
</div>
)}
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
)
}}
/>
<DialogFooter>
<Button type="submit" className="w-full bg-primary hover:bg-primary/90">

View File

@@ -1,6 +1,6 @@
'use client'
import { useState } from 'react'
import { useState, useRef, useEffect, Fragment } from 'react'
import { useRouter } from 'next/navigation'
import {
Table,
@@ -11,7 +11,7 @@ import {
TableRow,
} from '@/components/ui/table'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Key, Trash2, Mail, Loader2, Building2, Ban, Unlock } from 'lucide-react'
import { Key, Trash2, Mail, Loader2, Building2, Ban, Unlock, Search } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { deleteUser, resetPassword, updateUserRole } from '@/lib/actions/users'
import { assignCompanyToUser } from '@/lib/actions/companies'
@@ -39,6 +39,22 @@ interface UserListProps {
export function UserList({ initialUsers, companies }: UserListProps) {
const router = useRouter()
const [loadingId, setLoadingId] = useState<string | null>(null)
const [companyDropdownOpen, setCompanyDropdownOpen] = useState<string | null>(null)
const [companySearch, setCompanySearch] = useState('')
const [searchQuery, setSearchQuery] = useState('')
const [groupByCompany, setGroupByCompany] = useState(false)
const dropdownRef = useRef<HTMLDivElement>(null)
useEffect(() => {
function handleClickOutside(e: MouseEvent) {
if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
setCompanyDropdownOpen(null)
setCompanySearch('')
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [])
const handleDelete = async (id: string) => {
if (confirm('Möchten Sie diesen Benutzer wirklich löschen?')) {
@@ -95,6 +111,25 @@ export function UserList({ initialUsers, companies }: UserListProps) {
}
}
const filteredUsers = initialUsers.filter((user) => {
const emailMatch = user.email?.toLowerCase().includes(searchQuery.toLowerCase())
const companyMatch = user.company_name?.toLowerCase().includes(searchQuery.toLowerCase())
const roleMatch = user.role?.toLowerCase().includes(searchQuery.toLowerCase())
return emailMatch || companyMatch || roleMatch
})
const displayUsers = groupByCompany
? [...filteredUsers].sort((a, b) => {
const nameA = a.company_name || 'Keine Firma'
const nameB = b.company_name || 'Keine Firma'
if (!a.company_name && b.company_name) return 1
if (a.company_name && !b.company_name) return -1
return nameA.localeCompare(nameB)
})
: filteredUsers
let lastCompanyName: string | null = null
return (
<Card className="glass-dark border-white/10 shadow-2xl overflow-hidden">
<CardHeader>
@@ -104,6 +139,30 @@ export function UserList({ initialUsers, companies }: UserListProps) {
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
<div className="relative w-full max-w-sm">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500" />
<input
type="text"
placeholder="Benutzer suchen (E-Mail, Firma, Rolle)..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pl-9 pr-4 py-2 text-sm bg-white/5 border border-white/10 rounded-md text-slate-200 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 focus:ring-offset-slate-950 transition-all"
/>
</div>
<div className="flex items-center gap-2 bg-white/5 border border-white/10 rounded-md px-3 py-2 cursor-pointer hover:bg-white/10 transition-colors">
<input
type="checkbox"
id="groupByCompany"
checked={groupByCompany}
onChange={(e) => setGroupByCompany(e.target.checked)}
className="h-4 w-4 rounded border-white/10 bg-slate-950 text-primary focus:ring-primary focus:ring-offset-slate-950 accent-primary cursor-pointer"
/>
<label htmlFor="groupByCompany" className="text-xs text-slate-300 font-medium cursor-pointer select-none">
Nach Firma gruppieren
</label>
</div>
</div>
<Table>
<TableHeader>
<TableRow className="border-white/10 hover:bg-white/5">
@@ -115,14 +174,26 @@ export function UserList({ initialUsers, companies }: UserListProps) {
</TableRow>
</TableHeader>
<TableBody>
{initialUsers.map((user) => {
{displayUsers.map((user: any) => {
const role: Role = (['admin', 'partner', 'gesperrt'].includes(user.role) ? user.role : 'partner') as Role
const isLoadingRole = loadingId === user.id + '-role'
const isLoadingCompany = loadingId === user.id + '-company'
const isLoadingDelete = loadingId === user.id
const currentCompanyName = user.company_name || 'Keine Firma'
const showGroupHeader = groupByCompany && currentCompanyName !== lastCompanyName
lastCompanyName = currentCompanyName
return (
<TableRow key={user.id} className="border-white/5 hover:bg-white/5 transition-colors">
<Fragment key={user.id}>
{showGroupHeader && (
<TableRow className="bg-white/5 border-y border-white/10 hover:bg-white/5">
<TableCell colSpan={5} className="font-semibold text-primary py-2 px-4 text-xs tracking-wider uppercase">
Firma: {currentCompanyName}
</TableCell>
</TableRow>
)}
<TableRow className="border-white/5 hover:bg-white/5 transition-colors">
<TableCell className="font-medium text-white">
<div className="flex items-center gap-2">
<Mail className="w-4 h-4 text-slate-500" />
@@ -131,16 +202,20 @@ export function UserList({ initialUsers, companies }: UserListProps) {
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<Badge className={ROLE_BADGE_CLASSES[role]}>
{ROLE_LABELS[role]}
</Badge>
{isLoadingRole ? (
<Loader2 className="h-4 w-4 animate-spin text-slate-400" />
) : (
<select
value={role}
onChange={(e) => handleRoleChange(user.id, e.target.value as Role)}
className="ml-1 text-xs bg-white/5 border border-white/10 rounded px-2 py-1 text-slate-300 hover:bg-white/10 cursor-pointer focus:outline-none focus:ring-1 focus:ring-primary/50"
className={`text-xs font-semibold rounded px-3 py-1.5 cursor-pointer focus:outline-none focus:ring-2 transition-colors ${
role === 'admin'
? 'bg-purple-500/20 text-purple-300 border border-purple-500/40 focus:ring-purple-500/50'
: role === 'gesperrt'
? 'bg-red-500/20 text-red-300 border border-red-500/40 focus:ring-red-500/50'
: 'bg-blue-500/20 text-blue-300 border border-blue-500/40 focus:ring-blue-500/50'
}`}
style={{ appearance: 'auto' }}
>
<option value="admin">Admin</option>
<option value="partner">Partner</option>
@@ -150,21 +225,62 @@ export function UserList({ initialUsers, companies }: UserListProps) {
</div>
</TableCell>
<TableCell>
<div className="relative" ref={companyDropdownOpen === user.id ? dropdownRef : undefined}>
<div className="flex items-center gap-2">
<Building2 className="w-4 h-4 text-slate-500 shrink-0" />
{isLoadingCompany ? (
<Loader2 className="h-4 w-4 animate-spin text-slate-400" />
) : (
<select
value={user.company_id || ''}
onChange={(e) => handleCompanyChange(user.id, e.target.value)}
className="text-xs bg-white/5 border border-white/10 rounded px-2 py-1 text-slate-300 hover:bg-white/10 cursor-pointer focus:outline-none focus:ring-1 focus:ring-primary/50 max-w-[150px]"
<button
type="button"
onClick={() => {
setCompanyDropdownOpen(companyDropdownOpen === user.id ? null : user.id)
setCompanySearch('')
}}
className="text-xs bg-white/5 border border-white/10 rounded px-3 py-1.5 text-slate-300 hover:bg-white/10 cursor-pointer focus:outline-none focus:ring-1 focus:ring-primary/50 max-w-[180px] truncate text-left"
>
<option value="">Keine Firma</option>
{companies.map((c) => (
<option key={c.id} value={c.id}>{c.name}</option>
{user.company_name || 'Keine Firma'}
</button>
)}
</div>
{companyDropdownOpen === user.id && (
<div className="absolute z-50 mt-1 left-0 w-56 bg-slate-900 border border-white/10 rounded-lg shadow-xl overflow-hidden">
<div className="p-2 border-b border-white/10">
<input
type="text"
placeholder="Firma suchen..."
value={companySearch}
onChange={(e) => setCompanySearch(e.target.value)}
className="w-full text-xs bg-white/5 border border-white/10 rounded px-2 py-1.5 text-slate-200 placeholder-slate-500 focus:outline-none focus:ring-1 focus:ring-primary/50"
autoFocus
/>
</div>
<div className="max-h-40 overflow-y-auto">
<button
type="button"
onClick={() => { handleCompanyChange(user.id, ''); setCompanyDropdownOpen(null); setCompanySearch(''); }}
className={`w-full text-left text-xs px-3 py-2 hover:bg-white/10 transition-colors ${
!user.company_id ? 'text-primary font-semibold' : 'text-slate-300'
}`}
>
Keine Firma
</button>
{companies
.filter((c) => c.name.toLowerCase().includes(companySearch.toLowerCase()))
.map((c) => (
<button
key={c.id}
type="button"
onClick={() => { handleCompanyChange(user.id, c.id); setCompanyDropdownOpen(null); setCompanySearch(''); }}
className={`w-full text-left text-xs px-3 py-2 hover:bg-white/10 transition-colors ${
user.company_id === c.id ? 'text-primary font-semibold' : 'text-slate-300'
}`}
>
{c.name}
</button>
))}
</select>
</div>
</div>
)}
</div>
</TableCell>
@@ -205,6 +321,7 @@ export function UserList({ initialUsers, companies }: UserListProps) {
</div>
</TableCell>
</TableRow>
</Fragment>
)
})}
</TableBody>

View File

@@ -20,6 +20,7 @@ export function UpdatePasswordForm({
...props
}: React.ComponentPropsWithoutRef<"div">) {
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
@@ -29,11 +30,23 @@ export function UpdatePasswordForm({
setIsLoading(true);
setError(null);
if (password.length < 6) {
setError("Passwort muss mindestens 6 Zeichen lang sein.");
setIsLoading(false);
return;
}
if (password !== confirmPassword) {
setError("Die Passwörter stimmen nicht überein.");
setIsLoading(false);
return;
}
try {
await updatePassword(password);
router.push("/");
} catch (error: unknown) {
setError(error instanceof Error ? error.message : "An error occurred");
setError(error instanceof Error ? error.message : "Ein Fehler ist aufgetreten");
} finally {
setIsLoading(false);
}
@@ -41,30 +54,43 @@ export function UpdatePasswordForm({
return (
<div className={cn("flex flex-col gap-6", className)} {...props}>
<Card>
<Card className="glass-dark border-white/10 text-white shadow-2xl">
<CardHeader>
<CardTitle className="text-2xl">Reset Your Password</CardTitle>
<CardDescription>
Please enter your new password below.
<CardTitle className="text-2xl">Neues Passwort festlegen</CardTitle>
<CardDescription className="text-slate-300">
Bitte geben Sie Ihr neues Passwort ein und bestätigen Sie es.
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleForgotPassword}>
<div className="flex flex-col gap-6">
<div className="grid gap-2">
<Label htmlFor="password">New password</Label>
<Label htmlFor="password">Neues Passwort</Label>
<Input
id="password"
type="password"
placeholder="New password"
placeholder="Neues Passwort"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
className="bg-white/5 border-white/10 text-white"
/>
</div>
<div className="grid gap-2">
<Label htmlFor="confirmPassword">Passwort bestätigen</Label>
<Input
id="confirmPassword"
type="password"
placeholder="Passwort bestätigen"
required
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="bg-white/5 border-white/10 text-white"
/>
</div>
{error && <p className="text-sm text-red-500">{error}</p>}
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? "Saving..." : "Save new password"}
<Button type="submit" className="w-full bg-primary hover:bg-primary/90" disabled={isLoading}>
{isLoading ? "Speichern..." : "Neues Passwort speichern"}
</Button>
</div>
</form>

View File

@@ -32,11 +32,11 @@ export async function getUsers() {
}));
}
export async function createUser(data: { email: string; password?: string; role?: 'admin' | 'partner'; email_confirm?: boolean; company_id?: string }) {
export async function createUser(data: { email: string; role?: 'admin' | 'partner'; email_confirm?: boolean; company_id?: string }) {
const admin = createAdminClient();
const { data: { user }, error } = await admin.auth.admin.createUser({
email: data.email,
password: data.password || Math.random().toString(36).slice(-10),
password: Math.random().toString(36).slice(-10) + Math.random().toString(36).slice(-10),
email_confirm: data.email_confirm ?? true,
});
if (error) throw error;
@@ -48,6 +48,29 @@ export async function createUser(data: { email: string; password?: string; role?
.upsert({ id: user.id, role, company_id: data.company_id || null }, { onConflict: 'id' });
if (dbError) throw dbError;
// Generate recovery link to let user set password
try {
const { data: linkData, error: linkError } = await admin.auth.admin.generateLink({
type: 'recovery',
email: data.email,
});
if (!linkError && linkData) {
const tokenHash = (linkData as any)?.properties?.hashed_token;
if (tokenHash) {
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://staging.hephex.de';
const setupLink = `${siteUrl}/auth/confirm?token_hash=${tokenHash}&type=recovery&next=/auth/update-password`;
await sendMail({
to: data.email,
subject: 'Willkommen bei Hephex - Passwort erstellen',
text: `Ihr Account wurde erstellt. Klicken Sie auf den folgenden Link, um Ihr Passwort festzulegen und Ihr Konto zu aktivieren: ${setupLink}`,
html: `<p>Ihr Account wurde erstellt.</p><p>Klicken Sie <a href="${setupLink}">hier</a>, um Ihr Passwort festzulegen und Ihr Konto zu aktivieren.</p>`,
});
}
}
} catch (mailError) {
console.error('Failed to send welcome setup mail:', mailError);
}
revalidatePath('/admin/users');
return user;
}