最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ES import passport - Stack Overflow

programmeradmin1浏览0评论

Can anyone help me use ES import version of the: require('./config/passport')(passport);. I cant get this to work. I don't think you can use both ES import and require at the same time. I get and error that require is undefined.

import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
import dotenv from 'dotenv';
import { createRequire } from 'module';
const URL = createRequire(import.meta.url);
import passport from 'passport'


import postRoutes from './routes/posts.js'
import userRoutes from './routes/user.js'
import loginRoutes from './routes/login.js'

const app = express();
dotenv.config();
require('./config/passport')(passport);

app.use(passport.initialize());
app.use(passport.session());

Can anyone help me use ES import version of the: require('./config/passport')(passport);. I cant get this to work. I don't think you can use both ES import and require at the same time. I get and error that require is undefined.

import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
import dotenv from 'dotenv';
import { createRequire } from 'module';
const URL = createRequire(import.meta.url);
import passport from 'passport'


import postRoutes from './routes/posts.js'
import userRoutes from './routes/user.js'
import loginRoutes from './routes/login.js'

const app = express();
dotenv.config();
require('./config/passport')(passport);

app.use(passport.initialize());
app.use(passport.session());
Share Improve this question asked Mar 22, 2021 at 17:28 Sean BurnettSean Burnett 1093 silver badges9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Yes, we can not use require which is monjs modules with import which is ES6 modules. Though the solution is really simple. Basically, you have to pass passport as an argument to the function exported from ./config/passport. All you have to do is just import the function as is and pass passport as an argument.

So here's what you need to do:-


config/passport.js

export default = (passport) => {
 /* use passport here */
}

index.js

import passport from "passport";
import passportConfig from "./config/passport";

passportConfig(passport);

Aryaman is correct but I would like to offer a slightly different solution.

I would remend that you keep passports logic out of the main app.js/ index.js file as much as possible. I create a config folder with the main passport.js and then a strategies folder that has logic for how users will login.

in your main entry point file eg app.js

pull in passport's config passing app.

import express from 'express';
const app = express();
require('./src/config/passport')(app);

Your config file eg:passport.js should look like this

import passport from 'passport';

require('./strategies/local.strategy')(); //Or whatever strategy you are using

const passportConfig = (app) => {
  app.use(passport.initialize());
  app.use(passport.session());
  // stores user to session
  passport.serializeUser((user, done) => {
    done(null, user);
  });

  // retrieves user from session
  passport.deserializeUser((user, done) => {
    done(null, user);
  });
};

export default passportConfig;

Example local strategy aka custom strategy

import passport from 'passport';
import { Strategy } from 'passport-local';
import axios from 'axios';

const localStrategy = () => {
  passport.use(new Strategy(
    {
      usernameField: 'userName',
      passwordField: 'password',
    },
    (username, password, done) => {
        const loginUrl = `${process.env.base_url}/api/core/security/login`;
        const body = {
          InstanceName: process.env.instance_name,
          Username: username,
          UserDomain: process.env.user_domain,
          Password: password,
        };
        axios.post(loginUrl, body)
          .then((response) => {
            if (response.data.IsSuccessful === true) {
              const user = {
                token: response.data.RequestedObject.SessionToken,
                userId: response.data.UserId,
                userName: username,
              };
              done(null, user);
            } else {
              // handle failed login
            }
          })
          .catch((error) => 
            //Handle the error
        }
      ))
    }

    export default localStrategy;
发布评论

评论列表(0)

  1. 暂无评论