mirror of
https://github.com/rgrgogu/new_starr.git
synced 2026-09-27 00:12:54 +08:00
70 lines
2.8 KiB
JavaScript
70 lines
2.8 KiB
JavaScript
/***********************************************************************************************************************************************************************
|
|
* File Name: passport.config.js
|
|
* Type of Program: Configuration
|
|
* Description: Passport.js strategy configuration.
|
|
* Registers the Google OAuth 2.0 strategy. On first login via Google
|
|
* a new user record is auto-created with reg_type="google".
|
|
* Returns a signed JWT payload after successful authentication.
|
|
* Author: rgrgogu
|
|
* Date Created: Oct. 6, 2025
|
|
***********************************************************************************************************************************************************************
|
|
* HOW TO USE:
|
|
* In server.js:
|
|
* require('./config/passport.config');
|
|
* app.use(passport.initialize());
|
|
* In routes:
|
|
* router.get('/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
|
|
* router.get('/google/callback', passport.authenticate('google', { session: false }), handler);
|
|
***********************************************************************************************************************************************************************/
|
|
const passport = require('passport');
|
|
const { Strategy: GoogleStrategy } = require('passport-google-oauth20');
|
|
const mdl_Users = require('../models/users/users.mdl');
|
|
|
|
passport.use(
|
|
new GoogleStrategy(
|
|
{
|
|
clientID: process.env.GOOGLE_CLIENT_ID,
|
|
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
|
|
callbackURL: process.env.GOOGLE_CALLBACK_URL,
|
|
},
|
|
async (accessToken, refreshToken, profile, done) => {
|
|
try {
|
|
const email = profile.emails?.[0]?.value;
|
|
if (!email) return done(new Error('No email returned from Google'), null);
|
|
|
|
let user = await mdl_Users.findOne({ where: { email } });
|
|
|
|
if (!user) {
|
|
// Auto-register Google users as 'user' acc_type
|
|
user = await mdl_Users.create({
|
|
email,
|
|
reg_type: 'google',
|
|
acc_type: 'user',
|
|
is_active: true,
|
|
is_verified: true, // Google accounts are pre-verified
|
|
personal_info: {
|
|
name: {
|
|
given_name: profile.name?.givenName || '',
|
|
last_name: profile.name?.familyName || '',
|
|
full_name: profile.displayName || '',
|
|
},
|
|
avatar: {
|
|
url: profile.photos?.[0]?.value || null,
|
|
},
|
|
},
|
|
});
|
|
}
|
|
|
|
if (!user.is_active) {
|
|
return done(null, false, { message: 'Account is deactivated.' });
|
|
}
|
|
|
|
return done(null, user);
|
|
} catch (err) {
|
|
return done(err, null);
|
|
}
|
|
}
|
|
)
|
|
);
|
|
|
|
module.exports = passport; |