package com.ankurm.authdemo.auth;

import com.ankurm.authdemo.auth.LegacyDirectory.DirectoryUnavailableException;
import com.ankurm.authdemo.auth.LegacyDirectory.LegacyUser;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.FactorGrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.ArrayList;
import java.util.List;

/**
 * A second provider for the same token type. It answers three different ways:
 * null ("not my user, ask the next provider"), an exception (a verdict), or a token (success).
 */
public class LegacyDirectoryAuthProvider implements AuthenticationProvider {

    private final LegacyDirectory directory;
    private final PasswordEncoder passwordEncoder;

    public LegacyDirectoryAuthProvider(LegacyDirectory directory, PasswordEncoder passwordEncoder) {
        this.directory = directory;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String rawPassword = authentication.getCredentials().toString();

        LegacyUser user;
        try {
            user = directory.find(username).orElse(null);
        } catch (DirectoryUnavailableException ex) {
            // A system failure, not a credentials failure.
            throw new AuthenticationServiceException("Legacy directory unavailable", ex);
        }

        if (user == null) {
            return null; // not my user: let the next provider decide
        }
        if (user.locked()) {
            throw new LockedException("Account locked");
        }
        if (!passwordEncoder.matches(rawPassword, user.passwordHash())) {
            throw new BadCredentialsException("Invalid credentials provided");
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        user.roles().forEach(role -> authorities.add(new SimpleGrantedAuthority(role)));
        authorities.add(FactorGrantedAuthority.fromAuthority(FactorGrantedAuthority.PASSWORD_AUTHORITY));
        return UsernamePasswordAuthenticationToken.authenticated(username, null, authorities);
    }

    @Override
    public boolean supports(Class<?> authenticationType) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authenticationType);
    }
}
