RRHHUserController.java 6.84 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
import org.springframework.data.repository.query.Param;
10 11
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
12
import org.springframework.security.core.userdetails.UsernameNotFoundException;
13 14 15 16 17
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
18 19
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
20

21
import javax.mail.MessagingException;
22
import javax.servlet.http.HttpServletRequest;
23 24 25
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
26 27 28 29 30 31 32 33 34 35 36

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

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

37 38 39 40 41
    @GetMapping("/")
    public String redirectOnHome(){
        return "redirect:/home";
    }

42 43 44 45 46 47 48
    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new RRHHUser());

        return "registration";
    }

49
    @GetMapping("/login")
Cesar Giulano Gonzalez Maqueda committed
50 51 52 53
    public String getLogin(Model model, HttpServletRequest request) {
        if(request.getParameter("error")!=null){
            model.addAttribute("error", "Credenciales Incorrectas");
        }
54 55 56
        return "login";
    }

57
    @PostMapping("/process_register")
58 59 60
    public RedirectView processRegister(HttpServletRequest request, RRHHUser user, RedirectAttributes redirectAttributes) {
        RedirectView redirectView = new RedirectView("/register",true);
        redirectAttributes.addFlashAttribute("success", "Datos actualizados");
61
        if(Long.parseLong(request.getParameter("registrationCode")) != REGISTER_CODE){
62 63
            redirectAttributes.addFlashAttribute("error", "Codigo Incorrecto");
            return redirectView;
64 65 66 67 68 69
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodedPassword);

        rrhhUserRepository.save(user);
70 71 72
        redirectView.setUrl("/login");
        redirectAttributes.addFlashAttribute("success", "Registro Correcto");
        return redirectView;
73
    }
74

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    @GetMapping("/edit-user-data")
    public String editUserData(HttpServletRequest request, Model model){
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        model.addAttribute("user", rrhhUserRepository.findByEmail(auth.getPrincipal().toString()));
        return "edit-user-data";
    }

    @PostMapping("/edit-user-data")
    public RedirectView processEditUser(HttpServletRequest request, RRHHUser user,
                                        RedirectAttributes redirectAttributes){
        RRHHUser editUser = rrhhUserRepository.findByEmail(SecurityContextHolder.getContext().getAuthentication()
                .getPrincipal().toString());
        if(user.getEmail()!=null){
            editUser.setEmail(user.getEmail());
        }
        if(user.getFirstName()!=null){
            editUser.setFirstName(user.getFirstName());
        }
        if(user.getLastName()!=null){
            editUser.setLastName(user.getLastName());
        }
        rrhhUserRepository.save(editUser);
        RedirectView redirectView = new RedirectView("/home",true);
        redirectAttributes.addFlashAttribute("success", "Datos actualizados");
        return redirectView;
    }

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 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    @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:/";
    }

181
}
182 183 184 185 186 187 188

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