Refactored user-service to use the database.

This commit is contained in:
Yohan Boujon 2024-12-22 00:06:06 +01:00
parent a8c796b049
commit 34938cba02
7 changed files with 92 additions and 156 deletions

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
target/
**/.env
*.tmp
.vscode/

View file

@ -24,7 +24,7 @@ Course Exercice : Application to help others
- [ ] `Rest` Create a Help Request
- [ ] `Rest` Modify the Help Request status
- [ ] `Rest` Create a User Feedback
- [ ] `Soap` Gather User Feedbacks
- [ ] `Rest` Gather User Feedbacks
## Check `SOAP` Requests

View file

@ -3,12 +3,17 @@ 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;
@Entity
@Table(name = "roles", schema = "service-architecture")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "name", nullable = false, unique = true)
private String name;
// Getters and Setters

View file

@ -13,6 +13,16 @@
<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>
</dependencies>
<build>

View file

@ -0,0 +1,55 @@
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;
@Entity
@Table(name = "users", schema = "service-architecture")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "id_role", nullable = false)
private int idRole;
@Column(name = "username", nullable = false, unique = true)
private String username;
@Column(name = "password", nullable = false)
private String password;
// Getters and Setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getIdRole() {
return idRole;
}
public void setIdRole(int idRole) {
this.idRole = idRole;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View file

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

View file

@ -6,22 +6,20 @@ import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
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("/users")
public class UserServiceApplication {
private final Map<Long, User> userDatabase = new HashMap<>();
private final AtomicLong idGenerator = new AtomicLong(1);
@Autowired
private UserRepository userRepository;
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
// CORS Configuration
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@ -34,154 +32,15 @@ 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);
return user;
// Post should be : /create_user?idRole=1&username=toto&password=1234
@PostMapping("/create_user")
public User createUser(int idRole, String username, String password) {
User user = new User();
user.setIdRole(idRole);
user.setUsername(username);
user.setPassword(password);
return userRepository.save(user);
}
// Get a user by ID
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return Optional.ofNullable(userDatabase.get(id))
.orElseThrow(() -> new RuntimeException("User not found"));
}
// Authenticate a user
@PostMapping("/authenticate")
public AuthResponse authenticate(@RequestBody AuthRequest authRequest) {
return userDatabase.values().stream()
.filter(user -> user.getEmail().equals(authRequest.getEmail()) && user.getPassword().equals(authRequest.getPassword()))
.findFirst()
.map(user -> new AuthResponse(user.getId(), "Authentication successful", true))
.orElse(new AuthResponse(null, "Authentication failed", false));
}
// 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) {
throw new RuntimeException("User not found");
}
return "User deleted successfully";
}
// Data transfer objects
static class AuthRequest {
private String email;
private String password;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
static class AuthResponse {
private Long userId;
private String message;
private boolean success;
public AuthResponse(Long userId, String message, boolean success) {
this.userId = userId;
this.message = message;
this.success = success;
}
public Long getUserId() {
return userId;
}
public String getMessage() {
return message;
}
public boolean isSuccess() {
return success;
}
}
// User entity
static class User {
private Long id;
private String name;
private String email;
private String password;
private String role; // REQUESTER, VOLUNTEER, ADMIN
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
}