zerobyte/app/lib/auth-middlewares/convert-legacy-user.ts
Nico 451aed8983
Multi users (#381)
* feat(db): add support for multiple users and organizations

* feat: backfill entities with new organization id

* refactor: filter all backend queries to surface only organization specific entities

* refactor: each org has its own restic password

* test: ensure organization is created

* chore: pr feedbacks

* refactor: filter by org id in all places

* refactor: download restic password from stored db password

* refactor(navigation): use volume id in urls instead of name

* feat: disable registrations

* refactor(auth): bubble up auth error to hono

* refactor: use async local storage for cleaner context sharing

* refactor: enable user registration vs disabling it

* test: multi-org isolation

* chore: final cleanup
2026-01-20 22:28:22 +01:00

52 lines
1.6 KiB
TypeScript

import { hashPassword } from "better-auth/crypto";
import { and, eq, ne } from "drizzle-orm";
import { db } from "~/server/db/db";
import { account, usersTable } from "~/server/db/schema";
import type { AuthMiddlewareContext } from "../auth";
import { UnauthorizedError } from "http-errors-enhanced";
export const convertLegacyUserOnFirstLogin = async (ctx: AuthMiddlewareContext) => {
const { path, body } = ctx;
if (path !== "/sign-in/username") {
return;
}
const legacyUser = await db.query.usersTable.findFirst({
where: and(eq(usersTable.username, body.username.trim().toLowerCase()), ne(usersTable.passwordHash, "")),
});
if (legacyUser) {
const isValid = await Bun.password.verify(body.password, legacyUser.passwordHash ?? "");
if (isValid) {
await db.transaction(async (tx) => {
const newUserId = crypto.randomUUID();
const accountId = crypto.randomUUID();
await tx.delete(usersTable).where(eq(usersTable.id, legacyUser.id));
await tx.insert(usersTable).values({
id: newUserId,
username: legacyUser.username,
email: legacyUser.email,
name: legacyUser.name,
hasDownloadedResticPassword: legacyUser.hasDownloadedResticPassword,
emailVerified: false,
role: "admin", // In legacy system, the only user is an admin
});
await tx.insert(account).values({
id: accountId,
providerId: "credential",
accountId: legacyUser.username,
userId: newUserId,
password: await hashPassword(body.password),
createdAt: new Date(),
});
});
} else {
throw new UnauthorizedError("Invalid credentials");
}
}
};