package com.sonic.common.auth;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

/**
 * 为测试环境准备的dummy认证检查拦截器.
 * @author code
 */
@Slf4j
public class DummyAuthInterceptor implements HandlerInterceptor {

    private static final String AUTH_HEADER = "Authorization";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 对于dummy的token，携带的信息是明文传输的
        String authorization = request.getHeader(AUTH_HEADER);
        if (Strings.isNullOrEmpty(authorization)) {
            return true;
        }
        Token token = Token.from(authorization);
        AuthCaller authCaller = JSON.parseObject(token.getToken(), AuthCaller.class);
        request.setAttribute(AuthInterceptor.AUTH_PAYLOAD_KEY, authCaller);

        OriginalCaller caller;
        String originalCallerHeader = request.getHeader(AuthInterceptor.ORIGINAL_CALLER_HEADER_NAME);
        if (!Strings.isNullOrEmpty(originalCallerHeader)) {
            caller = JSONObject.parseObject(originalCallerHeader, OriginalCaller.class);
        } else {
            caller = OriginalCaller.fromAuthCaller(authCaller);
        }
        request.setAttribute(AuthInterceptor.CALLER_PAYLOAD_KEY, caller);
        return true;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @ToString
    private static class Token {
        private static final transient String DELIMITER = StringUtils.SPACE;

        private String type;

        private String token;

        public static Token from(String header) {
            return Token.builder()
                    .type(StringUtils.substringBefore(header, DELIMITER))
                    .token(StringUtils.substringAfter(header, DELIMITER))
                    .build();
        }
    }
}
