refactor: migrate authentication routes to user router and update related components

This commit continues the refactoring of authentication-related code by:

- Moving authentication routes from `auth.ts` to `user.ts`
- Updating import paths and function calls across components
- Removing commented-out authentication code
- Simplifying user-related queries and mutations
- Updating server-side authentication handling
This commit is contained in:
Mauricio Siu
2025-02-22 22:02:12 -06:00
parent b00c12965a
commit 0478419f7c
30 changed files with 394 additions and 615 deletions

View File

@@ -6,7 +6,7 @@ import { organization, twoFactor } from "better-auth/plugins";
import { and, desc, eq } from "drizzle-orm";
import { db } from "../db";
import * as schema from "../db/schema";
import { sendVerificationEmail } from "../verification/send-verification-email";
import { sendEmail } from "../verification/send-verification-email";
import { IS_CLOUD } from "../constants";
export const auth = betterAuth({
@@ -30,7 +30,11 @@ export const auth = betterAuth({
autoSignInAfterVerification: true,
sendVerificationEmail: async ({ user, url }) => {
console.log("Sending verification email to", user.email);
await sendVerificationEmail(user.email, url);
await sendEmail({
email: user.email,
subject: "Verify your email",
text: `Click the link to verify your email: ${url}`,
});
},
},
emailAndPassword: {
@@ -45,6 +49,13 @@ export const auth = betterAuth({
return bcrypt.compareSync(password, hash);
},
},
sendResetPassword: async ({ user, url }) => {
await sendEmail({
email: user.email,
subject: "Reset your password",
text: `Click the link to reset your password: ${url}`,
});
},
},
databaseHooks: {
user: {

View File

@@ -1,6 +1,5 @@
import { db } from "@dokploy/server/db";
import {
type apiCreateUserInvitation,
invitation,
member,
organization,
@@ -10,42 +9,6 @@ import { TRPCError } from "@trpc/server";
import { eq } from "drizzle-orm";
import { IS_CLOUD } from "../constants";
export type User = typeof users_temp.$inferSelect;
export const createInvitation = async (
_input: typeof apiCreateUserInvitation._type,
_adminId: string,
) => {
// await db.transaction(async (tx) => {
// const result = await tx
// .insert(auth)
// .values({
// email: input.email.toLowerCase(),
// rol: "user",
// password: bcrypt.hashSync("01231203012312", 10),
// })
// .returning()
// .then((res) => res[0]);
// if (!result) {
// throw new TRPCError({
// code: "BAD_REQUEST",
// message: "Error creating the user",
// });
// }
// const expiresIn24Hours = new Date();
// expiresIn24Hours.setDate(expiresIn24Hours.getDate() + 1);
// const token = randomBytes(32).toString("hex");
// await tx
// .insert(users)
// .values({
// adminId: adminId,
// authId: result.id,
// token,
// expirationDate: expiresIn24Hours.toISOString(),
// })
// .returning();
// });
};
export const findUserById = async (userId: string) => {
const user = await db.query.users_temp.findFirst({
where: eq(users_temp.id, userId),
@@ -69,34 +32,6 @@ export const findOrganizationById = async (organizationId: string) => {
return organizationResult;
};
export const updateUser = async (userId: string, userData: Partial<User>) => {
const user = await db
.update(users_temp)
.set({
...userData,
})
.where(eq(users_temp.id, userId))
.returning()
.then((res) => res[0]);
return user;
};
export const updateAdminById = async (
_adminId: string,
_adminData: Partial<User>,
) => {
// const admin = await db
// .update(admins)
// .set({
// ...adminData,
// })
// .where(eq(admins.adminId, adminId))
// .returning()
// .then((res) => res[0]);
// return admin;
};
export const isAdminPresent = async () => {
const admin = await db.query.member.findFirst({
where: eq(member.role, "owner"),

View File

@@ -1,5 +1,5 @@
import { db } from "@dokploy/server/db";
import { member, type users_temp } from "@dokploy/server/db/schema";
import { member, users_temp } from "@dokploy/server/db/schema";
import { TRPCError } from "@trpc/server";
import { and, eq } from "drizzle-orm";
@@ -235,3 +235,16 @@ export const findMemberById = async (
}
return result;
};
export const updateUser = async (userId: string, userData: Partial<User>) => {
const user = await db
.update(users_temp)
.set({
...userData,
})
.where(eq(users_temp.id, userId))
.returning()
.then((res) => res[0]);
return user;
};

View File

@@ -30,6 +30,7 @@ class LogRotationManager {
private async getStateFromDB(): Promise<boolean> {
// const setting = await db.query.admins.findFirst({});
// return setting?.enableLogRotation ?? false;
return false;
}
private async setStateInDB(_active: boolean): Promise<void> {

View File

@@ -11,13 +11,14 @@ import { runMariadbBackup } from "./mariadb";
import { runMongoBackup } from "./mongo";
import { runMySqlBackup } from "./mysql";
import { runPostgresBackup } from "./postgres";
import { findAdmin } from "../../services/admin";
export const initCronJobs = async () => {
console.log("Setting up cron jobs....");
const admin = await findAdmin();
if (admin?.enableDockerCleanup) {
if (admin?.user.enableDockerCleanup) {
scheduleJob("docker-cleanup", "0 0 * * *", async () => {
console.log(
`Docker Cleanup ${new Date().toLocaleString()}] Running docker cleanup`,
@@ -25,7 +26,7 @@ export const initCronJobs = async () => {
await cleanUpUnusedImages();
await cleanUpDockerBuilder();
await cleanUpSystemPrune();
await sendDockerCleanupNotifications(admin.adminId);
await sendDockerCleanupNotifications(admin.user.id);
});
}
@@ -42,7 +43,7 @@ export const initCronJobs = async () => {
await cleanUpDockerBuilder(serverId);
await cleanUpSystemPrune(serverId);
await sendDockerCleanupNotifications(
admin.adminId,
admin.user.id,
`Docker cleanup for Server ${name} (${serverId})`,
);
});

View File

@@ -2,7 +2,15 @@ import {
sendDiscordNotification,
sendEmailNotification,
} from "../utils/notifications/utils";
export const sendVerificationEmail = async (email: string, url: string) => {
export const sendEmail = async ({
email,
subject,
text,
}: {
email: string;
subject: string;
text: string;
}) => {
await sendEmailNotification(
{
fromAddress: process.env.SMTP_FROM_ADDRESS || "",
@@ -12,14 +20,8 @@ export const sendVerificationEmail = async (email: string, url: string) => {
username: process.env.SMTP_USERNAME || "",
password: process.env.SMTP_PASSWORD || "",
},
"Confirm your email | Dokploy",
`
Welcome to Dokploy!
Please confirm your email by clicking the link below:
<a href="${url}">
Confirm Email
</a>
`,
subject,
text,
);
return true;