Graphql query to check passport/google authentication

孤人 提交于 2020-12-13 04:48:16

问题


I want to implement graphql query to check if I'm logged in or not. First part is similar for what we all can see on passport docs and youtube/github tutorials:

I: Introduction(if anybody know what is all about you can skip to problem part):

modules/auth.js

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',
      },
      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)
        }
      }
    )
  )

server.js(Introduction part):

const express = require('express');
const cors = require('cors');
const path = require('path');
const mongoose = require('mongoose');
require('dotenv').config();
const passport = require('passport');
require('./modules/auth');

const cookieSession = require('cookie-session');

// #6 Initialize an Express application
const app = express();

app.use(cors());

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: 'http://localhost:4000/graphql',
  failureRedirect: 'http://localhost:4000/graphql',
}));

II: Problem

server.js ( what is working, but not graphql )

// Auth middleware that checks if the user is logged in
const isLoggedIn = (req, res, next) => {
  if (req.user) {
      next();
  } else {
      res.sendStatus(401);
  }
}

app.get('/good', isLoggedIn, (req, res) => res.send(`Welcome mr ${req.user}!`));

server.js( what I've tried):

const server = new ApolloServer({ 
  typeDefs: typeDefs,
  resolvers: resolvers,
  // context: ({ req, res }) => ({ req, res }) 
  context: ({ req }) => ({
    getUser: () => req.user,
    logout: () => req.logout(),
  })
});
server.applyMiddleware({ app });

resolver.js:

Query: {
    users: () => User.find({}),
    currentUser: (parent, args, context) => context.getUser()
  },

Does anyone have an idea how to do it?

来源:https://stackoverflow.com/questions/63181710/graphql-query-to-check-passport-google-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!