0% found this document useful (0 votes)
0 views

Week11Task Program

This document provides a Node.js application using Express that implements JWT for user authentication and authorization. It includes routes for user registration, login, and CRUD operations for student records, with JWT verification for protected routes. The application connects to a MySQL database and requires the installation of jsonwebtoken and bcryptjs packages.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Week11Task Program

This document provides a Node.js application using Express that implements JWT for user authentication and authorization. It includes routes for user registration, login, and CRUD operations for student records, with JWT verification for protected routes. The application connects to a MySQL database and requires the installation of jsonwebtoken and bcryptjs packages.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

11. For the above application create authorized end points using JWT (JSON Web Token).

index.js

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
app.use(cors());
app.use(bodyParser.json());

// MySQL Database connection


const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "studentsDB"
});

db.connect(err => {
if (err) {
console.error("Error connecting to MySQL:", err);
return;
}
console.log("MySQL connected");
});

// Middleware to verify JWT


const verifyToken = (req, res, next) => {
const token = req.headers["authorization"];
if (!token) {
return res.status(403).json({ message: "Access denied. No token provided." });
}

jwt.verify(token.split(" ")[1], SECRET_KEY, (err, decoded) => {


if (err) {
return res.status(401).json({ message: "Invalid token" });
}
req.user = decoded;
next();
});
};

// Routes

// User Registration
app.post("/register", async (req, res) => {
const { username, password } = req.body;

// Hash the password


const hashedPassword = await bcrypt.hash(password, 10);

const query = "INSERT INTO users (username, password) VALUES (?, ?)";
db.query(query, [username, hashedPassword], (err, result) => {
if (err) {
return res.status(400).json({ error: err.message });
}
res.status(201).json({ message: "User registered successfully" });
});
});

// User Login
app.post("/login", (req, res) => {
const { username, password } = req.body;

const query = "SELECT * FROM users WHERE username = ?";


db.query(query, [username], async (err, result) => {
if (err) return res.status(500).json({ error: err.message });
if (result.length === 0) return res.status(401).json({ message: "Invalid credentials" });

const user = result[0];

// Compare password
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(401).json({ message: "Invalid credentials" });

// Generate JWT
const token = jwt.sign({ id: user.id, username: user.username }, SECRET_KEY, { expiresIn:
"1h" });
res.json({ token });
});
});

// Get all students (Protected Route)


app.get("/students", verifyToken, (req, res) => {
const query = "SELECT * FROM students";
db.query(query, (err, result) => {
if (err) return res.status(500).json({ error: err.message });
res.json(result);
});
});

// Get a single student (Protected Route)


app.get("/students/:id", verifyToken, (req, res) => {
const query = "SELECT * FROM students WHERE id = ?";
db.query(query, [req.params.id], (err, result) => {
if (err) return res.status(500).json({ error: err.message });
if (result.length === 0) return res.status(404).json({ message: "Student not found" });
res.json(result[0]);
});
});

// Create a student (Protected Route)


app.post("/students", verifyToken, (req, res) => {
const { name, age, course } = req.body;
const query = "INSERT INTO students (name, age, course) VALUES (?, ?, ?)";
db.query(query, [name, age, course], (err, result) => {
if (err) return res.status(400).json({ error: err.message });
res.status(201).json({ id: result.insertId, name, age, course });
});
});

// Update a student (Protected Route)


app.put("/students/:id", verifyToken, (req, res) => {
const { name, age, course } = req.body;
const query = "UPDATE students SET name = ?, age = ?, course = ? WHERE id = ?";
db.query(query, [name, age, course, req.params.id], (err, result) => {
if (err) return res.status(400).json({ error: err.message });
if (result.affectedRows === 0) return res.status(404).json({ message: "Student not found" });
res.json({ id: req.params.id, name, age, course });
});
});
// Delete a student (Protected Route)
app.delete("/students/:id", verifyToken, (req, res) => {
const query = "DELETE FROM students WHERE id = ?";
db.query(query, [req.params.id], (err, result) => {
if (err) return res.status(500).json({ error: err.message });
if (result.affectedRows === 0) return res.status(404).json({ message: "Student not found" });
res.json({ message: "Student deleted successfully" });
});
});

// Start the server


app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});

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 index.js

http://localhost:5000/register

http://localhost:5000/login

You might also like