com.neusoft.mid.clwapi.interceptor.OauthTokenCheckInterceptor.java Source code

Java tutorial

Introduction

Here is the source code for com.neusoft.mid.clwapi.interceptor.OauthTokenCheckInterceptor.java

Source

/**
 * @(#)OauthTokenCheckInterceptor.java 2013-4-2
 *
 * Copyright 2013 Neusoft Group Ltd. All rights reserved.
 * Neusoft PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.neusoft.mid.clwapi.interceptor;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.ws.rs.core.Response;

import org.apache.commons.lang.StringUtils;
import org.apache.cxf.helpers.CastUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.neusoft.mid.clwapi.common.ErrorConstant;
import com.neusoft.mid.clwapi.common.ModCommonConstant;
import com.neusoft.mid.clwapi.common.UserInfoKey;
import com.neusoft.mid.clwapi.entity.oauth.MobileUsrAllInfo;
import com.neusoft.mid.clwapi.mapper.OauthMapper;
import com.neusoft.mid.clwapi.service.common.UsrOauthService;

/**
 * token?. token????token????.
 * token?,token??HTTP??Header??;
 * ??token?,???400HTTP?;
 * ?token???,???401HTTP?;
 * token?,??298HTTP?.
 * 
 * @author <a href="mailto:majch@neusoft.com">majch </a>
 * @version $Revision 1.0 $ 2013-4-2 ?4:25:18
 */
public class OauthTokenCheckInterceptor extends AbstractPhaseInterceptor<Message> {

    /**
     * .
     */
    private static Logger logger = LoggerFactory.getLogger(ModCommonConstant.LOGGER_NAME);

    private static final String ACCESS_TOKEN = "access_token";
    @Autowired
    private UsrOauthService usrOauthService;

    @Autowired
    private OauthMapper oauthMapper;

    /**
     * @param phase
     */
    public OauthTokenCheckInterceptor(final String phase) {
        super(phase);
    }

    public OauthTokenCheckInterceptor() {
        this(Phase.UNMARSHAL);
    }

