rajah 11 месяцев назад
Родитель
Сommit
cc9292dda2
20 измененных файлов с 281 добавлено и 218 удалено
  1. 8 0
      bin/main/application.properties
  2. 32 0
      src/main/java/fr/triplea/demovote/persistence/dao/ParticipantRepository.java
  3. 3 9
      src/main/java/fr/triplea/demovote/persistence/dto/UserCredentials.java
  4. 2 0
      src/main/java/fr/triplea/demovote/persistence/model/Role.java
  5. 0 71
      src/main/java/fr/triplea/demovote/security/MyRememberMeServices.java
  6. 1 1
      src/main/java/fr/triplea/demovote/security/MyUserDetailsService.java
  7. 3 3
      src/main/java/fr/triplea/demovote/spring/CreateDefaultValues.java
  8. 0 32
      src/main/java/fr/triplea/demovote/spring/MvcConfig.java
  9. 16 37
      src/main/java/fr/triplea/demovote/spring/SecurityConfig.java
  10. 71 1
      src/main/java/fr/triplea/demovote/web/controller/AccountController.java
  11. 73 28
      src/main/java/fr/triplea/demovote/web/controller/AuthController.java
  12. 2 2
      src/main/java/fr/triplea/demovote/web/controller/BulletinController.java
  13. 5 5
      src/main/java/fr/triplea/demovote/web/controller/CategorieController.java
  14. 1 1
      src/main/java/fr/triplea/demovote/web/controller/MessageController.java
  15. 26 8
      src/main/java/fr/triplea/demovote/web/controller/ParticipantController.java
  16. 3 3
      src/main/java/fr/triplea/demovote/web/controller/PreferenceController.java
  17. 1 1
      src/main/java/fr/triplea/demovote/web/controller/PresentationController.java
  18. 20 10
      src/main/java/fr/triplea/demovote/web/controller/ProductionController.java
  19. 6 6
      src/main/java/fr/triplea/demovote/web/controller/VariableController.java
  20. 8 0
      src/main/resources/application.properties

+ 8 - 0
bin/main/application.properties

@@ -11,3 +11,11 @@ spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
 logging.level.org.springframework=INFO
 
 server.servlet.context-path=/demovote-api/v1
+
+#logging.file.name=logs/demovote.log
+
+#logging.logback.rollingpolicy.file-name-pattern=logs/%d{yyyy-MM, aux}/demovote.%d{yyyy-MM-dd}.%i.log
+#logging.logback.rollingpolicy.max-file-size=2MB
+#logging.logback.rollingpolicy.total-size-cap=10MB
+#logging.logback.rollingpolicy.max-history=5
+

+ 32 - 0
src/main/java/fr/triplea/demovote/persistence/dao/ParticipantRepository.java

@@ -74,6 +74,38 @@ public interface ParticipantRepository extends JpaRepository<Participant, Intege
   @NativeQuery("SELECT DISTINCT p.* FROM vote.participants_roles AS rp INNER JOIN vote.participants AS p ON rp.numero_participant = p.numero_participant INNER JOIN vote.roles AS r ON rp.numero_role = r.numero_role WHERE p.flag_actif IS TRUE AND r.flag_actif IS TRUE AND rp.numero_role = :role ORDER BY p.nom ASC, p.prenom ASC, p.pseudonyme ASC ")
   List<Participant> findByRole(@Param("role") Role role);
 
+  @NativeQuery("SELECT DISTINCT "
+      + "TO_CHAR(p.date_creation, 'DD/MM/YYYY HH24:MI:SS') as date_creation, "
+      + "TO_CHAR(p.date_modification, 'DD/MM/YYYY HH24:MI:SS') as date_modification, "
+      + "p.numero_participant, "
+      + "p.nom, "
+      + "p.prenom, "
+      + "p.pseudonyme, "
+      + "'' AS mot_de_passe, "
+      + "p.groupe, "
+      + "p.delai_deconnexion, "
+      + "p.adresse, "
+      + "p.code_postal, "
+      + "p.ville, "
+      + "p.pays, "
+      + "p.numero_telephone, "
+      + "p.email, "
+      + "p.statut, "
+      + "p.flag_machine, "
+      + "p.commentaire, "
+      + "p.flag_jour1, "
+      + "p.flag_jour2, "
+      + "p.flag_jour3, "
+      + "p.flag_dodo_sur_place, "
+      + "p.flag_amigabus, "
+      + "p.mode_paiement, "
+      + "TO_CHAR(p.date_inscription, 'DD/MM/YYYY HH24:MI:SS') as date_inscription, "
+      + "CAST(p.somme_recue AS VARCHAR) AS somme_recue, "
+      + "p.flag_arrive "
+      + "FROM vote.participants AS p "
+      + "WHERE p.pseudonyme = :pseudo AND p.flag_actif IS TRUE ")
+  ParticipantTransfer searchByPseudonyme(@Param("pseudo") String pseudonyme);
+
   @NativeQuery("SELECT DISTINCT p.* FROM vote.participants AS p WHERE p.flag_actif IS TRUE AND p.pseudonyme = :pseudo ORDER BY p.nom ASC, p.prenom ASC, p.pseudonyme ASC ")
   Participant findByPseudonyme(@Param("pseudo") String pseudonyme);
   

