Homework & Coding Practice

Homework/Practice Coding Assignment (20-min)

Extend Your API to Include User Authentication Using a Token

Steps:

  1. Step 1: Install jsonwebtoken:

    bash코드 복사npm install jsonwebtoken
  2. Step 2: Modify server.js to include authentication middleware:

    javascript코드 복사const jwt = require('jsonwebtoken');
    const SECRET_KEY = 'your_secret_key';
    
    // Middleware to authenticate token
    const authenticateToken = (req, res, next) => {
      const token = req.header('Authorization');
      if (!token) return res.status(401).send('Access Denied');
      try {
        const verified = jwt.verify(token, SECRET_KEY);
        req.user = verified;
        next();
      } catch (err) {
        res.status(400).send('Invalid Token');
      }
    };
    
    // Login route to generate token
    app.post('/login', (req, res) => {
      const username = req.body.username;
      const token = jwt.sign({ username }, SECRET_KEY, { expiresIn: '1h' });
      res.json({ token });
    });
    
    // Protect routes with the middleware
    app.get('/tasks', authenticateToken, (req, res) => {
      res.json(tasks);
    });
  3. Step 3: Run the server and test the following:

    • Use Postman to send a POST request to /login with a JSON body:

      json코드 복사{
        "username": "testuser"
      }
    • Copy the token from the response and include it in the Authorization header for subsequent /tasks requests.


Write Documentation for Your API Endpoints

  • Create a simple Markdown file (README.md) to document the API:

    markdown코드 복사## Task API Documentation
    
    ### Endpoints:
    
    - **GET /tasks**
      - Description: Retrieve all tasks.
      - Authorization: Bearer token required.
      - Example Response:
        ```json
        [
          { "id": 1, "title": "Task 1", "completed": false }
        ]
        ```
    
    - **POST /tasks**
      - Description: Add a new task.
      - Body:
        ```json
        {
          "title": "Task Title",
          "completed": false
        }
        ```
      - Example Response:
        ```json
        {
          "id": 3,
          "title": "Task Title",
          "completed": false
        }
        ```
    
    - **PUT /tasks/:id**
      - Description: Update a task by ID.
      - Body:
        ```json
        {
          "title": "Updated Title",
          "completed": true
        }
        ```
      - Example Response:
        ```json
        {
          "id": 3,
          "title": "Updated Title",
          "completed": true
        }
        ```
    
    - **DELETE /tasks/:id**
      - Description: Delete a task by ID.
      - Example Response:
        - Status: 204 No Content.

Last updated