Added user tab and oauth2, streamlined readme

This commit is contained in:
fuomag9
2025-12-28 15:14:56 +01:00
parent f8a673cc03
commit be21f46ad5
28 changed files with 3213 additions and 245 deletions

View File

@@ -0,0 +1,75 @@
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/src/lib/auth";
import { getUserById, updateUserPassword } from "@/src/lib/models/user";
import { createAuditEvent } from "@/src/lib/models/audit";
import bcrypt from "bcryptjs";
export async function POST(request: NextRequest) {
try {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const body = await request.json();
const { currentPassword, newPassword } = body;
if (!newPassword || newPassword.length < 12) {
return NextResponse.json(
{ error: "New password must be at least 12 characters long" },
{ status: 400 }
);
}
const userId = Number(session.user.id);
const user = await getUserById(userId);
if (!user) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
// If user has a password, verify current password
if (user.password_hash) {
if (!currentPassword) {
return NextResponse.json(
{ error: "Current password is required" },
{ status: 400 }
);
}
const isValid = bcrypt.compareSync(currentPassword, user.password_hash);
if (!isValid) {
return NextResponse.json(
{ error: "Current password is incorrect" },
{ status: 401 }
);
}
}
// Hash new password
const newPasswordHash = bcrypt.hashSync(newPassword, 12);
// Update password
await updateUserPassword(userId, newPasswordHash);
// Audit log
await createAuditEvent({
userId,
action: user.password_hash ? "password_changed" : "password_set",
entityType: "user",
entityId: userId,
summary: user.password_hash ? "User changed their password" : "User set a password",
});
return NextResponse.json({
success: true,
message: "Password updated successfully"
});
} catch (error) {
console.error("Password change error:", error);
return NextResponse.json(
{ error: "Failed to change password" },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,72 @@
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/src/lib/auth";
import db, { nowIso } from "@/src/lib/db";
import { pendingOAuthLinks } from "@/src/lib/db/schema";
import { eq, and, lt } from "drizzle-orm";
import { registerFailedAttempt } from "@/src/lib/rate-limit";
export async function POST(request: NextRequest) {
try {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const userId = Number(session.user.id);
// Rate limiting: prevent OAuth linking spam
const rateLimitKey = `oauth-link:${userId}`;
const rateLimitResult = registerFailedAttempt(rateLimitKey);
if (rateLimitResult.blocked) {
return NextResponse.json(
{ error: "Too many OAuth linking attempts. Please try again later." },
{ status: 429 }
);
}
const body = await request.json();
const { provider } = body;
if (!provider) {
return NextResponse.json({ error: "Provider is required" }, { status: 400 });
}
const userEmail = session.user.email;
if (!userEmail) {
return NextResponse.json({ error: "User email not found" }, { status: 400 });
}
const now = new Date();
const expiresAt = new Date(now.getTime() + 5 * 60 * 1000); // 5 minutes from now
// Clean up old expired entries for all users
await db.delete(pendingOAuthLinks).where(lt(pendingOAuthLinks.expiresAt, nowIso()));
// Delete any existing pending link for THIS USER and this provider
// (unique index will prevent duplicates, but we delete explicitly for clarity)
await db.delete(pendingOAuthLinks).where(
and(
eq(pendingOAuthLinks.userId, userId),
eq(pendingOAuthLinks.provider, provider)
)
);
// Insert new pending link record for THIS USER only
await db.insert(pendingOAuthLinks).values({
userId,
provider,
userEmail,
createdAt: nowIso(),
expiresAt: expiresAt.toISOString()
});
return NextResponse.json({ success: true });
} catch (error) {
console.error("OAuth linking start error:", error);
return NextResponse.json(
{ error: "Failed to start OAuth linking" },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,76 @@
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/src/lib/auth";
import { getUserById } from "@/src/lib/models/user";
import { createAuditEvent } from "@/src/lib/models/audit";
import db from "@/src/lib/db";
import { users } from "@/src/lib/db/schema";
import { eq } from "drizzle-orm";
import { nowIso } from "@/src/lib/db";
export async function POST(request: NextRequest) {
try {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const userId = Number(session.user.id);
const user = await getUserById(userId);
if (!user) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
// Must have a password before unlinking OAuth
if (!user.password_hash) {
return NextResponse.json(
{ error: "Cannot unlink OAuth: You must set a password first" },
{ status: 400 }
);
}
// Must be using OAuth to unlink
if (user.provider === "credentials") {
return NextResponse.json(
{ error: "No OAuth account to unlink" },
{ status: 400 }
);
}
const previousProvider = user.provider;
// Revert to credentials-only
const email = user.email;
const username = email.replace(/@localhost$/, "") || email.split("@")[0];
await db
.update(users)
.set({
provider: "credentials",
subject: `${username}@localhost`,
updatedAt: nowIso()
})
.where(eq(users.id, userId));
// Audit log
await createAuditEvent({
userId,
action: "oauth_unlinked",
entityType: "user",
entityId: userId,
summary: `User unlinked OAuth account: ${previousProvider}`,
data: JSON.stringify({ provider: previousProvider })
});
return NextResponse.json({
success: true,
message: "OAuth account unlinked successfully"
});
} catch (error) {
console.error("OAuth unlink error:", error);
return NextResponse.json(
{ error: "Failed to unlink OAuth account" },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,77 @@
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/src/lib/auth";
import { updateUserProfile } from "@/src/lib/models/user";
import { createAuditEvent } from "@/src/lib/models/audit";
export async function POST(request: NextRequest) {
try {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const userId = Number(session.user.id);
const body = await request.json();
const { avatarUrl } = body;
// Validate avatarUrl is either null or a base64 image string
if (avatarUrl !== null && typeof avatarUrl !== "string") {
return NextResponse.json(
{ error: "Invalid avatar data" },
{ status: 400 }
);
}
// If avatarUrl is provided, validate it's a base64 image
if (avatarUrl !== null) {
if (!avatarUrl.startsWith("data:image/")) {
return NextResponse.json(
{ error: "Avatar must be a base64-encoded image" },
{ status: 400 }
);
}
// Check base64 size (rough estimate: base64 is ~33% larger than binary)
// 2MB binary = ~2.7MB base64, so limit to 3MB base64 string
if (avatarUrl.length > 3 * 1024 * 1024) {
return NextResponse.json(
{ error: "Avatar image is too large" },
{ status: 400 }
);
}
}
// Update user avatar
const updatedUser = await updateUserProfile(userId, {
avatar_url: avatarUrl
});
if (!updatedUser) {
return NextResponse.json(
{ error: "User not found" },
{ status: 404 }
);
}
// Audit log
await createAuditEvent({
userId,
action: avatarUrl ? "avatar_updated" : "avatar_deleted",
entityType: "user",
entityId: userId,
summary: avatarUrl ? "User updated profile picture" : "User removed profile picture",
data: JSON.stringify({ hasAvatar: !!avatarUrl })
});
return NextResponse.json({
success: true,
avatarUrl: updatedUser.avatar_url
});
} catch (error) {
console.error("Avatar update error:", error);
return NextResponse.json(
{ error: "Failed to update avatar" },
{ status: 500 }
);
}
}