NaverLogin.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. package com.style24.front.biz.thirdparty;
  2. import com.gagaframework.web.parameter.GagaMap;
  3. import com.gagaframework.web.util.GagaFileUtil;
  4. import com.google.gson.Gson;
  5. import com.google.gson.GsonBuilder;
  6. import com.google.gson.JsonObject;
  7. import com.style24.core.support.env.TscConstants;
  8. import com.style24.front.support.security.session.TsfSession;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.apache.commons.lang3.StringUtils;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.beans.factory.annotation.Value;
  13. import org.springframework.core.env.Environment;
  14. import org.springframework.http.HttpEntity;
  15. import org.springframework.http.HttpHeaders;
  16. import org.springframework.http.MediaType;
  17. import org.springframework.http.ResponseEntity;
  18. import org.springframework.stereotype.Component;
  19. import org.springframework.util.LinkedMultiValueMap;
  20. import org.springframework.util.MultiValueMap;
  21. import org.springframework.web.client.RestTemplate;
  22. import javax.annotation.PostConstruct;
  23. import java.net.URI;
  24. /**
  25. * 네이버 로그인
  26. *
  27. * @author jsshin
  28. * @since 2021. 02. 05
  29. */
  30. @Component
  31. @Slf4j
  32. public class NaverLogin {
  33. @Autowired
  34. private Environment env;
  35. @Autowired
  36. private RestTemplate restTemplate;
  37. @Value("${has-ssl}")
  38. private String hasSsl;
  39. private String callBackUrl;
  40. private String clientId;
  41. private String clientSecret;
  42. private String profiles;
  43. private String tokenUrl;
  44. private String userInfoUrl;
  45. private String authorizeUrl;
  46. private String protocal;
  47. @PostConstruct
  48. public void init() {
  49. callBackUrl = env.getProperty("naver.login.callbackUrl");
  50. clientId = env.getProperty("naver.clientId");
  51. clientSecret = env.getProperty("naver.clientSecret");
  52. profiles = env.getProperty("spring.profiles.active").toLowerCase();
  53. tokenUrl = env.getProperty("naver.tokenUrl");
  54. userInfoUrl = env.getProperty("naver.userInfoUrl");
  55. authorizeUrl = env.getProperty("naver.authorizeUrl");
  56. boolean isSslServer = Boolean.parseBoolean(hasSsl);
  57. if (isSslServer) {
  58. protocal = "https://";
  59. } else {
  60. protocal = "http://";
  61. }
  62. log.debug("\n\n---- Naver initialization started ----");
  63. log.debug("callBackUrl: [{}]", callBackUrl);
  64. log.debug("clientId: [{}]", clientId);
  65. log.debug("clientSecret: [{}]", clientSecret);
  66. log.debug("profiles: [{}]", profiles);
  67. log.debug("tokenUrl: [{}]", tokenUrl);
  68. log.debug("userInfoUrl: [{}]", userInfoUrl);
  69. log.debug("authorizeUrl: [{}]", authorizeUrl);
  70. log.debug("\n--- Naver initialization completed ----\n");
  71. }
  72. public String getAuthorizeUrl(String state) {
  73. StringBuilder apiUrlBuilder = new StringBuilder();
  74. String redirectUri = GagaFileUtil.getConcatenationPath(protocal + TsfSession.getHttpServletRequest().getServerName(), callBackUrl);
  75. apiUrlBuilder.append(authorizeUrl)
  76. .append("?response_type=code&client_id=")
  77. .append(clientId)
  78. .append("&redirect_uri=")
  79. .append(redirectUri)
  80. .append("&state=")
  81. .append(state);
  82. log.info("apiUrlBuilder ===> {}", apiUrlBuilder.toString());
  83. return apiUrlBuilder.toString();
  84. }
  85. public GagaMap getAccessTocken(String code, String state) {
  86. GagaMap resultMap = new GagaMap();
  87. String requestGb = "";
  88. try {
  89. MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
  90. params.add("grant_type", "authorization_code");
  91. params.add("client_id", clientId);
  92. params.add("client_secret", clientSecret);
  93. params.add("code", code);
  94. params.add("state", state);
  95. // state 값에 리다이렉트 url 같이 넘겨줌
  96. if (StringUtils.isNotBlank(state)) {
  97. String[] stateArr = StringUtils.split(state, "!@!");
  98. requestGb = stateArr[1];
  99. }
  100. // Header
  101. HttpHeaders headers = new HttpHeaders();
  102. headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
  103. HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
  104. URI url = URI.create(tokenUrl);
  105. // POST방식으로 호출
  106. ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
  107. log.info("getAccessTocken responseEntity.getStatusCode(): {} ", responseEntity.getStatusCode());
  108. String jsonResult = responseEntity.getBody();
  109. log.info("getAccessTocken responseEntity.getBody(): {} ", jsonResult);
  110. Gson gson = new GsonBuilder().create();
  111. JsonObject obj = gson.fromJson(jsonResult, JsonObject.class);
  112. resultMap.setString("access_token", obj.get("access_token").toString());
  113. resultMap.setString("refresh_token", obj.get("refresh_token").toString());
  114. resultMap.setString("requestGb", requestGb);
  115. } catch (Exception e) {
  116. log.error(e.getMessage());
  117. }
  118. return resultMap;
  119. }
  120. public GagaMap getNaverUserInfo(String accessToken) {
  121. GagaMap resultMap = new GagaMap();
  122. try {
  123. MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
  124. // Header
  125. HttpHeaders headers = new HttpHeaders();
  126. headers.set("Authorization", "Bearer " + accessToken);
  127. headers.add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
  128. HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params, headers);
  129. URI url = URI.create(userInfoUrl);
  130. // POST방식으로 호출
  131. ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
  132. log.info("getNaverUserInfo responseEntity.getStatusCode(): {} ", responseEntity.getStatusCode());
  133. String jsonResult = responseEntity.getBody();
  134. log.info("getNaverUserInfo responseEntity.getBody(): {} ", jsonResult);
  135. Gson gson = new GsonBuilder().create();
  136. JsonObject obj = gson.fromJson(jsonResult, JsonObject.class);
  137. GagaMap response = gson.fromJson(obj.get("response"), GagaMap.class);
  138. String snsId = response.getString("id");
  139. String custNm = this.uniCodeDeCode(response.getString("name"));
  140. String email = response.getString("email");
  141. String cellphnno = response.getString("mobile");
  142. String birthYmd = response.getString("birthyear") + response.getString("birthday").replaceAll("-","");
  143. String sexGb = response.getString("gender").equals("M")? TscConstants.Gender.MALE.value() : TscConstants.Gender.FEMALE.value();
  144. String ci = this.requestReplace(response.getString("ci"),"encodeData");
  145. resultMap.setString("snsId", snsId);
  146. resultMap.setString("custNm", custNm);
  147. resultMap.setString("email", email);
  148. resultMap.setString("ci", ci);
  149. resultMap.setString("cellPhnno", cellphnno);
  150. resultMap.setString("birthYmd", birthYmd);
  151. resultMap.setString("sexGb", sexGb);
  152. } catch (Exception e) {
  153. log.error(e.getMessage());
  154. }
  155. return resultMap;
  156. }
  157. public GagaMap getRefreshTocken(String refreshToken) {
  158. GagaMap resultMap = new GagaMap();
  159. try {
  160. MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
  161. params.add("grant_type", "refresh_token");
  162. params.add("client_id", clientId);
  163. params.add("client_secret", clientSecret);
  164. params.add("refresh_token", refreshToken);
  165. // Header
  166. HttpHeaders headers = new HttpHeaders();
  167. headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
  168. HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
  169. URI url = URI.create(tokenUrl);
  170. // POST방식으로 호출
  171. ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
  172. log.info("getRefreshTocken responseEntity.getStatusCode(): {} ", responseEntity.getStatusCode());
  173. String jsonResult = responseEntity.getBody();
  174. log.info("getRefreshTocken responseEntity.getBody(): {} ", jsonResult);
  175. Gson gson = new GsonBuilder().create();
  176. JsonObject obj = gson.fromJson(jsonResult, JsonObject.class);
  177. resultMap.setString("access_token", obj.get("access_token").toString());
  178. } catch (Exception e) {
  179. log.error(e.getMessage());
  180. }
  181. return resultMap;
  182. }
  183. public GagaMap saveUnlink(String accessToken) {
  184. GagaMap resultMap = new GagaMap();
  185. try {
  186. MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
  187. params.add("grant_type", "delete");
  188. params.add("client_id", clientId);
  189. params.add("client_secret", clientSecret);
  190. params.add("access_token", accessToken);
  191. params.add("service_provider", "NAVER");
  192. // Header
  193. HttpHeaders headers = new HttpHeaders();
  194. headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
  195. HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
  196. URI url = URI.create(tokenUrl);
  197. // POST방식으로 호출
  198. ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
  199. log.info("saveUnlink : responseEntity.getStatusCode(): {} ", responseEntity.getStatusCode());
  200. String jsonResult = responseEntity.getBody();
  201. log.info("saveUnlink : responseEntity.getBody(): {} ", jsonResult);
  202. Gson gson = new GsonBuilder().create();
  203. JsonObject obj = gson.fromJson(jsonResult, JsonObject.class);
  204. resultMap.setString("access_token", obj.get("access_token").toString());
  205. resultMap.setString("result", obj.get("result").toString());
  206. } catch (Exception e) {
  207. log.error(e.getMessage());
  208. }
  209. return resultMap;
  210. }
  211. public String requestReplace (String paramValue, String gubun) {
  212. String result = "";
  213. if (paramValue != null) {
  214. paramValue = paramValue.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
  215. paramValue = paramValue.replaceAll("\\*", "");
  216. paramValue = paramValue.replaceAll("\\?", "");
  217. paramValue = paramValue.replaceAll("\\[", "");
  218. paramValue = paramValue.replaceAll("\\{", "");
  219. paramValue = paramValue.replaceAll("\\(", "");
  220. paramValue = paramValue.replaceAll("\\)", "");
  221. paramValue = paramValue.replaceAll("\\^", "");
  222. paramValue = paramValue.replaceAll("\\$", "");
  223. paramValue = paramValue.replaceAll("'", "");
  224. paramValue = paramValue.replaceAll("@", "");
  225. paramValue = paramValue.replaceAll("%", "");
  226. paramValue = paramValue.replaceAll(";", "");
  227. paramValue = paramValue.replaceAll(":", "");
  228. paramValue = paramValue.replaceAll("-", "");
  229. paramValue = paramValue.replaceAll("#", "");
  230. paramValue = paramValue.replaceAll("--", "");
  231. paramValue = paramValue.replaceAll("-", "");
  232. paramValue = paramValue.replaceAll(",", "");
  233. if(!"encodeData".equals(gubun)){
  234. paramValue = paramValue.replaceAll("\\+", "");
  235. paramValue = paramValue.replaceAll("/", "");
  236. paramValue = paramValue.replaceAll("=", "");
  237. }
  238. result = paramValue;
  239. }
  240. return result;
  241. }
  242. public String uniCodeDeCode(String unicode) {
  243. if (StringUtils.isBlank(unicode)) {
  244. return "";
  245. }
  246. StringBuffer str = new StringBuffer();
  247. char ch = 0;
  248. for( int i= unicode.indexOf("\\u"); i > -1; i = unicode.indexOf("\\u") ){
  249. ch = (char)Integer.parseInt( unicode.substring( i + 2, i + 6 ) ,16);
  250. str.append( unicode.substring(0, i) );
  251. str.append( String.valueOf(ch) );
  252. unicode = unicode.substring(i + 6);
  253. }
  254. str.append(unicode);
  255. return str.toString();
  256. }
  257. }