package com.nuliji.tools.shiro;

import com.alibaba.fastjson.JSON;
import com.nuliji.tools.Response;
import com.nuliji.tools.shiro.inter.HeaderTokenManager;
import com.nuliji.tools.shiro.inter.impl.RealmHeaderToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

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

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

    @Autowired
    private HeaderTokenManager tokenManager;

    public TokenFilter(HeaderTokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        logger.debug("tokenFilter: {}", ((HttpServletRequest)request).getRequestURI());
        HttpServletRequest req = (HttpServletRequest) request;
        return req.getHeader("token") != null;
    }

//    @Override
//    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
//        HttpServletRequest req = (HttpServletRequest) request;
//        String token = req.getHeader("token");
//        if (token == null || token.isEmpty()) {
//            return false;
//        }
//        return true;
//    }

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("token");
        // 获取无状态Token
        RealmHeaderToken realmHeaderToken = tokenManager.getToken(token);
        return realmHeaderToken;
    }
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
                                     ServletRequest request, ServletResponse response) {
        logger.error(e.getMessage());
        return false;
    }

    @Override
    protected boolean sendChallenge(ServletRequest request, ServletResponse response) {
        saveRequest(request);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
        response.setCharacterEncoding("UTF-8"); //避免乱码
        try {
            response.getWriter().write(JSON.toJSONString( new Response(101, "未授权访问", null)));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
        return false;
    }
}
