Add frontend and backend user management features with authentication

This commit is contained in:
Lemonochrme 2024-12-16 16:48:51 +01:00
parent 4c5cd27b87
commit a1dbde5a91
5 changed files with 203 additions and 54 deletions

View file

@ -13,15 +13,18 @@ mvn compile
Une fois le projet compilé, lancer les différents services SOAP et REST via `Spring Boot` :
```
mvn spring-boot:run -pl rest-service
mvn spring-boot:run -pl user-service
```
```
mvn spring-boot:run -pl soap-service
curl -X GET http://localhost:8082/volunteers/requests
curl -X POST "http://localhost:8082/volunteers/1/help?requestId=123"
curl -X POST -H "Content-Type: application/json" -d '{"description":"Available for emergency aid"}' http://localhost:8082/volunteers/1/spontaneous
```
Vérifier le bon fonctionnement en accédant à `localhost:8080/hello` pour REST et `localhost:8081/ws` pour SOAP.

View file

@ -2,7 +2,9 @@ package insa.application.helpapp.rest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
@ -19,9 +21,23 @@ public class RequestServiceApplication {
SpringApplication.run(RequestServiceApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
private final RestTemplate restTemplate = new RestTemplate();
// Create a new help request
@PostMapping
public HelpRequest createRequest(@RequestBody HelpRequest request) {
if (request.getUserId() == null || request.getDetails() == null) {
throw new RuntimeException("User ID and details are required");
}
// Validate user via UserService
if (!isUserValid(request.getUserId())) {
throw new RuntimeException("Invalid user ID");
}
long id = idGenerator.getAndIncrement();
request.setId(id);
request.setStatus("Pending");
@ -29,58 +45,36 @@ public class RequestServiceApplication {
return request;
}
// Get all requests (with optional status filter)
@GetMapping
public List<HelpRequest> getAllRequests(@RequestParam(required = false) String status) {
if (status == null) {
return new ArrayList<>(requestDatabase.values());
}
List<HelpRequest> filteredRequests = new ArrayList<>();
// Get requests for a specific user
@GetMapping("/user/{userId}")
public List<HelpRequest> getRequestsByUser(@PathVariable Long userId) {
List<HelpRequest> userRequests = new ArrayList<>();
for (HelpRequest request : requestDatabase.values()) {
if (request.getStatus().equalsIgnoreCase(status)) {
filteredRequests.add(request);
if (request.getUserId().equals(userId)) {
userRequests.add(request);
}
}
return filteredRequests;
return userRequests;
}
// Get a specific request by ID
@GetMapping("/{id}")
public HelpRequest getRequest(@PathVariable Long id) {
return Optional.ofNullable(requestDatabase.get(id))
.orElseThrow(() -> new RuntimeException("Request not found"));
}
// Update a request (e.g., status or details)
@PutMapping("/{id}")
public HelpRequest updateRequest(@PathVariable Long id, @RequestBody HelpRequest updatedRequest) {
if (!requestDatabase.containsKey(id)) {
throw new RuntimeException("Request not found");
// Simulate user validation (integration with UserService)
private boolean isUserValid(Long userId) {
try {
// Call UserService to check if the user exists
String url = "http://localhost:8083/users/" + userId;
restTemplate.getForObject(url, Object.class); // Throws exception if user doesn't exist
return true;
} catch (Exception e) {
return false;
}
HelpRequest existingRequest = requestDatabase.get(id);
if (updatedRequest.getDetails() != null) {
existingRequest.setDetails(updatedRequest.getDetails());
}
if (updatedRequest.getStatus() != null) {
existingRequest.setStatus(updatedRequest.getStatus());
}
return existingRequest;
}
// Delete a request
@DeleteMapping("/{id}")
public String deleteRequest(@PathVariable Long id) {
if (requestDatabase.remove(id) == null) {
throw new RuntimeException("Request not found");
}
return "Request deleted successfully";
}
// HelpRequest entity
static class HelpRequest {
private Long id;
private Long userId;
private String details;
private String status; // e.g., Pending, Validated, Rejected, Completed
private String status; // Pending, Validated, Rejected, Completed
// Getters and setters
public Long getId() {
@ -91,6 +85,14 @@ public class RequestServiceApplication {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getDetails() {
return details;
}

View file

@ -22,6 +22,9 @@ public class UserServiceApplication {
// Create a new user
@PostMapping
public User createUser(@RequestBody User user) {
if (user.getPassword() == null || user.getRole() == null) {
throw new RuntimeException("Password and role are required");
}
long id = idGenerator.getAndIncrement();
user.setId(id);
userDatabase.put(id, user);
@ -35,18 +38,35 @@ public class UserServiceApplication {
.orElseThrow(() -> new RuntimeException("User not found"));
}
// Update a user by ID
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
if (!userDatabase.containsKey(id)) {
throw new RuntimeException("User not found");
}
updatedUser.setId(id);
userDatabase.put(id, updatedUser);
return updatedUser;
// Authenticate a user
@PostMapping("/authenticate")
public String authenticate(@RequestParam String email, @RequestParam String password) {
return userDatabase.values().stream()
.filter(user -> user.getEmail().equals(email) && user.getPassword().equals(password))
.findFirst()
.map(user -> "Authentication successful for user ID: " + user.getId())
.orElse("Authentication failed");
}
// Delete a user by ID
// Update user details (excluding password)
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
User existingUser = Optional.ofNullable(userDatabase.get(id))
.orElseThrow(() -> new RuntimeException("User not found"));
if (updatedUser.getName() != null) {
existingUser.setName(updatedUser.getName());
}
if (updatedUser.getEmail() != null) {
existingUser.setEmail(updatedUser.getEmail());
}
if (updatedUser.getRole() != null) {
existingUser.setRole(updatedUser.getRole());
}
return existingUser;
}
// Delete a user
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) {
if (userDatabase.remove(id) == null) {
@ -60,7 +80,8 @@ public class UserServiceApplication {
private Long id;
private String name;
private String email;
private String role;
private String password;
private String role; // REQUESTER, VOLUNTEER, ADMIN
// Getters and setters
public Long getId() {
@ -87,6 +108,14 @@ public class UserServiceApplication {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}

View file

@ -0,0 +1,3 @@
```bash
python -m http.server 8000
```

112
helpapp-frontend/index.html Normal file
View file

@ -0,0 +1,112 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HelpApp - Simple Frontend</title>
</head>
<body>
<h1>HelpApp - Test Frontend</h1>
<!-- User Service -->
<section>
<h2>User Service</h2>
<form id="create-user-form">
<h3>Create User</h3>
<input type="text" id="user-name" placeholder="Name" required>
<input type="email" id="user-email" placeholder="Email" required>
<input type="password" id="user-password" placeholder="Password" required>
<select id="user-role" required>
<option value="REQUESTER">Requester</option>
<option value="VOLUNTEER">Volunteer</option>
<option value="ADMIN">Admin</option>
</select>
<button type="submit">Create User</button>
</form>
<form id="get-user-form">
<h3>Get User by ID</h3>
<input type="number" id="get-user-id" placeholder="User ID" required>
<button type="submit">Get User</button>
</form>
<div id="user-response"></div>
</section>
<!-- Request Service -->
<section>
<h2>Request Service</h2>
<form id="create-request-form">
<h3>Create Help Request</h3>
<input type="number" id="request-user-id" placeholder="User ID" required>
<input type="text" id="request-details" placeholder="Request Details" required>
<button type="submit">Create Request</button>
</form>
<form id="get-requests-form">
<h3>Get Requests by User ID</h3>
<input type="number" id="get-requests-user-id" placeholder="User ID" required>
<button type="submit">Get Requests</button>
</form>
<div id="request-response"></div>
</section>
<script>
const userServiceBaseUrl = 'http://localhost:8083/users';
const requestServiceBaseUrl = 'http://localhost:8082/requests';
// Handle User Creation
document.getElementById('create-user-form').addEventListener('submit', async (e) => {
e.preventDefault();
const name = document.getElementById('user-name').value;
const email = document.getElementById('user-email').value;
const password = document.getElementById('user-password').value;
const role = document.getElementById('user-role').value;
const response = await fetch(userServiceBaseUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, email, password, role }),
});
const data = await response.json();
document.getElementById('user-response').innerText = JSON.stringify(data, null, 2);
});
// Handle Get User by ID
document.getElementById('get-user-form').addEventListener('submit', async (e) => {
e.preventDefault();
const userId = document.getElementById('get-user-id').value;
const response = await fetch(`${userServiceBaseUrl}/${userId}`);
const data = await response.json();
document.getElementById('user-response').innerText = JSON.stringify(data, null, 2);
});
// Handle Request Creation
document.getElementById('create-request-form').addEventListener('submit', async (e) => {
e.preventDefault();
const userId = document.getElementById('request-user-id').value;
const details = document.getElementById('request-details').value;
const response = await fetch(requestServiceBaseUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId, details }),
});
const data = await response.json();
document.getElementById('request-response').innerText = JSON.stringify(data, null, 2);
});
// Handle Get Requests by User ID
document.getElementById('get-requests-form').addEventListener('submit', async (e) => {
e.preventDefault();
const userId = document.getElementById('get-requests-user-id').value;
const response = await fetch(`${requestServiceBaseUrl}/user/${userId}`);
const data = await response.json();
document.getElementById('request-response').innerText = JSON.stringify(data, null, 2);
});
</script>
</body>
</html>