【问题标题】:GoogleOAuth with passport, graphql-yoga and prisma带有护照、graphql-yoga 和 prisma 的 GoogleOAuth
【发布时间】:2019-03-13 23:37:00
【问题描述】:

目前,我正在通过 Google 构建登录功能,但遇到了一些让我有些困惑的问题。

我们可以在一个项目中同时使用 Restful API 和 Graphql API 吗?除了谷歌身份验证,我们需要一些路由来处理它。对于 CRUD 操作,我们使用 Graphql。

类似这样的:

const { GraphQLServer } = require('graphql-yoga');
const { Prisma } = require('prisma-binding');
const resolvers = require('./resolvers');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {

  // mongoose.
  User.findById(id).then(user => {
    done(null, user);
  });

});

passport.use(new GoogleStrategy(
  {
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: '/auth/google/callback',
  },
  (accessToken, refreshToken, profile, done) => {
    console.log(profile);

    // After receive profile info from google, call mutation and save
    // profile into database.
  }
));

const db = new Prisma({
  typeDefs: 'src/generated/prisma.graphql',
  endpoint: process.env.PRISMA_ENDPOINT,
  debug: true,
  secret: process.env.PRISMA_SECRET,
});

const server = new GraphQLServer({
  typeDefs: './src/schema.graphql',
  resolvers,
  resolverValidationOptions: {
    requireResolversForResolveType: false
  },
  context: req => ({ ...req, db })
});

server.express.get('/auth/connect', passport.authenticate('google', {
  scope: ['profile', 'email']
}));

server.express.get('/auth/google/callback', passport.authenticate('google'));

server.start(() => console.log(`Server is running on ${process.env.PRISMA_ENDPOINT}`));

GoogleStrategy的回调函数中,如何调用Mutation并将Google的所有配置文件信息保存到数据库?

(accessToken, refreshToken, profile, done) => {
    console.log(profile);

    // After receiving profile info from google, call mutation and save
    // profile into the database.
  }

deserializeUserserializeUser 函数中。之前,当我使用 Nodejs 和 MongoDB 时,我已经这样做了:

passport.serializeUser((user, done) => {
   done(null, user.id);
});

passport.deserializeUser((id, done) => {

  // mongoose.
  User.findById(id).then(user => {
    done(null, user);
  });

});

而使用 Prisma 和 Graphql,如何用突变解决这个问题?

【问题讨论】:

    标签: passport.js graphql prisma


    【解决方案1】:

    在您的服务器中,您创建prisma-binding 实例,然后将其传递给graphql-yoga 的上下文。这允许您在解析器中进行 prisma 操作,如下所示:

    context.db.query.user({where: {id: 'ABCD'}})
    

    但这并不意味着您不能在其他地方使用 prisma-binding 实例!

    在您的护照回调中,您可以访问您的 prisma-binding 实例并调用查询和突变:

    db.mutation.createUser({data: {name: 'John Doe'}})
    

    【讨论】:

      猜你喜欢
      • 2019-03-04
      • 2019-06-11
      • 2019-02-20
      • 2019-09-06
      • 2019-12-18
      • 2019-08-03
      • 2019-05-08
      • 2019-04-24
      • 2020-09-28
      相关资源
      最近更新 更多