diff --git a/api/controllers/InboxController.ts b/api/controllers/InboxController.ts index ac2077c..09352f6 100644 --- a/api/controllers/InboxController.ts +++ b/api/controllers/InboxController.ts @@ -18,7 +18,7 @@ export async function createInbox({ ? new mongoose.Types.ObjectId(domain_id) : undefined; inbox.name = name; - inbox.email = email || `${name.replace(/[^a-zA-Z0-9]/g, "-")}@${process.env.DEFAULT_EMAIL_DOMAIN}`; + inbox.email = email || await getNewRandomInboxEmail({ name }); await inbox.save(); return inbox; } @@ -60,7 +60,8 @@ export async function getInboxByEmail(email: string) { } export async function getNewRandomInboxEmail({ name }: { name: string }) { - const email = `${name.replace(/[^a-zA-Z0-9]/g, "-")}-${Math.random() + const lowerCaseName = name.toLowerCase(); + const email = `${lowerCaseName.replace(/[^a-zA-Z0-9]/g, "-")}-${Math.random() .toString(36) .substring(2, 12)}@${process.env.DEFAULT_EMAIL_DOMAIN}`; const inbox = await getInboxByEmail(email); diff --git a/api/routes/v1/inboxes/index.ts b/api/routes/v1/inboxes/index.ts index 48d9767..bcdbb6c 100644 --- a/api/routes/v1/inboxes/index.ts +++ b/api/routes/v1/inboxes/index.ts @@ -5,8 +5,10 @@ import { expressValidatorMiddleware } from "../../../middlewares/expressValidato import { createInbox, deleteInboxByOrganizationIdAndInboxId, + getInboxByEmail, getInboxByOrganizationIdAndInboxId, getInboxesByOrganizationId, + getNewRandomInboxEmail, } from "../../../controllers/InboxController"; import { sendWebhookEvent } from "../../../controllers/WebhookAttemptController"; import messagesRouter from "./messages"; @@ -40,7 +42,9 @@ router.post( res: Response ) => { let domainId: string | undefined; + let username: string | undefined; if (req.body.email) { + username = req.body.email?.split("@")[0]; const domainName = req.body.email?.split("@")[1]; if (!domainName) { return res.status(400).json({ error: "Invalid email address" }); @@ -49,18 +53,29 @@ router.post( organizationId: req.organization._id.toString(), name: domainName, }); - if (!domain) { - return res.status(404).json({ error: "Domain not found" }); + + if (domain) { + domainId = domain._id.toString(); } + } - domainId = domain._id.toString(); + let email = undefined; + if (domainId) { + email = req.body.email; + } else if (username) { + const defaultEmail = `${username}@${process.env.DEFAULT_EMAIL_DOMAIN}`; + if (await getInboxByEmail(defaultEmail)) { + email = await getNewRandomInboxEmail({ name: username }); + } else { + email = defaultEmail; + } } const inbox = await createInbox({ organization_id: req.organization._id.toString(), name: req.body.name, domain_id: domainId, - email: domainId && req.body.email, + email, }); await sendWebhookEvent({ diff --git a/app/app/pages/login.vue b/app/app/pages/login.vue index 7eec48a..446643f 100644 --- a/app/app/pages/login.vue +++ b/app/app/pages/login.vue @@ -42,7 +42,7 @@