+ 3 - 9
src/main/java/fr/triplea/demovote/persistence/dto/LoginTransfer.java → src/main/java/fr/triplea/demovote/persistence/dto/UserCredentials.java

@@ -1,6 +1,6 @@
 package fr.triplea.demovote.persistence.dto;
 
-public class LoginTransfer
+public class UserCredentials
 {
   
   private String username;
@@ -11,14 +11,6 @@ public class LoginTransfer
   public void setPassword(String s) { this.password = new String(s); }
   public String getPassword() { return this.password; }
   
-  private String token;
-  public void setToken(String s) { this.token = new String(s); }
-  public String getToken() { return this.token; }
-    
-  private Integer id;
-  public void setId(int i) { this.id = i; }
-  public Integer getId() { return this.id; }
-  
   private String nom;
   public void setNom(String s) { this.nom = new String(s); }
   public String getNom() { return this.nom; }
@@ -30,7 +22,9 @@ public class LoginTransfer
   private String role;
   public void setRole(String s) { this.role = new String(s); }
   public String getRole() { return this.role; }
+  public boolean hasRole() { if (this.role != null) { if (!(this.role.isBlank())) { return true; }} return false; }
 
+  public UserCredentials() {}
   
   @Override
   public String toString() 

+ 2 - 0
src/main/java/fr/triplea/demovote/persistence/model/Role.java

@@ -76,6 +76,8 @@ public class Role
   
   public void setLibelle(String str) { if (str != null) { this.libelle = StringUtils.truncate(str, 64); } }
   public String getLibelle() { return this.libelle; }
+  @Transient
+  public boolean isRole(String s) { if (this.libelle != null) { if (this.libelle.equals("ROLE_" + s)) { return true; } } return false; }
  
   public List<Participant> getParticipants() { return participants; }
   public void setUsers(final List<Participant> participants) { this.participants = participants; }

+ 0 - 71
src/main/java/fr/triplea/demovote/security/MyRememberMeServices.java

@@ -1,71 +0,0 @@
-package fr.triplea.demovote.security;
-
-import java.util.Date;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.authentication.AuthenticationDetailsSource;
-import org.springframework.security.authentication.RememberMeAuthenticationToken;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
-import org.springframework.security.core.authority.mapping.NullAuthoritiesMapper;
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.security.core.userdetails.UserDetailsService;
-import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
-import org.springframework.security.web.authentication.rememberme.PersistentRememberMeToken;
-import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
-import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
-
-import fr.triplea.demovote.persistence.dao.ParticipantRepository;
-import fr.triplea.demovote.persistence.model.Participant;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-
-public class MyRememberMeServices extends PersistentTokenBasedRememberMeServices 
-{
-
-  @Autowired
-  private ParticipantRepository participantRepository;
-
-  private String key;
-  private PersistentTokenRepository tokenRepository;
-
-  private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper();
-  private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
-
-  public MyRememberMeServices(String key, UserDetailsService userDetailsService, PersistentTokenRepository tokenRepository) 
-  {
-    super(key, userDetailsService, tokenRepository);
-    this.key = key;
-    this.tokenRepository = tokenRepository;
-  }
-
-
-  @Override
-  protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) 
-  {
-    String pseudonyme = ((Participant) successfulAuthentication.getPrincipal()).getPseudonyme();
-
-    PersistentRememberMeToken persistentToken = new PersistentRememberMeToken(pseudonyme, generateSeriesData(), generateTokenData(), new Date());
-
-    try 
-    {
-      tokenRepository.createNewToken(persistentToken);
-      
-      this.setCookie(new String[] { persistentToken.getSeries(), persistentToken.getTokenValue() }, this.getTokenValiditySeconds(), request, response);
-    } 
-    catch (Exception e) {}
-  }
-
-  @Override
-  protected Authentication createSuccessfulAuthentication(HttpServletRequest request, UserDetails user) 
-  {
-    Participant participant = participantRepository.findByPseudonyme(user.getUsername());
-    
-    RememberMeAuthenticationToken auth = new RememberMeAuthenticationToken(key, participant, authoritiesMapper.mapAuthorities(user.getAuthorities()));
-    
-    auth.setDetails(authenticationDetailsSource.buildDetails(request));
-    
-    return auth;
-  }
-
-}

+ 1 - 1
src/main/java/fr/triplea/demovote/security/MyUserDetailsService.java

@@ -38,7 +38,7 @@ public class MyUserDetailsService implements UserDetailsService
 
       Set<GrantedAuthority> authorities = participant.getRoles().stream().map((role) -> new SimpleGrantedAuthority(role.getLibelle())).collect(Collectors.toSet());
 
