package com.xmomen.module.core.web.mgt;

import com.xmomen.module.account.service.UserService;
import com.xmomen.module.base.constant.AppConstants;
import com.xmomen.module.base.entity.CdMember;
import com.xmomen.module.base.service.MemberService;
import com.xmomen.module.user.entity.SysUsers;

import org.apache.shiro.authc.Authenticator;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.SubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;


public class WebSecurityManagerExt extends DefaultWebSecurityManager {

    @Autowired
    UserService userService;

    @Autowired
    MemberService memberService;

    //重写doCreateSubject方法，用于创建Subject对象
    protected Subject doCreateSubject(SubjectContext context) {
    	//创建Subject对象
    	Subject subject = this.getSubjectFactory().createSubject(context);
        //获取Subject对象中的用户名
        String username = (String) subject.getPrincipal();
        //如果用户名不为空
        if(username != null){
        	//后端用户数据源
            SysUsers sysUsers = userService.findByUsername(username);
            //如果后端用户数据源不为空
            if(sysUsers !=null && sysUsers.getId() != null){
                //将后端用户ID存入Session中
                subject.getSession().setAttribute(AppConstants.SESSION_USER_ID_KEY, sysUsers.getId());
            } else {
            	//前端用户数据源
            	CdMember memberQuery = new CdMember();
            	memberQuery.setPhoneNumber(username);
            	//前端用户数据源
            	CdMember member = memberService.findMember(memberQuery);
            	//如果前端用户数据源不为空
            	if(member != null && member.getId() != null) {
            		//将前端用户ID存入Session中
            		subject.getSession().setAttribute(AppConstants.SESSION_USER_ID_KEY, member.getId());
            	}
            }
        }
        //返回Subject对象
        return subject;
    }

    //重写setAuthenticator方法，用于设置Authenticator
    @Override
	public void setAuthenticator(Authenticator authenticator) throws IllegalArgumentException {
		//调用父类方法
		super.setAuthenticator(authenticator);
		//如果Authenticator是ModularRealmAuthenticator类型
		if (authenticator instanceof ModularRealmAuthenticator) {
            //设置Realms
            ((ModularRealmAuthenticator) authenticator).setRealms(getRealms());
        }
	}
}
