Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.3 kB
1
Indexable
Never
const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();
app.use(express.json());

// Secret key for JWT (should be kept secret in production)
const secretKey = 'your-secret-key';

// In-memory database for storing registered users
const users = [];

// Register API
app.post('/register', (req, res) => {
  const { username, password } = req.body;
  // Simulate user registration and store the username
  users.push(username);

  // Create a JWT token with the username
  const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' });

  // Send the JWT token back to the client
  res.json({ token });
});

// Login API
app.post('/login', (req, res) => {
  const { token } = req.body;
  try {
    // Verify the JWT token and extract the username
    const decoded = jwt.verify(token, secretKey);
    const username = decoded.username;

    // Check if the username exists in the registered users database
    if (users.includes(username)) {
      res.json({ message: 'success' });
    } else {
      res.json({ message: 'fail' });
    }
  } catch (error) {
    // Handle token verification errors
    res.json({ message: 'fail' });
  }
});

// Start the server on port 3000
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});