Guest User

Untitled

a guest
Jan 18th, 2019
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.33 KB | None | 0 0
  1. package com.tecnics.proxy.controllers;
  2.  
  3. import com.tecnics.proxy.filters.FilterUtils;
  4. import com.tecnics.proxy.models.MFA;
  5. import com.tecnics.proxy.models.User;
  6. import com.tecnics.proxy.service.*;
  7. import com.tecnics.proxy.utils.Constants;
  8. import com.tecnics.proxy.utils.HttpUtils;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.beans.factory.annotation.Value;
  13. import org.springframework.core.io.ClassPathResource;
  14. import org.springframework.http.*;
  15. import org.springframework.stereotype.Controller;
  16. import org.springframework.ui.Model;
  17. import org.springframework.util.StreamUtils;
  18. import org.springframework.validation.BindingResult;
  19. import org.springframework.web.bind.annotation.*;
  20.  
  21. import javax.servlet.http.Cookie;
  22. import javax.servlet.http.HttpServletRequest;
  23. import javax.servlet.http.HttpServletResponse;
  24. import javax.servlet.http.HttpSession;
  25. import javax.validation.Valid;
  26. import java.io.IOException;
  27. import java.util.List;
  28. import java.util.Map;
  29.  
  30. /**
  31. * Created by tecnicsdev on 2/7/18.
  32. */
  33.  
  34. @Controller
  35. public class LoginController {
  36.  
  37. private Logger logger = LoggerFactory.getLogger(LoginController.class);
  38.  
  39. LoginService loginService;
  40. ProxyServer proxyServer;
  41. FilterUtils filterUtils;
  42. CacheService cacheService;
  43. DataServices dataServices;
  44. HttpServletRequest request;
  45.  
  46. @Value("${okta-redirect-url}")
  47. String oktaRedirectUrl;
  48. @Value("${okta-cookie-name}")
  49. String oktaCookieName;
  50. @Value("${server.servlet.context-path}")
  51. String proxyServerContextPath;
  52. @Value("${resourceServerLandingPage}")
  53. String resourceServerLandingPage;
  54. @Value("${login-page}")
  55. String loginPage;
  56.  
  57. String redirect="redirect:";
  58.  
  59. @Autowired
  60. LoginController(LoginService loginService, ProxyServer proxyServer, FilterUtils filterUtils,
  61. CacheService cacheService, DataServices dataServices, HttpServletRequest request){
  62. this.loginService=loginService;
  63. this.proxyServer=proxyServer;
  64. this.filterUtils=filterUtils;
  65. this.cacheService=cacheService;
  66. this.dataServices=dataServices;
  67. this.request=request;
  68. }
  69.  
  70. @GetMapping(value = "${login-page}")
  71. public String loginOkta(Model model, HttpServletResponse response){
  72. removeCookies(response);
  73. prepareLoginModel(model, null, null);
  74. return "signin";
  75. }
  76.  
  77. void prepareLoginModel(Model model, String errorMsg, String successMsg){
  78. List<Map<String, String>> institutionList = cacheService.getInstitutions();
  79.  
  80. model.addAttribute("user", new User());
  81. model.addAttribute("institutionList", institutionList);
  82. model.addAttribute("error", errorMsg);
  83. model.addAttribute("success", successMsg);
  84. }
  85.  
  86. @PostMapping(value = "${login-page}")
  87. public String login(@ModelAttribute @Valid User user, BindingResult result, Model model){
  88. if(result.hasErrors()){
  89. prepareLoginModel(model, "Invalid data submitted", null);
  90. return "signin";
  91. }
  92. logger.debug("login initiated");
  93. HttpSession session = request.getSession(true);
  94. String username=HttpUtils.buildUsername(user);
  95. int institutionId = user.getInstitutionId();
  96. String password = user.getPassword();
  97. user.setUsername(username);
  98. session.setAttribute("username", username);
  99. session.setAttribute("institutionId", institutionId);
  100. session.setAttribute("password", password);
  101. return processLogin(user, "sso", model);
  102. }
  103.  
  104.  
  105. String processLogin(User user, String loginType, Model model){
  106. Map<String, Object> authMap= loginService.login(user, loginType);
  107. if(authMap!=null){
  108. String status = (String) authMap.get("status");
  109. if(status.equals(Constants.SUCCESS)){
  110. String redirectUrl =(String) authMap.get("redirectUrl");
  111. String nonce =(String) authMap.get("nonce");
  112. HttpUtils.storeNonceInSession(request, nonce);
  113. ResponseEntity<String> responseEntity = loginService.executeRedirectUri(redirectUrl, null);
  114. HttpHeaders headers = responseEntity.getHeaders();
  115. Map<String, String> paramMap = loginService.parseCodeAndStateFromHeaders(headers);
  116. if(paramMap!=null){
  117. String code=paramMap.get("code");
  118. String state=paramMap.get("state");
  119. return String.format("%s%s?code=%s&state=%s", redirect, oktaRedirectUrl, code, state);
  120. }
  121. return redirect+loginPage;
  122. }else if(status.equals(Constants.MFAREQUIRED)){
  123. List<Map<String, String>> factors = (List<Map<String, String>>) authMap.get(Constants.FACTORS);
  124. model.addAttribute(Constants.FACTORS, factors);
  125. model.addAttribute("contextPath", proxyServerContextPath);
  126. model.addAttribute("mfa", new MFA());
  127. return "verifyFactor";
  128. }else if(status.equals(Constants.LOCKEDOUT)){
  129. prepareLoginModel(model, "Your account is locked. Please contact your Administrator.", null);
  130. dataServices.postSecurityEvent(user.getUsername(), user.getInstitutionId(), Constants.LOGINEVENT, Constants.LOCKOUTERRMSG, Constants.FAILED);
  131. HttpUtils.invalidateSession(request);
  132. return loginPage;
  133. }else if(status.equals(Constants.MFAENROLL)){
  134. List<Map<String, String>> factors = (List<Map<String, String>>) authMap.get(Constants.FACTORS);
  135. model.addAttribute(Constants.FACTORS, factors);
  136. model.addAttribute("contextPath", proxyServerContextPath);
  137. return "factorSetup";
  138. }else if(status.equals(Constants.PASSWORD_EXPIRED)){
  139. String stateToken = (String) authMap.get(Constants.STATETOKEN);
  140. model.addAttribute(Constants.STATETOKEN, stateToken);
  141. model.addAttribute("logintype", loginType);
  142. return "passwordExpired";
  143. }else {
  144. dataServices.postSecurityEvent(user.getUsername(), user.getInstitutionId(), Constants.LOGINEVENT, Constants.ERRORLOGINMSG, Constants.FAILED);
  145. HttpUtils.invalidateSession(request);
  146. prepareLoginModel(model, "Your credentials are incorrect. Please re-enter your information.", null);
  147. return loginPage;
  148. }
  149. }else {
  150. dataServices.postSecurityEvent(user.getUsername(), user.getInstitutionId(), Constants.LOGINEVENT, Constants.ERRORLOGINMSG, Constants.FAILED);
  151. HttpUtils.invalidateSession(request);
  152. prepareLoginModel(model, "Your credentials are incorrect. Please re-enter your information.", null);
  153. return loginPage;
  154. }
  155. }
  156.  
  157. @GetMapping(value = "authorization-code/callback")
  158. public void redirectCallback(@RequestParam("code") String code, @RequestParam("state") String state,
  159. HttpServletResponse response, HttpServletRequest request) throws IOException {
  160. HttpSession session = request.getSession();
  161. String username= (String) session.getAttribute("username");
  162. int institutionId= (int) session.getAttribute("institutionId");
  163.  
  164. String accessToken = loginService.exchangeCode(code);
  165. if(username!=null && institutionId !=0){
  166. dataServices.postSecurityEvent(username, institutionId, Constants.LOGINEVENT, Constants.SUCCESSLOGINMSG, Constants.SUCCESS);
  167. HttpUtils.invalidateSession(request);
  168. }
  169. response=filterUtils.removeTokenCookies(request, response);
  170. if(accessToken!=null){
  171. Cookie cookie = new Cookie(oktaCookieName, accessToken);
  172. cookie.setPath(proxyServerContextPath);
  173. response.addCookie(cookie);
  174. if(state.equals("sso")){
  175. loginService.executeSSOCall(accessToken);
  176. }else {
  177. response.sendRedirect(proxyServerContextPath + resourceServerLandingPage);
  178. }
  179. }else {
  180. response.sendRedirect(proxyServerContextPath + loginPage);
  181. }
  182. }
  183.  
  184. @GetMapping(value = "logo/{imageName}", produces = MediaType.IMAGE_PNG_VALUE)
  185. public ResponseEntity<byte[]> loadimage(@PathVariable("imageName") String imageName) throws IOException {
  186. ClassPathResource imgFile = new ClassPathResource("static/" + imageName + ".png");
  187. byte[] bytes = StreamUtils.copyToByteArray(imgFile.getInputStream());
  188.  
  189. return ResponseEntity
  190. .ok()
  191. .contentType(MediaType.IMAGE_PNG)
  192. .body(bytes);
  193. }
  194.  
  195. @ResponseBody
  196. @GetMapping(value = "logout")
  197. public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
  198. removeCookies(response);
  199. response.sendRedirect(proxyServerContextPath + loginPage);
  200. }
  201.  
  202.  
  203. @GetMapping(value = "**/resource/{fileName}", produces = {"text/javascript", "text/css"})
  204. public ResponseEntity<byte[]> loadStaticJsFile(@PathVariable("fileName") String fileName) throws IOException {
  205. byte[] bytes = null;
  206. if(fileName.endsWith(".js")){
  207. ClassPathResource imgFile = new ClassPathResource("static/public/js/" + fileName);
  208. bytes = StreamUtils.copyToByteArray(imgFile.getInputStream());
  209. } else if(fileName.endsWith(".css")){
  210. ClassPathResource imgFile = new ClassPathResource("static/public/css/" + fileName);
  211. bytes = StreamUtils.copyToByteArray(imgFile.getInputStream());
  212. }
  213. return ResponseEntity
  214. .ok()
  215. .body(bytes);
  216. }
  217.  
  218. void removeCookies(HttpServletResponse response){
  219. Cookie[] cookies = request.getCookies();
  220. if(cookies!=null && cookies.length>0){
  221. for (Cookie cookie:cookies) {
  222. String cookieName = cookie.getName();
  223. String cookieValue = cookie.getValue();
  224. if(cookieName.equals(oktaCookieName)){
  225. cacheService.removeTokens(cookieValue);
  226. }
  227. }
  228. filterUtils.removeTokenCookies(request, response);
  229. }
  230. }
  231. }
Add Comment
Please, Sign In to add comment