package edu.asu.conceptpower.servlet.web.profile;

import java.security.Principal;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import edu.asu.conceptpower.servlet.users.IUserManager;
import edu.asu.conceptpower.servlet.web.profile.backing.PasswordBean;
import edu.asu.conceptpower.users.User;

@Controller
public class ChangePasswordController {
    
    @Autowired
    private IUserManager userManager;

    @RequestMapping(value = "/auth/profile/password/change", method = RequestMethod.GET)
    public String showChangePassword(Model model, Principal principal) {
        model.addAttribute("passwordBean", new PasswordBean());
        
        return "auth/profile/password";
    }
    
    @RequestMapping(value = "/auth/profile/password/change", method = RequestMethod.POST)
    public String changePassword(@Valid @ModelAttribute PasswordBean passwordBean, BindingResult results, Model model, Principal principal) {
        if (results.hasErrors()) {
            passwordBean.setOldPassword("");
            return "auth/profile/password";
        }
        
        String oldPasswordEncrypt = BCrypt.hashpw(passwordBean.getOldPassword(), BCrypt.gensalt());
        User user = userManager.getUser(principal.getName(), oldPasswordEncrypt);
        if (user != null) {
            user.setPw(passwordBean.getPassword());
            userManager.storeModifiedPassword(user);
            return "redirect:/auth/profile";
        }
        
        model.addAttribute("show_error_alert", true);
        model.addAttribute("error_alert_msg", "Your password could not be changed. The old password you've entered was incorrect.");
        model.addAttribute("passwordBean", new PasswordBean());
        return "auth/profile/password";
    }
}

@@ -778,20 +778,16 @@
 oller %7B%0A
-    
 %0A    @Au
@@ -1059,24 +1059,16 @@
 ean());%0A
-        
 %0A       
@@ -1106,20 +1106,16 @@
 ;%0A    %7D%0A
-    
 %0A    @Re
@@ -1307,32 +1307,44 @@
 ts, Model model,
+%0A           
  Principal princ
@@ -1489,116 +1489,8 @@
   %7D%0A
-        %0A        String oldPasswordEncrypt = BCrypt.hashpw(passwordBean.getOldPassword(), BCrypt.gensalt());
 %0A   
@@ -1518,19 +1518,20 @@
 Manager.
-get
+find
 User(pri
@@ -1550,28 +1550,8 @@
 me()
-, oldPasswordEncrypt
 );%0A 
@@ -1573,16 +1573,79 @@
  != null
+ && BCrypt.checkpw(passwordBean.getOldPassword(), user.getPw())
 ) %7B%0A    
@@ -1800,24 +1800,16 @@
       %7D%0A
-        
 %0A       
@@ -1900,16 +1900,32 @@
 rt_msg%22,
+%0A               
  %22Your p

check password correctly