blob: d53b07d341d4c0ab88cf9c46a58face3aafb0b8f (
plain) (
tree)
|
|
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const cors = require('cors'); // Import CORS
const app = express();
app.use(bodyParser.json());
app.use(cors()); // Use the CORS middleware
const users = []; // In-memory user storage, replace with a database in production
// Secret key for JWT
const JWT_SECRET = 'your_jwt_secret_key';
// Register route
app.post('/register', async (req, res) => {
const { username, password } = req.body;
console.log('Register endpoint called with:', { username, password }); // Log the input
if (!username || !password) {
return res.status(400).send('Username and password are required');
}
const hashedPassword = await bcrypt.hash(password, 10);
users.push({ username, password: hashedPassword });
res.status(201).send('User registered');
});
// Login route
app.post('/login', async (req, res) => {
const { username, password } = req.body;
console.log('Login endpoint called with:', { username, password }); // Log the input
const user = users.find((u) => u.username === username);
if (!user) {
return res.status(400).send('Invalid username or password');
}
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(400).send('Invalid username or password');
}
const token = jwt.sign({ username: user.username }, JWT_SECRET, { expiresIn: '1h' });
res.json({ token });
});
const PORT = 5000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
|