package com.steerinfo.auth.utils;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.steerinfo.framework.constant.ShiroConstant;
import com.steerinfo.framework.utils.jwt.JwtUtils;

import io.jsonwebtoken.Claims;

public class JwtUtil {
	/**
	 * 读取JWT的header信息中的userid
	 * @return
	 */
	public static String getUseridByToken() {
		if (RequestContextHolder.getRequestAttributes() == null){
			return "-";
		}
	    try{
	    	HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
			String jwt = request.getHeader(ShiroConstant.HEADERS_AUTHORIZATION);
		    if (jwt == null) {
		      return "-";
		    }
	    	String token = jwt.replaceFirst(ShiroConstant.AUTH_BEARER_START, "");
		    Claims claims = JwtUtils.parseJWT(token);
		    if ((claims.containsKey("exp")) && (claims.containsKey("sub"))) {
		    	String json = (String)claims.get("sub");
		    	JSONObject jo = JSONObject.parseObject(json);
		    	//jo-{"workDate":"2020-03-06 10:21","orgCode":"110100","id":"admin","userName":"admin","userCode":"admin"}
		    	return jo.getString("userName");
		    }
	    }catch(Exception e){
	    	return "-";
	    }
		return "-";
	}
}
