changed the folder structure. separated the routes and added the authmiddleware for authentication
This commit is contained in:
@@ -1,2 +1,6 @@
|
|||||||
JWT_SECRET_KEY=your_secret_key_here
|
JWT_SECRET_KEY=your_secret_key_here
|
||||||
TOKEN_HEADER_KEY=auth-token
|
TOKEN_HEADER_KEY=auth-token
|
||||||
|
DB_HOST=localhost
|
||||||
|
DB_USER=root
|
||||||
|
DB_PASSWORD=12345678
|
||||||
|
DB_NAME=popcen
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
const express = require("express");
|
||||||
|
const router = express.Router();
|
||||||
|
const db = require("../../config/db");
|
||||||
|
const verifyToken = require("../../middlewares/authMiddleware");
|
||||||
|
|
||||||
|
router.get("/", verifyToken, (req, res) => {
|
||||||
|
const caseidPattern = req.query.caseidPattern + "%";
|
||||||
|
const batchno = parseInt(req.query.batchno, 10) || 1;
|
||||||
|
const sql =
|
||||||
|
"SELECT id, uuid, caseid, modified_time FROM popcen WHERE caseid LIKE ? LIMIT ? OFFSET ?";
|
||||||
|
const limit = 1000;
|
||||||
|
const offset = (batchno - 1) * limit;
|
||||||
|
|
||||||
|
db.query(sql, [caseidPattern, limit, offset], (err, results) => {
|
||||||
|
if (err) {
|
||||||
|
console.error(err);
|
||||||
|
return res.status(500).send("Server error");
|
||||||
|
}
|
||||||
|
res.json({ batchno, results });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
const express = require("express");
|
||||||
|
const router = express.Router();
|
||||||
|
const db = require("../../config/db");
|
||||||
|
const verifyToken = require("../../middlewares/authMiddleware");
|
||||||
|
|
||||||
|
router.get("/", verifyToken, (req, res) => {
|
||||||
|
const caseidPattern = req.query.caseidPattern + "%";
|
||||||
|
const sql = "SELECT COUNT(id) AS count FROM popcen WHERE caseid LIKE ?";
|
||||||
|
|
||||||
|
db.query(sql, [caseidPattern], (err, results) => {
|
||||||
|
if (err) {
|
||||||
|
console.error(err);
|
||||||
|
return res.status(500).send("Server error");
|
||||||
|
}
|
||||||
|
res.json(results[0].count);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
const express = require("express");
|
||||||
|
const router = express.Router();
|
||||||
|
const jwt = require("jsonwebtoken");
|
||||||
|
const db = require("../../config/db");
|
||||||
|
|
||||||
|
// User login endpoint
|
||||||
|
router.post("/login", (req, res) => {
|
||||||
|
const { username, password } = req.body;
|
||||||
|
|
||||||
|
if (!username || !password) {
|
||||||
|
return res.status(400).send("Username and password are required");
|
||||||
|
}
|
||||||
|
|
||||||
|
const sql = "SELECT * FROM tbl_user WHERE username = ?";
|
||||||
|
db.query(sql, [username], (err, results) => {
|
||||||
|
if (err) {
|
||||||
|
console.error(err);
|
||||||
|
return res.status(500).send("Server error");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (results.length === 0) {
|
||||||
|
return res.status(401).send("Invalid credentials");
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = results[0];
|
||||||
|
|
||||||
|
if (password === user.password) {
|
||||||
|
let jwtSecretKey = process.env.JWT_SECRET_KEY || "defaultSecretKey";
|
||||||
|
let data = { userId: user.id, username: user.username };
|
||||||
|
|
||||||
|
const token = jwt.sign(data, jwtSecretKey, { expiresIn: "1h" });
|
||||||
|
return res.json({ token });
|
||||||
|
} else {
|
||||||
|
return res.status(401).send("Invalid credentials");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
const mysql = require("mysql2");
|
||||||
|
const dotenv = require("dotenv");
|
||||||
|
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
const db = mysql.createConnection({
|
||||||
|
host: process.env.DB_HOST,
|
||||||
|
user: process.env.DB_USER,
|
||||||
|
password: process.env.DB_PASSWORD,
|
||||||
|
database: process.env.DB_NAME,
|
||||||
|
});
|
||||||
|
|
||||||
|
db.connect((err) => {
|
||||||
|
if (err) {
|
||||||
|
console.error("Database connection failed:", err.stack);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log("Connected to the MySQL database.");
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = db;
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
const jwt = require("jsonwebtoken");
|
||||||
|
|
||||||
|
const verifyToken = (req, res, next) => {
|
||||||
|
const token = req.header("Authorization");
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return res.status(403).send("A token is required for authentication");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const jwtSecretKey = process.env.JWT_SECRET_KEY || "default_secret_key";
|
||||||
|
const decoded = jwt.verify(token.replace("Bearer ", ""), jwtSecretKey);
|
||||||
|
req.user = decoded;
|
||||||
|
} catch (err) {
|
||||||
|
return res.status(401).send("Invalid Token");
|
||||||
|
}
|
||||||
|
|
||||||
|
return next();
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = verifyToken;
|
||||||
@@ -1,128 +1,28 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const dotenv = require('dotenv');
|
const dotenv = require("dotenv");
|
||||||
const jwt = require('jsonwebtoken');
|
const bodyParser = require("body-parser");
|
||||||
const mysql = require('mysql2');
|
|
||||||
const bcrypt = require('bcrypt');
|
|
||||||
const bodyParser = require('body-parser'); // To parse JSON body
|
|
||||||
|
|
||||||
|
// Initialize app
|
||||||
const app = express();
|
const app = express();
|
||||||
|
|
||||||
// Middleware
|
// Load environment variables
|
||||||
app.use(bodyParser.json()); // To handle JSON requests
|
|
||||||
|
|
||||||
// Set up Global configuration access
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
|
// Middleware for parsing JSON
|
||||||
|
app.use(bodyParser.json());
|
||||||
|
|
||||||
|
// Import routes
|
||||||
|
const popcenRoutes = require("./api/routes/popcen");
|
||||||
|
const popcenCountRoutes = require("./api/routes/popcenCount");
|
||||||
|
const userRoutes = require("./api/routes/user");
|
||||||
|
|
||||||
// MySQL Database connection
|
// Use routes
|
||||||
const db = mysql.createConnection({
|
app.use("/popcen", popcenRoutes);
|
||||||
host: 'localhost',
|
app.use("/popcenCount", popcenCountRoutes);
|
||||||
user: 'root',
|
app.use("/user", userRoutes);
|
||||||
password: '12345678',
|
|
||||||
database: 'popcen',
|
|
||||||
});
|
|
||||||
|
|
||||||
db.connect((err) => {
|
|
||||||
if (err) {
|
|
||||||
console.error('Database connection failed:', err.stack);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
console.log('Connected to the MySQL database.');
|
|
||||||
});
|
|
||||||
|
|
||||||
// Login endpoint
|
|
||||||
app.post('/user/login', (req, res) => {
|
|
||||||
const { username, password } = req.body;
|
|
||||||
|
|
||||||
if (!username || !password) {
|
|
||||||
return res.status(400).send('Username and password are required');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if the user exists in the database
|
|
||||||
const sql = 'SELECT * FROM tbl_user WHERE username = ?';
|
|
||||||
db.query(sql, [username], async (err, results) => {
|
|
||||||
if (err) {
|
|
||||||
console.error(err);
|
|
||||||
return res.status(500).send('Server error');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (results.length === 0) {
|
|
||||||
return res.status(401).send('Invalid credentials');
|
|
||||||
}
|
|
||||||
|
|
||||||
const user = results[0];
|
|
||||||
|
|
||||||
// Compare provided password with stored password (you should hash passwords in a real app)
|
|
||||||
if (password === user.password) { // Use bcrypt.compare() for hashed passwords
|
|
||||||
// Generate JWT
|
|
||||||
let jwtSecretKey = process.env.JWT_SECRET_KEY || 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsInVzZXJuYW1lIjoidGVzdHVzZXIiLCJpYXQiOjE3MjY2NDg3MzksImV4cCI6MTcyNjY1MjMzOX0.pMxA46X2WyiY1HFW6xxJj9JIcBzZI3t39THKUEUikcw'; // Fallback if env var is missing
|
|
||||||
let data = {
|
|
||||||
userId: user.id,
|
|
||||||
username: user.username,
|
|
||||||
};
|
|
||||||
|
|
||||||
const token = jwt.sign(data, jwtSecretKey, { expiresIn: '1h' });
|
|
||||||
return res.json({ token });
|
|
||||||
} else {
|
|
||||||
return res.status(401).send('Invalid credentials');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
// Verification of JWT
|
|
||||||
app.get("/user/validateToken", (req, res) => {
|
|
||||||
let tokenHeaderKey = process.env.TOKEN_HEADER_KEY;
|
|
||||||
let jwtSecretKey = process.env.JWT_SECRET_KEY;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const token = req.header(tokenHeaderKey);
|
|
||||||
|
|
||||||
const verified = jwt.verify(token, jwtSecretKey);
|
|
||||||
if (verified) {
|
|
||||||
return res.send("Successfully Verified");
|
|
||||||
} else {
|
|
||||||
return res.status(401).send("Access Denied");
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
return res.status(401).send("Invalid Token");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
app.get('/popcen', (req, res) => {
|
|
||||||
|
|
||||||
const caseidPattern = req.query.caseidPattern + '%';
|
|
||||||
const batchno = parseInt(req.query.batchno, 10) || 1;
|
|
||||||
const sql = 'SELECT id, uuid, caseid, modified_time FROM popcen WHERE caseid LIKE ? LIMIT ? OFFSET ?';
|
|
||||||
const limit = 1000;
|
|
||||||
const offset = (batchno - 1) * limit;
|
|
||||||
db.query(sql, [caseidPattern, limit, offset], (err, results) => {
|
|
||||||
if (err) {
|
|
||||||
console.error(err);
|
|
||||||
return res.status(500).send('Server error');
|
|
||||||
}
|
|
||||||
res.json(results);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
app.get('/popcenCount', (req, res) => {
|
|
||||||
const caseidPattern = req.query.caseidPattern + '%';
|
|
||||||
const sql = 'SELECT COUNT(id) AS count FROM popcen WHERE caseid LIKE ?';
|
|
||||||
db.query(sql, [caseidPattern], (err, results) => {
|
|
||||||
if (err) {
|
|
||||||
console.error(err);
|
|
||||||
return res.status(500).send('Server error');
|
|
||||||
}
|
|
||||||
res.json(results[0].count);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
|
// Start server
|
||||||
const PORT = 3000;
|
const PORT = 3000;
|
||||||
app.listen(PORT, () => {
|
app.listen(PORT, () => {
|
||||||
console.log(`Server is running on port ${PORT}`);
|
console.log(`Server is running on port ${PORT}`);
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user