daily pastebin goal
23%
SHARE
TWEET

Untitled

a guest Feb 16th, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //server
  2.  
  3. const { ApolloServer } = require("apollo-server");
  4.  
  5. const typeDefs = require("./typeDefs");
  6. const resolvers = require("./resolvers");
  7. const { findOrCreateUser } = require("./controllers/userController");
  8. const mongoose = require("mongoose");
  9. require("dotenv").config();
  10.  
  11. mongoose
  12.   .connect(process.env.MONGO_URI, { useNewUrlParser: true })
  13.   .then(() => console.log("DB connected!"))
  14.   .catch(err => console.error(err));
  15.  
  16. const server = new ApolloServer({
  17.   typeDefs,
  18.   resolvers,
  19.   context: async ({ req }) => {
  20.     let authToken = null;
  21.     let currentUser = null;
  22.     try {
  23.       authToken = req.headers.authorization;
  24.       if (authToken) {
  25.         currentUser = await findOrCreateUser(authToken);
  26.       }
  27.     } catch (err) {
  28.       console.warn(`Unable to authenticate using auth token: ${authToken}`);
  29.     }
  30.     return { authToken, currentUser };
  31.   }
  32. });
  33.  
  34. server.listen().then(({ url }) => {
  35.   console.log(`Server listening on ${url}`);
  36. });
  37.  
  38.  
  39. //userController.js
  40.  
  41. const User = require("../models/User");
  42. const { AuthenticationError } = require("apollo-server");
  43. const { OAuth2Client } = require("google-auth-library");
  44. const client = new OAuth2Client(process.env.OAUTH_CLIENT_ID);
  45.  
  46. exports.findOrCreateUser = async token => {
  47.   if (!token) {
  48.     throw new AuthenticationError("No auth token provided");
  49.   }
  50.   const googleUser = await verifyAuthToken(token);
  51.   const user = await checkIfUserExists(googleUser.email);
  52.   return user ? user : saveUser(googleUser);
  53. };
  54.  
  55. const checkIfUserExists = async email => await User.findOne({ email }).exec();
  56.  
  57. const saveUser = googleUser => {
  58.   const { email, name, picture } = googleUser;
  59.   const user = { email, name, picture };
  60.   return new User(user).save();
  61. };
  62.  
  63. const verifyAuthToken = async token => {
  64.   try {
  65.     const ticket = await client.verifyIdToken({
  66.       idToken: token,
  67.       audience: process.env.OAUTH_CLIENT_ID
  68.     });
  69.     return ticket.getPayload();
  70.   } catch (err) {
  71.     console.error("Error verifying auth token", err);
  72.   }
  73. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top