Jul 22, 2024
passport
, un middleware para Node.js simplificado y modular que facilita la autenticación.npm init -y
npm install express debug dotenv mongodb nodemon
.env
.index.js
para configurar el servidor Express básico.npm install passport passport-google-oauth20 express-session
index.js
:
import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
import session from 'express-session';
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: 'http://localhost:3000/auth/google/callback'
}, (accessToken, refreshToken, profile, cb) => {
return cb(null, profile);
}));
passport.serializeUser((user, cb) => {
cb(null, user);
});
passport.deserializeUser((obj, cb) => {
cb(null, obj);
});
express-session
en el servidor:
app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
cookie: { maxAge: 3600000 } // 1 hora
}));
app.use(passport.initialize());
app.use(passport.session());
app.get('/auth/google',
passport.authenticate('google', { scope: ['profile'] })
);
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/' }),
(req, res) => {
res.redirect('/profile');
}
);
app.get('/profile', (req, res) => {
if (req.isAuthenticated()) {
res.send('Logged in');
} else {
res.redirect('/');
}
});
app.get('/logout', (req, res) => {
req.logout((err) => {
if (err) { return next(err); }
res.redirect('/');
});
});
const createUser = async (profile) => {
// Lógica para guardar usuario en la base de datos
};
const getUserById = async (id) => {
// Lógica para obtener usuario por ID
};
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/' }),
async (req, res) => {
const user = await getUserById(req.user.id);
if (!user) {
await createUser(req.user);
}
res.redirect('/profile');
}
);