<form action="/login" method="post">
<div> <label for="username">Username</label> <input id="username" name="username" type="text"
autocomplete="username" required /> </div>
<div> <label for="current-password">Password</label> <input id="current-password" name="password"
type="password" autocomplete="current-password" required /> </div>
<div> <button type="submit">Sign in</button> </div>
</form>
const express = require("express");
const Redis = require("ioredis");
const session = require("express-session");
const passport = require("passport");
const RedisStore = require("connect-redis")(session);
const LocalStrategy = require("passport-local").Strategy;
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
app.use(bodyParser.urlencoded());
app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
app.engine("html", ejs.__express);
app.set("view engine", "html");
passport.serializeUser((user, done) => {
done(null, user.username);
});
passport.deserializeUser(function (username, done) {
done(null, { username });
});
app.use(
session({
name: "ang_server_session",
secret: "ang test",
resave: false,
rolling: true,
saveUninitialized: false,
cookie: {
maxAge: 86400000,
secure: false,
httpOnly: true,
path: "",
sameSite: "strict",
domain: "",
},
store: new RedisStore({
client: new Redis({
host: "114.115.134.189",
port: 6379,
db: 10,
password: "***",
}),
}),
})
);
app.use(passport.initialize());
app.use(passport.session());
passport.use(
new LocalStrategy(
{ usernameField: "username", passwordField: "password" },
function (username, password, done) {
if (username == "ang" && password == "11111") {
return done(null, { username, password });
} else {
return done(null, false, { message: "账户或密码错误" });
}
}
)
);
app.get("/", function (req, res) {
if (req.isAuthenticated()) {
res.send(
"欢迎您!" + req.session.passport.user + "!" + '<a href="logout">登出</a>'
);
} else {
res.send('您好!游客!<a href="login">请登录</a>');
}
});
app.get("/login", function (req, res) {
res.render("login");
});
app.post(
"/login",
passport.authenticate("local", {
failureRedirect: "/login",
failureMessage: true,
}),
function (req, res) {
res.redirect("/");
}
);
app.get("/logout", function (req, res) {
req.logout();
res.redirect("/");
});
const server = app.listen(8081, function () {
const host = server.address().address;
const port = server.address().port;
console.log("应用实例,访问地址为 http://%s:%s", host, port);
});