#node.js #reactjs #mongodb #express #passport.js
Вопрос:
Используя React axios, отправьте имя пользователя и пароль на серверную часть(узел). req,authenticate() возвращает значение true только при входе в систему, после чего автоматически становится ложным.
Проверка пользователя, аутентифицирован ли он с помощью нового запроса get, называемого checkAuth, и проверка, является ли req.IsAuthenticated() истинным или ложным
Если учетные данные пользователя совпадают с данными в базе данных, запрос на запись для входа делает req.IsAuthenticated истинным, но при проверке с помощью запроса checkAuth get он возвращает false
Вот код бэкенда
require("dotenv").config();
const express = require("express");
const app = express();
const https = require("https");
const cors = require("cors");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const mongoose = require("mongoose");
const multer = require("multer");
const session = require("express-session");
const passport = require("passport");
const passportLocal = require("passport-local");
const passportLocalMongoose = require("passport-local-mongoose");
const storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, "../frontend/public/images");
},
filename: function(req, file, cb){
cb(null, Date.now() "-image-" file.originalname);
}
});
var upload = multer({
storage: storage,
fileFilter: (req, file, cb) => {
if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg" || file.mimetype == "video/mp4") {
cb(null, true);
} else {
cb(null, false);
return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
}
}
});
const mongoose_Url = "mongodb srv://" process.env.Mongoose_Username ":" process.env.Mongoose_Password "@cluster0.g55a6.mongodb.net/databaseName";
mongoose.connect(mongoose_Url, {useNewUrlParser: true, useUnifiedTopology: true});
// mongoose.connect('mongodb://localhost:27017/photoFile', {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.set("useCreateIndex", true);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(
cors({
origin: "http://localhost:3000", // <-- location of the react app were connecting to
// credentials: true,
})
);
app.use(session({
secret: process.env.secret,
resave: false,
saveUninitialized: false,
maxAge: 24*60*60*1000
}));
app.use(cookieParser("secretcode"));
app.use(passport.initialize());
app.use(passport.session());
// mongoose.connect(mongoose_Url, {useNewUrlParser: true, useUnifiedTopology: true});
// // mongoose.connect('mongodb://localhost:27017/photoFile', {useNewUrlParser: true, useUnifiedTopology: true});
// mongoose.set("useCreateIndex", true);
const messageSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "Please add the your name"]
},
email: {
type: String,
required: [true, "Please add the your email"]
},
contactno:{
type: String
},
message:{
type: String,
required: [true, "Please add the your email"]
},
dateTime: {
type: String
}
});
const adminSchema = new mongoose.Schema({
username: {
type: String,
required: [true, "Please add your username"]
},
password: {
type: String
}
});
const subscriberSchema = new mongoose.Schema({
email: {
type: String,
required: [true, "Please add your email"]
}
});
const blogSchema = new mongoose.Schema({
blogTitle:{
type: String,
required: [true, "blog title missing"]
},
blogImage:{
type: String
},
blogVideo: {
type: String
},
blogContent:{
type: String,
required: [true, "blog content missing"]
},
blogAuthor:{
type: String
}
});
const gallerySchema = new mongoose.Schema({
picture: String
});
adminSchema.plugin(passportLocalMongoose);
const Admin = mongoose.model("Admin", adminSchema);
const Subscriber = mongoose.model("Subscriber", subscriberSchema);
const Message = mongoose.model("Message", messageSchema);
const Blog = mongoose.model("Blog", blogSchema);
const Gallery = mongoose.model("Gallery", gallerySchema);
passport.use(Admin.createStrategy());
passport.serializeUser(Admin.serializeUser());
passport.deserializeUser(Admin.deserializeUser());
app.get("/checkAuth", function(req,res){
//console.log("req.user: " req.user);
console.log("check Authentication Route: " req.isAuthenticated());
if(req.isAuthenticated()){
res.send(req.isAuthenticated());
}
else{
res.send(false);
}
});
app.get("/logout", function(req,res){
req.logout();
res.send("Successfully Logged Out");
console.log("Logout Access: " req.isAuthenticated());
});
app.post("/admin-register", function(req, res){
console.log(req.body);
Admin.register({username: req.body.username, active: false}, req.body.password, function(err, user) {
if (err) {
console.log(err);
}
else{
var authenticate = Admin.authenticate();
authenticate(req.body.username, req.body.password, function(err, result) {
if (err) {
console.log(err);
}
else{
console.log(result);
}
// Value 'result' is set to false. The user could not be authenticated since the user is not active
});
res.send("Successfully Registered")
}
});
});
app.post("/admin-login", function(req, res, next){
console.log(req.body);
passport.authenticate("local", (err, user, info)=>{
if(err) throw err;
if(!user) {
res.send("User not found");
accessStatus = req.isAuthenticated();
}
else{
req.login(user, err=>{
if(err) throw err;
res.send("Succesfully Authenticated");
accessStatus = req.isAuthenticated();
console.log("isAuth Status: " req.isAuthenticated());
});
}
// console.log("Error " err);
// console.log("Info: " info);
// console.log("User: " user);
})(req, res, next);
});
app.listen(process.env.PORT || 5000, function(){
console.log("App listening on Port 5000");
})