2026-02-21 19:07:05 +00:00

52 lines
1.5 KiB
JavaScript

const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const { getPool } = require("./db.js");
// 🧠 Save user to DB or fetch if exists
async function findOrCreateUser(profile, provider) {
const email = profile.emails?.[0]?.value || `${profile.id}@facebook.com`;
const name = profile.displayName;
const pool = await getPool();
const [existing] = await pool.execute(
"SELECT * FROM tbl_userlogin WHERE email = ? LIMIT 1",
[email]
);
if (existing.length) return existing[0];
const userid = uuidv4();
await pool.execute(
"INSERT INTO tbl_userlogin (userid, name, email, password, provider) VALUES (?, ?, ?, ?, ?)",
[userid, name, email, null, provider]
);
return { userid, name, email, provider };
}
// 🔹 Google
passport.use(
new GoogleStrategy(
{
clientID: "657565817895-sqmh7bd4cef3j7c7cmuno1tpbhg7fjbo.apps.googleusercontent.com",
clientSecret: "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",
callbackURL: `https://api.socialbuddy.co/api/auth/google/callback`,
},
async (accessToken, refreshToken, profile, done) => {
const user = await findOrCreateUser(profile, "google");
done(null, user);
}
)
);
// 🔹 Serialize/deserialize
passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((user, done) => done(null, user));
module.exports = passport;