Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision

Target

Select target project
  • fatima-ezzahra.majidi.etu/gestion-des-stages
1 result
Select Git revision
Show changes
Commits on Source (2)
...@@ -13,6 +13,7 @@ import org.springframework.security.core.context.SecurityContextHolder; ...@@ -13,6 +13,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
...@@ -54,41 +55,29 @@ public class AuthController { ...@@ -54,41 +55,29 @@ public class AuthController {
String username = loginRequest.get("username"); String username = loginRequest.get("username");
String password = loginRequest.get("password"); String password = loginRequest.get("password");
System.out.println("🔍 Attempting login for: " + username); Optional<User> user = userService.findByUsername(username);
if (user.isEmpty()) {
if (username == null || password == null) { return ResponseEntity.status(401).body("Invalid credentials");
System.out.println("❌ Username or password is missing in the request.");
return ResponseEntity.status(400).body(Map.of("error", "Username and password are required"));
}
Optional<User> userOptional = userService.findByUsername(username);
if (userOptional.isEmpty()) {
System.out.println("❌ User not found!");
return ResponseEntity.status(401).body(Map.of("error", "Invalid credentials"));
} }
User user = userOptional.get();
System.out.println("✅ User found: " + username);
try { try {
Authentication authentication = authenticationManager.authenticate( Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(username, password) new UsernamePasswordAuthenticationToken(username, password)
); );
// Update security context on successful authentication
SecurityContextHolder.getContext().setAuthentication(authentication); SecurityContextHolder.getContext().setAuthentication(authentication);
System.out.println("✅ Login successful for user: " + username);
// ✅ 🔥 Renvoie les rôles de l'utilisateur dans la réponse // ✅ Send username & familyname in the response
return ResponseEntity.ok(Map.of( Map<String, Object> responseBody = new HashMap<>();
"message", "Login successful", responseBody.put("id", user.get().getId()); // 🔥 Ajoute l'ID ici
"username", user.getUsername(), responseBody.put("username", user.get().getUsername());
"roles", user.getRoles() // Retourne les rôles ici responseBody.put("familyname", user.get().getFamilyname()); // Assure-toi que ce champ existe bien
)); responseBody.put("roles", user.get().getRoles());
responseBody.put("message", "Login successful");
return ResponseEntity.ok(responseBody);
} catch (Exception e) { } catch (Exception e) {
System.out.println("❌ Authentication failed for user " + username + ": " + e.getMessage()); return ResponseEntity.status(401).body("Invalid username or password");
return ResponseEntity.status(401).body(Map.of("error", "Invalid username or password"));
} }
} }
......
...@@ -74,4 +74,10 @@ public class StudentController { ...@@ -74,4 +74,10 @@ public class StudentController {
studentService.deleteStudent(id); studentService.deleteStudent(id);
return ResponseEntity.noContent().build(); return ResponseEntity.noContent().build();
} }
@GetMapping("/with-role")
public ResponseEntity<List<Student>> getStudentsWithRoleEtudiant() {
List<Student> students = studentService.getStudentsByRole("ROLE_ETUDIANT");
return ResponseEntity.ok(students);
}
} }
...@@ -14,43 +14,31 @@ public class Student { ...@@ -14,43 +14,31 @@ public class Student {
@OneToMany(mappedBy = "student", cascade = CascadeType.ALL) @OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
private List<Candidacy> candidacies; private List<Candidacy> candidacies;
@OneToOne
@JoinColumn(name = "user_id", unique = true)
private User user; // Ajout de la liaison avec User
public Student() {} public Student() {}
public Student(Long id, String firstname, String lastname) { public Student(Long id, String firstname, String lastname, User user) {
this.id = id; this.id = id;
this.firstname = firstname; this.firstname = firstname;
this.lastname = lastname; this.lastname = lastname;
this.user = user;
} }
public Long getId() { public Long getId() { return id; }
return id; public void setId(Long id) { this.id = id; }
}
public void setId(Long id) { public String getFirstname() { return firstname; }
this.id = id; public void setFirstname(String firstname) { this.firstname = firstname; }
}
public String getFirstname() { public String getLastname() { return lastname; }
return firstname; public void setLastname(String lastname) { this.lastname = lastname; }
}
public void setFirstname(String firstname) { public List<Candidacy> getCandidacies() { return candidacies; }
this.firstname = firstname; public void setCandidacies(List<Candidacy> candidacies) { this.candidacies = candidacies; }
}
public String getLastname() { public User getUser() { return user; }
return lastname; public void setUser(User user) { this.user = user; }
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public List<Candidacy> getCandidacies() {
return candidacies;
}
public void setCandidacies(List<Candidacy> candidacies) {
this.candidacies = candidacies;
}
} }
...@@ -11,14 +11,17 @@ import java.util.stream.Collectors; ...@@ -11,14 +11,17 @@ import java.util.stream.Collectors;
@Entity @Entity
@Table(name = "users") @Table(name = "users")
public class User implements UserDetails { // Implements UserDetails public class User implements UserDetails { // Implements UserDetails
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private Long id;
@Column(unique = true, nullable = false) @Column(nullable = false)
private String username; private String username;
@Column(nullable = false)
private String familyname; // ✅ Added familyname
@JsonIgnore @JsonIgnore
@Column(nullable = false) @Column(nullable = false)
private String password; private String password;
...@@ -26,12 +29,13 @@ public class User implements UserDetails { // ✅ Implements UserDetails ...@@ -26,12 +29,13 @@ public class User implements UserDetails { // ✅ Implements UserDetails
@ElementCollection(fetch = FetchType.EAGER) @ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id")) @CollectionTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"))
@Column(name = "role") @Column(name = "role")
private Set<String> roles; // Roles stored in a separate table private Set<String> roles; // Roles stored in a separate table
public User() {} public User() {}
public User(String username, String password, Set<String> roles) { public User(String username, String familyname, String password, Set<String> roles) {
this.username = username; this.username = username;
this.familyname = familyname;
this.password = password; this.password = password;
this.roles = roles; this.roles = roles;
} }
...@@ -52,6 +56,14 @@ public class User implements UserDetails { // ✅ Implements UserDetails ...@@ -52,6 +56,14 @@ public class User implements UserDetails { // ✅ Implements UserDetails
this.username = username; this.username = username;
} }
public String getFamilyname() {
return familyname;
}
public void setFamilyname(String familyname) {
this.familyname = familyname;
}
public String getPassword() { public String getPassword() {
return password; return password;
} }
...@@ -96,6 +108,6 @@ public class User implements UserDetails { // ✅ Implements UserDetails ...@@ -96,6 +108,6 @@ public class User implements UserDetails { // ✅ Implements UserDetails
@Override @Override
public String toString() { public String toString() {
return "User{id=" + id + ", username='" + username + "', roles=" + roles + "}"; return "User{id=" + id + ", username='" + username + "', familyname='" + familyname + "', roles=" + roles + "}";
} }
} }
...@@ -2,8 +2,16 @@ package com.example.gestionstagesbackend.repositories; ...@@ -2,8 +2,16 @@ package com.example.gestionstagesbackend.repositories;
import com.example.gestionstagesbackend.model.Student; import com.example.gestionstagesbackend.model.Student;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository @Repository
public interface StudentRepository extends JpaRepository<Student, Long> { public interface StudentRepository extends JpaRepository<Student, Long> {
@Query("SELECT s FROM Student s WHERE s.user.id IN (SELECT u.id FROM User u WHERE :role MEMBER OF u.roles)")
List<Student> findStudentsByRole(@Param("role") String role);
Optional<Student> findByFirstnameAndLastname(String firstname, String lastname);
} }
...@@ -2,9 +2,14 @@ package com.example.gestionstagesbackend.repositories; ...@@ -2,9 +2,14 @@ package com.example.gestionstagesbackend.repositories;
import com.example.gestionstagesbackend.model.User; import com.example.gestionstagesbackend.model.User;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.Optional; import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Long> { public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username); Optional<User> findByUsername(String username);
@Query("SELECT u FROM User u WHERE :role MEMBER OF u.roles")
List<User> findByRole(@Param("role") String role);
} }
...@@ -34,4 +34,17 @@ public class StudentService { ...@@ -34,4 +34,17 @@ public class StudentService {
throw new IllegalArgumentException("Student with ID " + id + " does not exist."); throw new IllegalArgumentException("Student with ID " + id + " does not exist.");
} }
} }
public void createStudentIfNotExists(String firstname, String lastname) {
if (studentRepository.findByFirstnameAndLastname(firstname, lastname).isEmpty()) {
Student student = new Student();
student.setFirstname(firstname);
student.setLastname(lastname);
studentRepository.save(student);
System.out.println("✅ Created student: " + firstname + " " + lastname);
}
}
public List<Student> getStudentsByRole(String role) {
return studentRepository.findStudentsByRole(role);
}
} }
...@@ -3,6 +3,7 @@ package com.example.gestionstagesbackend.services; ...@@ -3,6 +3,7 @@ package com.example.gestionstagesbackend.services;
import com.example.gestionstagesbackend.model.User; import com.example.gestionstagesbackend.model.User;
import com.example.gestionstagesbackend.repositories.UserRepository; import com.example.gestionstagesbackend.repositories.UserRepository;
import jakarta.annotation.PostConstruct; import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
...@@ -54,20 +55,31 @@ public class UserService implements UserDetailsService { ...@@ -54,20 +55,31 @@ public class UserService implements UserDetailsService {
@PostConstruct @PostConstruct
public void createDefaultUsers() { public void createDefaultUsers() {
createUserIfNotExists("admin", "admin123", Set.of("ROLE_ADMIN")); createUserIfNotExists("admin", "admin123", "Admin", "ROLE_ADMIN");
createUserIfNotExists("etudiant", "etudiant123", Set.of("ROLE_ETUDIANT")); createUserIfNotExists("etudiant1", "etudiant123", "Etudiant1", "ROLE_ETUDIANT");
createUserIfNotExists("entreprise", "entreprise123", Set.of("ROLE_ENTREPRISE")); createUserIfNotExists("etudiant2", "etudiant123", "Etudiant2", "ROLE_ETUDIANT");
createUserIfNotExists("superviseur", "superviseur123", Set.of("ROLE_SUPERVISEUR")); createUserIfNotExists("entreprise", "entreprise123", "Entreprise", "ROLE_ENTREPRISE");
createUserIfNotExists("superviseur", "superviseur123", "Superviseur", "ROLE_SUPERVISEUR");
} }
private void createUserIfNotExists(String username, String password, Set<String> roles) { private void createUserIfNotExists(String username, String password, String familyname, String role) {
if (userRepository.findByUsername(username).isEmpty()) { if (userRepository.findByUsername(username).isEmpty()) {
User user = new User(); User user = new User();
user.setUsername(username); user.setUsername(username);
user.setPassword(passwordEncoder.encode(password)); user.setPassword(passwordEncoder.encode(password));
user.setRoles(roles); user.setFamilyname(familyname);
user.setRoles(Set.of(role));
userRepository.save(user); userRepository.save(user);
System.out.println("✅ Created user: " + username + " with roles " + roles);
// Si l'utilisateur est un étudiant, on crée un étudiant associé
if (role.equals("ROLE_ETUDIANT")) {
studentService.createStudentIfNotExists(username, familyname);
}
System.out.println("✅ Created user: " + username + " with role " + role);
} }
} }
@Autowired
private StudentService studentService; // Injection du service pour créer un étudiant
} }