我有一个与Mongodb数据库连接的TypeOrm / React应用,其中服务器位于端口4000上,客户端位于端口3000上。 在客户端上,我创建了文件googleAuth:
import passport from 'passport';
import {User} from './entity/User';
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const googleOptions = {
clientID: process.env.clientID,
clientSecret: process.env.clientSecret,
callbackURL: 'http://localhost:4000/auth/google/callback',
profileFields: ['id', 'email', 'first_name', 'last_name'],
};
const googleCallback = (_accessToken: any, _refreshToken: any, profile: any, done: any) => {
const matchingUser = User.findOne({googleId: profile.id});
if (matchingUser) {
done(null, matchingUser);
return;
}
const newUser = {
googleId: profile.id,
firstName: profile.name.givenName,
lastName: profile.name.familyName,
email: profile.emails && profile.emails[0] && profile.emails[0].value
};
User.create(newUser);
done(null, newUser);
}
export const googleAuth = () => passport.use(new GoogleStrategy(
googleOptions,
googleCallback
));
我的index.ts(server)文件如下:
import "reflect-metadata";
import {createConnection} from "typeorm";
import "dotenv/config"
import express from "express";
import { ApolloServer } from "apollo-server-express";
import { buildSchema } from "type-graphql";
import cors from "cors";
import { PostResolver } from "./resolvers/PostResolver";
import { UserResolver } from "./resolvers/UserResolver";
import path from 'path';
import passport from "passport";
import { googleAuth} from './googleAuth';
(async () => {
await createConnection();
googleAuth();
passport.serializeUser(function(user: any, done: any) {
done(null, user);
});
passport.deserializeUser(function(user: any, done: any) {
done(null, user);
});
const app = express();
app.use(cors());
app.use(passport.initialize());
app.get('/auth/google', passport.authenticate('google', { scope: ['email'] }));
app.get('/auth/google/callback', passport.authenticate('google', {
successRedirect: 'http://localhost:4000/graphql',
failureRedirect: 'http://localhost:4000/graphql',
}));
const apolloServer = new ApolloServer({
schema: await buildSchema({
resolvers: [ PostResolver, UserResolver ]
}),
context: ({ req }) => ({
getUser: () => req.user,
logout: () => req.logout()
})
// context: ({ req, res }) => ({ req, res })
});
apolloServer.applyMiddleware({ app });
app.use(express.static('public'));
app.get('*', (_, res) => {
res.sendFile(path.resolve(__dirname, '../public', 'index.html'))
});
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Server started on port ${port}`));
})();
我的UserResolver:
import {
Resolver,
Query,
Ctx
} from "type-graphql";
import { User } from "../entity/User";
import { MyContext } from '../MyContext';
import { ExpressContext } from "apollo-server-express/dist/ApolloServer";
@Resolver()
export class UserResolver {
@Query(() => [User])
users() {
return User.find();
}
@Query(() => String)
getUser(@Ctx() { req }: ExpressContext) {
console.log(req);
return `your user id is: ${req.user}`;
}
}
在https://console.developers.google.com的凭证中,我添加了 授权的JavaScript来源:http:// localhost:4000
在授权的重定向URI中:http:// localhost:4000 / auth / google / callback
我可以登录,但无法获取任何数据。我知道这是非常混乱的代码,但我需要组织并重写它。 首先,我想知道应该在凭据中添加哪些域和重定向。 二是配置服务器。 第三创建UserResolvers。 第四,与客户获取数据。