因此,我将其构建在同一个文件夹中。为此,我需要为每个创建单独的 index.js 文件和视图文件夹。目前,节点模块、package.json 和 package-lock.json 文件对于两者都是通用的。我的问题是如何在同一个文件夹中单独创建这两个文件夹,例如文件夹结构应该如何以及如何运行它们而不会因此而出现任何错误?
这是我用于谷歌身份验证的index.js文件
const express = require('express');
const app = express();
const session = require('express-session');
app.set('view engine', 'ejs');
app.use(session({
resave: false,
saveUninitialized: true,
secret: 'SECRET'
}));
app.get('/', function(req, res) {
res.render('pages/auth');
});
const port = process.env.PORT || 3000;
app.listen(port , () => console.log('App listening on port ' + port));
//passport setup
var passport = require('passport');
var userProfile;
app.use(passport.initialize());
app.use(passport.session());
app.get('/success', (req, res) => {
res.render('pages/success', {user: userProfile});
});
app.get('/error', (req, res) => res.send("error logging in"));
passport.serializeUser(function(user, cb) {
cb(null, user);
});
passport.deserializeUser(function(obj, cb) {
cb(null, obj);
});
// Google authentication
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const GOOGLE_CLIENT_ID = 'our-google-client-id';
const GOOGLE_CLIENT_SECRET = 'our-google-client-secret';
passport.use(new GoogleStrategy({
clientID: "550505972338-ne0ackpiobejl4p4uo61j7bvvg93tuo9.apps.googleusercontent.com",
clientSecret: "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",
callbackURL: "http://localhost:3000/auth/google/callback"
},
function(accessToken, refreshToken, profile, done) {
userProfile=profile;
return done(null, userProfile);
}
));
app.get('/auth/google',
passport.authenticate('google', { scope : ['profile', 'email'] }));
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/error' }),
function(req, res) {
// Successful authentication
res.redirect('/success');
});
create a separate file for this purpose and export the passport after making this change to the passport
******************************* Passport File *******************************
// Configure Google OAuth
passport.use(new GoogleStrategy.Strategy({
clientID: process.env.clientID,
clientSecret: process.env.clientSecret,
callbackURL: '/auth/google/callback',
scope: ['profile', 'email']
},
async (accessToken, refreshToken, profile, done) => {
try {
// Check for existing user or create new
// Customer is my model use yours
const existingUser = await Customer.findOne({ email: profile.emails[0].value })
if (existingUser) {
return done(null, existingUser);
}
console.log(profile)
const body = {
email: profile.emails[0].value,
firstName: profile.given_name,
lastName: profile.family_name,
provider: profile.provider
}
const newUser = await createUser(body)
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(null, user);
})
return done(null, newUser)
} catch (error) {
console.error('Error during Google authentication:', error);
return done(error);
}
})
)
// Configure Facebook OAuth
passport.use(
new FacebookStrategy.Strategy({
clientID: process.env.FACEBOOK_CLIENT_ID,
clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
callbackURL: '/auth/facebook/callback',
profileFields: ['id', 'displayName', 'emails', 'photos'], // Request Customer profile details
},
async (accessToken, refreshToken, profile, done) => {
try {
// Check for existing user or create new
const existingUser = await Customer.findOne({ facebookId: profile.id })
if (existingUser) {
return done(null, existingUser);
}
const body = {
facebookId: profile.id,
firstName: profile.name.givenName,
lastName: profile.name.familyName,
provider: profile.provider
}
const newUser = await createUser(body)
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(null, user);
})
return done(null, newUser)
} catch (error) {
console.error('Error during Facebook OAuth:', error)
return done(error, false) // Handle errors appropriately
}
})
)
// important to export this passport
export default passport
***********************Index File*******************************
//Import the passport from location of your passport like this
import passport from "../middlewares/passport"
//Google
app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }))
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/customer/login' }), ThirdPartyAuth)
//Facebook
app.get('/auth/facebook', passport.authenticate('facebook'))
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), ThirdPartyAuth)
********************* Controller file or save it somewhere *************
export const ThirdPartyAuth = async (req: Request, res: Response, next: NextFunction) => {
// Successful authentication, generate JWT
// Handle the Auth and create user object
res.json(user) //send user to client....
})