📜  MEAN stack auth (1)

📅  最后修改于: 2023-12-03 15:17:36.196000             🧑  作者: Mango

MEAN Stack Auth

Are you looking for a full-stack solution for your authentication needs? Look no further than the MEAN stack!

What is the MEAN stack?

The MEAN stack is a combination of technologies that allow for the development of full-stack web applications. MEAN stands for:

  • MongoDB: a NoSQL database
  • Express: a Node.js web application framework
  • Angular: a front-end framework
  • Node.js: a server-side JavaScript runtime

By using the MEAN stack, you can create a complete web application that includes a database, server-side logic, and a modern front-end.

Why use the MEAN stack for authentication?

The MEAN stack is an ideal choice for building authentication systems for several reasons:

  • JavaScript throughout: With the MEAN stack, you can use the same language (JavaScript) on both the front-end and back-end of your application. This can make development faster and easier.
  • Modular and flexible: Each component of the MEAN stack is modular, making it easy to swap out pieces or add new functionality as needed.
  • Open-source and community-driven: All of the technologies that make up the MEAN stack are open-source, which means that there is a vast community of developers supporting and improving them. This can give you confidence in the reliability and security of your authentication system.
How to implement authentication with the MEAN stack

Implementing authentication with the MEAN stack involves several components. Here is a high-level overview of the process:

  1. Create a user model: Use MongoDB to define a schema for storing user data.
const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
  name: String,
  email: String,
  password: String,
});

module.exports = mongoose.model('User', UserSchema);
  1. Set up a server: Use Express and Node.js to create a server that handles authentication requests and communicates with the database.
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const User = require('userModel');

mongoose.connect('mongodb://localhost/auth_demo', { useNewUrlParser: true });

const app = express();

app.use(bodyParser.json());

app.post('/register', (req, res) => {
  const { name, email, password } = req.body;
  const user = new User({ name, email, password });
  user.save((err) => {
    if (err) {
      res.status(500).send('Error saving user to database');
    } else {
      res.status(200).send('User successfully registered');
    }
  });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
  1. Create a login page: Use Angular to create a login form that sends data to the server.
<form (ngSubmit)="onSubmit()">
  <label>
    Email:
    <input type="email" [(ngModel)]="email" name="email" required>
  </label>
  <br>
  <label>
    Password:
    <input type="password" [(ngModel)]="password" name="password" required>
  </label>
  <br>
  <button type="submit">Login</button>
</form>
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-login',
  template: `
    <form (ngSubmit)="onSubmit()">
      <label>
        Email:
        <input type="email" [(ngModel)]="email" name="email" required>
      </label>
      <br>
      <label>
        Password:
        <input type="password" [(ngModel)]="password" name="password" required>
      </label>
      <br>
      <button type="submit">Login</button>
    </form>
  `,
})
export class LoginComponent {
  email = '';
  password = '';

  constructor(private http: HttpClient) {}

  onSubmit() {
    this.http.post('/login', { email: this.email, password: this.password })
      .subscribe((res) => {
        console.log(`Response from server: ${res}`);
      });
  }
}
  1. Handle authentication: On the server, verify the user's credentials and return a JSON web token (JWT) if they are correct.
const jwt = require('jsonwebtoken');

// ...

app.post('/login', (req, res) => {
  const { email, password } = req.body;
  User.findOne({ email }, (err, user) => {
    if (err || !user) {
      res.status(401).send('User not found');
    } else if (user.password !== password) {
      res.status(401).send('Incorrect password');
    } else {
      const token = jwt.sign({ userId: user._id }, 'secret_key');
      res.status(200).send({ token });
    }
  });
});
  1. Authenticate requests: On the front-end, store the JWT in a cookie or localStorage and attach it to each request for authenticated resources.
import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    // Get the JWT from localStorage
    const token = localStorage.getItem('token');

    // Clone the request and attach the token
    const authReq = req.clone({
      setHeaders: { Authorization: `Bearer ${token}` }
    });

    return next.handle(authReq);
  }
}

That's it! With these components in place, you can create a robust authentication system using the MEAN stack.

Conclusion

The MEAN stack is a powerful and flexible solution for building full-stack web applications. By leveraging technologies like MongoDB, Express, Angular, and Node.js, you can create feature-rich and scalable authentication systems that can meet the needs of any application.

If you're new to the MEAN stack, check out these resources to get started: