aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorschererleander <leander@schererleander.de>2025-07-02 22:18:13 +0200
committerschererleander <leander@schererleander.de>2025-07-02 22:18:13 +0200
commitc12ca8a52d27b1931d826df10119984f2a7c58dd (patch)
treeeca7e5e8f5f7fb7351047b49036def52b66172b2
parent899d50098c20c5652040e989932628d63af28301 (diff)
feat: add authentication API
-rw-r--r--src/app/api/auth/[...nextauth]/route.ts6
-rw-r--r--src/app/api/auth/register/route.ts61
2 files changed, 67 insertions, 0 deletions
diff --git a/src/app/api/auth/[...nextauth]/route.ts b/src/app/api/auth/[...nextauth]/route.ts
new file mode 100644
index 0000000..264f925
--- /dev/null
+++ b/src/app/api/auth/[...nextauth]/route.ts
@@ -0,0 +1,6 @@
+import NextAuth from "next-auth"
+import { authOptions } from "@/lib/auth"
+
+const handler = NextAuth(authOptions)
+
+export { handler as GET, handler as POST } \ No newline at end of file
diff --git a/src/app/api/auth/register/route.ts b/src/app/api/auth/register/route.ts
new file mode 100644
index 0000000..3276756
--- /dev/null
+++ b/src/app/api/auth/register/route.ts
@@ -0,0 +1,61 @@
+import { NextRequest, NextResponse } from "next/server"
+import bcrypt from "bcryptjs"
+import dbConnect from "@/lib/mongodb"
+import User from "@/model/User"
+import { registerSchema, formatZodError } from "@/lib/validation"
+
+export async function POST(request: NextRequest) {
+ try {
+ const body = await request.json()
+
+ const result = registerSchema.safeParse(body)
+
+ if (!result.success) {
+ const errors = formatZodError(result.error)
+
+ return NextResponse.json(
+ { error: "Validation failed", details: errors },
+ { status: 400 }
+ )
+ }
+
+ const { name, email, password } = result.data
+
+ await dbConnect()
+
+ const existingUser = await User.findOne({ email })
+ if (existingUser) {
+ return NextResponse.json(
+ { error: "User already exists" },
+ { status: 409 }
+ )
+ }
+
+ const hashedPassword = await bcrypt.hash(password, 12)
+
+ const user = await User.create({
+ name,
+ email,
+ password: hashedPassword,
+ })
+
+ return NextResponse.json(
+ { message: "User created successfully", userId: user._id },
+ { status: 201 }
+ )
+ } catch (error) {
+ console.error("Registration error:", error)
+
+ if (error && typeof error === 'object' && 'code' in error && error.code === 11000) {
+ return NextResponse.json(
+ { error: "User already exists" },
+ { status: 409 }
+ )
+ }
+
+ return NextResponse.json(
+ { error: "Internal server error" },
+ { status: 500 }
+ )
+ }
+} \ No newline at end of file