我的结构如下:
前端是一个有角度的6应用程序,后端是带有express mongodb和Passport进行身份验证的nodejs。当我使用邮递员测试身份验证时,一切正常。但是当我使用我的角度应用程序和HttPClient时,我一直收到用户未登录时发送的消息。
这是我的主要server.js:
<p>Lorem ipsum dolor sit <strong>amet, <em>cons</em>ectetur adipiscing elit.</strong> Morbi rhoncus lacinia orci a dapibus. Nulla facilisi. Sed id nibh ornare, aliquet ante nec, efficitur leo. Sed viverra ex turpis,</p>
这是我的护照策略:
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import key from './config/key';
import session from 'express-session';
import index from './routes/index';
import users from './routes/users';
import dreams from './routes/dreams';
import cookieParse from 'cookie'
const passport = require('passport');
import flash from 'connect-flash';
const cookieSession = require('cookie-session');
//init express
const app = express();
require('./config/passport')(passport);
const router = express.Router();
const db = key.mongoURI;
app.use(cors());
app.use(bodyParser.json());
app.use(session({
secret: 'secret'
}));
// pasport middelware
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect(db)
.then(() => console.log('mongoDB Connected...'))
.catch(err => console.log(err));
// const connection = mongoose.connection;
//
// //establish mongoose connection
// connection.once('open', () => {
// console.log('MongoDB database connection established succesfully');
// });
//routes :
app.use('/',index);
app.use('/users', users);
app.use('/dreams', dreams);
app.listen(4000, () => console.log('Express server running on port 4000'));
这是我的登录路线:
const LocalStrategy = require('passport-local').Strategy;
import mongoose from 'mongoose';
import bcrypt from 'bcryptjs';
import User from '../models/user'
// Load User Model
module.exports = function (passport) {
passport.use(
new LocalStrategy({ usernameField: 'email'}, (email, password, done) =>{
//Match User
User.findOne({email: email})
.then(user => {
if(!user){
return done(null, false, { message: 'That email is not registered'});
}
//Match password
bcrypt.compare(password, user.password, (err, isMatch) => {
if(err) throw err;
if(isMatch){
return done(null, user);
}else{
return done(null, false, {message: 'Password Incorrect'});
}
});
})
.catch(err => console.log(err));
})
);
passport.serializeUser(function (user, done) {
console.log(user);
done(null, user.id);
});
passport.deserializeUser(function(id, done){
User.findById(id, function (err, user) {
done(err, user);
})
})
};
最后是我的身份验证:
import express from 'express';
import User from '../models/user'
import bcrypt from 'bcryptjs'
import passport from 'passport';
const app = express();
const router = express.Router();
const {ensureAuthenticated} = require('../config/auth');
//All users : DELETE THIS !!!
router.get("/all", (req, res) => {
User.find((err, users) => {
if (err)
console.log(err);
else
res.json(users);
});
});
//Login Page
router.get("/login", (req, res) => res.status(401).send("wrong password"));
router.get("/loggedIn",ensureAuthenticated, (req, res) => res.send(req.user.id));
router.get("/login/error", (req, res) => res.send("error"));
//Register Page
router.get("/register", (req, res) => res.send("Register"));
//register Handle
router.post('/register', (req, res) => {
const {name, email, password, password2} = req.body;
let errors = [];
//check required fields
if (!name || !email || !password || !password2) {
errors.push({msg: 'Please fill in all fields'});
}
//check if passwords match
if (password != password2) {
errors.push({msg: 'Passwords do not match'});
}
//check if passwords is at least 6 characters long
if (password.length < 6) {
errors.push({msg: 'Password should be at least 6 characters'});
}
if (errors.length > 0) {
res.send({error: errors});
} else {
User.findOne({email: email})
.then(user => {
if (user) {
errors.push({msg: "Email is already registered"});
res.send({error: errors});
} else {
const newUser = new User({
name,
email,
password
});
//hash password
bcrypt.genSalt(10, (err, salt) =>
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
//set password to hashed
newUser.password = hash;
newUser.save()
.then(user => {
res.redirect("/users/login");
})
.catch(err => console.log(err))
}));
}
});
}
});
//Login
// Login
router.post('/login', passport.authenticate('local'),
function(req, res) {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
res.send(req.user);
}
);
router.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
module.exports = router;