diff options
Diffstat (limited to 'backend/index.js')
-rw-r--r-- | backend/index.js | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/backend/index.js b/backend/index.js new file mode 100644 index 0000000..d53b07d --- /dev/null +++ b/backend/index.js @@ -0,0 +1,57 @@ +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}`); +}); |