package com.konkerlabs.platform.registry.security;

import com.konkerlabs.platform.registry.business.model.Tenant;
import com.konkerlabs.platform.registry.business.model.User;
import com.konkerlabs.platform.registry.business.repositories.UserRepository;
import com.konkerlabs.platform.registry.config.EmailConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.Random;

@Service("tenantUserDetails")
public class TenantUserDetailsService implements UserDetailsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TenantUserDetailsService.class);
    private static final int MIN_DELAY_TIME = 100;
    private static final int MAX_DELAY_TIME = 250;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private EmailConfig emailConfig;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        // Delay time introduced to prevent user enumeration attack
        Random random = new Random();
        int delayTime = random.nextInt(MAX_DELAY_TIME - MIN_DELAY_TIME) + MIN_DELAY_TIME;
        try {
            Thread.sleep(delayTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        User user = userRepository.findOne(Optional.of(email).orElse("").trim().toLowerCase());
        if (user == null || user.isActive() == false) {
            invalidCredentials(email);

        } else if (Optional.ofNullable(user).isPresent() &&
                emailConfig.isEnabled() &&
                !user.isActive()) {
            invalidCredentials(email);
        }
        
        return user;
    }

	private void invalidCredentials(String email) {
		User noUser = User.builder().email(email).tenant(
		        Tenant.builder().name("NOT_FOUND").domainName("NOT_FOUND").build()
		).build();
		LOGGER.debug("User not found",
		         noUser.toURI(),
		         noUser.getTenant().getLogLevel());
		 throw new UsernameNotFoundException("authentication.credentials.invalid");
	}
}

@@ -1048,20 +1048,16 @@
  = 250;%0A
-    
 %0A    @Au
@@ -1107,20 +1107,16 @@
 sitory;%0A
-    
 %0A    @Au
@@ -1705,17 +1705,16 @@
       if
- 
 (user ==
@@ -1722,38 +1722,9 @@
 null
- %7C%7C user.isActive() == false) 
+)
 %7B%0A  
@@ -1721,36 +1721,33 @@
  null)%7B%0A        
- 
-   
+%09
 invalidCredentia
@@ -1826,24 +1826,19 @@
         
-        
+%09%09%09
 emailCon
@@ -1864,24 +1864,19 @@
         
-        
+%09%09%09
 !user.is
@@ -1895,20 +1895,17 @@
         
-    
+%09
 invalidC

revert TenantUserDetailsService