-      return new org.springframework.security.core.userdetails.User(participant.getEmail(), participant.getMotDePasse(), authorities);
+      return new org.springframework.security.core.userdetails.User(participant.getPseudonyme(), participant.getMotDePasse(), authorities);
     } 
     catch (final Exception e) { throw new RuntimeException(e); }
    }

+ 3 - 3
src/main/java/fr/triplea/demovote/spring/CreateDefaultValues.java

@@ -39,9 +39,9 @@ public class CreateDefaultValues implements ApplicationListener<ContextRefreshed
   {
     if (initialise) { return; } 
     
-    Role adminRole = addRoleIfMissing("Administrateur");
-    Role orgaRole = addRoleIfMissing("Organisateur");
-    Role userRole = addRoleIfMissing("Participant");
+    Role adminRole = addRoleIfMissing("ROLE_ADMIN");
+    Role orgaRole = addRoleIfMissing("ROLE_ORGA");
+    Role userRole = addRoleIfMissing("ROLE_USER");
     
     
     List<Participant> participants = participantRepository.findAll();

+ 0 - 32
src/main/java/fr/triplea/demovote/spring/MvcConfig.java

@@ -1,32 +0,0 @@
-package fr.triplea.demovote.spring;
-
-import org.springframework.boot.web.server.WebServerFactoryCustomizer;
-import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
-import org.springframework.web.servlet.config.annotation.EnableWebMvc;
-import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
-import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-
-
-@Configuration
-@ComponentScan(basePackages = { "fr.triplea.demovote.web" })
-@EnableWebMvc
-public class MvcConfig implements WebMvcConfigurer 
-{
-
-  public MvcConfig() { super(); }
-
-  @Override
-  public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { configurer.enable(); }
-
-  @Override
-  public void addResourceHandlers(final ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/", "/resources/"); }
-
-
-  @Bean
-  WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> enableDefaultServlet() { return (factory) -> factory.setRegisterDefaultServlet(true); }
-
-}

+ 16 - 37
src/main/java/fr/triplea/demovote/spring/SecurityConfig.java

@@ -1,10 +1,11 @@
 package fr.triplea.demovote.spring;
 
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.security.authentication.AuthenticationManager;
 import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
+import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
 import org.springframework.security.core.session.SessionRegistry;
@@ -12,62 +13,40 @@ import org.springframework.security.core.session.SessionRegistryImpl;
 import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
 import org.springframework.security.crypto.password.PasswordEncoder;
 import org.springframework.security.web.SecurityFilterChain;
-import org.springframework.security.web.authentication.rememberme.InMemoryTokenRepositoryImpl;
-
-import fr.triplea.demovote.security.MyRememberMeServices;
-import fr.triplea.demovote.security.MyUserDetailsService;
 
 @Configuration
 @EnableWebSecurity
+@EnableMethodSecurity
+@ComponentScan("fr.triplea.demovote.security")
 public class SecurityConfig
 {
+ 
 
-  @Autowired
-  private MyUserDetailsService userDetailsService;
-  
   @Bean
-  AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception { return authConfig.getAuthenticationManager(); }
+  AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { return authenticationConfiguration.getAuthenticationManager(); }
 
-  
   @Bean
+  PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(11); }
+
+  @Bean
+  SessionRegistry sessionRegistry() { return new SessionRegistryImpl(); }
+
+   @Bean
   SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception 
   {
     http.csrf((csrf) -> csrf.disable());
     
     http.authorizeHttpRequests((authorizeHttpRequests) -> authorizeHttpRequests
-      .requestMatchers("/auth/**").permitAll()
-      .requestMatchers("/divers/**").permitAll()
-      .requestMatchers("/account/**").hasAuthority("Participant")
-      .requestMatchers("/preference/**").hasAuthority("Participant")
-      .requestMatchers("/message/**").hasAuthority("Participant")
-      .requestMatchers("/urne/**").hasAuthority("Participant")
-      .requestMatchers("/resultats/**").hasAuthority("Participant")
-      .requestMatchers("/variable/**").hasAuthority("Administrateur")
-      .requestMatchers("/categorie/**").hasAuthority("Administrateur")
-      .requestMatchers("/participant/**").hasAnyAuthority("Administrateur", "Organisateur")
-      .requestMatchers("/production/**").hasAuthority("Administrateur")
-      .requestMatchers("/presentation/**").hasAuthority("Administrateur")
+      .requestMatchers("/divers/**", "/sign/**").permitAll()
+      .requestMatchers("/account/**", "/preference/**", "/message/**", "/urne/**", "/resultats/**").hasRole("USER")
+      .requestMatchers("/variable/**", "/categorie/**", "/production/**", "/presentation/**").hasRole("ADMIN")
+      .requestMatchers("/participant/**").hasAnyRole("ADMIN", "ORGA")
       .anyRequest().authenticated()
     );
 
     http.sessionManagement((sessionManagement) -> sessionManagement.maximumSessions(2).sessionRegistry(sessionRegistry()));
 
-    http.rememberMe((remember) -> remember.rememberMeServices(rememberMeServices()));
-
     return http.build();
   }
 
-  @Bean
-  MyRememberMeServices rememberMeServices() 
-  {
-    MyRememberMeServices rememberMeServices = new MyRememberMeServices("Alr34dy", userDetailsService, new InMemoryTokenRepositoryImpl());
-    return rememberMeServices;
-  }
-
-  @Bean
-  SessionRegistry sessionRegistry() { return new SessionRegistryImpl(); }
-
-  @Bean
-  PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(11); }
-
 }

