Fixed an issue with "/connect" when the token does not exists. Administration Service is now a package enabling any other services to check the token stored in the database. Removed feedback and volunteer services.

This commit is contained in:
Yohan Boujon 2024-12-22 15:28:30 +01:00
parent 2596c12178
commit 292aea3d96
18 changed files with 211 additions and 370 deletions

View file

@ -18,8 +18,8 @@ Course Exercice : Application to help others
### APIs
- [ ] `Rest` Create user
- [ ] `Rest` Login with user and password
- [X] `Rest` Create user
- [X] `Rest` Login with user and password
- [ ] `Rest` Make sure admin can do everything and users don't
- [ ] `Rest` Create a Help Request
- [ ] `Rest` Modify the Help Request status

View file

@ -6,24 +6,27 @@
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>administration-service</artifactId>
<packaging>jar</packaging>
<dependencies>
<!-- Dépendance pour créer un service REST -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Plugin Maven pour Spring Boot -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.1.4</version>
</plugin>
<!-- Plugin pour configurer le compilateur -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>

View file

@ -0,0 +1,23 @@
package insa.application.helpapp.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AdministrationService {
@Autowired
private ConnectionRepository connectionRepository;
public boolean checkToken(int idUser, String token) {
List<Connection> connections = connectionRepository.findByIdUser(idUser);
if (connections.isEmpty()) {
return false;
}
Connection c = connections.getFirst();
return c.getToken().equals(token) && c.getExpiresAt().isAfter(java.time.LocalDateTime.now());
}
}

View file

@ -1,39 +0,0 @@
package insa.application.helpapp.rest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@SpringBootApplication
@RestController
@RequestMapping("/admin/requests")
public class AdministrationServiceApplication {
private final Map<Long, String> requestStatusDatabase = new HashMap<>();
public static void main(String[] args) {
SpringApplication.run(AdministrationServiceApplication.class, args);
}
// Validate a request
@PutMapping("/{id}/validate")
public String validateRequest(@PathVariable Long id) {
requestStatusDatabase.put(id, "Validated");
return "Request " + id + " validated.";
}
// Reject a request with justification
@PutMapping("/{id}/reject")
public String rejectRequest(@PathVariable Long id, @RequestParam String reason) {
requestStatusDatabase.put(id, "Rejected: " + reason);
return "Request " + id + " rejected for reason: " + reason;
}
// View request statuses
@GetMapping
public Map<Long, String> viewAllStatuses() {
return requestStatusDatabase;
}
}

View file

@ -1,40 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0">
<parent>
<groupId>insa.application.helpapp</groupId>
<artifactId>helpapp</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>feedback-service</artifactId>
<dependencies>
<!-- Dépendance pour créer un service REST -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Plugin Maven pour Spring Boot -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.1.4</version>
</plugin>
<!-- Plugin pour configurer le compilateur -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>21</source>
<target>21</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View file

@ -1,83 +0,0 @@
package insa.application.helpapp.rest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
@SpringBootApplication
@RestController
@RequestMapping("/feedbacks")
public class FeedbackServiceApplication {
private final Map<Long, Feedback> feedbackDatabase = new HashMap<>();
private final AtomicLong idGenerator = new AtomicLong(1);
public static void main(String[] args) {
SpringApplication.run(FeedbackServiceApplication.class, args);
}
// Add feedback
@PostMapping
public Feedback addFeedback(@RequestBody Feedback feedback) {
long id = idGenerator.getAndIncrement();
feedback.setId(id);
feedbackDatabase.put(id, feedback);
return feedback;
}
// Get feedback by request ID
@GetMapping("/request/{requestId}")
public List<Feedback> getFeedbackByRequest(@PathVariable Long requestId) {
List<Feedback> feedbackList = new ArrayList<>();
for (Feedback feedback : feedbackDatabase.values()) {
if (feedback.getRequestId().equals(requestId)) {
feedbackList.add(feedback);
}
}
return feedbackList;
}
// Feedback entity
static class Feedback {
private Long id;
private Long requestId;
private String comment;
private Integer rating; // 1 to 5
// Getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getRequestId() {
return requestId;
}
public void setRequestId(Long requestId) {
this.requestId = requestId;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Integer getRating() {
return rating;
}
public void setRating(Integer rating) {
this.rating = rating;
}
}
}

