package com.iformall.shiro;

import com.iformall.common.ErrorCode;
import com.iformall.domain.po.MallUserInfo;
import com.iformall.enums.EnumLoginType;
import com.iformall.enums.EnumMallUserStatus;
import com.iformall.service.MallUserInfoService;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class MyRetryLimitCredentialsMatcher extends HashedCredentialsMatcher {
    @Resource
    private MallUserInfoService userService;

    @Override
    public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) {
        if(authcToken instanceof UseriFormallToken) {
            UseriFormallToken tk = (UseriFormallToken) authcToken;
            if(tk.getType().equals(EnumLoginType.NOPASSWD)){
                // 获取用户的输入的账号.
                String username = (String)tk.getPrincipal();
                MallUserInfo user = userService.getByUsername(username);
                if(user == null) {
                    throw new UnknownAccountException(ErrorCode.USER_IS_EMPTY.getMessage());
                }
                // 用户被禁用
                if(user.getStatus()==null ||!EnumMallUserStatus.VALID.getCode().equals(user.getStatus())) {
                    throw new DisabledAccountException(ErrorCode.USER_IS_LOCKED.getMessage());
                }
                return true;
            }
            boolean matches = super.doCredentialsMatch(authcToken, info);
            return matches;
        }
        boolean matches =super.doCredentialsMatch(authcToken, info);
        return matches;
    }
}
