MainController.java 8.1 KB
package com.PFE.ServerManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.*;
import java.sql.Timestamp;
import java.util.*;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.Authentication;

import javax.servlet.annotation.MultipartConfig;

@Controller
@MultipartConfig(fileSizeThreshold = 20971520)
public class MainController {

    @Autowired
    CustomerRepository customerRepository;

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    MajRepository majRepository;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @GetMapping(value="/")
    public String homeRedirection(){
        return "redirect:home";
    }

    @GetMapping(value="/home")
    public ModelAndView home() {
        ModelAndView modelAndView = new ModelAndView();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Customer customer = customerRepository.findByEmail(auth.getName());
        modelAndView.addObject("customerName", customer.getEmail().split("@")[0]);
        modelAndView.addObject("customerRole", customer.getRole());
        modelAndView.setViewName("home");
        return modelAndView;
    }

    @GetMapping(value="/session")
    public ModelAndView session() {
        ModelAndView modelAndView = new ModelAndView();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Customer customer = customerRepository.findByEmail(auth.getName());
        modelAndView.addObject("customerName", customer.getEmail().split("@")[0]);
        modelAndView.addObject("customerRole", customer.getRole());
        modelAndView.addObject("customerMaj", customer.getMaj());
        modelAndView.setViewName("session");
        return modelAndView;
    }

    @GetMapping(path="/registration")
    public ModelAndView registration() {
        ModelAndView modelAndView = new ModelAndView();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Customer customer = customerRepository.findByEmail(auth.getName());
        modelAndView.addObject("customerName", customer.getEmail().split("@")[0]);
        modelAndView.addObject("customerRole", customer.getRole());
        modelAndView.setViewName("registration");
        return modelAndView;
    }

    @GetMapping(path="/denied")
    public String denied() {
        return "denied";
    }

    @PostMapping(path="/registration")
    public ModelAndView addNewUser(@RequestParam String email, @RequestParam String password, @RequestParam String role) {
        //Model map, ModelAndView ou l'utilisation direct comme dans la méthode précédente sont 3 méthodes qui permettent d'envoyer des informations et donc de changer l'apparence d'une page
        ModelAndView modelAndView = new ModelAndView(); // il n'est peut être pas utile d'utiliser ModelAndView
        Customer n = new Customer();
        n.setEmail(email);
        n.setPassword(bCryptPasswordEncoder.encode(password));
        n.setId((int)(customerRepository.count() + 1));
        n.setActive(1);
        Customer temp = customerRepository.findByEmail(email);
        Role userRole = roleRepository.findByRole(role);
        n.setRoles(new HashSet<Role>(Arrays.asList(userRole)));
        //utilisé uniquement pour continuer à afficher l'utilisateur connecté//
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Customer customer = customerRepository.findByEmail(auth.getName());
        modelAndView.addObject("customerName", customer.getEmail().split("@")[0]);
        modelAndView.addObject("customerRole", customer.getRole());
        modelAndView.setViewName("registration");

        if(temp != null) {
            modelAndView.addObject("message", "L'utilisateur existe déjà !");
            modelAndView.addObject("fail", true);
        }
        else {
            modelAndView.addObject("message", "L'utilisateur a bien été ajouté !");
            modelAndView.addObject("ok", true);
            customerRepository.save(n);
        }
        modelAndView.setViewName("registration");
        return modelAndView;
    }

    @RequestMapping(value = "/file", method = RequestMethod.POST)
    @ResponseStatus(value = HttpStatus.OK)
    public void submit(@RequestParam MultipartFile file) {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Customer customer = customerRepository.findByEmail(auth.getName());
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        File dirs = new File("files/" + customer.getEmail().split("@")[0] + "_" + timestamp.getTime());
        dirs.mkdirs();
        OutputStream outputStream = null;
        InputStream inputStream = null;

        try {
            inputStream = file.getInputStream();
            File newFile = new File(dirs.getPath() + "/" + file.getOriginalFilename());
            if (!newFile.exists()) {
                newFile.createNewFile();
            }
            outputStream = new FileOutputStream(newFile);
            int read = 0;
            byte[] bytes = new byte[1024];

            while((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
        }

        catch (IOException e) {
            e.printStackTrace();
        }

        finally {
            try {
                outputStream.close();
            }
            catch(IOException e) {

            }
        }
    }


    @GetMapping(path="/login")
    public ModelAndView login() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");
        return modelAndView;
    }

    /*@GetMapping(path="/all")
    public @ResponseBody Iterable<Customer> getAllUsers() {
        return customerRepository.findAll();
    }*/
    @GetMapping(path="/all")
    public ModelAndView getAllUsers() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("all");

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Customer customer = customerRepository.findByEmail(auth.getName());
        modelAndView.addObject("customerName", customer.getEmail().split("@")[0]);
        modelAndView.addObject("customerRole", customer.getRole());

        /*List<Customer> list = new ArrayList<Customer>();
        Iterator<Customer> listIterator = customerRepository.findAll().iterator();
        while (listIterator.hasNext()) {
            list.add(listIterator.next());
        }*/
        List<Customer> list = customerRepository.findAll(); // attention : la méthode findAll() de JpaRepository retourne une liste alors que celle de CrudRepository retourne un itérable
        modelAndView.addObject("list", list);
        return modelAndView;
    }


    @GetMapping(value="/success")
    public String success(){
        return "success";
    }

    @GetMapping(path="/test")
    public String testGet() {
        return "test";
    }

    @PostMapping(path="/savemaj")
    public String saveMaj(@RequestParam String name, @RequestParam String date, @RequestParam String nodes){
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Customer customer = customerRepository.findByEmail(auth.getName());
        Maj maj_c = new Maj();
        maj_c.setMaj(name);
        maj_c.setDate(date);
        maj_c.setNodes(nodes);
        maj_c.setMaj_id((int)(majRepository.count() + 1));
        majRepository.save(maj_c); // ajouter la mise a jour dans la table
        HashSet<Maj> majs = new HashSet<Maj>(Arrays.asList(maj_c));
        majs.addAll(customer.getMaj());
        customer.setMaj(majs);
        customerRepository.save(customer); // permet de rendre effective la jointure entre customer et maj
        return "redirect:/session";
    }
}