top.lionxxw.zuulservice.filter.BookingCarPreFilter.java Source code

Java tutorial

Introduction

Here is the source code for top.lionxxw.zuulservice.filter.BookingCarPreFilter.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package top.lionxxw.zuulservice.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import java.util.logging.Logger;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.DEBUG_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 *
 * @author darren.shuxing.liu
 * Zuulpre??filterType, filterOrder, run, shouldFilter
 */
@Component
public class BookingCarPreFilter extends ZuulFilter {
    /**
     *
     */
    protected static final Logger logger = Logger.getLogger(BookingCarPreFilter.class.getName());

    /**
     * 
     *pre?
     *routing
     *post ?
     *error??
     * @return String
     */
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return DEBUG_FILTER_ORDER;
    }

    /*
    *??
    */
    @Override
    public boolean shouldFilter() {
        //
        return true;
    }

    /*
    *
    */
    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        Object userid = request.getParameter("userid");
        if (userid == null) {
            logger.info("user id is null");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("user id cann't be null");
            } catch (Exception e) {
            }

            return null;
        }
        //??
        if (!auth(userid.toString())) {
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(402);
            try {
                ctx.getResponse().getWriter().write("User didn't pass authorization");
            } catch (Exception e) {
            }
            return null;
        }

        //??user idTokenZuul
        String accesstoken = encode(userid.toString());
        logger.info(String.format("pre routing, token = {%s}", accesstoken));
        ctx.addZuulRequestHeader("Authorization", accesstoken);

        logger.info("added token to zuul request");
        return null;
    }

    private String encode(String origin) {
        byte[] encodedBytes = Base64.getEncoder().encode(origin.getBytes());
        return new String(encodedBytes);
    }

    //??
    private boolean auth(String userid) {
        return true;
    }

}