benoit-bremaud / angular-social-network

Angular is better than Somfony
MIT License
1 stars 0 forks source link

Create authentication service in Angular #5

Closed benoit-bremaud closed 2 months ago

benoit-bremaud commented 2 months ago

Description : Implement an authentication service to handle user registration and login.

Steps :

benoit-bremaud commented 2 months ago

Description Create routes for user registration and login, and implement middleware for authentication using JSON Web Tokens (JWT).

Steps

benoit-bremaud commented 2 months ago
benoit-bremaud commented 2 months ago
benoit-bremaud commented 2 months ago
benoit-bremaud commented 2 months ago

Implement Middleware for Protecting Routes

benoit-bremaud commented 2 months ago

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;
benoit-bremaud commented 2 months ago

Update app.js to Include Authentication Routes and Middleware

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}); });

benoit-bremaud commented 2 months ago
  • [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;
benoit-bremaud commented 2 months ago

URL: POST http://localhost:3000/api/auth/register Body (JSON):

{
  "username": "testuser",
  "email": "testuser@example.com",
  "password": "password123"
}
benoit-bremaud commented 2 months ago
  • [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"
}

Image

benoit-bremaud commented 2 months ago

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.

benoit-bremaud commented 2 months ago
  • [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.

Image