本文介绍了护照-本地猫鼬:createStrategy不是函数/身份验证不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在此入门项目之上构建尝试使用 passport-local-mongoose 添加用户登录.

I'm building on top of this starter project and trying to add user login with passport-local-mongoose.

根据我尝试使用该策略的两种方式中的哪一种,我会遇到此错误:

Depending on which of the two ways I try to use the strategy I'm getting either this error:

[1] passport.use(User.createStrategy());
[1]                   ^
[1] TypeError: User.createStrategy is not a function

或此错误:

[1] passport.use(new LocalStrategy(User.authenticate()));
[1]                                     ^
[1] TypeError: User.authenticate is not a function

我已经尝试了很多搜索以寻求解决方案,但是似乎找不到任何相关的东西.

I've tried googling around a lot for a solution but can't seem to find anything relevant.

据我了解,./models/user.ts中的userSchema.plugin(passportLocalMongoose);应该将功能添加到模型中. 配置Passport/Passport-Local 简化的Passport/Passport-Local Configuration 显示如何设置起来,但似乎对我不起作用.

As I understand it userSchema.plugin(passportLocalMongoose); in ./models/user.ts should add the functions to the model. Configure Passport/Passport-Local and Simplified Passport/Passport-Local Configuration show how to set it up but it doesn't seem to work for me.

相关的依赖版本:

  "dependencies": {
    "cookie-parser": "^1.4.3",
    "express": "^4.14.0",
    "express-session": "^1.15.3",
    "mongoose": "^4.7.2",
    "passport": "^0.3.2",
    "passport-local": "^1.0.0",
    "passport-local-mongoose": "^4.0.0",
    "session-file-store": "^1.0.0",
    "typescript": "~2.2.0",
  },
  "devDependencies": {
    "ts-node": "~2.0.0",
  },

./models/user.ts

import * as mongoose from 'mongoose';
const passportLocalMongoose = require('passport-local-mongoose');

const userSchema = new mongoose.Schema({
  email: String,
  password: String,
  displayname: String,
  groups: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Group'
  }]
});

userSchema.plugin(passportLocalMongoose, {
  usernameField: 'email'
});

const User = mongoose.model('User', userSchema);

export default User;

./app.ts的相关部分

import * as express from 'express';
import * as cookieParser from 'cookie-parser';
import * as session from 'express-session';
const FileStore = require('session-file-store')(session);
import * as mongoose from 'mongoose';
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

const app: express.Express = express();

const cookieSecret = 'asdf';
app.use(cookieParser(cookieSecret));
app.use(session({
  secret: cookieSecret,
  resave: false,
  saveUninitialized: false,
  store: new FileStore()
}));

// Configure passport middleware
app.use(passport.initialize());
app.use(passport.session());

// Configure passport-local to use User model for authentication
const User = require('./models/user');
passport.use(User.createStrategy());
// Alternatively: passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

完成./app.ts

import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as cookieParser from 'cookie-parser';
import * as session from 'express-session';
const FileStore = require('session-file-store')(session);
import * as path from 'path';
import * as logger from 'morgan';
import * as mongoose from 'mongoose';
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

// import index from './routes/index';
// import users from './routes/users';

const app: express.Express = express();

// // view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
// app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const cookieSecret = '';
app.use(cookieParser(cookieSecret));
app.use(session({
  secret: cookieSecret,
  resave: false,
  saveUninitialized: false,
  store: new FileStore()
}));
app.use(express.static(path.join(__dirname, 'public')));

// Configure passport middleware
app.use(passport.initialize());
app.use(passport.session());

// Configure passport-local to use User model for authentication
const User = require('./models/user');
passport.use(User.createStrategy());
// Alternatively: passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

// app.use('/', index);
// app.use('/users', users);

// routes
const routeModules = require('require-all')({
  dirname: __dirname + '/routes',
  filter: (filename: string) => {
    filename = filename.toLowerCase();
    if ((filename.endsWith('.ts') && !filename.endsWith('.spec.ts'))
      || (filename.endsWith('.js') && !filename.endsWith('.spec.js'))) {
      return filename.substr(0, filename.length - 3);
    }
  },
  map: name => '/' + name
});
function resolve(root: string, modules): void {
  for (const name of Object.keys(modules)) {
    if (!name.startsWith('/')) {
      return;
    }
    const module = modules[name];
    if (module.default && module.default.route) {
      console.log(`Add router ${root + name}`);
      const router = module.default as express.Router;
      app.use(root, router);
    } else {
      resolve(root + name, module);
    }
  }
}
resolve('', routeModules);

// Default to main page, angular route takes over
app.use((req, res) => {
  res.sendFile(path.join(__dirname, 'public/index.html'));
});

// // catch 404 and forward to error handler
// app.use((req, res, next) => {
//   var err = new Error('Not Found');
//   err['status'] = 404;
//   next(err);
// });

// // error handlers

// // development error handler
// // will print stacktrace
// if (app.get('env') === 'development') {

//   app.use((error: any, req, res, next) => {
//     res.status(error['status'] || 500);
//     res.render('error', {
//       message: error.message,
//       error
//     });
//   });
// }

// // production error handler
// // no stacktraces leaked to user
// app.use((error: any, req, res, next) => {
//   res.status(error['status'] || 500);
//   res.render('error', {
//     message: error.message,
//     error: {}
//   });
//   return null;
// });

export default app;


// Connect to MongoDB
mongoose.connect('mongodb://localhost/test');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  console.log('MongoDB connected');
});

推荐答案

像这样更新user.ts文件:

Update your user.ts file like this:

import * as mongoose from 'mongoose';
import * as passportLocalMongoose from 'passport-local-mongoose';
import { PassportLocalSchema } from 'mongoose';

const userSchema = new mongoose.Schema({
  email: String,
  password: String,
  displayname: String,
  groups: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Group'
  }]
});

userSchema.plugin(passportLocalMongoose, {
  usernameField: 'email'
});

const User = mongoose.model('User', userSchema as PassportLocalSchema);

export default User;

对我有用.

这篇关于护照-本地猫鼬:createStrategy不是函数/身份验证不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 11:18