package com.xingxi.api.configuration.security;

import com.xingxi.common.core.domain.entity.SysUser;
import com.xingxi.api.common.JWTUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

class JwtAuthenticationConverter implements AuthenticationConverter {
    public static final String AUTHENTICATION_SCHEME_BEARER = "Bearer";

    public JwtAuthenticationConverter() {
    }

    @Override
    public UsernamePasswordAuthenticationToken convert(HttpServletRequest request) {
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (header == null) {
            return null;
        }

        header = header.trim();
        if (!StringUtils.startsWithIgnoreCase(header, AUTHENTICATION_SCHEME_BEARER)) {
            return null;
        }

        if (header.equalsIgnoreCase(AUTHENTICATION_SCHEME_BEARER)) {
            throw new BadCredentialsException("Empty bearer authentication token");
        }

        String bearerToken = header.substring(7);
        SysUser sysUser = new SysUser();

        try {
            Jws<Claims> claimsJws = JWTUtils.parseJwt(bearerToken);
            Claims claimsJwsBody = claimsJws.getBody();
            String openid = claimsJwsBody.getSubject();
            Date issuedAt = claimsJwsBody.getIssuedAt();
            sysUser.setLoginDate(issuedAt);
            sysUser.setWxOpenId(openid);
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }

        return new UsernamePasswordAuthenticationToken(sysUser, "");
    }

}
