// Path: src/main/java/cn/iflyapi/blog/util/JwtUtils.java
// public class JwtUtils {
// 
//     private final static Logger logger = LoggerFactory.getLogger(JwtUtils.class);
// 
//     //一个月
//     private static long EXPIRED_TIME = 60 * 60 * 24 * 30;
// 
//     private static String key = "secret";
// 
//     public static String getToken(Long userId, String nickName) throws Exception {
//         Map<String, Object> mapHeader = new HashMap<>(2);
//         mapHeader.put("alg", "HS256");
//         mapHeader.put("typ", "JWT");
//         long iat = System.currentTimeMillis();
//         long exp = iat + EXPIRED_TIME * 1000L;
//         return JWT.create()
//                 .withHeader(mapHeader)
//                 .withIssuedAt(new Date(iat))
//                 .withExpiresAt(new Date(exp))
//                 .withClaim("userId", String.valueOf(userId))
//                 .withClaim("nickName", nickName)
//                 .sign(Algorithm.HMAC256(key));
//     }
// 
//     public static Map<String, Claim> verify(String token) {
//         DecodedJWT jwt;
//         try {
//             JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key)).build();
//             jwt = verifier.verify(token);
//             Map<String, Claim> claims = jwt.getClaims();
//             return jwt.getClaims();
//         } catch (Exception ex) {
//             logger.error("verify jwt token failed, token={}", token, ex);
//             return null;
//         }
// 
//     }
// 
// 
// /*    public static void main(String[] args) {
//         Map<String, Object> map = new HashMap<>();
//         map.put("userName", "flyhero");
//         try {
//             String t = getToken(map);
//             Thread.sleep(10000);
//             verify(t);
//         } catch (InvalidClaimException e) {
//             System.out.println("InvalidClaimException");
//         } catch (SignatureVerificationException e) {
//             System.out.println("SignatureVerificationException");
//         } catch (Exception e) {
// 
//         }
//     }*/
// }


import cn.iflyapi.blog.util.JwtUtils;
import com.auth0.jwt.interfaces.Claim;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
package cn.iflyapi.blog.controller;



/**
 * author: flyhero
 * date: 2018-12-12 7:48 PM
 */
public abstract class BaseController {

    protected HttpServletRequest request;

    protected HttpServletResponse response;


    /**
     * ModelAttribute标注的方法会在Controller类的每个映射url的控制执行方法之前执行
     *
     * @param request
     * @param response
     */
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.response = response;
        this.request = request;
    }


    /**
     * 获取当前用户id
     *
     * @return
     */
    protected Long getUserId() {
        Map<String, Claim> map = getStringClaimMap();
        if (CollectionUtils.isEmpty(map) || null == map.get("userId")) {
            return null;
        }
        return Long.valueOf(map.get("userId").asString());
    }

    /**
     * 获取当前用户昵称
     *
     * @return
     */
    protected String getNickName() {
        Map<String, Claim> map = getStringClaimMap();
        if (CollectionUtils.isEmpty(map)  || null == map.get("nickName")) {
            return null;
        }
        return map.get("nickName").asString();
    }

    private Map<String, Claim> getStringClaimMap() {
        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token)) {
            return null;
        }
// Path: src/main/java/cn/iflyapi/blog/util/JwtUtils.java
// public class JwtUtils {
// 
//     private final static Logger logger = LoggerFactory.getLogger(JwtUtils.class);
// 
//     //一个月
//     private static long EXPIRED_TIME = 60 * 60 * 24 * 30;
// 
//     private static String key = "secret";
// 
//     public static String getToken(Long userId, String nickName) throws Exception {
//         Map<String, Object> mapHeader = new HashMap<>(2);
//         mapHeader.put("alg", "HS256");
//         mapHeader.put("typ", "JWT");
//         long iat = System.currentTimeMillis();
//         long exp = iat + EXPIRED_TIME * 1000L;
//         return JWT.create()
//                 .withHeader(mapHeader)
//                 .withIssuedAt(new Date(iat))
//                 .withExpiresAt(new Date(exp))
//                 .withClaim("userId", String.valueOf(userId))
//                 .withClaim("nickName", nickName)
//                 .sign(Algorithm.HMAC256(key));
//     }
// 
//     public static Map<String, Claim> verify(String token) {
//         DecodedJWT jwt;
//         try {
//             JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key)).build();
//             jwt = verifier.verify(token);
//             Map<String, Claim> claims = jwt.getClaims();
//             return jwt.getClaims();
//         } catch (Exception ex) {
//             logger.error("verify jwt token failed, token={}", token, ex);
//             return null;
//         }
// 
//     }
// 
// 
// /*    public static void main(String[] args) {
//         Map<String, Object> map = new HashMap<>();
//         map.put("userName", "flyhero");
//         try {
//             String t = getToken(map);
//             Thread.sleep(10000);
//             verify(t);
//         } catch (InvalidClaimException e) {
//             System.out.println("InvalidClaimException");
//         } catch (SignatureVerificationException e) {
//             System.out.println("SignatureVerificationException");
//         } catch (Exception e) {
// 
//         }
//     }*/
// }


// Path: src/main/java/cn/iflyapi/blog/controller/BaseController.java
import cn.iflyapi.blog.util.JwtUtils;
import com.auth0.jwt.interfaces.Claim;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

package cn.iflyapi.blog.controller;



/**
 * author: flyhero
 * date: 2018-12-12 7:48 PM
 */
public abstract class BaseController {

    protected HttpServletRequest request;

    protected HttpServletResponse response;


    /**
     * ModelAttribute标注的方法会在Controller类的每个映射url的控制执行方法之前执行
     *
     * @param request
     * @param response
     */
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.response = response;
        this.request = request;
    }


    /**
     * 获取当前用户id
     *
     * @return
     */
    protected Long getUserId() {
        Map<String, Claim> map = getStringClaimMap();
        if (CollectionUtils.isEmpty(map) || null == map.get("userId")) {
            return null;
        }
        return Long.valueOf(map.get("userId").asString());
    }

    /**
     * 获取当前用户昵称
     *
     * @return
     */
    protected String getNickName() {
        Map<String, Claim> map = getStringClaimMap();
        if (CollectionUtils.isEmpty(map)  || null == map.get("nickName")) {
            return null;
        }
        return map.get("nickName").asString();
    }

    private Map<String, Claim> getStringClaimMap() {
        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        return JwtUtils.verify(token);