+ 71 - 1
src/main/java/fr/triplea/demovote/web/controller/AccountController.java

@@ -1,11 +1,21 @@
 package fr.triplea.demovote.web.controller;
 
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.crypto.password.PasswordEncoder;
 import org.springframework.web.bind.annotation.CrossOrigin;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
 import fr.triplea.demovote.persistence.dao.ParticipantRepository;
+import fr.triplea.demovote.persistence.dto.ParticipantTransfer;
+import fr.triplea.demovote.persistence.model.Participant;
 
 
 @CrossOrigin(origins = "http://localhost:4200")
@@ -16,7 +26,67 @@ public class AccountController
 
   @Autowired
   private ParticipantRepository participantRepository;
+  
+  @Autowired
+  private PasswordEncoder passwordEncoder;
+
 
-  // TODO 
+  @GetMapping(value = "/form")
+  @PreAuthorize("hasAnyRole('USER')")
+  public ResponseEntity<ParticipantTransfer> getForm() 
+  { 
+    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
+    
+    if (authentication != null)
+    {
+      ParticipantTransfer found = participantRepository.searchByPseudonyme(authentication.getName());
+      
+      if (found != null) { return ResponseEntity.ok(found); }
+    }
+    
+    return ResponseEntity.notFound().build();
+  }
  
+  @PutMapping(value = "/update")
+  @PreAuthorize("hasAnyRole('USER')")
+  public ResponseEntity<Object> update(@RequestBody(required = true) ParticipantTransfer participant) 
+  { 
+    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
+    
+    if (authentication != null)
+    {
+      Participant found = participantRepository.findByPseudonyme(authentication.getName());
+      
+      if (found != null)
+      {
+        found.setEnabled(true);
+
+        found.setNom(participant.nom());
+        found.setPrenom(participant.prenom());
+        
+        final String mdp = participant.motDePasse();
+        if (mdp != null) { if (!(mdp.isBlank())) { found.setMotDePasse(passwordEncoder.encode(mdp.trim())); } } 
+        
+        found.setGroupe(participant.groupe()); 
+        found.setDelaiDeconnexion(participant.delaiDeconnexion());
+        found.setAdresse(participant.adresse());
+        found.setCodePostal(participant.codePostal());
+        found.setVille(participant.ville());
+        found.setPays(participant.pays());
+        found.setNumeroTelephone(participant.numeroTelephone());
+        found.setEmail(participant.email());
+         
+        found.setCommentaire(participant.commentaire());
+       
+        // TODO: modify password in session
+        
+        participantRepository.save(found);
+      
+        return ResponseEntity.ok(participant);
+      }
+    } 
+    
+    return ResponseEntity.notFound().build();
+  }
+
 }

+ 73 - 28
src/main/java/fr/triplea/demovote/web/controller/AuthController.java

@@ -2,12 +2,15 @@ package fr.triplea.demovote.web.controller;
 
 import java.util.List;
 
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.ResponseEntity;
 import org.springframework.security.authentication.AuthenticationManager;
 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.crypto.password.PasswordEncoder;
 import org.springframework.web.bind.annotation.CrossOrigin;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestBody;
@@ -15,58 +18,100 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
 import fr.triplea.demovote.persistence.dao.ParticipantRepository;
-import fr.triplea.demovote.persistence.dto.LoginTransfer;
+import fr.triplea.demovote.persistence.dto.UserCredentials;
 import fr.triplea.demovote.persistence.model.Participant;
 import fr.triplea.demovote.persistence.model.Role;
 
 
 @CrossOrigin(origins = "http://localhost:4200")
 @RestController
