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 const dynamic = 'force-dynamic'
export default async function AdminUsersPage() { export default async function AdminUsersPage() {
const companies = await getCompanies()
return ( return (
<div className="flex-1 space-y-8 p-8 pt-6"> <div className="flex-1 space-y-8 p-8 pt-6">
<div className="flex items-center justify-between space-y-2"> <div className="flex items-center justify-between space-y-2">
@@ -21,7 +23,7 @@ export default async function AdminUsersPage() {
</p> </p>
</div> </div>
<div className="flex items-center space-x-2"> <div className="flex items-center space-x-2">
<UserDialog /> <UserDialog companies={companies} />
</div> </div>
</div> </div>
<Suspense fallback={<div className="h-40 w-full animate-pulse bg-white/5 rounded-xl" />}> <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, useRef, useEffect } from 'react'
import { useState } from 'react'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import { useForm } from 'react-hook-form' import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod' import { zodResolver } from '@hookform/resolvers/zod'
@@ -25,36 +23,53 @@ import {
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { createUser } from '@/lib/actions/users' import { createUser } from '@/lib/actions/users'
import { Plus } from 'lucide-react' import { Plus, Building2 } from 'lucide-react'
const userSchema = z.object({ const userSchema = z.object({
email: z.string().email('Ungültige E-Mail-Adresse'), 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']), role: z.enum(['admin', 'partner']),
company_id: z.string().optional().or(z.literal('')),
}) })
type UserFormValues = z.infer<typeof userSchema> 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 [open, setOpen] = useState(false)
const [dropdownOpen, setDropdownOpen] = useState(false)
const [search, setSearch] = useState('')
const dropdownRef = useRef<HTMLDivElement>(null)
const router = useRouter() 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>({ const form = useForm<UserFormValues>({
resolver: zodResolver(userSchema) as any, resolver: zodResolver(userSchema) as any,
defaultValues: { defaultValues: {
email: '', email: '',
password: '',
role: 'partner', role: 'partner',
company_id: '',
}, },
}) })
async function onSubmit(values: UserFormValues) { async function onSubmit(values: UserFormValues) {
try { try {
// If password is empty string, omit it
const payload = { const payload = {
email: values.email, email: values.email,
role: values.role, role: values.role,
...(values.password ? { password: values.password } : {}) company_id: values.company_id || undefined,
} }
await createUser(payload) await createUser(payload)
setOpen(false) setOpen(false)
@@ -66,7 +81,14 @@ export function UserDialog() {
} }
return ( return (
<Dialog open={open} onOpenChange={setOpen}> <Dialog open={open} onOpenChange={(val) => {
setOpen(val)
if (!val) {
form.reset()
setDropdownOpen(false)
setSearch('')
}
}}>
<DialogTrigger asChild> <DialogTrigger asChild>
<Button className="bg-primary hover:bg-primary/90"> <Button className="bg-primary hover:bg-primary/90">
<Plus className="mr-2 h-4 w-4" /> Benutzer neu anlegen <Plus className="mr-2 h-4 w-4" /> Benutzer neu anlegen
@@ -76,7 +98,7 @@ export function UserDialog() {
<DialogHeader> <DialogHeader>
<DialogTitle>Neuen Benutzer anlegen</DialogTitle> <DialogTitle>Neuen Benutzer anlegen</DialogTitle>
<DialogDescription className="text-slate-300"> <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> </DialogDescription>
</DialogHeader> </DialogHeader>
@@ -116,16 +138,80 @@ export function UserDialog() {
/> />
<FormField <FormField
control={form.control} control={form.control}
name="password" name="company_id"
render={({ field }) => ( render={({ field }) => {
<FormItem> const selectedCompany = companies.find((c) => c.id === field.value)
<FormLabel className="text-white">Passwort (optional)</FormLabel> return (
<FormItem className="flex flex-col">
<FormLabel className="text-white">Firma (optional)</FormLabel>
<FormControl> <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> </FormControl>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
)} )
}}
/> />
<DialogFooter> <DialogFooter>
<Button type="submit" className="w-full bg-primary hover:bg-primary/90"> <Button type="submit" className="w-full bg-primary hover:bg-primary/90">

View File

@@ -1,6 +1,6 @@
'use client' 'use client'
import { useState } from 'react' import { useState, useRef, useEffect, Fragment } from 'react'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import { import {
Table, Table,
@@ -11,7 +11,7 @@ import {
TableRow, TableRow,
} from '@/components/ui/table' } from '@/components/ui/table'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' 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 { Button } from '@/components/ui/button'
import { deleteUser, resetPassword, updateUserRole } from '@/lib/actions/users' import { deleteUser, resetPassword, updateUserRole } from '@/lib/actions/users'
import { assignCompanyToUser } from '@/lib/actions/companies' import { assignCompanyToUser } from '@/lib/actions/companies'
@@ -39,6 +39,22 @@ interface UserListProps {
export function UserList({ initialUsers, companies }: UserListProps) { export function UserList({ initialUsers, companies }: UserListProps) {
const router = useRouter() const router = useRouter()
const [loadingId, setLoadingId] = useState<string | null>(null) 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) => { const handleDelete = async (id: string) => {
if (confirm('Möchten Sie diesen Benutzer wirklich löschen?')) { 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 ( return (
<Card className="glass-dark border-white/10 shadow-2xl overflow-hidden"> <Card className="glass-dark border-white/10 shadow-2xl overflow-hidden">
<CardHeader> <CardHeader>
@@ -104,6 +139,30 @@ export function UserList({ initialUsers, companies }: UserListProps) {
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent> <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> <Table>
<TableHeader> <TableHeader>
<TableRow className="border-white/10 hover:bg-white/5"> <TableRow className="border-white/10 hover:bg-white/5">
@@ -115,14 +174,26 @@ export function UserList({ initialUsers, companies }: UserListProps) {
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{initialUsers.map((user) => { {displayUsers.map((user: any) => {
const role: Role = (['admin', 'partner', 'gesperrt'].includes(user.role) ? user.role : 'partner') as Role const role: Role = (['admin', 'partner', 'gesperrt'].includes(user.role) ? user.role : 'partner') as Role
const isLoadingRole = loadingId === user.id + '-role' const isLoadingRole = loadingId === user.id + '-role'
const isLoadingCompany = loadingId === user.id + '-company' const isLoadingCompany = loadingId === user.id + '-company'
const isLoadingDelete = loadingId === user.id const isLoadingDelete = loadingId === user.id
const currentCompanyName = user.company_name || 'Keine Firma'
const showGroupHeader = groupByCompany && currentCompanyName !== lastCompanyName
lastCompanyName = currentCompanyName
return ( 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"> <TableCell className="font-medium text-white">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Mail className="w-4 h-4 text-slate-500" /> <Mail className="w-4 h-4 text-slate-500" />
@@ -131,16 +202,20 @@ export function UserList({ initialUsers, companies }: UserListProps) {
</TableCell> </TableCell>
<TableCell> <TableCell>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Badge className={ROLE_BADGE_CLASSES[role]}>
{ROLE_LABELS[role]}
</Badge>
{isLoadingRole ? ( {isLoadingRole ? (
<Loader2 className="h-4 w-4 animate-spin text-slate-400" /> <Loader2 className="h-4 w-4 animate-spin text-slate-400" />
) : ( ) : (
<select <select
value={role} value={role}
onChange={(e) => handleRoleChange(user.id, e.target.value as 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="admin">Admin</option>
<option value="partner">Partner</option> <option value="partner">Partner</option>
@@ -150,21 +225,62 @@ export function UserList({ initialUsers, companies }: UserListProps) {
</div> </div>
</TableCell> </TableCell>
<TableCell> <TableCell>
<div className="relative" ref={companyDropdownOpen === user.id ? dropdownRef : undefined}>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Building2 className="w-4 h-4 text-slate-500 shrink-0" /> <Building2 className="w-4 h-4 text-slate-500 shrink-0" />
{isLoadingCompany ? ( {isLoadingCompany ? (
<Loader2 className="h-4 w-4 animate-spin text-slate-400" /> <Loader2 className="h-4 w-4 animate-spin text-slate-400" />
) : ( ) : (
<select <button
value={user.company_id || ''} type="button"
onChange={(e) => handleCompanyChange(user.id, e.target.value)} onClick={() => {
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]" 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> {user.company_name || 'Keine Firma'}
{companies.map((c) => ( </button>
<option key={c.id} value={c.id}>{c.name}</option> )}
</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> </div>
</TableCell> </TableCell>
@@ -205,6 +321,7 @@ export function UserList({ initialUsers, companies }: UserListProps) {
</div> </div>
</TableCell> </TableCell>
</TableRow> </TableRow>
</Fragment>
) )
})} })}
</TableBody> </TableBody>

View File

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