package com.ankurm.authdemo.mfa;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
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 java.util.ArrayList;
import java.util.List;

/** The MFA hook: keeps every authority the user already has and adds the one-time-token factor. */
public class OtpStepUpProvider implements AuthenticationProvider {

    private final OtpVerifier verifier;

    public OtpStepUpProvider(OtpVerifier verifier) {
        this.verifier = verifier;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        OtpAuthenticationToken otp = (OtpAuthenticationToken) authentication;
        Authentication current = otp.current();
        String username = current.getName();

        if (!verifier.verify(username, String.valueOf(otp.getCredentials()))) {
            throw new BadCredentialsException("Invalid one-time code");
        }

        List<GrantedAuthority> authorities = new ArrayList<>(current.getAuthorities());
        authorities.add(FactorGrantedAuthority.fromAuthority(FactorGrantedAuthority.OTT_AUTHORITY));
        return UsernamePasswordAuthenticationToken.authenticated(current.getPrincipal(), null, authorities);
    }

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