How to create a Frontend Module for JWT Authentication in Angular?

Here’s an example of a module for the frontend using Angular. This module handles JWT authentication and includes functions for login, logout, and checking authentication status.

				
					import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private apiUrl = 'http://localhost:3000'; // API endpoint

  constructor(private http: HttpClient) { }

  // Login function
  login(username: string, password: string): Observable<any> {
    const url = `${this.apiUrl}/login`;
    const body = { username, password };

    return this.http.post<any>(url, body).pipe(
      map(response => {
        // Save the token in local storage
        localStorage.setItem('token', response.token);
        return response;
      }),
      catchError(error => {
        return of(error);
      })
    );
  }

  // Logout function
  logout(): void {
    // Remove the token from local storage
    localStorage.removeItem('token');
  }

  // Check if user is authenticated
  isAuthenticated(): boolean {
    const token = localStorage.getItem('token');
    return !!token; // Return true if token exists, false otherwise
  }

  // Get the authentication token
  getAuthToken(): string | null {
    return localStorage.getItem('token');
  }

  // Add the authentication token to the request headers
  addAuthHeaders(headers: HttpHeaders): HttpHeaders {
    const token = this.getAuthToken();
    if (token) {
      return headers.set('Authorization', token);
    }
    return headers;
  }
}
				
			

To use this module in your Angular components, you’ll need to import and inject the AuthService and use its functions. Here’s an example:

				
					import { Component } from '@angular/core';
import { AuthService } from './auth.service';

@Component({
  selector: 'app-login',
  template: `
    <form (ngSubmit)="login()">
      <!-- Login form fields -->
      <input type="text" [(ngModel)]="username" name="username">
      <input type="password" [(ngModel)]="password" name="password">
      <button type="submit">Login</button>
    </form>
  `
})
export class LoginComponent {
  username: string;
  password: string;

  constructor(private authService: AuthService) { }

  login(): void {
    this.authService.login(this.username, this.password).subscribe(
      response => {
        // Handle successful login response
      },
      error => {
        // Handle login error
      }
    );
  }
}
				
			

In your Angular component, you can use authService.isAuthenticated() to check if the user is authenticated, and authService.logout() to log out the user.

Remember to customize the API endpoint in the apiUrl variable to match your backend server’s URL.

Note that this is a simplified example, and in a real-world application, you would typically handle error handling, user feedback, and other necessary functionality based on your specific requirements.