feat(auth): unify bot messenger linking with first-time user creation
This commit is contained in:
@@ -31,6 +31,48 @@ app.get('/healthz', (_, res) => {
|
||||
res.json({ status: 'ok' });
|
||||
});
|
||||
|
||||
function buildDefaultFullName(email) {
|
||||
const localPart = email.split('@')[0]?.trim();
|
||||
if (!localPart) {
|
||||
return 'Новый пользователь';
|
||||
}
|
||||
|
||||
return localPart
|
||||
.replace(/[._-]+/g, ' ')
|
||||
.split(' ')
|
||||
.filter(Boolean)
|
||||
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
async function resolveUserForMessenger({ userId, email }) {
|
||||
if (userId) {
|
||||
const byId = await prisma.user.findUnique({ where: { id: userId } });
|
||||
if (byId) {
|
||||
return byId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!email) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalizedEmail = email.trim().toLowerCase();
|
||||
if (!normalizedEmail) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return prisma.user.upsert({
|
||||
where: { email: normalizedEmail },
|
||||
update: {},
|
||||
create: {
|
||||
email: normalizedEmail,
|
||||
fullName: buildDefaultFullName(normalizedEmail),
|
||||
role: 'CLIENT',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
app.post('/bot/messenger-login', async (req, res) => {
|
||||
const webhookToken = process.env.BOT_LOGIN_WEBHOOK_TOKEN;
|
||||
const providedToken = req.body?.token;
|
||||
@@ -53,15 +95,9 @@ app.post('/bot/messenger-login', async (req, res) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const user = userId
|
||||
? await prisma.user.findUnique({ where: { id: userId } })
|
||||
: await prisma.user.findFirst({
|
||||
where: {
|
||||
email: {
|
||||
equals: email,
|
||||
mode: 'insensitive',
|
||||
},
|
||||
},
|
||||
const user = await resolveUserForMessenger({
|
||||
userId,
|
||||
email,
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
@@ -69,6 +105,16 @@ app.post('/bot/messenger-login', async (req, res) => {
|
||||
return;
|
||||
}
|
||||
|
||||
await prisma.messengerConnection.updateMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
type: channel,
|
||||
isActive: true,
|
||||
NOT: { channelId },
|
||||
},
|
||||
data: { isActive: false },
|
||||
});
|
||||
|
||||
await prisma.messengerConnection.upsert({
|
||||
where: {
|
||||
userId_type_channelId: {
|
||||
|
||||
Reference in New Issue
Block a user