Module for the frontend using Angular for session-based authentication. This module handles login, logout, and checking authentication status.
import { Injectable } from '@angular/core';
import { HttpClient } 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 {
const url = `${this.apiUrl}/login`;
const body = { username, password };
return this.http.post(url, body).pipe(
map(response => {
// Store the session information in local storage or other client-side storage
localStorage.setItem('userId', response.userId);
localStorage.setItem('username', response.username);
return response;
}),
catchError(error => {
return of(error);
})
);
}
// Logout function
logout(): void {
// Clear the session information from local storage or other client-side storage
localStorage.removeItem('userId');
localStorage.removeItem('username');
}
// Check if user is authenticated
isAuthenticated(): boolean {
const userId = localStorage.getItem('userId');
const username = localStorage.getItem('username');
return !!userId && !!username; // Return true if both userId and username exist, false otherwise
}
// Get the user ID
getUserId(): string | null {
return localStorage.getItem('userId');
}
// Get the username
getUsername(): string | null {
return localStorage.getItem('username');
}
}
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: `
`
})
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.