user creation and invites
This commit is contained in:
31
app/(auth)/admin/create-user/page.tsx
Normal file
31
app/(auth)/admin/create-user/page.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
'use client'
|
||||
import { useState } from 'react'
|
||||
|
||||
export default function CreateUserPage() {
|
||||
const [form, setForm] = useState({ username: '', password: '', role: 'GUEST' })
|
||||
const [success, setSuccess] = useState(false)
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
await fetch('/api/admin/create-user', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(form),
|
||||
})
|
||||
setSuccess(true)
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="max-w-sm mx-auto mt-10 space-y-4">
|
||||
<h1 className="text-xl font-bold">Create Local User</h1>
|
||||
<input placeholder="Username" onChange={e => setForm({ ...form, username: e.target.value })} />
|
||||
<input placeholder="Password" type="password" onChange={e => setForm({ ...form, password: e.target.value })} />
|
||||
<select onChange={e => setForm({ ...form, role: e.target.value })}>
|
||||
<option value="COUPLE">COUPLE</option>
|
||||
<option value="PLANNER">PLANNER</option>
|
||||
<option value="GUEST">GUEST</option>
|
||||
</select>
|
||||
<button className="btn">Create</button>
|
||||
{success && <p className="text-green-600">User created</p>}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import React from 'react'
|
||||
|
||||
export default async function DashboardPage() {
|
||||
const events = await queries.fetchEvents()
|
||||
console.log(events)
|
||||
// console.log(events)
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -12,15 +12,17 @@ export default async function DashboardPage() {
|
||||
<div className='border rounded-lg max-w-6xl mx-auto p-6 space-y-4'>
|
||||
<h2 className='text-xl font-bold'>Your Events</h2>
|
||||
{events.map((item) => (
|
||||
<div key={item.id}>
|
||||
<p>ID: {item.id}</p>
|
||||
<p>Name: {item.name}</p>
|
||||
<p>Date: {item.date ? item.date.toISOString() : 'null'}</p>
|
||||
<p>Location: {item.location ? item.location : 'null'}</p>
|
||||
<p>Creator ID:{item.creatorId}</p>
|
||||
<p>Created At:{item.createdAt.toISOString()}</p>
|
||||
|
||||
</div>
|
||||
<Link key={item.id} href={`/events/${item.id}`} >
|
||||
<div className='hover:cursor-pointer border rounded-xl p-2'>
|
||||
<p>ID: {item.id}</p>
|
||||
<p>Name: <strong>{item.name}</strong></p>
|
||||
<p>Date: {item.date ? item.date.toISOString() : 'null'}</p>
|
||||
<p>Location: {item.location ? item.location : 'null'}</p>
|
||||
<p>Creator ID:{item.creatorId}</p>
|
||||
<p>Created At:{item.createdAt.toISOString()}</p>
|
||||
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
<Link
|
||||
href={'/events'}
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { queries } from '@/lib/queries'
|
||||
import React from 'react'
|
||||
|
||||
export default function SingleEventPage() {
|
||||
export default async function SingleEventPage({ params }: { params: { eventId: string }}) {
|
||||
console.log(params)
|
||||
const data = await queries.singleEvent(params.eventId)
|
||||
|
||||
return (
|
||||
<div>
|
||||
SINGLE EVENT PAGE
|
||||
<h1 className='text-4xl font-bold'>
|
||||
{data?.name}
|
||||
</h1>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -10,10 +10,32 @@ export default async function EventsPage() {
|
||||
<div>
|
||||
Events
|
||||
<div>
|
||||
{allEvents.length == 0 && (
|
||||
{allEvents.length == 0 ? (
|
||||
<>
|
||||
You don't have any events yet. <Link href={'/events/create'} className='underline'>Create One!</Link>
|
||||
</>
|
||||
) : (
|
||||
<table className='table-auto w-full'>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Event Name</th>
|
||||
<th>Event Date</th>
|
||||
<th>Created by</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{allEvents.map((item) => (
|
||||
<tr
|
||||
key={item.id}
|
||||
className='text-center'
|
||||
>
|
||||
<td className=''><Link href={`/events/${item.id}`}>{item.name}</Link></td>
|
||||
<td className=''>{item.date?.toDateString()}</td>
|
||||
<td className=''>{item.creatorId}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
35
app/(auth)/user/[username]/page.tsx
Normal file
35
app/(auth)/user/[username]/page.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import SendInviteForm from '@/components/SendInviteForm';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { notFound } from 'next/navigation';
|
||||
import React from 'react'
|
||||
|
||||
export default async function UserPage({ params }: { params: { username: string } }) {
|
||||
const raw = params.username
|
||||
const username = raw.startsWith('@') ? raw.slice(1) : raw
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { username },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
name: true,
|
||||
role: true,
|
||||
createdAt: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!user) notFound()
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="max-w-2xl mx-auto py-10">
|
||||
<h1 className="text-3xl font-bold mb-2">@{username}</h1>
|
||||
<p className="text-gray-600">Email: {user.email}</p>
|
||||
<p className="text-gray-600">Role: {user.role}</p>
|
||||
<p className="text-gray-500 text-sm">Joined: {user.createdAt.toDateString()}</p>
|
||||
</div>
|
||||
<h2 className='text-xl font-bold'>Invite More People</h2>
|
||||
<SendInviteForm />
|
||||
</>
|
||||
)
|
||||
}
|
||||
12
app/(public)/invite/accept/page.tsx
Normal file
12
app/(public)/invite/accept/page.tsx
Normal file
@@ -0,0 +1,12 @@
|
||||
import { verifyInvite } from '@/lib/invite';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export default async function AcceptInvitePage({ searchParams }: { searchParams: { token?: string } }) {
|
||||
const invite = searchParams.token ? await verifyInvite(searchParams.token) : null
|
||||
|
||||
if (!invite || invite.accepted || new Date(invite.expiresAt) < new Date()) {
|
||||
return <div className='text-center mt-10'>Invalid or expired invitation.</div>
|
||||
}
|
||||
|
||||
redirect(`/signup?token=${invite.token}`)
|
||||
}
|
||||
@@ -7,6 +7,7 @@ export default function SetupPage() {
|
||||
const [role, setRole] = useState<'COUPLE' | 'PLANNER' | null>(null);
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [username, setUsername] = useState('');
|
||||
|
||||
async function handleSetup(e:React.FormEvent) {
|
||||
e.preventDefault();
|
||||
@@ -31,13 +32,13 @@ export default function SetupPage() {
|
||||
className='hover:cursor-pointer dark:bg-white dark:text-black rounded px-4 py-2'
|
||||
onClick={() => setRole('COUPLE')}
|
||||
>
|
||||
I'm part of the Couple
|
||||
I'm part of the Couple
|
||||
</button>
|
||||
<button
|
||||
className='hover:cursor-pointer dark:bg-white dark:text-black rounded px-4 py-2'
|
||||
onClick={() => setRole('PLANNER')}
|
||||
>
|
||||
I'm the Planner
|
||||
I'm the Planner
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
@@ -45,6 +46,13 @@ export default function SetupPage() {
|
||||
return (
|
||||
<form onSubmit={handleSetup} className="space-y-4">
|
||||
<h2>Create your account ({role})</h2>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Choose a username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="Email"
|
||||
|
||||
23
app/(public)/signup/page.tsx
Normal file
23
app/(public)/signup/page.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import { verifyInvite } from '@/lib/invite'
|
||||
import SignupForm from '@/components/SignupForm'
|
||||
|
||||
interface Props {
|
||||
searchParams: {
|
||||
token?: string
|
||||
}
|
||||
}
|
||||
|
||||
export default async function SignupPage({ searchParams }: Props) {
|
||||
const invite = searchParams.token ? await verifyInvite(searchParams.token) : null
|
||||
|
||||
if (!invite || invite.accepted || new Date(invite.expiresAt) < new Date()) {
|
||||
return <div className="text-center mt-10">Invalid or expired invitation.</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-md mx-auto mt-10">
|
||||
<h1 className="text-2xl font-bold mb-4">Complete Your Signup</h1>
|
||||
<SignupForm invite={invite} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
19
app/api/admin/create-user/route.ts
Normal file
19
app/api/admin/create-user/route.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { mutations } from '@/lib/mutations'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.json()
|
||||
|
||||
if (!body.username || !body.password || !body.role) {
|
||||
return new NextResponse('Missing fields', { status: 400 })
|
||||
}
|
||||
|
||||
const user = await mutations.createUser({
|
||||
username: body.username,
|
||||
password: body.password,
|
||||
role: body.role,
|
||||
email: '',
|
||||
})
|
||||
|
||||
return NextResponse.json({ id: user.id })
|
||||
}
|
||||
@@ -15,7 +15,6 @@ export const authOptions: NextAuthOptions = {
|
||||
},
|
||||
async authorize(credentials) {
|
||||
if (!credentials?.email || !credentials?.password) {
|
||||
console.log('[AUTH] Missing credentials')
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -24,28 +23,24 @@ export const authOptions: NextAuthOptions = {
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
console.log('[AUTH] User not found')
|
||||
return null
|
||||
}
|
||||
|
||||
if (!user.password) {
|
||||
console.log('[AUTH] User has no password set')
|
||||
return null
|
||||
}
|
||||
|
||||
const isValid = await bcrypt.compare(credentials.password, user.password)
|
||||
if (!isValid) {
|
||||
console.log('[AUTH] Invalid password')
|
||||
return null
|
||||
}
|
||||
|
||||
console.log('[AUTH] Successful login', user.email)
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
role: user.role,
|
||||
username: user.username!,
|
||||
}
|
||||
},
|
||||
}),
|
||||
@@ -58,6 +53,7 @@ export const authOptions: NextAuthOptions = {
|
||||
if (user) {
|
||||
token.id = user.id
|
||||
token.role = user.role
|
||||
token.username = user.username
|
||||
}
|
||||
return token
|
||||
},
|
||||
@@ -65,6 +61,7 @@ export const authOptions: NextAuthOptions = {
|
||||
if (session.user) {
|
||||
session.user.id = token.id as string
|
||||
session.user.role = token.role as "COUPLE" | "PLANNER" | "GUEST"
|
||||
session.user.username = token.username as string
|
||||
}
|
||||
return session
|
||||
},
|
||||
|
||||
52
app/api/invite/send/route.ts
Normal file
52
app/api/invite/send/route.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getServerSession } from 'next-auth'
|
||||
import { authOptions } from '../../auth/[...nextauth]/route'
|
||||
import { sendInviteEmail } from '@/lib/email'
|
||||
import { createInvite } from '@/lib/invite'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions)
|
||||
|
||||
if (!session?.user || !['COUPLE', 'PLANNER'].includes(session.user.role)) {
|
||||
return new NextResponse('Unauthorized', { status: 403 })
|
||||
}
|
||||
|
||||
const { email, role } = await req.json()
|
||||
if (!email || !role) {
|
||||
return NextResponse.json({ message: 'Missing email or role' }, { status: 400 })
|
||||
}
|
||||
|
||||
const existingUser = await prisma.user.findUnique({ where: { email } })
|
||||
if (existingUser) {
|
||||
return NextResponse.json({ message: 'User with this email already exists' }, { status: 400 })
|
||||
}
|
||||
|
||||
const existingInvite = await prisma.inviteToken.findFirst({
|
||||
where: {
|
||||
email,
|
||||
accepted: false,
|
||||
},
|
||||
})
|
||||
|
||||
if (existingInvite) {
|
||||
return NextResponse.json({ message: 'An invite already exists for this email' }, { status: 400 })
|
||||
}
|
||||
|
||||
const invite = await createInvite({ email, role })
|
||||
const inviteUrl = `${process.env.NEXT_PUBLIC_BASE_URL}/invite/accept?token=${invite.token}`
|
||||
|
||||
await sendInviteEmail({
|
||||
to: email,
|
||||
inviterName: session.user.email || 'A wedding planner',
|
||||
inviteUrl,
|
||||
role,
|
||||
})
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error) {
|
||||
console.error('[INVITE SEND ERROR]', error)
|
||||
return NextResponse.json({ message: 'Internal Server Error' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
20
app/api/invite/validate/route.ts
Normal file
20
app/api/invite/validate/route.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
// app/api/invite/validate/route.ts
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const { token } = await req.json()
|
||||
|
||||
const invite = await prisma.inviteToken.findUnique({
|
||||
where: { token },
|
||||
})
|
||||
|
||||
if (!invite || invite.accepted) {
|
||||
return new NextResponse('Invalid or expired invite', { status: 400 })
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
email: invite.email,
|
||||
role: invite.role,
|
||||
})
|
||||
}
|
||||
@@ -3,7 +3,14 @@ import { prisma } from '@/lib/prisma';
|
||||
import bcrypt from 'bcrypt';
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const { email, password, role } = await req.json();
|
||||
const { email, username, password, role } = await req.json();
|
||||
|
||||
const existingUsername = await prisma.user.findUnique({
|
||||
where: { username },
|
||||
})
|
||||
if (existingUsername) {
|
||||
return new NextResponse('Username already taken', { status: 400 })
|
||||
}
|
||||
|
||||
const existing = await prisma.user.findUnique({ where: { email }});
|
||||
if (existing) return new NextResponse('User already exists', { status: 400 });
|
||||
@@ -12,6 +19,7 @@ export async function POST(req: NextRequest) {
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
email,
|
||||
username,
|
||||
password: hashed,
|
||||
role
|
||||
}
|
||||
|
||||
55
app/api/signup/from-invite/route.ts
Normal file
55
app/api/signup/from-invite/route.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import bcrypt from 'bcrypt'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const { token, username, password } = await req.json()
|
||||
|
||||
if (!token || !username || !password) {
|
||||
return NextResponse.json({ message: 'Missing fields' }, { status: 400 })
|
||||
}
|
||||
|
||||
const invite = await prisma.inviteToken.findUnique({
|
||||
where: { token },
|
||||
})
|
||||
|
||||
if (!invite || invite.accepted || new Date(invite.expiresAt) < new Date()) {
|
||||
return NextResponse.json({ message: 'Invalid or expired invite' }, { status: 400 })
|
||||
}
|
||||
|
||||
const existingUser = await prisma.user.findFirst({
|
||||
where: {
|
||||
OR: [
|
||||
{ email: invite.email },
|
||||
{ username },
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
if (existingUser) {
|
||||
return NextResponse.json({ message: 'A user with this email or username already exists' }, { status: 400 })
|
||||
}
|
||||
|
||||
const hashedPassword = await bcrypt.hash(password, 10)
|
||||
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
email: invite.email,
|
||||
username,
|
||||
role: invite.role,
|
||||
password: hashedPassword,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.inviteToken.update({
|
||||
where: { token },
|
||||
data: { accepted: true },
|
||||
})
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (err) {
|
||||
console.error('[SIGNUP ERROR]', err)
|
||||
return new NextResponse('Internal Server Error', { status: 500 })
|
||||
}
|
||||
}
|
||||
12
app/api/test-email/route.ts
Normal file
12
app/api/test-email/route.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { sendInviteEmail } from '@/lib/email'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
export async function GET() {
|
||||
await sendInviteEmail({
|
||||
to: 'brian@briannelson.dev',
|
||||
token: 'testtoken123',
|
||||
inviterName: 'Test Admin',
|
||||
})
|
||||
|
||||
return NextResponse.json({ status: 'sent' })
|
||||
}
|
||||
Reference in New Issue
Block a user