55 lines
1.4 KiB
JavaScript
55 lines
1.4 KiB
JavaScript
const express = require("express");
|
|
const session = require("express-session");
|
|
const bodyParser = require("body-parser");
|
|
|
|
const app = express();
|
|
const port = 3000;
|
|
|
|
app.use(bodyParser.urlencoded({ extended: false }))
|
|
app.use(bodyParser.json())
|
|
app.use(session({
|
|
secret: "hello kitty",
|
|
resave: false,
|
|
saveUninitialized: true,
|
|
cookie: { secret: false }
|
|
}))
|
|
|
|
const isAuthenticated = (req, res, next) => {
|
|
if (req.session.user)
|
|
next();
|
|
else
|
|
res.status(401).send("You are not authenticated!");
|
|
}
|
|
|
|
app.post("/login", (req, res) => {
|
|
const { username, password } = req.body;
|
|
if (username === "admin" && password === "password") {
|
|
req.session.user = { id: 1, username };
|
|
res.send("User logged in");
|
|
} else {
|
|
res.status(401).send("Invaild credentials");
|
|
}
|
|
})
|
|
|
|
app.post("/logout", (req, res) => {
|
|
req.session.destroy((error) => {
|
|
if (error)
|
|
return res.status(500).send("Could not log out.");
|
|
res.send("Logout successful")
|
|
})
|
|
})
|
|
|
|
app.get("/protected", isAuthenticated, (req, res) => {
|
|
res.send("This is a protected route");
|
|
})
|
|
|
|
app.get("/profile", isAuthenticated, (req, res) => {
|
|
res.send(`Welcome ${req.session.user.username}`);
|
|
})
|
|
|
|
app.listen(port, (error) => {
|
|
if (error)
|
|
console.log(error);
|
|
console.log(`server is running: http://localhost:${port}`);
|
|
})
|