package org.datacite.mds.web.ui.controller;

import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.datacite.mds.domain.AllocatorOrDatacentre;
import org.datacite.mds.service.MagicAuthStringService;
import org.datacite.mds.util.Utils;
import org.datacite.mds.util.ValidationUtils;
import org.datacite.mds.web.ui.model.ChangePasswordModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@RequestMapping("/resources/change_password")
@Controller
public class ChangePasswordController {
    
    Logger log4j = Logger.getLogger(ChangePasswordController.class);

    @Autowired
    private MagicAuthStringService magicAuthStringService;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    @RequestMapping(method = RequestMethod.GET)
    public String createForm(@RequestParam(value = "symbol", required = true) String symbol,
            @RequestParam(value = "auth", required = true) String auth, Model model) {
        AllocatorOrDatacentre user = Utils.findAllocatorOrDatacentreBySymbol(symbol);
        if (!magicAuthStringService.isValidAuthString(user, auth)) {
            return "password/expired";
        }
        model.addAttribute("password", new ChangePasswordModel());
        return "password/change";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String changePassword(@ModelAttribute("password") @Valid ChangePasswordModel changePasswordModel,
            BindingResult result, @RequestParam(value = "symbol", required = true) String symbol,
            @RequestParam(value = "auth", required = true) String auth, Model model) {
        AllocatorOrDatacentre user = Utils.findAllocatorOrDatacentreBySymbol(symbol);
        if (!magicAuthStringService.isValidAuthString(user, auth)) {
            return "password/expired";
        }
        if (result.hasErrors()) {
            model.addAttribute("password", changePasswordModel);
            ValidationUtils.copyFieldErrorToObject(result, "equal");
            log4j.debug("form has error: password not changed");
            return "password/change";
        }
        
        user.setPassword(passwordEncoder.encodePassword(changePasswordModel.getFirst(),null));
        user.merge();
        log4j.debug("password succesfully changed for '" + symbol + "'");
        
        return "password/success";
    }
}

@@ -38,16 +38,62 @@
 oller;%0A%0A
+import javax.servlet.http.HttpServletRequest;%0A
 import j
@@ -516,32 +516,404 @@
 ion.
-encoding.PasswordEncoder
+AuthenticationManager;%0Aimport org.springframework.security.authentication.UsernamePasswordAuthenticationToken;%0Aimport org.springframework.security.authentication.encoding.PasswordEncoder;%0Aimport org.springframework.security.core.Authentication;%0Aimport org.springframework.security.core.context.SecurityContextHolder;%0Aimport org.springframework.security.web.authentication.WebAuthenticationDetails
 ;%0Aim
@@ -1054,109 +1054,8 @@
 lt;%0A
-import org.springframework.validation.FieldError;%0Aimport org.springframework.validation.ObjectError;%0A
 impo
@@ -1398,20 +1398,16 @@
 oller %7B%0A
-    
 %0A    Log
@@ -1543,20 +1543,81 @@
 ervice;%0A
+%0A
     
+@Autowired%0A    AuthenticationManager authenticationManager;%0A
 %0A    @Au
@@ -2541,32 +2541,60 @@
 uth, Model model
+, HttpServletRequest request
 ) %7B%0A        Allo
@@ -3066,24 +3066,16 @@
       %7D%0A
-        
 %0A       
@@ -3154,16 +3154,17 @@
 First(),
+ 
 null));%0A
@@ -3199,21 +3199,20 @@
   log4j.
-debug
+info
 (%22passwo
@@ -3258,24 +3258,25 @@
 + %22'%22);%0A
+%0A
         
 %0A       
@@ -3271,42 +3271,809 @@
     
-%0A        return %22password/success%22
+if (SecurityContextHolder.getContext().getAuthentication() == null) %7B%0A            // autologin if not logged in already%0A            log4j.info(%22autologin as '%22 + symbol + %22'%22);%0A            login(symbol, changePasswordModel.getFirst(), request);%0A        %7D else %7B%0A            log4j.info(%22no autologin because already logged in%22);%0A        %7D%0A%0A        return %22password/success%22;%0A    %7D%0A%0A    private void login(String symbol, String password, HttpServletRequest request) %7B%0A        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(symbol, password);%0A        token.setDetails(new WebAuthenticationDetails(request));%0A        Authentication authentication = authenticationManager.authenticate(token);%0A        SecurityContextHolder.getContext().setAuthentication(authentication)
 ;%0A  

change password: auto login