Задать вопрос
@EmKotlety

Почему получаем ошибку «Непредвиденная ошибка!» при авторизации passport + react?

Как только выбираю аккаунт гугл для регистрации - получаю ошибку на экране {
"message": "Непредвиденная ошибка!"
}Файл app.js(сервер)
const express = require ('express')
const authRouter = require('./routes/auth.routes')
const googleRouter = require('./routes/auth-passwordjs-routes')
const mongoose = require('mongoose')
const config = require('config')
const  libsConfig = require('./libs/libsConfig')
const User = require('./models/User')
const app = express()
const cors = require('./middleware/cors.js')
const corss = require('cors')
const session = require("express-session");
const MongoStore = require('connect-mongodb-session')(session)
const passport = require("passport");
app.use(
    corss({
      origin: "http://localhost:3000", // allow to server to accept request from different origin
      methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
      credentials: true // allow session cookie from browser to pass through
    })
  );
const errorHandler = require('./middleware/ErrorHandlerMiddleware.js')
app.use(cors)
app.use(express.json())
const store = new MongoStore({
    collection: 'sessions',
    uri: config.get('mongoUri')
})
app.use(session({
    secret: libsConfig.session.secret,
    key: libsConfig.session.key,
    cookie: libsConfig.session.cookie,
    store: store,
    resave: false,
    saveUninitialized: true
}));
app.use("/api/auth" , authRouter)
app.use("/api/authgoogle/", googleRouter)
app.use(passport.initialize());
app.use(passport.session());
///////////////////////
let GoogleStrategy = require( 'passport-google-oauth2' ).Strategy;

    passport.serializeUser((user, done) => {
        done(null, user);
    });
    passport.deserializeUser(function (email, done) {
        User.findOne({ email }).exec((err, user) => {
          done(err, user);
        });
      });

    //============ GOOGLE
    passport.use( new GoogleStrategy({
            clientID: libsConfig.oauth.googleAuth.clientID,
            clientSecret: libsConfig.oauth.googleAuth.clientSecret,
            callbackURL: libsConfig.oauth.googleAuth.callbackURL,
            passReqToCallback   : true
        },
        function(request, accessToken, refreshToken, profile, cb, done) {
            console.log('ееееееееее',  libsConfig.oauth.googleAuth.clientSecret)
            User.findOrCreate({ googleId: profile.id }, function (err, user) {
                return cb(err, user);
              });
        }));
///////////////////////
// Обработка ошибок
app.use(errorHandler)
const PORT = config.get('port') || 5000
async function start(){
    try{
        await mongoose.connect(config.get('mongoUri'), {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useCreateIndex: true
        })
        app.listen(PORT, () => console.log(`server has been started on ${PORT}...`))
    }catch(e){
        console.log('Server Error', e.message)
        process.exit(1)//завершение процесса
    }
}
start()

Файл с роутом для авторизации через гугл:
const Router = require('express')
const router = new Router()
const passport = require("passport");
const CLIENT_HOME_PAGE_URL = "http://localhost:3000";

router.get('/registration/google',
 passport.authenticate('google',{scope : ['email', 'profile']}));


router.get(`/registration/google/callback`,
  passport.authenticate('google', {
      successRedirect: CLIENT_HOME_PAGE_URL,
      failureRedirect: CLIENT_HOME_PAGE_URL
  })

);
router.get("/success", (req, res) => {
  if (req.user) {
    res.json({
      success: true,
      message: "user has successfully authenticated",
      user: req.user,
      cookies: req.cookies
    });
  }
});

// when login failed, send failed msg
router.get("/failed", (req, res) => {
  res.status(401).json({
    success: false,
    message: "user failed to authenticate."
  });
});

// When logout, redirect to client
router.get("/logout", (req, res) => {
  req.logout();
  res.redirect(CLIENT_HOME_PAGE_URL);
});
module.exports = router;

Файл libsconfig:
const libsConfig = {};
libsConfig.session = {
    "secret": "VerySecretKEy",
    "key": "sid",
    "cookie": {
        "path": "/",
        "httpOnly": true,
        "maxAge": null
    }
};
libsConfig.oauth = {
    'facebookAuth' : {
        'clientID': 'your_client_id',
        'clientSecret': 'your_client_secret',
        'callbackURL': '/registration/facebook/callback'
    },
    'googleAuth' : {
        'clientID': XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,
        'clientSecret':  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,
        'callbackURL': 'http://localhost:5000/api/authgoogle/registration/google/callback'
    }
};

module.exports = libsConfig;

файл cors.js:
function cors(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, PUT, PATCH, POST, DELETE");
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
    next();
}

module.exports = cors

и сам запрос:
const  _handleSignInClick = (e) => {
    e.preventDefault();
    window.open("http://localhost:5000/api/authgoogle/registration/google", "_self");
  };
  • Вопрос задан
  • 83 просмотра
Подписаться 1 Простой Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы