- Full-stack rental marketplace application - React frontend with TypeScript - Node.js/Express backend with JWT authentication - Features: item listings, rental requests, calendar availability, user profiles
77 lines
1.8 KiB
JavaScript
77 lines
1.8 KiB
JavaScript
const express = require('express');
|
|
const jwt = require('jsonwebtoken');
|
|
const { User } = require('../models'); // Import from models/index.js to get models with associations
|
|
const router = express.Router();
|
|
|
|
router.post('/register', async (req, res) => {
|
|
try {
|
|
const { username, email, password, firstName, lastName, phone } = req.body;
|
|
|
|
const existingUser = await User.findOne({
|
|
where: {
|
|
[require('sequelize').Op.or]: [{ email }, { username }]
|
|
}
|
|
});
|
|
|
|
if (existingUser) {
|
|
return res.status(400).json({ error: 'User already exists' });
|
|
}
|
|
|
|
const user = await User.create({
|
|
username,
|
|
email,
|
|
password,
|
|
firstName,
|
|
lastName,
|
|
phone
|
|
});
|
|
|
|
const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, {
|
|
expiresIn: '7d'
|
|
});
|
|
|
|
res.status(201).json({
|
|
user: {
|
|
id: user.id,
|
|
username: user.username,
|
|
email: user.email,
|
|
firstName: user.firstName,
|
|
lastName: user.lastName
|
|
},
|
|
token
|
|
});
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
router.post('/login', async (req, res) => {
|
|
try {
|
|
const { email, password } = req.body;
|
|
|
|
const user = await User.findOne({ where: { email } });
|
|
|
|
if (!user || !(await user.comparePassword(password))) {
|
|
return res.status(401).json({ error: 'Invalid credentials' });
|
|
}
|
|
|
|
const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, {
|
|
expiresIn: '7d'
|
|
});
|
|
|
|
res.json({
|
|
user: {
|
|
id: user.id,
|
|
username: user.username,
|
|
email: user.email,
|
|
firstName: user.firstName,
|
|
lastName: user.lastName
|
|
},
|
|
token
|
|
});
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
module.exports = router; |