Update src/config/passport.js
Browse files- src/config/passport.js +24 -0
src/config/passport.js
CHANGED
|
@@ -2,6 +2,24 @@ import passport from 'passport';
|
|
| 2 |
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
|
| 3 |
import User from '../models/User.js';
|
| 4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
passport.serializeUser((user, done) => {
|
| 6 |
done(null, user.id); // Save only ID to session
|
| 7 |
});
|
|
@@ -32,10 +50,16 @@ passport.use(
|
|
| 32 |
return done(null, existingUser);
|
| 33 |
}
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
// Create new user
|
| 36 |
const newUser = await new User({
|
| 37 |
googleId: profile.id,
|
| 38 |
email: profile.emails[0].value,
|
|
|
|
| 39 |
displayName: profile.displayName,
|
| 40 |
firstName: profile.name.givenName,
|
| 41 |
lastName: profile.name.familyName
|
|
|
|
| 2 |
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
|
| 3 |
import User from '../models/User.js';
|
| 4 |
|
| 5 |
+
async function generateUniqueUsername(email) {
|
| 6 |
+
const base = email
|
| 7 |
+
.split('@')[0]
|
| 8 |
+
.toLowerCase()
|
| 9 |
+
.replace(/[^a-z0-9]/g, '_')
|
| 10 |
+
.slice(0, 15); // leave room for suffix
|
| 11 |
+
|
| 12 |
+
let username = base;
|
| 13 |
+
let suffix = 0;
|
| 14 |
+
|
| 15 |
+
while (await User.exists({ username })) {
|
| 16 |
+
suffix += 1;
|
| 17 |
+
username = `${base}_${suffix}`;
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
return username;
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
passport.serializeUser((user, done) => {
|
| 24 |
done(null, user.id); // Save only ID to session
|
| 25 |
});
|
|
|
|
| 50 |
return done(null, existingUser);
|
| 51 |
}
|
| 52 |
|
| 53 |
+
const email = profile.emails[0].value;
|
| 54 |
+
|
| 55 |
+
// 👇 AUTO-GENERATE USERNAME
|
| 56 |
+
const username = await generateUniqueUsername(email);
|
| 57 |
+
|
| 58 |
// Create new user
|
| 59 |
const newUser = await new User({
|
| 60 |
googleId: profile.id,
|
| 61 |
email: profile.emails[0].value,
|
| 62 |
+
username,
|
| 63 |
displayName: profile.displayName,
|
| 64 |
firstName: profile.name.givenName,
|
| 65 |
lastName: profile.name.familyName
|