Я пытаюсь создать схему для системы аутентификации пользователей, но получаю указанное выше сообщение об ошибке. Я создал две новые страницы со следующим кодом:
Пользователи. js
var mongoose = require ('mongoose');
var crypto = require ('crypto');
var jwt = require('jsonwebtoken');
var userSchema = new mongoose.Schema({
email:{
type: String,
unique: true,
required: true
},
name: {
type: String,
required: true
},
hash: String,
salt: String
});
userSchema.methods.setPassword = function(password){
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
};
//when the setPassword method is called and supplied with a password, the salt and hash will be generated
//for users and added to the model instance - password is never saved anywhere, and not even stored in memory
userSchema.methods.validPassword = function(password){
var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
return this.hash === hash;
};
userSchema.methods.generateJwt = function(){
var expiry = new Date();
expiry.setDate(expiry.getDate() + 7);
return jwt.sign({
_id: this._id,
email: this.email,
name: this.name,
exp: parseInt(expiry.getTime() / 1000),
}, process.env.JWT_SECRET);
};
/*var User = mongoose.model('user');
var user = new User();
user.name = "User's name";
user.email = "test@example.com";
user.setPassword("myPassword");
user.save();*/
аутентификация. js
var passport = require('passport');
var mongoose = require('mongoose');
var User = mongoose.model('User');
var sendJSONreponse = function(res, status, content) {
res.status(status);
res.json(content);
};
//register controller for the API
module.exports.register = function(req, res){
if(!req.body.name || !req.body.email || !req.body.password){
sendJSONreponse(res, 400, {
"message": "All fields required"
});
return;
}
var user = new User();
user.name = req.body.name;
user.email = req.body.email;
user.setPassword(req.body.password);
user.save(function(err) {
var token;
if (err){
sendJSONreponse(res, 404, err);
} else{
token = user.generateJwt();
sendJSONreponse(res, 200, {
"token" : token
});
}
});
};
//Login controller for the API
module.exports.login = function(req, res) {
if(!req.body.email || !req.body.password){
sendJSONreponse (res, 400, {
"message" : "All fields required"
});
return;
}
passport.authenticate('local', function(err, user, info){
var token;
if (err){
sendJSONreponse(res, 404, err);
return;
}
if(user){
token = user.generateJwt();
sendJSONreponse(res, 200, {
"token" : token
});
} else {
sendJSONreponse(res, 401, info);
}
}) (req, res);
};
module.exports = router;
приложение. js Это часть кода, который относится к приведенному выше
require('dotenv');
var express = require('express');
var createError = require('http-errors');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var uglifyJS = require("uglify-js");
var fs = require ('fs');
var passport = require('passport');
//require('./app_api/models/blogModel');
require('./app_api/models/db');
require('./app_api/config/passport');
var routesApi = require('./app_api/routes/index');
var mongoose = require("mongoose");
var mongoDB = "mongodb://**********************************;
mongoose.Promise = global.Promise;
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => console.log('connection successful'))
.catch((err) => console.log(err));
/*BRING IN SCHEMAS AND MODELS*/
require('./users');
var app = express();
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(bodyParser.urlencoded({
extended: true
}));
// view engine setup
app.set('views', path.join(__dirname, 'app_server', 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'app_client')));
app.use(passport.initialize());
app.use('/api', routesApi);
//make db accessible to router
// app.use(function(req, res, next){
// req.db=db;
// next();
// });
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
// catch unauthorised errors
app.use(function (err, req, res, next){
if (err.name === 'UnauthorizedError'){
res.status(401);
res.json({"message" : err.name + ": " + err.message});
}
});
module.exports = app;
Я следил учебник и форматирование эт c. правильно; Я просто не знаю, откуда взялась ошибка.
Заранее спасибо!