fixed so the code compiles
This commit is contained in:
+18
-8
@@ -3,19 +3,29 @@ const { Strategy: GoogleStrategy } = require('passport-google-oauth20');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const db = require('../db');
|
||||
|
||||
async function generateUniqueUsername(base) {
|
||||
const candidate = base.toLowerCase();
|
||||
const taken = await db.user.findFirst({ where: { username: candidate } });
|
||||
if (!taken) return candidate;
|
||||
function deriveBase(email) {
|
||||
const local = email.split('@')[0];
|
||||
const sanitized = local
|
||||
.replace(/\./g, '_')
|
||||
.replace(/[^a-zA-Z0-9_]/g, '')
|
||||
.slice(0, 15)
|
||||
.toLowerCase();
|
||||
return sanitized || 'user';
|
||||
}
|
||||
|
||||
async function generateUniqueUsername(email) {
|
||||
const base = deriveBase(email);
|
||||
const taken = await db.user.findFirst({ where: { username: base } });
|
||||
if (!taken) return base;
|
||||
let attempts = 0;
|
||||
while (attempts < 20) {
|
||||
const suffix = String(Math.floor(1000 + Math.random() * 9000));
|
||||
const username = `${candidate}${suffix}`;
|
||||
const username = `${base}_${suffix}`;
|
||||
const collision = await db.user.findFirst({ where: { username } });
|
||||
if (!collision) return username;
|
||||
attempts++;
|
||||
}
|
||||
return `${candidate}${Date.now()}`;
|
||||
return `${base}_${Date.now()}`;
|
||||
}
|
||||
|
||||
passport.use(
|
||||
@@ -31,7 +41,7 @@ passport.use(
|
||||
let user = await db.user.findUnique({ where: { googleId: profile.id } });
|
||||
|
||||
if (!user) {
|
||||
const username = await generateUniqueUsername(email.split('@')[0]);
|
||||
const username = await generateUniqueUsername(email);
|
||||
user = await db.user.create({
|
||||
data: {
|
||||
googleId: profile.id,
|
||||
@@ -51,7 +61,7 @@ passport.use(
|
||||
},
|
||||
});
|
||||
if (!user.username) {
|
||||
const username = await generateUniqueUsername((user.email ?? '').split('@')[0]);
|
||||
const username = await generateUniqueUsername(user.email ?? '');
|
||||
user = await db.user.update({ where: { id: user.id }, data: { username } });
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user