RRHHUserController.java 6.16 KB
Newer Older
1 2 3 4
package com.roshka.controller;

import com.roshka.modelo.RRHHUser;
import com.roshka.repositorio.RRHHUserRepository;
5 6 7
import com.roshka.service.EmailAsyncService;
import com.roshka.service.RRHHUserService;
import net.bytebuddy.utility.RandomString;
8
import org.springframework.beans.factory.annotation.Autowired;
9 10 11 12 13 14 15
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
16 17 18
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
19 20
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
21 22
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
23 24 25
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
26

27 28
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
29
import javax.servlet.http.HttpServletRequest;
30 31 32 33
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
34 35 36 37 38 39 40 41 42 43 44

@Controller
public class RRHHUserController {
    private static final long REGISTER_CODE = 1234;
    RRHHUserRepository rrhhUserRepository;

    @Autowired
    public RRHHUserController(RRHHUserRepository rrhhUserRepository){
        this.rrhhUserRepository = rrhhUserRepository;
    }

45 46 47 48 49
    @GetMapping("/")
    public String redirectOnHome(){
        return "redirect:/home";
    }

50 51 52 53 54 55 56
    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new RRHHUser());

        return "registration";
    }

57
    @GetMapping("/login")
Cesar Giulano Gonzalez Maqueda committed
58 59 60 61
    public String getLogin(Model model, HttpServletRequest request) {
        if(request.getParameter("error")!=null){
            model.addAttribute("error", "Credenciales Incorrectas");
        }
62 63 64
        return "login";
    }

65 66 67 68 69 70 71 72 73 74 75 76 77
    @PostMapping("/process_register")
    public String processRegister(HttpServletRequest request, RRHHUser user) {
        if(Long.parseLong(request.getParameter("registrationCode")) != REGISTER_CODE){
            return "redirect:/register";
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodedPassword);

        rrhhUserRepository.save(user);

        return "register_success";
    }
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166

    @Autowired
    private RRHHUserService userService;

    @Autowired
    private EmailAsyncService emailAsyncService;

    @GetMapping("/forgot-password")
    public String showForgotPasswordForm(HttpServletRequest request, Model model) {
        model.addAttribute("error", request.getParameter("error"));
//        if(request.getParameter("error")!=null){
//
//        }
        return "forgot_password_form";
    }

    @PostMapping("/forgot-password")
    public String processForgotPassword(HttpServletRequest request, Model model) {
        String email = request.getParameter("email");
        String token = RandomString.make(30);

        try {
            userService.updateResetPasswordToken(token, email);
        }catch (UsernameNotFoundException e){
            model.addAttribute("error", "Error al enviar el mail. Checkee sus credenciales " +
                    "y intentelo de nuevo.");
            return "forgot_password_form";
        }
        String resetPasswordLink = Utility.getSiteURL(request) + "/reset-password?token=" + token;
        ExecutorService emailExecutor = Executors.newSingleThreadExecutor();
        emailExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    emailAsyncService.sendEmail(email, resetPasswordLink);
                } catch (IOException | MessagingException e) {
                    e.printStackTrace();
                }
            }
        });
        emailExecutor.shutdown();

        return "forgot_password_form";
    }



    @GetMapping("/reset-password")
    public String showResetPasswordForm(@Param(value = "token") String token, Model model) {
        RRHHUser user = userService.getByResetPasswordToken(token);
        model.addAttribute("token", token);

        if (user == null) {
            model.addAttribute("error", "Invalid Token");
            return "error";
        }

        return "reset_password_form";
    }

    @PostMapping("/reset-password")
    public String processResetPassword(HttpServletRequest request, Model model) {
        String token = request.getParameter("token");
        String password = request.getParameter("password");

        RRHHUser user = userService.getByResetPasswordToken(token);
        model.addAttribute("title", "Reset your password");

        if (user == null) {
            model.addAttribute("error", "Invalid Token");
            return "message";
        } else {
            userService.updatePassword(user, password);

            model.addAttribute("success", "You have successfully changed your password.");
        }

        return "redirect:/";
    }

    @ResponseStatus(HttpStatus.PERMANENT_REDIRECT)
    @ExceptionHandler({UsernameNotFoundException.class})
    public RedirectView handleValidationExceptions(
            RedirectAttributes redir, UsernameNotFoundException ex) {
        RedirectView redirectView = new RedirectView("/forgot-password", true);
        redir.addAttribute("error", "Error al enviar el mail. Checkee sus credenciales" +
                " y intentelo de nuevo");
        return redirectView;
    }
167
}
168 169 170 171 172 173 174

class Utility {
    public static String getSiteURL(HttpServletRequest request) {
        String siteURL = request.getRequestURL().toString();
        return siteURL.replace(request.getServletPath(), "");
    }
}