feat: Refactor user management to replace email with username across the application

This commit is contained in:
2025-07-28 22:25:23 +02:00
parent 6fc2e6703b
commit 07b4af5f24
14 changed files with 298 additions and 96 deletions

View File

@@ -4,7 +4,7 @@ import bcrypt from "bcryptjs";
import { z } from "zod";
const loginSchema = z.object({
email: z.string().email("Invalid email format"),
username: z.string().min(1, "Username is required"),
password: z.string().min(6, "Password must be at least 6 characters"),
});
@@ -13,7 +13,7 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
Credentials({
name: "credentials",
credentials: {
email: { label: "Email", type: "email" },
username: { label: "Username", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
@@ -28,13 +28,13 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
const user = db
.prepare(
`
SELECT id, email, name, password_hash, role, is_active,
SELECT id, username, name, password_hash, role, is_active,
failed_login_attempts, locked_until
FROM users
WHERE email = ? AND is_active = 1
WHERE username = ? AND is_active = 1
`
)
.get(validatedFields.email);
.get(validatedFields.username);
if (!user) {
throw new Error("Invalid credentials");
@@ -75,7 +75,7 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
userId: user.id,
resourceType: RESOURCE_TYPES.SESSION,
details: {
email: validatedFields.email,
username: validatedFields.username,
reason: "invalid_password",
failed_attempts: user.failed_login_attempts + 1,
},
@@ -107,7 +107,7 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
userId: user.id,
resourceType: RESOURCE_TYPES.SESSION,
details: {
email: user.email,
username: user.username,
role: user.role,
},
});
@@ -117,7 +117,7 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
return {
id: user.id,
email: user.email,
username: user.username,
name: user.name,
role: user.role,
};
@@ -128,30 +128,29 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
},
}),
],
session: {
strategy: "jwt",
maxAge: 30 * 24 * 60 * 60, // 30 days
},
callbacks: {
async jwt({ token, user }) {
if (user) {
token.role = user.role;
token.userId = user.id;
token.username = user.username;
}
return token;
},
async session({ session, token }) {
if (token) {
session.user.id = token.userId;
session.user.id = token.sub;
session.user.role = token.role;
session.user.username = token.username;
}
return session;
},
},
pages: {
signIn: "/auth/signin",
signOut: "/auth/signout",
error: "/auth/error",
},
debug: process.env.NODE_ENV === "development",
session: {
strategy: "jwt",
maxAge: 24 * 60 * 60, // 24 hours
},
secret: process.env.NEXTAUTH_SECRET,
});