-@RequestMapping("/auth")
+@RequestMapping("/sign")
 public class AuthController 
 {
-
+  private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
+  
   @Autowired
   private AuthenticationManager authenticationManager;
 
   @Autowired
   private ParticipantRepository participantRepository;
   
-  @PostMapping("/signin")
-  public ResponseEntity<LoginTransfer> authenticateUser(@RequestBody LoginTransfer loginTransfer)
+  @Autowired
+  private PasswordEncoder passwordEncoder;
+
+
+  @PostMapping(value = "/in")
+  public ResponseEntity<UserCredentials> signIn(@RequestBody UserCredentials uc)
   {
-    Participant found = participantRepository.findByPseudonyme(loginTransfer.getUsername());
+    String usrn = uc.getUsername(); if (usrn == null) { usrn = ""; } else { usrn = usrn.trim(); }
+    String pass = uc.getPassword(); if (pass == null) { pass = ""; } else { pass = pass.trim(); }
+    
+    if (usrn.isEmpty() || pass.isEmpty()) { return ResponseEntity.notFound().build(); }
+    
+    Participant found = participantRepository.findByPseudonyme(usrn);
     
     if (found != null)
-    {      
-      UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginTransfer.getUsername(), loginTransfer.getPassword());
+    { 
+      logger.info("compte trouvé, passhash=" + found.getMotDePasse());
       
-      Authentication authentication = authenticationManager.authenticate(token);
-     
-      SecurityContextHolder.getContext().setAuthentication(authentication);
+      logger.info("pass=" + passwordEncoder.encode(pass));
       
-      loginTransfer.setPassword("xxx");
-      loginTransfer.setToken(token.toString());
-      loginTransfer.setId(found.getNumeroParticipant());
-      loginTransfer.setNom(found.getNom());
-      loginTransfer.setPrenom(found.getPrenom());
+      if (passwordEncoder.matches(pass, found.getMotDePasse()))
+      {
+        logger.info("mot de passe ok");
 
-      List<Role> roles = found.getRoles();
-      
-      loginTransfer.setRole("Participant");
-      
-      for (Role role : roles) 
-      {  
-        if (role.getLibelle().equals("Administrateur")) { loginTransfer.setRole("Administrateur"); break; }
-        else 
-        if (role.getLibelle().equals("Organisateur")) { loginTransfer.setRole("Organisateur"); break; }
-      }
+        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(usrn, found.getMotDePasse());
+ 
+        //Authentication auth = authenticationManager.authenticate(token); <-- // TODO : doesn't work
        
-      return ResponseEntity.ok(loginTransfer);
+        //logger.info("auth");
+
+        //SecurityContextHolder.getContext().setAuthentication(auth);
+        
+        //logger.info("in scholder");
+        
+        uc = new UserCredentials();
+        
+        uc.setUsername(usrn);
+        uc.setPassword("<success@auth>");
+        uc.setNom(found.getNom());
+        uc.setPrenom(found.getPrenom());
+
+        List<Role> roles = found.getRoles();
+         
+        if (!(uc.hasRole())) { for (Role role : roles) { if (role.isRole("ADMIN")) { uc.setRole("ADMIN"); } } }
+        if (!(uc.hasRole())) { for (Role role : roles) { if (role.isRole("ORGA")) { uc.setRole("ORGA"); } } }
+        if (!(uc.hasRole())) { uc.setRole("USER"); }
+
+        return ResponseEntity.ok(uc);
+      }      
     }
     
-    return ResponseEntity.notFound().build();
+    uc = new UserCredentials();
+    
+    uc.setUsername("");
+    uc.setPassword("");
+    uc.setNom("");
+    uc.setPrenom("");
+    uc.setRole("");
+   
+    return ResponseEntity.ok(uc);
   }
 
+  @PostMapping("/out")
+  public ResponseEntity<UserCredentials> signOut()
+  {
+    SecurityContextHolder.clearContext();
+    
+    UserCredentials uc = new UserCredentials();
+    
+    uc.setUsername("");
+    uc.setPassword("");
+    uc.setNom("");
+    uc.setPrenom("");
+    uc.setRole("");
+
+    return ResponseEntity.ok(uc);
+  }
   
 }

+ 2 - 2
src/main/java/fr/triplea/demovote/web/controller/BulletinController.java

@@ -43,7 +43,7 @@ public class BulletinController
   private ProductionRepository productionRepository;
 
   @PostMapping(value = "/create")
-  @PreAuthorize("hasAuthority('Participant')")
+  @PreAuthorize("hasRole('USER')")
   public ResponseEntity<Object> add(@RequestParam(required = true) int cat_id, @RequestParam(required = true) int part_id, @RequestParam(required = true) int prod_id) 
   { 
     Bulletin bul = bulletinRepository.findByCategorieAndParticipant(cat_id, part_id);
@@ -127,7 +127,7 @@ public class BulletinController
   }
 
   @DeleteMapping(value = "/delete/{id}")