    /**
     * token?.
     * 
     * @param message
     */
    @Override
    public void handleMessage(Message message) throws Fault {
        logger.info("???");
        String token = "";
        boolean isExistToken = false;
        Response response = null;
        Map<String, List<String>> reqHeaders = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS));
        if (reqHeaders != null) {
            for (Map.Entry<String, List<String>> e : reqHeaders.entrySet()) {
                if (ACCESS_TOKEN.equalsIgnoreCase(e.getKey())) {
                    token = e.getValue().get(0);
                    isExistToken = true;
                }
            }
        } else {
            logger.info("HTTP???HEADER?");
            response = Response.status(Response.Status.BAD_REQUEST).entity(ErrorConstant.ERROR10001.toJson())
                    .header("Content-Type", "application/json;charset=UTF-8").build();
        }
        if (!isExistToken || StringUtils.isEmpty(StringUtils.strip(token))) {
            logger.info("HTTP?HEADER??\"access_token\"?");
            response = Response.status(Response.Status.BAD_REQUEST).entity(ErrorConstant.ERROR20000.toJson())
                    .header("Content-Type", "application/json;charset=UTF-8").build();
        } else {
            logger.info("?access_token=" + token);
            if (checkToken(token)) {
                try {
                    MobileUsrAllInfo userInfo = usrOauthService.getMblUsrInfoByToken(token);

                    if (null == userInfo) {
                        logger.info("access_token?");
                        response = Response.status(Response.Status.UNAUTHORIZED)
                                .entity(ErrorConstant.ERROR20001.toJson())
                                .header("Content-Type", "application/json;charset=UTF-8").build();
                    } else {
                        if ("0".equals(userInfo.getIsMobileAllow())) {
                            logger.info("?ID[" + userInfo.getEnterpriseId()
                                    + "]?");
                            response = Response.status(297).entity(ErrorConstant.ERROR10107.toJson()).build();
                            oauthMapper.logoutUsrOauth(userInfo.getAccessToken(), userInfo.getUsrId());
                            logger.info("??");
                        } else if (userInfo.getValidSeconds() > 0) {
                            // token??HTTPHeader.
                            addUserInfo2HttpHeaderInfo(reqHeaders, userInfo);
                            message.put(Message.PROTOCOL_HEADERS, reqHeaders);
                        } else {
                            logger.info(
                                    "access_token?,?");
                            response = Response.status(298).build();
                        }
                    }
                } catch (Exception e) {
                    logger.error("?token??", e);
                    response = Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                            .entity(ErrorConstant.ERROR90000.toJson())
                            .header("Content-Type", "application/json;charset=UTF-8").build();
                }
            } else {
                logger.info("HTTP?HEADER\"access_token\"???");
                response = Response.status(Response.Status.BAD_REQUEST).entity(ErrorConstant.ERROR10002.toJson())
                        .header("Content-Type", "application/json;charset=UTF-8").build();
            }
        }
        message.getExchange().put(Response.class, response);
    }

    /**
     * token??HTTPHeader.
     * 
     * @param reqHeaders
     *            HTTPHeader?.
     * @param userInfo
     *            token??
     * @return ?HTTPHeader?.
     */
    private Map<String, List<String>> addUserInfo2HttpHeaderInfo(Map<String, List<String>> reqHeaders,
            MobileUsrAllInfo userInfo) {
        reqHeaders.put(UserInfoKey.USR_ID, Arrays.asList(userInfo.getUsrId()));
        logger.info("?HTTP Headerusr_id:" + userInfo.getUsrId());

        reqHeaders.put(UserInfoKey.ENTERPRISE_ID, Arrays.asList(userInfo.getEnterpriseId()));
        logger.info("?HTTP Headerenterprise_id:" + userInfo.getEnterpriseId());

        reqHeaders.put(UserInfoKey.ORGANIZATION_ID, Arrays.asList(userInfo.getOrganizationId()));
        logger.info("?HTTP Headerorganization_id:" + userInfo.getOrganizationId());

        reqHeaders.put(UserInfoKey.QUES_ETAG, Arrays.asList("" + userInfo.getUserQuesEtag()));
        logger.info("?HTTP Headerques_ETag:" + userInfo.getUserQuesEtag());

        reqHeaders.put(UserInfoKey.MSG_ETAG, Arrays.asList("" + userInfo.getUserMsgEtag()));
        logger.info("?HTTP Headermsg_ETag:" + userInfo.getUserMsgEtag());

        reqHeaders.put(UserInfoKey.TEMPLATE_ETAG, Arrays.asList(userInfo.getUserTemplateEtag()));
        logger.info("?HTTP Headertemplate_ETag:" + userInfo.getUserTemplateEtag());

        reqHeaders.put(UserInfoKey.RULE_ETAG, Arrays.asList(userInfo.getUserSendRuleEtag()));
        logger.info("?HTTP Headerrule_ETag:" + userInfo.getUserSendRuleEtag());

        reqHeaders.put(UserInfoKey.EN_RPT_DSC_ETAG, Arrays.asList(userInfo.getEntReportDscEtag()));
        logger.info("?HTTP Headeren_rpt_dsc_ETag:" + userInfo.getEntReportDscEtag());
        return reqHeaders;
    }

    /**
     * token???
     * 
     * @param token
     * @return
     */
    private boolean checkToken(String token) {
        if (token.length() != 16) {
            logger.info("access_token?:" + token.length() + "?");
            return false;
        } else {
            try {
                byte[] tokenByteArray = token.getBytes("UTF-8");
                // Validate the key
                for (byte b : tokenByteArray) {
                    if (b == ' ' || b == '\n' || b == '\r' || b == 0) {
                        logger.info("access_token???");
                        return false;
                    }
                }
            } catch (UnsupportedEncodingException e) {
                logger.error("tokenUTF-8?", e);
                return false;
            }
        }
        return true;
    }

}