package com.nuliji.tools.shiro;

import com.nuliji.tools.shiro.inter.impl.RealmUsernamePasswordToken;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Set;

/**
 * Created by GaoJie on 2017/11/3.
 */
public class DevelopFilter extends BasicHttpAuthenticationFilter {

    private static final Logger logger = LoggerFactory.getLogger(DevelopFilter.class);

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        if(!subject.isAuthenticated() && !subject.isRemembered()){
            logger.debug("not login");
            return false;
        }
        String[] rolesArray = (String[])((String[])mappedValue);
        if(rolesArray != null && rolesArray.length != 0) {
//            subject.getPrincipals();
            Set<String> roles = CollectionUtils.asSet(rolesArray);
            for(String role: roles){
                if(subject.hasRole(role)) return true;
                logger.debug("not {}", role);
            }
        }
        return false;
    }

    @Override
    protected AuthenticationToken createToken(String username, String password, boolean rememberMe, String host) {
        RealmUsernamePasswordToken token = new RealmUsernamePasswordToken(username, password, DevelopRealm.class);
        token.setHost(host);
        token.setRememberMe(rememberMe);

        return token;
    }
}
