49 lines
1.4 KiB
JavaScript
49 lines
1.4 KiB
JavaScript
|
const express = require('express');
|
||
|
const bodyParser = require('body-parser');
|
||
|
const cookieParser = require('cookie-parser');
|
||
|
const path = require('path');
|
||
|
const authMiddleware = require('./middlewares/authMiddleware');
|
||
|
const PORT = 9000;
|
||
|
const app = express();
|
||
|
|
||
|
// Middleware to parse form data and cookies
|
||
|
app.use(bodyParser.urlencoded({ extended: true }));
|
||
|
app.use(cookieParser());
|
||
|
|
||
|
// Serve static files (login page)
|
||
|
app.use(express.static(path.join(__dirname, 'public')));
|
||
|
|
||
|
// Login route
|
||
|
app.post('/login', (req, res) => {
|
||
|
const { username, password } = req.body;
|
||
|
|
||
|
// Hardcoded credentials
|
||
|
const validUsername = 'user';
|
||
|
const validPassword = '1234';
|
||
|
|
||
|
if (username === validUsername && password === validPassword) {
|
||
|
// Set a cookie to indicate the user is logged in
|
||
|
res.cookie('isLoggedIn', true, { httpOnly: true });
|
||
|
res.redirect('/dashboard');
|
||
|
} else {
|
||
|
res.status(401).send('<h1>Invalid username or password</h1><a href="/login">Try Again</a>');
|
||
|
}
|
||
|
});
|
||
|
|
||
|
// Protected route
|
||
|
app.get('/dashboard', authMiddleware, (req, res) => {
|
||
|
res.send('<h1>Welcome to the Dashboard</h1><a href="/logout">Logout</a>');
|
||
|
});
|
||
|
|
||
|
// Logout route
|
||
|
app.get('/logout', (req, res) => {
|
||
|
res.clearCookie('isLoggedIn'); // Remove the login cookie
|
||
|
res.redirect('/login'); // Redirect to the login page
|
||
|
});
|
||
|
|
||
|
|
||
|
app.listen(PORT, () => {
|
||
|
console.log(`Server is running at http://localhost:${PORT}`);
|
||
|
});
|
||
|
|