-  @PreAuthorize("hasAuthority('Participant')")
+  @PreAuthorize("hasRole('USER')")
   public ResponseEntity<Map<String, Boolean>> remove(@PathVariable int id) 
   { 
     if (id > 0) { bulletinRepository.deleteById(id); }

+ 5 - 5
src/main/java/fr/triplea/demovote/web/controller/CategorieController.java

@@ -31,14 +31,14 @@ public class CategorieController
 
 
   @GetMapping(value = "/list")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public List<Categorie> getList() 
   { 
     return categorieRepository.findAll(); 
   }
 
   @GetMapping(value = "/form/{id}")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public ResponseEntity<Categorie> getForm(@PathVariable int id)
   { 
     Categorie c = categorieRepository.findById(id);
@@ -49,7 +49,7 @@ public class CategorieController
   }
 
   @PostMapping(value = "/create")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public Categorie create(@RequestBody(required = true) Categorie categorie) 
   { 
     Categorie found = categorieRepository.findById(0);
@@ -62,7 +62,7 @@ public class CategorieController
   }
 
   @PutMapping(value = "/update/{id}")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public ResponseEntity<Object> update(@PathVariable int id, @RequestBody(required = true) Categorie categorie) 
   { 
     Categorie found = categorieRepository.findById(id);
@@ -88,7 +88,7 @@ public class CategorieController
   }
 
   @DeleteMapping(value = "/delete/{id}")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public ResponseEntity<Map<String, Boolean>> disableCategorie(@PathVariable int id) 
   { 
     Categorie c = categorieRepository.getReferenceById(id);

+ 1 - 1
src/main/java/fr/triplea/demovote/web/controller/MessageController.java

@@ -24,7 +24,7 @@ public class MessageController
   
   
   @GetMapping(value = "/list/{id}")
-  @PreAuthorize("hasAuthority('Participant')")
+  @PreAuthorize("hasRole('USER')")
   public List<Message> getList(@PathVariable int id)
   { 
     return messageRepository.findAll(id, id); 

+ 26 - 8
src/main/java/fr/triplea/demovote/web/controller/ParticipantController.java

@@ -10,6 +10,7 @@ import java.util.UUID;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.ResponseEntity;
 import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.security.crypto.password.PasswordEncoder;
 import org.springframework.web.bind.annotation.CrossOrigin;
 import org.springframework.web.bind.annotation.DeleteMapping;
 import org.springframework.web.bind.annotation.GetMapping;
@@ -37,11 +38,14 @@ public class ParticipantController
 
   @Autowired
   private ParticipantRepository participantRepository;
+  
+  @Autowired
+  private PasswordEncoder passwordEncoder;
 
   
 
   @GetMapping(value = "/list")
-  @PreAuthorize("hasAnyAuthority('Participant', 'Organisateur')")
+  @PreAuthorize("hasAnyRole('ADMIN', 'ORGA')")
   public List<ParticipantList> getList() 
   { 
     return participantRepository.getList(); 
@@ -49,14 +53,14 @@ public class ParticipantController
 
   
   @GetMapping(value = "/option-list")
-  @PreAuthorize("hasAnyAuthority('Participant', 'Organisateur')")
+  @PreAuthorize("hasAnyRole('ADMIN', 'ORGA')")
   public List<ParticipantOptionList> getOptionList() 
   { 
     return participantRepository.getOptionList(); 
   }
 
   @GetMapping(value = "/form/{id}")
-  @PreAuthorize("hasAnyAuthority('Participant', 'Organisateur')")
+  @PreAuthorize("hasAnyRole('ADMIN', 'ORGA')")
   public ResponseEntity<ParticipantTransfer> getForm(@PathVariable int id) 
   { 
     ParticipantTransfer p = participantRepository.searchById(id);
@@ -67,7 +71,7 @@ public class ParticipantController
   }
 
   @PostMapping(value = "/create")
-  @PreAuthorize("hasAnyAuthority('Participant', 'Organisateur')")
+  @PreAuthorize("hasAnyRole('ADMIN', 'ORGA')")
   public ResponseEntity<Object> create(@RequestBody(required = true) ParticipantTransfer participant) 
   { 
     Participant found = participantRepository.findById(0);
@@ -85,8 +89,12 @@ public class ParticipantController
 
           found.setNom(participant.nom());
           found.setPrenom(participant.prenom());
+          
           found.setPseudonyme(participant.pseudonyme());
-          found.setMotDePasse(participant.motDePasse());
+ 
+          final String mdp = participant.motDePasse();
+          if (mdp != null) { if (!(mdp.isBlank())) { found.setMotDePasse(passwordEncoder.encode(mdp.trim())); } } 
+          
           found.setGroupe(participant.groupe()); 
           found.setDelaiDeconnexion(participant.delaiDeconnexion());
           found.setAdresse(participant.adresse());
@@ -95,7 +103,7 @@ public class ParticipantController
           found.setPays(participant.pays());
           found.setNumeroTelephone(participant.numeroTelephone());
           found.setEmail(participant.email());
-         
+                   
           if (participant.statut().equals("PAYE_CHEQUE")) { found.setStatut(ParticipantStatut.PAYE_CHEQUE); }
           else if(participant.statut().equals("PAYE_ESPECES")) { found.setStatut(ParticipantStatut.PAYE_ESPECES); }
           else if(participant.statut().equals("VIREMENT_BANCAIRE")) { found.setStatut(ParticipantStatut.VIREMENT_BANCAIRE); }
@@ -122,6 +130,8 @@ public class ParticipantController
           found.setDateInscription(LocalDateTime.now());
           found.setArrived(participant.arrived());
           
+          // TODO: set roles
+          
           Participant created = participantRepository.save(found);
         
           return ResponseEntity.ok(created);
@@ -133,7 +143,7 @@ public class ParticipantController
   }
 
   @PutMapping(value = "/update/{id}")
-  @PreAuthorize("hasAnyAuthority('Participant', 'Organisateur')")
+  @PreAuthorize("hasAnyRole('ADMIN', 'ORGA')")
   public ResponseEntity<Object> update(@PathVariable int id, @RequestBody(required = true) ParticipantTransfer participant) 
   { 
     Participant found = participantRepository.findById(id);
@@ -145,7 +155,12 @@ public class ParticipantController
 
       found.setNom(participant.nom());
       found.setPrenom(participant.prenom());
+      
       found.setPseudonyme(participant.pseudonyme());
+
+      final String mdp = participant.motDePasse();
+      if (mdp != null) { if (!(mdp.isBlank())) { found.setMotDePasse(passwordEncoder.encode(mdp.trim())); } } 
+
       found.setGroupe(participant.groupe()); 
       found.setDelaiDeconnexion(participant.delaiDeconnexion());
       found.setAdresse(participant.adresse());
@@ -180,6 +195,9 @@ public class ParticipantController
       try { found.setSommeRecue(new BigDecimal(participant.sommeRecue())); } catch (Exception e) { found.setSommeRecue(new BigDecimal("0.00")); }
       found.setArrived(participant.arrived());
       
+      // TODO: modify password in session
+      // TODO: modify roles
+
       Participant updated = participantRepository.save(found);
     
       return ResponseEntity.ok(updated);
@@ -189,7 +207,7 @@ public class ParticipantController
   }
 
   @DeleteMapping(value = "/delete/{id}")
-  @PreAuthorize("hasAnyAuthority('Participant', 'Organisateur')")
+  @PreAuthorize("hasAnyRole('ADMIN', 'ORGA')")
   public ResponseEntity<Map<String, Boolean>> disableParticipant(@PathVariable int id) 
   { 
     Participant found = participantRepository.getReferenceById(id);

+ 3 - 3
src/main/java/fr/triplea/demovote/web/controller/PreferenceController.java

@@ -29,14 +29,14 @@ public class PreferenceController
 
   
   @PostMapping(value = "/list")
-  @PreAuthorize("hasAuthority('Participant')")
+  @PreAuthorize("hasRole('USER')")
   public List<Preference> get(@RequestParam(required = true) Participant numParticipant, @RequestParam(required = false) int numTraitement) 
   { 
     return preferenceRepository.findByParticipantAndTraitement(numParticipant, numTraitement); 
   }
 
   @PostMapping(value = "/create")
-  @PreAuthorize("hasAuthority('Participant')")
+  @PreAuthorize("hasRole('USER')")
   public Preference create(@RequestBody(required = true) Preference preference) 
   { 
     Preference found = preferenceRepository.findById(0);
@@ -47,7 +47,7 @@ public class PreferenceController
   }
 
   @PutMapping(value = "/update/{id}")
-  @PreAuthorize("hasAuthority('Participant')")
+  @PreAuthorize("hasRole('USER')")
   public ResponseEntity<Preference> update(@PathVariable int id, @RequestBody(required = true) Preference preference) 
   { 
     Preference found = preferenceRepository.findById(id);

+ 1 - 1
src/main/java/fr/triplea/demovote/web/controller/PresentationController.java

@@ -23,7 +23,7 @@ public class PresentationController
   private PresentationRepository presentationRepository;
  
   @GetMapping(value = "/list")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public List<Presentation> getList() 
   {
     return presentationRepository.findAll(); 

+ 20 - 10
src/main/java/fr/triplea/demovote/web/controller/ProductionController.java

@@ -53,7 +53,7 @@ public class ProductionController
 
   
   @GetMapping(value = "/list")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public List<Production> getList(@RequestParam(required = false) String type) 
   { 
     List<ProductionShort> prods = productionRepository.findAllWithoutArchive();
@@ -66,7 +66,7 @@ public class ProductionController
   }
 
   @GetMapping(value = "/file/{id}")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   @ResponseBody
   public ResponseEntity<Resource> getFile(@PathVariable int id) 
   {
@@ -87,7 +87,7 @@ public class ProductionController
   }
 
   @GetMapping(value = "/form/{id}")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public ResponseEntity<Production> getForm(@PathVariable int id)
   { 
     ProductionShort p = productionRepository.findByIdWithoutArchive(id);
@@ -98,7 +98,7 @@ public class ProductionController
   }
 
   @GetMapping(value = "/formfile/{id}")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public ResponseEntity<ProductionFile> getFormFile(@PathVariable int id)
   { 
     ProductionFile p = productionRepository.findByIdForUpload(id);
@@ -109,7 +109,7 @@ public class ProductionController
   }
 
   @PostMapping(value = "/create")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public ResponseEntity<Map<String, Boolean>> create(@RequestBody(required = true) ProductionTransfer production, HttpServletRequest request) 
   { 
     Participant participant = participantRepository.findById(production.numeroParticipant());
@@ -119,7 +119,7 @@ public class ProductionController
       Production fresh = new Production();
             
       fresh.setNumeroProduction(null);
-      fresh.setAdresseIP(new Inet(request.getRemoteAddr()));
+      fresh.setAdresseIP(new Inet(this.getClientIP(request)));
       
       if (production.type().equals("EXECUTABLE")) { fresh.setType(ProductionType.EXECUTABLE); }
       else if (production.type().equals("GRAPHE")) { fresh.setType(ProductionType.GRAPHE); }
@@ -153,7 +153,7 @@ public class ProductionController
   }
  
   @PutMapping(value = "/update/{id}")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public ResponseEntity<Map<String, Boolean>> update(@PathVariable int id, @RequestBody(required = true) ProductionUpdate production) 
   { 
     Production found = productionRepository.findById(id);
@@ -167,7 +167,7 @@ public class ProductionController
         found.setParticipant(participant);
         found.setEnabled(true);
         
-        found.setAdresseIP(new Inet(request.getRemoteAddr()));
+        found.setAdresseIP(new Inet(this.getClientIP(request)));
         
         if (production.type().equals("EXECUTABLE")) { found.setType(ProductionType.EXECUTABLE); }
         else if (production.type().equals("GRAPHE")) { found.setType(ProductionType.GRAPHE); }
@@ -198,7 +198,7 @@ public class ProductionController
   }
   
   @PutMapping(value = "/upload/{id}")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public ResponseEntity<Map<String, Boolean>> update(@PathVariable int id, @RequestBody(required = true) ProductionFile production) 
   { 
     Production found = productionRepository.findById(id);
@@ -235,7 +235,7 @@ public class ProductionController
   }
 
   @DeleteMapping(value = "/delete/{id}")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public ResponseEntity<Map<String, Boolean>> disableProduction(@PathVariable int id) 
   { 
     Production found = productionRepository.getReferenceById(id);
@@ -255,4 +255,14 @@ public class ProductionController
     return ResponseEntity.notFound().build(); 
   }
 
+  
+  private final String getClientIP(HttpServletRequest request) 
+  {
+    final String h = request.getHeader("X-Forwarded-For");
+    
+    if (h != null) { if (!(h.isBlank())) { if (!(h.contains(request.getRemoteAddr()))) { return h.split(",")[0]; } } } 
+    
+    return request.getRemoteAddr();
+  }
+
 }

+ 6 - 6
src/main/java/fr/triplea/demovote/web/controller/VariableController.java

@@ -34,7 +34,7 @@ public class VariableController
 
 
   @GetMapping(value = "/list")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public List<Variable> getList(@RequestParam(required = false) String type) 
   { 
     if (type == null) { return variableRepository.findAll(); }
@@ -45,14 +45,14 @@ public class VariableController
   }
   
   @GetMapping(value = "/option-list")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public List<VariableTypeOptionList> getOptionList() 
   { 
     return variableRepository.getTypes(); 
   }
  
   @GetMapping(value = "/form/{id}")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public ResponseEntity<Variable> getForm(@PathVariable int id) 
   { 
     Variable v = variableRepository.findById(id);
@@ -63,7 +63,7 @@ public class VariableController
   }
 
   @PostMapping(value = "/create")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public Variable create(@RequestBody(required = true) Variable variable) 
   { 
     Variable found = variableRepository.findById(0);
@@ -76,7 +76,7 @@ public class VariableController
   }
  
   @PutMapping(value = "/update/{id}")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public ResponseEntity<Variable> update(@PathVariable int id, @RequestBody(required = true) Variable variable) 
   { 
     Variable found = variableRepository.findById(id);
@@ -97,7 +97,7 @@ public class VariableController
   }
 
   @DeleteMapping(value = "/delete/{id}")
-  @PreAuthorize("hasAuthority('Administrateur')")
+  @PreAuthorize("hasRole('ADMIN')")
   public ResponseEntity<Map<String, Boolean>> deleteVariable(@PathVariable int id) 
   { 
     Variable found = variableRepository.findById(id);

+ 8 - 0
src/main/resources/application.properties

@@ -11,3 +11,11 @@ spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
 logging.level.org.springframework=INFO
 
 server.servlet.context-path=/demovote-api/v1
+
+#logging.file.name=logs/demovote.log
+
+#logging.logback.rollingpolicy.file-name-pattern=logs/%d{yyyy-MM, aux}/demovote.%d{yyyy-MM-dd}.%i.log
+#logging.logback.rollingpolicy.max-file-size=2MB
+#logging.logback.rollingpolicy.total-size-cap=10MB
+#logging.logback.rollingpolicy.max-history=5
+