Closed benoit-bremaud closed 2 months ago
Description Create routes for user registration and login, and implement middleware for authentication using JSON Web Tokens (JWT).
Steps
git checkout development
git checkout -b feature/auth-routes
cd backend
npm install bcrypt jsonwebtoken
mkdir -p routes
touch routes/auth.js
Implement Middleware for Protecting Routes
mkdir -p middleware
touch middleware/authMiddleware.js
Implement Middleware for Protecting Routes
- [x] Create a middleware folder and an authMiddleware.js file:
mkdir -p middleware touch middleware/authMiddleware.js
Content of backend/middleware/authMiddleware.js
import jwt from 'jsonwebtoken';
const authMiddleware = (req, res, next) => {
const token = req.header('Authorization').replace('Bearer ', '');
if (!token) {
return res.status(401).send('Access denied. No token provided.');
}
try {
const decoded = jwt.verify(token, 'your_jwt_secret');
req.user = decoded;
next();
} catch (error) {
res.status(400).send('Invalid token');
}
};
export default authMiddleware;
Update app.js to Include Authentication Routes and Middleware
import express from 'express';
import mongoose from 'mongoose';
import authRoutes from './routes/auth.js';
import authMiddleware from './middleware/authMiddleware.js';
import Post from './models/Post.js';
const app = express(); const port = 3000;
app.use(express.json());
// Connect to MongoDB mongoose.connect('mongodb://localhost:27017/angular-social-network').then(() => { console.log('Connected to MongoDB'); }).catch(err => { console.error('Error connecting to MongoDB', err); });
// Use authentication routes app.use('/api/auth', authRoutes);
// Protected route example app.post('/api/posts', authMiddleware, async (req, res) => { const { title, content, author } = req.body; try { const post = new Post({ title, content, author }); await post.save(); res.status(201).send(post); } catch (error) { res.status(400).send('Error creating post'); } });
app.get('/', (req, res) => { res.send('Hello World!'); });
app.listen(port, () => {
console.log(Server is running at http://localhost:${port}
);
});
- [x] Create a routes folder and an auth.js file if they don't already exist:
mkdir -p routes touch routes/auth.js
Content of backend/routes/auth.js
import express from 'express';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import User from '../models/User.js';
const router = express.Router();
// Register route
router.post('/register', async (req, res) => {
const { username, email, password } = req.body;
try {
const hashedPassword = await bcrypt.hash(password, 10);
const user = new User({ username, email, password: hashedPassword });
await user.save();
res.status(201).send(user);
} catch (error) {
res.status(400).send('Error registering user');
}
});
// Login route
router.post('/login', async (req, res) => {
const { email, password } = req.body;
try {
const user = await User.findOne({ email });
if (!user) {
return res.status(404).send('User not found');
}
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(401).send('Invalid password');
}
const token = jwt.sign({ id: user._id }, 'your_jwt_secret', { expiresIn: '1h' });
res.json({ token });
} catch (error) {
res.status(400).send('Error logging in');
}
});
export default router;
URL: POST http://localhost:3000/api/auth/register
Body (JSON):
{
"username": "testuser",
"email": "testuser@example.com",
"password": "password123"
}
- [x] Test User Registration
URL:
POST http://localhost:3000/api/auth/register
Body (JSON):{ "username": "testuser", "email": "testuser@example.com", "password": "password123" }
"testuser" already exist !
I tryed with :
URL: POST http://localhost:3000/api/auth/register
Body (JSON):
{
"username": "testuser_2",
"email": "testuser_2@example.com",
"password": "password1234"
}
URL: POST http://localhost:3000/api/auth/login
Body (JSON):
{
"email": "testuser@example.com",
"password": "password123"
}
Verify that you receive a JWT token upon successful login.
- [x] Test User Login
URL:
POST http://localhost:3000/api/auth/login
Body (JSON):{ "email": "testuser@example.com", "password": "password123" }
- [x] Verify that you receive a JWT token upon successful login.
Description : Implement an authentication service to handle user registration and login.
Steps :