package com.ningdatech.carapi.user.security.auth.password;

import java.util.Collection;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;

/**
 * @Author LiuXinXin
 * @Date 2020/8/3 8:52 下午
 * @Version 1.0
 **/
public class UsernamePasswordAuthToken extends AbstractAuthenticationToken {

    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;

    private final Object principal;

    private final Object credentials;

    private final String verificationCode;

    /**
     * This constructor can be safely used by any code that wishes to create a
     * <code>UsernamePasswordAuthenticationToken</code>, as the {@link #isAuthenticated()} will return
     * <code>false</code>.
     */
    public UsernamePasswordAuthToken(String principal, String credentials, String verificationCode) {
        super(null);
        this.principal = principal;
        this.credentials = credentials;
        this.verificationCode = verificationCode;
        setAuthenticated(false);
    }

    public UsernamePasswordAuthToken(Object principal, Object credentials,
                                     Collection<? extends GrantedAuthority> authorities, String verificationCode) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        this.verificationCode = verificationCode;
        // must use super, as we override
        super.setAuthenticated(true);
    }

    public Object getCredentials() {
        return this.credentials;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    public String getVerificationCode() {
        return verificationCode;
    }


    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {
            throw new IllegalArgumentException(
                    "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }
        super.setAuthenticated(false);
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
    }

}
