Что мне делать, чтобы получить req.user и req.logout, а также все запросы, созданные в промежуточном программном обеспечении паспорта в контексте ApolloServer. Так же, как у меня есть доступ к нему в
app.get ('/ good', isLoggedIn, (req, res) => res.send (req.user));
Я использую cook ie -session, paspport, паспорт-google-oauth20, express, apollo-server, express и пакеты cors
app.use(
cors({
origin: "http://localhost:3000",
credentials: true
})
);
app.use(cookieSession({
name: 'session',
keys: ['key1', 'key2']
}))
app.use(passport.initialize());
app.use(passport.session());
app.get('/auth/google', passport.authenticate('google', { scope: ['profile','email'] }));
app.get('/auth/google/callback', passport.authenticate('google', {
successRedirect: '/good',
failureRedirect: '/fail',
}));
app.get('/good', (req, res) => res.send(req.user));
// route for logging out
app.get('/logout', (req, res) => {
req.session = null;
req.logout();
res.redirect('/');
});
// Connect to Mongo(skipped)
const { ApolloServer } = require('apollo-server-express');
const typeDefs = require('./modules/graphqlschemas/index');
const resolvers = require('./modules/resolvers/index');
// #5 Initialize an Apollo server
const server = new ApolloServer({
typeDefs: typeDefs,
resolvers: resolvers,
context: ({ req }) => ({
getUser: () => {
console.log(req.user); // ! undefined !
},
logout: () => req.logout() // ! header not sent to the client error !
})
});
Вот мой файл googleAuth:
const GoogleStrategy = require('passport-google-oauth20').Strategy
const passport = require('passport');
const User = require('../models/user');
passport.serializeUser((user, done) => {
done(null, user.id)
})
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => done(err, user))
})
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: '/auth/google/callback',
proxy: true
},
async (accessToken, refreshToken, profile, done) => {
const newUser = {
googleId: profile.id,
displayName: profile.displayName,
firstName: profile.name.givenName,
lastName: profile.name.familyName,
image: profile.photos[0].value,
}
try {
let user = await User.findOne({ googleId: profile.id })
if (user) {
done(null, user)
} else {
user = await User.create(newUser)
done(null, user)
}
} catch (err) {
console.error(err)
}
}
)
)