View file

@ -7,12 +7,12 @@
<packaging>pom</packaging>
<modules>
<module>user-service</module>
<module>request-service</module>
<module>volunteer-service</module>
<module>feedback-service</module>
<!-- Administation-Service creates a dependency for other services -->
<module>administration-service</module>
<module>request-service</module>
<module>role-service</module>
<module>user-service</module>
</modules>
<dependencyManagement>

View file

@ -13,6 +13,22 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
<scope>runtime</scope>
</dependency>
<!-- Depends on Administation Service to check roles -->
<dependency>
<groupId>insa.application.helpapp</groupId>
<artifactId>administration-service</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>

View file

@ -0,0 +1,7 @@
package insa.application.helpapp.rest;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RequestRepository extends JpaRepository<Requests, Integer> {
}

View file

@ -1,35 +1,28 @@
package insa.application.helpapp.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
// import org.springframework.http.HttpStatus;
// import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
// import org.springframework.beans.factory.annotation.Autowired;
@SpringBootApplication
@RestController
@RequestMapping("/requests")
public class RequestServiceApplication {
private final Map<Long, HelpRequest> requestDatabase = new HashMap<>();
private final AtomicLong idGenerator = new AtomicLong(1);
@Autowired
private AdministrationService administrationService;
public static void main(String[] args) {
SpringApplication.run(RequestServiceApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
private final RestTemplate restTemplate = new RestTemplate();
// CORS Configuration
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@ -42,91 +35,11 @@ public class RequestServiceApplication {
};
}
// 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");
requestDatabase.put(id, request);
return request;
}
// 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.getUserId().equals(userId)) {
userRequests.add(request);
}
}
return userRequests;
}
// Get all help requests
@GetMapping
public List<HelpRequest> getAllRequests() {
return new ArrayList<>(requestDatabase.values());
}
// 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 entity
static class HelpRequest {
private Long id;
private Long userId;
private String details;
private String status; // Pending, Validated, Rejected, Completed
// Getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@PostMapping("/post_message")
public ResponseEntity<?> postMessage(@RequestParam int idUser,@RequestParam String token, @RequestParam String message) {
if(!administrationService.checkToken(idUser, token)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("User or token invalid.");
};
return ResponseEntity.ok("yessay");
}
}

View file

@ -0,0 +1,72 @@
package insa.application.helpapp.rest;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.persistence.Column;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import java.time.LocalDate;
@Entity
@Table(name = "requests", schema = "service-architecture")
public class Requests {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "id_status", nullable = false)
private int idStatus;
@Column(name = "id_user", nullable = false)
private int idUser;
@Column(name = "created_at", nullable = false, columnDefinition = "DATE DEFAULT CURRENT_DATE")
private LocalDate createdAt;
@Column(name = "message", nullable = false)
private String message;
// Getters and Setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getIdStatus() {
return idStatus;
}
public void setIdStatus(int idStatus) {
this.idStatus = idStatus;
}
public int getIdUser() {
return idUser;
}
public void setIdUser(int idUser) {
this.idUser = idUser;
}
public LocalDate getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDate createdAt) {
this.createdAt = createdAt;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View file

@ -23,6 +23,12 @@
<version>8.0.33</version>
<scope>runtime</scope>
</dependency>
<!-- Depends on Administation Service to check roles -->
<dependency>
<groupId>insa.application.helpapp</groupId>
<artifactId>administration-service</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>

View file

@ -0,0 +1,23 @@
package insa.application.helpapp.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private ConnectionRepository connectionRepository;
public boolean checkToken(int idUser, String token) {
List<Connection> connections = connectionRepository.findByIdUser(idUser);
if (connections.isEmpty()) {
return false;
}
Connection c = connections.getFirst();
return c.getToken().equals(token) && c.getExpiresAt().isAfter(java.time.LocalDateTime.now());
}
}

View file

