Как мне настроить прокси в Vue js для Passport + Google Oauth2? - PullRequest
1 голос
/ 12 марта 2020

Фон :

У меня есть proxy.config. js Настройка для запроса API в Vue. js, которая прекрасно работает. Кроме того, у меня есть компонент с кнопкой входа в систему, который использует ссылку (href) для направления на Passport + Google Oauth2, который находится на сервере.

Проблема : прокси в Vue сделал так, что я могу получить доступ к API, когда я нахожусь в режиме разработки, но я не могу использовать настройки входа в Google.

Вопрос : Каков наилучший способ входа в мое приложение в разработке ?

Express. js маршрут входа

const express = require("express");
const router = express.Router();
const passport = require("passport");

//auth with google
router.get(
  "/usergoogle",
  passport.authenticate("google", {
    scope: ["profile"]
  })
);

//callback route for google after athourization
router.get("/google/redirect", passport.authenticate("google"), (req, res) => {
  res.redirect("/userprofile");
});

//Logout
router.get("/logout", (req, res) => {
  req.session.destroy(() => {
    res.redirect("/");
  });
});

module.exports = router;

Express. js Паспорт

const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20");
require("dotenv").config();
const User = require("../models/userModel");

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

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

passport.use(
  new GoogleStrategy(
    {
      //options for the google strategy
      callbackURL: "https://ewbudget.herokuapp.com/auth/google/redirect",
      clientID: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET
    },
    (accessToken, refreshToken, profile, done) => {
      //passport callback function
      console.log("passport callback fired");

      //Check if user already exist in Db
      User.findOne({ googleId: profile.id }).then(currentUser => {
        if (currentUser) {
          //already have user
          done(null, currentUser);
        } else {
          //create new user
          new User({
            username: profile.username,
            name: profile.displayName,
            googleId: profile.id
          })
            .save()
            .then(newUser => {
              console.log(`$was just created`);
              done(null, newUser);
            });
        }
      });
    }
  )
);

Vue js Компонент входа

<template>
  <div class="home">
    <div class="container-fluid">
      <h1>Budgeting App</h1>
      <hr />
      <h2>Sign in</h2>
      <a
        @click="change()"
        class="btn btn-danger"
        href="auth/usergoogle"
        style="width:12em;"
      >Sign in with Google</a>
    </div>
  </div>
</template>

vue .config. js

const path = require("path");

module.exports = {
  outputDir: path.resolve(__dirname, "../backend/dist"),
  devServer: {
    proxy: {
      "/api": {
        target: "http://localhost:3000"
      },
      "/auth": {
        target: "http://localhost:3000"
      }
    }
  }
};
...