package com.bcxin.ars.rest.util;

import com.bcxin.ars.model.User;
import com.bcxin.ars.rest.shiro.CustomCredentialsMatcher;
import com.bcxin.ars.service.PermissionService;
import com.bcxin.ars.service.SecurityCompanyService;
import com.bcxin.ars.service.SecurityPersonService;
import com.bcxin.ars.service.UserService;
import com.bcxin.ars.util.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;

public class ArsRealm extends AuthorizingRealm {
	
	@Autowired
	private UserService userService;
	@Override
	public void setName(String name) {
		super.setName("ARS Realm");
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
        String host = ((UsernamePasswordToken) token).getHost();
        //平台角色
        String platform  = "";
        User user =  null  ;
		if(Constants.SaaSCode.equals(host)){//saas对接公司
			user = userService.findByComId(Long.parseLong(username));
        }else {
			user = userService.findByUsername(username, platform);
		}
		if(user == null) {
			return null;
		}
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
        return simpleAuthenticationInfo;  
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//		User user =  (User) principal.getPrimaryPrincipal();
//		Role role = user.getRole();
//		if(role != null) {
//			List<Permission> list = permissionService.findByRole(role.getId(),"1",Constants.MODULE_BA);
//			for(Permission p : list) {
//				simpleAuthorizationInfo.addStringPermission(p.getPermissionCode());
//			}
//		}
		return simpleAuthorizationInfo;
	}
	
	//清除缓存  
    public void clearCached() {  
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();  
        super.clearCache(principals);  
    }

    /** 
     * 设定Password校验. 
     */  
    @PostConstruct  
    public void initCredentialsMatcher() {  
    	//该句作用是重写shiro的密码验证，让shiro用我自己的验证  
        setCredentialsMatcher(new CustomCredentialsMatcher());  
  
    }  
}