@ -8,14 +8,13 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.hibernate.type.descriptor.java.LocalDateTimeJavaType;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.List;
import java.time.LocalDateTime;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Base64;
@ -31,9 +30,9 @@ public class UserServiceApplication {
// https://stackoverflow.com/users/774398/patrick
public static String generateRandomBase64Token(int byteLength) {
SecureRandom secureRandom = new SecureRandom();
byte[] token = new byte[byteLength-32];
byte[] token = new byte[byteLength - 32];
secureRandom.nextBytes(token);
return Base64.getUrlEncoder().withoutPadding().encodeToString(token); //base64 encoding
return Base64.getUrlEncoder().withoutPadding().encodeToString(token); // base64 encoding
}
public static void main(String[] args) {
@ -54,6 +53,7 @@ public class UserServiceApplication {
}
// Post should be : /create_user?idRole=1&username=toto&password=1234
// Response: created user
@PostMapping("/create_user")
public User createUser(@RequestParam int idRole, @RequestParam String username, @RequestParam String password) {
User user = new User();
@ -64,30 +64,49 @@ public class UserServiceApplication {
return userRepository.save(user);
}
// Post should be : /get_user?id=1
// Response: idRole (int), username (string)
@GetMapping("/get_user")
public ResponseEntity<?> getUser(@RequestParam int id) {
Optional<User> userOptional = userRepository.findById(id);
if (userOptional.isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("User ID not known.");
}
User user = userOptional.get();
Map<String, Object> response = new HashMap<>();
// Reponse to client
response.put("username", user.getUsername());
response.put("idRole", user.getIdRole());
return ResponseEntity.ok(response);
}
// Post should be : /connect?username=toto&password=1234
// Response can vary: Error if username/password doesn't exist/match
// Response if success: userId (int), expiresAt (time), token (varchar(128))
@PostMapping("/connect")
public ResponseEntity<?> connect(@RequestParam String username, @RequestParam String password)
{
public ResponseEntity<?> connect(@RequestParam String username, @RequestParam String password) {
List<User> users = userRepository.findByUsername(username);
// Checks username
if(users.isEmpty()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Username not known.");
if (users.isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Username not known.");
}
User user = users.getFirst();
// Checks password
if(!user.getPassword().equals(password)) {
if (!user.getPassword().equals(password)) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid password.");
}
// Checks if token already exists
List<Connection> connections = connectionRepository.findByIdUser(user.getId());
Map<String, Object> response = new HashMap<>();
Connection connection = new Connection();
if(!connections.isEmpty() && (connections.getFirst().getExpiresAt().isBefore(LocalDateTime.now())))
{
if (connections.isEmpty()
|| (!connections.isEmpty() && (connections.getFirst().getExpiresAt().isBefore(LocalDateTime.now())))) {
// Remove the old token
connectionRepository.delete(connections.getFirst());
if (!connections.isEmpty()) {
connectionRepository.delete(connections.getFirst());
}
// Create new token if password & username is correct
// Get User ID
connection.setidUser(user.getId());
@ -109,5 +128,4 @@ public class UserServiceApplication {
return ResponseEntity.ok(response);
}
}

View file

@ -1,40 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0">
<parent>
<groupId>insa.application.helpapp</groupId>
<artifactId>helpapp</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>volunteer-service</artifactId>
<dependencies>
<!-- Dépendance pour créer un service REST -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Plugin Maven pour Spring Boot -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.1.4</version>
</plugin>
<!-- Plugin pour configurer le compilateur -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>21</source>
<target>21</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View file

@ -1,38 +0,0 @@
package insa.application.helpapp.rest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@SpringBootApplication
@RestController
@RequestMapping("/volunteers")
public class VolunteerServiceApplication {
private final Map<Long, String> volunteerActions = new HashMap<>();
public static void main(String[] args) {
SpringApplication.run(VolunteerServiceApplication.class, args);
}
// View available requests (simulating)
@GetMapping("/requests")
public List<String> viewAvailableRequests() {
return List.of("Request 1: Grocery delivery", "Request 2: Medical help");
}
// Respond to a specific request
@PostMapping("/{volunteerId}/help")
public String respondToRequest(@PathVariable Long volunteerId, @RequestParam Long requestId) {
volunteerActions.put(requestId, "Volunteer " + volunteerId + " responded.");
return "Volunteer " + volunteerId + " responded to request " + requestId;
}
// View all volunteer actions
@GetMapping("/actions")
public Map<Long, String> viewActions() {
return volunteerActions;
}
}