package com.izouma.awesomeadmin.interceptor;

import com.izouma.awesomeadmin.shiro.AppToken;
import com.izouma.awesomeadmin.util.PropertiesFileLoader;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Base64;
import java.util.Date;

/**
 * Created by xiong on 2017/6/16.
 */
public class GlobalInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Subject subject = SecurityUtils.getSubject();
//        if (!request.getRequestURI().startsWith("/auth/") && !subject.isAuthenticated() && !request.getRequestURI().startsWith("/admin")) {
//            try {
//                String token = request.getHeader("api_token");
//                SecretKey key = Keys.hmacShaKeyFor(Base64.getDecoder().decode(PropertiesFileLoader.getProperties("jwtsecret").getBytes()));
//                Jwt jwt = Jwts.parser()
//                        .setSigningKey(key)
//                        .parse(token);
//                Claims claims = (Claims) jwt.getBody();
//                if (claims.getExpiration() != null) {
//                    if (claims.getExpiration().before(new Date())) {
//                        response.setStatus(403);
//                        return false;
//                    }
//                }
//            } catch (Exception e) {
//                response.setStatus(403);
//                return false;
//            }
//        }

        if (!subject.isAuthenticated()) {
            String token = request.getHeader("token");
            if (StringUtils.isNotEmpty(token)) {
                AppToken appToken = new AppToken(token);
                try {
                    subject.login(appToken);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.addHeader("Access-Control-Allow-Methods", "*");
        response.addHeader("Access-Control-Max-Age", "100");
        response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, token");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        return super.preHandle(request, response, handler);
    }

}
