11. For the above application create authorized end points using JWT (JSON Web Token).
[Link]
const express = require("express");
const mysql = require("mysql2");
const cors = require("cors");
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const app = express();
const PORT = 5000;
const SECRET_KEY = "your_secret_key"; // Change this in production
// Middleware
[Link](cors());
[Link]([Link]());
// MySQL Database connection
const db = [Link]({
host: "localhost",
user: "root",
password: "",
database: "studentsDB"
});
[Link](err => {
if (err) {
[Link]("Error connecting to MySQL:", err);
return;
}
[Link]("MySQL connected");
});
// Middleware to verify JWT
const verifyToken = (req, res, next) => {
const token = [Link]["authorization"];
if (!token) {
return [Link](403).json({ message: "Access denied. No token provided." });
}
[Link]([Link](" ")[1], SECRET_KEY, (err, decoded) => {
if (err) {
return [Link](401).json({ message: "Invalid token" });
}
[Link] = decoded;
next();
});
};
// Routes
// User Registration
[Link]("/register", async (req, res) => {
const { username, password } = [Link];
// Hash the password
const hashedPassword = await [Link](password, 10);
const query = "INSERT INTO users (username, password) VALUES (?, ?)";
[Link](query, [username, hashedPassword], (err, result) => {
if (err) {
return [Link](400).json({ error: [Link] });
}
[Link](201).json({ message: "User registered successfully" });
});
});
// User Login
[Link]("/login", (req, res) => {
const { username, password } = [Link];
const query = "SELECT * FROM users WHERE username = ?";
[Link](query, [username], async (err, result) => {
if (err) return [Link](500).json({ error: [Link] });
if ([Link] === 0) return [Link](401).json({ message: "Invalid credentials" });
const user = result[0];
// Compare password
const isMatch = await [Link](password, [Link]);
if (!isMatch) return [Link](401).json({ message: "Invalid credentials" });
// Generate JWT
const token = [Link]({ id: [Link], username: [Link] }, SECRET_KEY, { expiresIn:
"1h" });
[Link]({ token });
});
});
// Get all students (Protected Route)
[Link]("/students", verifyToken, (req, res) => {
const query = "SELECT * FROM students";
[Link](query, (err, result) => {
if (err) return [Link](500).json({ error: [Link] });
[Link](result);
});
});
// Get a single student (Protected Route)
[Link]("/students/:id", verifyToken, (req, res) => {
const query = "SELECT * FROM students WHERE id = ?";
[Link](query, [[Link]], (err, result) => {
if (err) return [Link](500).json({ error: [Link] });
if ([Link] === 0) return [Link](404).json({ message: "Student not found" });
[Link](result[0]);
});
});
// Create a student (Protected Route)
[Link]("/students", verifyToken, (req, res) => {
const { name, age, course } = [Link];
const query = "INSERT INTO students (name, age, course) VALUES (?, ?, ?)";
[Link](query, [name, age, course], (err, result) => {
if (err) return [Link](400).json({ error: [Link] });
[Link](201).json({ id: [Link], name, age, course });
});
});
// Update a student (Protected Route)
[Link]("/students/:id", verifyToken, (req, res) => {
const { name, age, course } = [Link];
const query = "UPDATE students SET name = ?, age = ?, course = ? WHERE id = ?";
[Link](query, [name, age, course, [Link]], (err, result) => {
if (err) return [Link](400).json({ error: [Link] });
if ([Link] === 0) return [Link](404).json({ message: "Student not found" });
[Link]({ id: [Link], name, age, course });
});
});
// Delete a student (Protected Route)
[Link]("/students/:id", verifyToken, (req, res) => {
const query = "DELETE FROM students WHERE id = ?";
[Link](query, [[Link]], (err, result) => {
if (err) return [Link](500).json({ error: [Link] });
if ([Link] === 0) return [Link](404).json({ message: "Student not found" });
[Link]({ message: "Student deleted successfully" });
});
});
// Start the server
[Link](PORT, () => {
[Link](`Server running on [Link]
});
Procedure:
npm install jsonwebtoken bcryptjs
We need a users table to store login credentials. Run this SQL command in MySQL:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);
Run:
node [Link]
[Link]
[Link]