E
E
EmKotlety2021-10-01 19:03:11
Express.js
EmKotlety, 2021-10-01 19:03:11

Why do we get the error "Unexpected error!" when authorizing passport + react?

As soon as I select a Google account for registration, I get an error on the screen {
"message": "Unforeseen error!"
}file app.js(server)

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()

The file with the route for authorization through Google:
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 file:
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 file:
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

and the query itself:
const  _handleSignInClick = (e) => {
    e.preventDefault();
    window.open("http://localhost:5000/api/authgoogle/registration/google", "_self");
  };

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question