2024-07-20 22:23:58 +02:00
|
|
|
import bcrypt from "bcrypt";
|
2025-08-15 20:15:58 +02:00
|
|
|
import type { z } from "zod/v4";
|
2024-07-20 22:23:58 +02:00
|
|
|
|
2025-12-16 23:37:44 +01:00
|
|
|
import { createLogger } from "@homarr/core/infrastructure/logs";
|
2024-07-20 22:23:58 +02:00
|
|
|
import type { Database } from "@homarr/db";
|
2024-07-27 11:38:51 +02:00
|
|
|
import { and, eq } from "@homarr/db";
|
2024-12-19 16:10:22 +01:00
|
|
|
import { users } from "@homarr/db/schema";
|
2025-04-06 12:37:28 +02:00
|
|
|
import type { userSignInSchema } from "@homarr/validation/user";
|
2024-07-20 22:23:58 +02:00
|
|
|
|
2025-12-16 23:37:44 +01:00
|
|
|
const logger = createLogger({ module: "basicAuthorization" });
|
|
|
|
|
|
2024-07-20 22:23:58 +02:00
|
|
|
export const authorizeWithBasicCredentialsAsync = async (
|
|
|
|
|
db: Database,
|
2025-04-06 12:37:28 +02:00
|
|
|
credentials: z.infer<typeof userSignInSchema>,
|
2024-07-20 22:23:58 +02:00
|
|
|
) => {
|
|
|
|
|
const user = await db.query.users.findFirst({
|
2024-12-02 20:44:49 +01:00
|
|
|
where: and(eq(users.name, credentials.name.toLowerCase()), eq(users.provider, "credentials")),
|
2024-07-20 22:23:58 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!user?.password) {
|
2025-12-16 23:37:44 +01:00
|
|
|
logger.info("User not found", { userName: credentials.name });
|
2024-07-20 22:23:58 +02:00
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-16 23:37:44 +01:00
|
|
|
logger.info("User is trying to log in. Checking password...", { userName: user.name });
|
2024-07-20 22:23:58 +02:00
|
|
|
const isValidPassword = await bcrypt.compare(credentials.password, user.password);
|
|
|
|
|
|
|
|
|
|
if (!isValidPassword) {
|
2025-12-16 23:37:44 +01:00
|
|
|
logger.warn("Password for user was incorrect", { userName: user.name });
|
2024-07-20 22:23:58 +02:00
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-16 23:37:44 +01:00
|
|
|
logger.info("User successfully authorized", { userName: user.name });
|
2024-07-20 22:23:58 +02:00
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
id: user.id,
|
|
|
|
|
name: user.name,
|
|
|
|
|
};
|
|
|
|
|
};
|