Index: mediator-service/branches/DS-801_JSON_Login/src/java/com/lemanscorp/mediation/LemansTokenBasedRememberMeServices.java =================================================================== diff -u -r8645 -r8649 --- mediator-service/branches/DS-801_JSON_Login/src/java/com/lemanscorp/mediation/LemansTokenBasedRememberMeServices.java (.../LemansTokenBasedRememberMeServices.java) (revision 8645) +++ mediator-service/branches/DS-801_JSON_Login/src/java/com/lemanscorp/mediation/LemansTokenBasedRememberMeServices.java (.../LemansTokenBasedRememberMeServices.java) (revision 8649) @@ -10,11 +10,11 @@ import java.util.Locale; import java.util.Map; import java.util.TimeZone; - import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +import com.lemanscorp.MediationUserDetailsService; +import com.lemanscorp.mediation.utils.MediatorSecurityHelperService; import org.apache.commons.codec.binary.Base64; import org.springframework.security.authentication.LockedException; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; @@ -23,7 +23,6 @@ import org.springframework.security.web.authentication.rememberme.InvalidCookieException; import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices; import org.springframework.util.StringUtils; - import com.lemanscorp.MediationUserDetails; import com.lemanscorp.mediation.utils.MediationUtilService; import com.lemanscorp.mediation.utils.SecrtekeyHelperService; @@ -47,158 +46,158 @@ @Override protected boolean isTokenExpired(long tokenExpiryTime) { - return tokenExpiryTime + (tokenValidityAdditionalGracePeriodSeconds * 1000L) < System.currentTimeMillis() ; - } + return tokenExpiryTime + (tokenValidityAdditionalGracePeriodSeconds * 1000L) < System.currentTimeMillis() ; + } //@Override - protected String makeTokenSignature(long tokenExpiryTime, String username, String password, String dealerCode, String domainid, int userId) { - String data = username //0 - + ":" + dealerCode //1 - + ":" + domainid //2 - + ":" + tokenExpiryTime //3 - + ":" + password //4 - + ":" + getKey() //5 - + ":" + userId; //6 - return shaPasswordEncoder.encodePassword(data, null); + protected String makeTokenSignature(long tokenExpiryTime, String username, String password, String dealerCode, String domainid, int userId) { + String data = username //0 + + ":" + dealerCode //1 + + ":" + domainid //2 + + ":" + tokenExpiryTime //3 + + ":" + password //4 + + ":" + getKey() //5 + + ":" + userId; //6 + return shaPasswordEncoder.encodePassword(data, null); } @Override - protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) { + protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) { - if (cookieTokens.length != 6) { - throw new InvalidCookieException("Cookie token did not contain 6" + - " tokens, but contained '" + Arrays.asList(cookieTokens) + "'"); - } + if (cookieTokens.length != 6) { + throw new InvalidCookieException("Cookie token did not contain 6" + + " tokens, but contained '" + Arrays.asList(cookieTokens) + "'"); + } - long tokenExpiryTime; + long tokenExpiryTime; - try { - tokenExpiryTime = new Long(cookieTokens[1]).longValue(); - } - catch (NumberFormatException nfe) { - throw new InvalidCookieException("Cookie token[1] did not contain a valid number (contained '" + - cookieTokens[1] + "')"); - } + try { + tokenExpiryTime = new Long(cookieTokens[1]).longValue(); + } + catch (NumberFormatException nfe) { + throw new InvalidCookieException("Cookie token[1] did not contain a valid number (contained '" + + cookieTokens[1] + "')"); + } - if (isTokenExpired(tokenExpiryTime)) { - logger.info("user for which token is expired:" - +" userName: "+ cookieTokens[0] - +": Cookie token:"+ cookieTokens[1] - +" token expiry in GMT:" +convertExpTimeToGMTDate(0, tokenExpiryTime) - +" tokenExpiryTime:"+tokenExpiryTime - +" userId:"+cookieTokens[5] ); - throw new InvalidCookieException("Cookie token[1] has expired (expired on '" - + new Date(tokenExpiryTime) + "'; current time is '" + new Date() + "')"); - } + if (isTokenExpired(tokenExpiryTime)) { + logger.info("user for which token is expired:" + +" userName: "+ cookieTokens[0] + +": Cookie token:"+ cookieTokens[1] + +" token expiry in GMT:" +convertExpTimeToGMTDate(0, tokenExpiryTime) + +" tokenExpiryTime:"+tokenExpiryTime + +" userId:"+cookieTokens[5] ); + throw new InvalidCookieException("Cookie token[1] has expired (expired on '" + + new Date(tokenExpiryTime) + "'; current time is '" + new Date() + "')"); + } - // Check the user exists. - // Defer lookup until after expiry time checked, to possibly avoid expensive database call. + // Check the user exists. + // Defer lookup until after expiry time checked, to possibly avoid expensive database call. - UserDetails userDetails = getUserDetailsService().loadUserByUsername(cookieTokens[0]); - - if(!userDetails.isAccountNonLocked()) { - throw new LockedException("The account has been locked "); - } + UserDetails userDetails = getUserDetailsService().loadUserByUsername(cookieTokens[0]); - // Check signature of token matches remaining details. - // Must do this after user lookup, as we need the DAO-derived password. - // If efficiency was a major issue, just add in a UserCache implementation, - // but recall that this method is usually only called once per HttpSession - if the token is valid, - // it will cause SecurityContextHolder population, whilst if invalid, will cause the cookie to be cancelled. - String dealerCode = null; - String domainId = null; - int userId = 0; - if(userDetails instanceof MediationUserDetails) { + if(!userDetails.isAccountNonLocked()) { + throw new LockedException("The account has been locked "); + } - MediationUserDetails mediationUserDetails = (MediationUserDetails)userDetails; - dealerCode = mediationUserDetails.getDealerCode(); - domainId = mediationUserDetails.getDomain(); - userId = mediationUserDetails.getUserId(); - } + // Check signature of token matches remaining details. + // Must do this after user lookup, as we need the DAO-derived password. + // If efficiency was a major issue, just add in a UserCache implementation, + // but recall that this method is usually only called once per HttpSession - if the token is valid, + // it will cause SecurityContextHolder population, whilst if invalid, will cause the cookie to be cancelled. + String dealerCode = null; + String domainId = null; + int userId = 0; + if(userDetails instanceof MediationUserDetails) { - String expectedTokenSignature = makeTokenSignature(tokenExpiryTime, userDetails.getUsername(), - userDetails.getPassword(), dealerCode, domainId, userId); + MediationUserDetails mediationUserDetails = (MediationUserDetails)userDetails; + dealerCode = mediationUserDetails.getDealerCode(); + domainId = mediationUserDetails.getDomain(); + userId = mediationUserDetails.getUserId(); + } - if (!equals(expectedTokenSignature,cookieTokens[2])) { - logger.warn("user for which cookie is rejected because of signature mismatch:" - +" domainId:" + domainId - +" dealerCode:"+dealerCode - +" userName: "+ userDetails.getUsername() - +" token expiry in GMT:" +convertExpTimeToGMTDate(0, tokenExpiryTime) - +" tokenExpiryTime:"+tokenExpiryTime - +" userId:"+userId); - throw new InvalidCookieException("Cookie token[2] contained signature '" + cookieTokens[2] - + "' but expected '" + expectedTokenSignature + "'"); - } + String expectedTokenSignature = makeTokenSignature(tokenExpiryTime, userDetails.getUsername(), + userDetails.getPassword(), dealerCode, domainId, userId); - tokenExpiryTime = new Long(cookieTokens[1]).longValue(); - - Authentication authentication = createSuccessfulAuthentication(request, userDetails); + if (!equals(expectedTokenSignature,cookieTokens[2])) { + logger.warn("user for which cookie is rejected because of signature mismatch:" + +" domainId:" + domainId + +" dealerCode:"+dealerCode + +" userName: "+ userDetails.getUsername() + +" token expiry in GMT:" +convertExpTimeToGMTDate(0, tokenExpiryTime) + +" tokenExpiryTime:"+tokenExpiryTime + +" userId:"+userId); + throw new InvalidCookieException("Cookie token[2] contained signature '" + cookieTokens[2] + + "' but expected '" + expectedTokenSignature + "'"); + } - //if refresh token is set to true always issue a new token - boolean refreshToken = false; - if(request.getAttribute("refreshToken") != null) { - refreshToken = ((Boolean) request.getAttribute("refreshToken")).booleanValue(); - } + tokenExpiryTime = new Long(cookieTokens[1]).longValue(); - if(refreshToken || shouldAutoRefreshToken(tokenExpiryTime)) { - //create a new cookie - onLoginSuccess(request, response,authentication); - } else { - //echo the existing cookie + Authentication authentication = createSuccessfulAuthentication(request, userDetails); - String cookieValue = encodeCookie(cookieTokens); + //if refresh token is set to true always issue a new token + boolean refreshToken = false; + if(request.getAttribute("refreshToken") != null) { + refreshToken = ((Boolean) request.getAttribute("refreshToken")).booleanValue(); + } + + if(refreshToken || shouldAutoRefreshToken(tokenExpiryTime)) { + //create a new cookie + onLoginSuccess(request, response,authentication); + } else { + //echo the existing cookie + + String cookieValue = encodeCookie(cookieTokens); response.setHeader(getCookieName(), cookieValue); //we do not want to add calculate the expiry date based on max age. Just echo the existing expiry time header. String tokenExpiryDateAsGMTString = convertExpTimeToGMTDate(0, tokenExpiryTime); response.setHeader(getCookieName()+"Expiry", tokenExpiryDateAsGMTString); - } - return userDetails; + } + return userDetails; } /** - * Constant time comparison to prevent against timing attacks. - * @param expected - * @param actual - * @return - */ - private static boolean equals(String expected, String actual) { - byte[] expectedBytes = bytesUtf8(expected); - byte[] actualBytes = bytesUtf8(actual); - if (expectedBytes.length != actualBytes.length) { - return false; - } + * Constant time comparison to prevent against timing attacks. + * @param expected + * @param actual + * @return + */ + private static boolean equals(String expected, String actual) { + byte[] expectedBytes = bytesUtf8(expected); + byte[] actualBytes = bytesUtf8(actual); + if (expectedBytes.length != actualBytes.length) { + return false; + } - int result = 0; - for (int i = 0; i < expectedBytes.length; i++) { - result |= expectedBytes[i] ^ actualBytes[i]; - } - return result == 0; - } + int result = 0; + for (int i = 0; i < expectedBytes.length; i++) { + result |= expectedBytes[i] ^ actualBytes[i]; + } + return result == 0; + } - private static byte[] bytesUtf8(String s) { - if(s == null) { - return null; - } - try { - return s.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new IllegalStateException("Could not get bytes in UTF-8 format",e); - } - } + private static byte[] bytesUtf8(String s) { + if(s == null) { + return null; + } + try { + return s.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException("Could not get bytes in UTF-8 format",e); + } + } @Override protected int calculateLoginLifetime(HttpServletRequest request, Authentication authentication) { return appTokenValiditySeconds; - } + } /** * Support both token and the cookie in the request */ @Override protected String extractRememberMeCookie(HttpServletRequest request) { - return mediationUtilService.extractLoginToken(request); + return mediationUtilService.extractLoginToken(request); } @Override @@ -211,16 +210,16 @@ response.setHeader(getCookieName(), cookieValue); //set expiry time in GMT - long expiryTime = System.currentTimeMillis(); - // SEC-949 - String tokenExpiryDateAsGMTString = convertExpTimeToGMTDate(maxAge, expiryTime); + long expiryTime = System.currentTimeMillis(); + // SEC-949 + String tokenExpiryDateAsGMTString = convertExpTimeToGMTDate(maxAge, expiryTime); response.setHeader(getCookieName()+"Expiry", tokenExpiryDateAsGMTString); } private String convertExpTimeToGMTDate(int maxAge, long expiryTime) { expiryTime += 1000L* (maxAge < 0 ? TWO_WEEKS_S : maxAge); - DateFormat dateFormat = new SimpleDateFormat("MMMM dd, yyyy HH:mm:ss z", Locale.US); + DateFormat dateFormat = new SimpleDateFormat("MMMM dd, yyyy HH:mm:ss z", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String tokenExpiryDateAsGMTString= dateFormat.format(new Date(expiryTime)); return tokenExpiryDateAsGMTString; @@ -229,73 +228,72 @@ * Override so that dealer code can be added in token and signature */ @Override - public void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, - Authentication successfulAuthentication) { + public void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, + Authentication successfulAuthentication) { - String username = retrieveUserName(successfulAuthentication); - String password = retrievePassword(successfulAuthentication); + String username = retrieveUserName(successfulAuthentication); + String password = retrievePassword(successfulAuthentication); - if (!StringUtils.hasLength(username)) { - logger.debug("Unable to retrieve username"); - return; - } + if (!StringUtils.hasLength(username)) { + logger.debug("Unable to retrieve username"); + return; + } + if (successfulAuthentication.getPrincipal() instanceof UserDetails) { + MediationUserDetails mediationUserDetails = (MediationUserDetails)successfulAuthentication.getPrincipal(); + if (!StringUtils.hasLength(password)) { + UserDetails user = ((MediationUserDetailsService)getUserDetailsService()). + loadUser(username,mediationUserDetails.getDealerCode(),mediationUserDetails.getDomain(),null); + password = user.getPassword(); - if (!StringUtils.hasLength(password)) { - UserDetails user = getUserDetailsService().loadUserByUsername(username); - password = user.getPassword(); + if (!StringUtils.hasLength(password)) { + logger.debug("Unable to obtain password for user: " + username); + return; + } + } - if (!StringUtils.hasLength(password)) { - logger.debug("Unable to obtain password for user: " + username); - return; - } - } + List results = secrtekeyHelperService.getDomainConf(mediationUserDetails.getDomain()); - //override default values with domain configuration - String domainId = mediationUtilService.findDomain(request); - List results = secrtekeyHelperService.getDomainConf(domainId); + if(results != null && results.size() > 0) { + Map result = (Map)results.get(0); + appTokenValiditySeconds = (Integer)(result).get("tokenValidityTime"); + tokenValidityAdditionalGracePeriodSeconds = (Integer)(result).get("tokenGracePeriod"); + tokenRefreshBeforeExpireInSeconds = (Integer)(result).get("tokenExpiration"); + } - if(results != null && results.size() > 0) { - Map result = (Map)results.get(0); - appTokenValiditySeconds = (Integer)(result).get("tokenValidityTime"); - tokenValidityAdditionalGracePeriodSeconds = (Integer)(result).get("tokenGracePeriod"); - tokenRefreshBeforeExpireInSeconds = (Integer)(result).get("tokenExpiration"); - } + int tokenLifetime = calculateLoginLifetime(request, successfulAuthentication); + long expiryTime = System.currentTimeMillis(); + // SEC-949 + expiryTime += 1000L* (tokenLifetime < 0 ? TWO_WEEKS_S : tokenLifetime); - int tokenLifetime = calculateLoginLifetime(request, successfulAuthentication); - long expiryTime = System.currentTimeMillis(); - // SEC-949 - expiryTime += 1000L* (tokenLifetime < 0 ? TWO_WEEKS_S : tokenLifetime); + //do not take from request signatures are made and verified based on data in DB (MediatorUserDetails) + String dealerCode = null; + Integer userId = 0; + String domainId = null; - //do not take from request signatures are made and verified based on data in DB (MediatorUserDetails) - String dealerCode = null; - Integer userId = 0; - if (successfulAuthentication.getPrincipal() instanceof UserDetails) { - MediationUserDetails userDetails = (MediationUserDetails)successfulAuthentication.getPrincipal(); - MediationUserDetails mediationUserDetails = (MediationUserDetails)userDetails; - dealerCode = mediationUserDetails.getDealerCode(); - domainId = mediationUserDetails.getDomain(); - userId = mediationUserDetails.getUserId(); + dealerCode = mediationUserDetails.getDealerCode(); + domainId = mediationUserDetails.getDomain(); + userId = mediationUserDetails.getUserId(); - //TODO:fix the dealer code and domain Id from token and if not then in the request. - String signatureValue = makeTokenSignature(expiryTime, username, password, dealerCode, domainId, userId); + //TODO:fix the dealer code and domain Id from token and if not then in the request. + String signatureValue = makeTokenSignature(expiryTime, username, password, dealerCode, domainId, userId); - //note that sequence of parameter matters the spring checks the signature value. - setCookie(new String[] {username, Long.toString(expiryTime), signatureValue, dealerCode, domainId, new Integer(userId).toString()}, tokenLifetime, request, response); + //note that sequence of parameter matters the spring checks the signature value. + setCookie(new String[] {username, Long.toString(expiryTime), signatureValue, dealerCode, domainId, new Integer(userId).toString()}, tokenLifetime, request, response); - if (logger.isDebugEnabled()) { - logger.debug("Added remember-me cookie for user '" + username + "', expiry: '" - + new Date(expiryTime) + "'"); - } - } - } + if (logger.isDebugEnabled()) { + logger.debug("Added remember-me cookie for user '" + username + "', expiry: '" + + new Date(expiryTime) + "'"); + } + } + } @Override protected void onLoginFail(HttpServletRequest request, HttpServletResponse response) { - String rememberMeCookie = extractRememberMeCookie(request); + String rememberMeCookie = extractRememberMeCookie(request); if(rememberMeCookie !=null) { String cookieAsPlainText = new String(Base64.decodeBase64(rememberMeCookie.getBytes())); @@ -316,21 +314,21 @@ +" dm:"+request.getParameter("dm") +" dealerCode:"+request.getParameter("dealerCode") +" userName:"+request.getParameter("userName") - ); + ); } } String retreiveTokenFromToken(HttpServletRequest request) { return null; - } + } /** * Add logic to decode token to get dealer code from it. */ @Override - protected String[] decodeCookie(String cookieValue) throws InvalidCookieException { - return mediationUtilService.decodeCookie(cookieValue); - } + protected String[] decodeCookie(String cookieValue) throws InvalidCookieException { + return mediationUtilService.decodeCookie(cookieValue); + } /** * Token should be refreshed if Difference between token expire time and current time is =< tokenValidityAdditionalGracePeriodSeconds * @param tokenExpiryTime @@ -341,10 +339,27 @@ if(shouldRefreshToken) { logger.info(" token refresh : tokenExpiryTime - System.currentTimeMillis() <= tokenRefreshBeforeExpireInSeconds * 1000L=>" + (tokenExpiryTime + "-"+ System.currentTimeMillis() +"<= "+ tokenRefreshBeforeExpireInSeconds +"* 1000L")); } - return shouldRefreshToken; - } + return shouldRefreshToken; + } public void setSecrtekeyHelperService(SecrtekeyHelperService secrtekeyHelperService) { this.secrtekeyHelperService = secrtekeyHelperService; } + + @Override + protected boolean rememberMeRequested(HttpServletRequest request, String parameter) { + + MediationUserDetails mediationUserDetails = MediatorSecurityHelperService.getPrincipal(); + String rememberMe = mediationUserDetails.getRememberMe(); + if(rememberMe != null && (rememberMe.equalsIgnoreCase("true") || rememberMe.equalsIgnoreCase("on") || rememberMe.equalsIgnoreCase("yes") || rememberMe.equals("1"))) { + return true; + } else { + if(this.logger.isDebugEnabled()) { + this.logger.debug("Did not send remember-me cookie"); + } + + return false; + } + } + } Index: mediator-service/branches/DS-801_JSON_Login/grails-app/services/com/lemanscorp/MediationUserDetails.groovy =================================================================== diff -u -r8645 -r8649 --- mediator-service/branches/DS-801_JSON_Login/grails-app/services/com/lemanscorp/MediationUserDetails.groovy (.../MediationUserDetails.groovy) (revision 8645) +++ mediator-service/branches/DS-801_JSON_Login/grails-app/services/com/lemanscorp/MediationUserDetails.groovy (.../MediationUserDetails.groovy) (revision 8649) @@ -11,13 +11,13 @@ @ToString class MediationUserDetails extends User { - final String domain, dealerCode, userType, whoForDealerCode, mcpId + final String domain, dealerCode, userType, whoForDealerCode, mcpId, rememberMe final Integer userTypeId, userId final userProfileXmlNode - MediationUserDetails(String username, String password, NodeChild userRoot) { + MediationUserDetails(String username, String password, String rememberMe, NodeChild userRoot) { super(username, password, true, userRoot.dealerStatus?.toString() != 'I', - true, !userRoot.locked.toBoolean(), authorities(userRoot)) + true, !userRoot.locked.toBoolean(), authorities(userRoot)) String trimedUserProfile = XmlUtil.serialize(new StreamingMarkupBuilder().bind { mkp.yield userRoot } ) userProfileXmlNode = new XmlSlurper().parseText(trimedUserProfile) domain = userRoot.domainId as String @@ -27,10 +27,11 @@ whoForDealerCode = userRoot.authorizedEntity?.entityId?.text() mcpId = userRoot.mcpId as String userId = userRoot.userId.size() ? userRoot.userId.toInteger() : null + this.rememberMe = rememberMe } static private List authorities(NodeChild userRoot) { - userRoot.permission.mediatorPermission.collect { new SimpleGrantedAuthority(it.text()) } + userRoot.permission.mediatorPermission.collect { new SimpleGrantedAuthority(it.text()) } } boolean hasPermission(String roleName) { Index: mediator-service/branches/DS-801_JSON_Login/grails-app/services/com/lemanscorp/MediationUserDetailsService.groovy =================================================================== diff -u -r8645 -r8649 --- mediator-service/branches/DS-801_JSON_Login/grails-app/services/com/lemanscorp/MediationUserDetailsService.groovy (.../MediationUserDetailsService.groovy) (revision 8645) +++ mediator-service/branches/DS-801_JSON_Login/grails-app/services/com/lemanscorp/MediationUserDetailsService.groovy (.../MediationUserDetailsService.groovy) (revision 8649) @@ -4,27 +4,23 @@ import groovy.util.slurpersupport.NodeChild import groovy.xml.QName import groovy.xml.XmlUtil - import javax.annotation.Resource - import org.apache.camel.ProducerTemplate import org.springframework.security.authentication.encoding.PasswordEncoder import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.web.context.request.RequestContextHolder - import com.lemanscorp.mediation.utils.MediationUtilService import com.lemanscorp.mediation.utils.RequestHelperService import com.lemanscorp.mediator.ServiceException - import javax.servlet.http.HttpServletRequest @SuppressWarnings('GrailsStatelessService') class MediationUserDetailsService implements UserDetailsService { @Resource MediationUtilService mediationUtilService - + @Resource(name='serviceHost') String serviceHost @@ -41,63 +37,75 @@ PasswordEncoder passwordEncoder @Override - UserDetails loadUserByUsername(String username) { createUserDetails(username) } + UserDetails loadUserByUsername(String username) { + createUserDetails(username) + } + + UserDetails loadUser(String username, String dealerCode, String dm, String rememberMe) { + createUserDetails(username, dealerCode, dm, rememberMe) + } private MediationUserDetails createUserDetails(String user) { + createUserDetails(user, null, null, null) + } + + private MediationUserDetails createUserDetails(String username, String dealerCode, String dm, String rememberMe) { HttpServletRequest request = RequestContextHolder.requestAttributes.request - Map userInfo = userInfo(user) - String testPermission = request.getHeader('TEST_PERMISSION') - boolean externalUser = userInfo.externalUser + Map userInfo = userInfo(username, dealerCode, dm) + String testPermission = request.getHeader('TEST_PERMISSION') + boolean externalUser = userInfo.externalUser NodeChild userRoot = userRoot(userInfo.dm, userInfo.username, userInfo.dealerCode, externalUser, testPermission) - assert userRoot != null - String userName = userRoot.userName as String + assert userRoot != null + String userNameFromDb = userRoot.userName as String String password = (userRoot.password as String) ?: passwordEncoder.encodePassword( - "${userInfo.dm}${userInfo.dealerCode}${userInfo.userName}", null) - new MediationUserDetails(userName, password, userRoot) + "${userInfo.dm}${userInfo.dealerCode}${userInfo.userName}", null) + new MediationUserDetails(userNameFromDb, password, rememberMe, userRoot) } - - private boolean testPermissionEnabled() { - System.getProperty('grails.env') == 'test' - } - - private Map userInfo(String user) { - String username = user + + private boolean testPermissionEnabled() { + System.getProperty('grails.env') == 'test' + } + + private Map userInfo(String usernameParam, String dealerCodeParam, String dmParam) { + String username = usernameParam + String dealerCode = dealerCodeParam + String dm = dmParam def request = RequestContextHolder.requestAttributes.request int domainNameIndex = username.toUpperCase()?.indexOf('@LEMANSCORP.COM') // probably when coming from Kerberos ! - def dealerCode if (domainNameIndex != -1) { username = username[0..domainNameIndex - 1] dealerCode = 'LEMANSCORP' } else { - dealerCode = mediationUtilService.findDealerCode(request) + dealerCode = dealerCode ?: mediationUtilService.findDealerCode(request) } if (!dealerCode) { throw new ServiceException(412, [message: 'dealerCode is required']) } - def dm = mediationUtilService.findDomain(request) + + dm = dm ?: mediationUtilService.findDomain(request) if (!dm) { throw new ServiceException(412, [message: 'domain is required']) } [username: username, dealerCode: dealerCode, dm: dm, externalUser: domainNameIndex == -1] } - + @SuppressWarnings(['CatchException']) private NodeChild userRoot(dm, String username, String dealerCode, boolean externalUser, String testPermission) { - NodeChild userRoot + NodeChild userRoot try { String cacheKey = mediationUtilService.createUserCacheKey(dm, dealerCode, username) - userRoot = mediationUtilService.getObjectFromCache('userCache', cacheKey) - String userProfile + userRoot = mediationUtilService.getObjectFromCache('userCache', cacheKey) + String userProfile if (userRoot == null) { - userProfile = loadUserProfile(dm, username, dealerCode, externalUser) - } - if (testPermission != null && testPermissionEnabled()) { - userProfile = loadUserProfile(dm, username, dealerCode, externalUser) - userRoot = addTestPermission(dm, testPermission, userProfile) - } - else { userRoot = userRoot ?: new XmlSlurper().parseText(userProfile) } + userProfile = loadUserProfile(dm, username, dealerCode, externalUser) + } + if (testPermission != null && testPermissionEnabled()) { + userProfile = loadUserProfile(dm, username, dealerCode, externalUser) + userRoot = addTestPermission(dm, testPermission, userProfile) + } + else { userRoot = userRoot ?: new XmlSlurper().parseText(userProfile) } - mediationUtilService.addToCache('userCache', cacheKey, userRoot) + mediationUtilService.addToCache('userCache', cacheKey, userRoot) userRoot.'password'.replaceNode { } userRoot } catch (Exception x) { @@ -106,28 +114,28 @@ } } - private String loadUserProfile(dm, String username, String dealerCode, boolean externalUser) { - String extQueryString = "dealerCode=${dealerCode}&userName=${username}&domain=${dm}" - String userProfile = requestHelperService.callService('direct:auth', tokenServiceHost, 'auth.context', '/mdsUserInfo', - extQueryString, null, [(RequestHelperService.INTERNAL_REQUEST): true], 'GET', null) - if (externalUser && userProfile == null) { - String message = "Username ${username} not found for dealerCode=${dealerCode}" + - " and domain=${dm} in MediationUserDetailsService" - throw new ServiceException(412, [message: message]) - } - userProfile - } + private String loadUserProfile(dm, String username, String dealerCode, boolean externalUser) { + String extQueryString = "dealerCode=${dealerCode}&userName=${username}&domain=${dm}" + String userProfile = requestHelperService.callService('direct:auth', tokenServiceHost, 'auth.context', '/mdsUserInfo', + extQueryString, null, [(RequestHelperService.INTERNAL_REQUEST): true], 'GET', null) + if (externalUser && userProfile == null) { + String message = "Username ${username} not found for dealerCode=${dealerCode}" + + " and domain=${dm} in MediationUserDetailsService" + throw new ServiceException(412, [message: message]) + } + userProfile + } - @SuppressWarnings('UnusedObject') - private NodeChild addTestPermission(dm, String testPermission, String userProfile) { - Node root = new XmlParser().parseText(userProfile) - Node permissionTop = new Node(root, new QName('permission')) - new Node(permissionTop, new QName('permission'), testPermission) - new Node(permissionTop, new QName('description'), 'TEST INJECTED') - String mediatorPermission = "permission_${dm}_${testPermission}" - new Node(permissionTop, new QName('mediatorPermission'), mediatorPermission) - String xml = XmlUtil.serialize(root) - NodeChild userRoot = new XmlSlurper().parseText(xml) - userRoot - } + @SuppressWarnings('UnusedObject') + private NodeChild addTestPermission(dm, String testPermission, String userProfile) { + Node root = new XmlParser().parseText(userProfile) + Node permissionTop = new Node(root, new QName('permission')) + new Node(permissionTop, new QName('permission'), testPermission) + new Node(permissionTop, new QName('description'), 'TEST INJECTED') + String mediatorPermission = "permission_${dm}_${testPermission}" + new Node(permissionTop, new QName('mediatorPermission'), mediatorPermission) + String xml = XmlUtil.serialize(root) + NodeChild userRoot = new XmlSlurper().parseText(xml) + userRoot + } } Index: mediator-service/branches/DS-801_JSON_Login/grails-app/services/com/lemanscorp/mediation/utils/RequestHelperService.groovy =================================================================== diff -u -r8645 -r8649 --- mediator-service/branches/DS-801_JSON_Login/grails-app/services/com/lemanscorp/mediation/utils/RequestHelperService.groovy (.../RequestHelperService.groovy) (revision 8645) +++ mediator-service/branches/DS-801_JSON_Login/grails-app/services/com/lemanscorp/mediation/utils/RequestHelperService.groovy (.../RequestHelperService.groovy) (revision 8649) @@ -14,7 +14,7 @@ @Resource(name='serviceHost') String commonServiceHost - + @Resource(name='tokenServiceHost') String tokenServiceHost @@ -25,35 +25,35 @@ Object callAuthService(pathInfo, method = 'GET', String body = null) { callService('direct:auth', tokenServiceHost, 'auth.context', pathInfo, - null, body, [shouldThrowException: false], method, null) + null, body, [shouldThrowException: false], method, null) } Object getCallService(String service, pathInfo, String queryString) { callService("direct:$service", null, "${service}.context", pathInfo, - queryString, null, [shouldThrowException: false], 'GET', null) + queryString, null, [shouldThrowException: false], 'GET', null) } - @SuppressWarnings(['GStringExpressionWithinString']) - Object callMediaService(String pathInfo, String queryString, body) { - callService("bean:mediaRoute?method=process(\${body}, \${headers})", null, 'media.context', - pathInfo, queryString, body, [shouldThrowException: false], null, null) - } + @SuppressWarnings(['GStringExpressionWithinString']) + Object callMediaService(String pathInfo, String queryString, body) { + callService("bean:mediaRoute?method=process(\${body}, \${headers})", null, 'media.context', + pathInfo, queryString, body, [shouldThrowException: false], null, null) + } Object callService(String service, pathInfo) { callService("direct:$service", null, "${service}.context", pathInfo, - null, null, [shouldThrowException: false], null, null) + null, null, [shouldThrowException: false], null, null) } - + Object callService(String service, Map headers, pathInfo) { callService("direct:$service", null, "${service}.context", pathInfo, - null, null, [shouldThrowException: false] + headers, null, null) + null, null, [shouldThrowException: false] + headers, null, null) } Object callService(String service, pathInfo, RequestMethod method, String body = null) { callService("direct:$service", null, "${service}.context", pathInfo, - null, body, [shouldThrowException: false], method.toString(), null) + null, body, [shouldThrowException: false], method.toString(), null) } - + Object callService(route, serviceContextRootName, pathInfo) { callService(route, null, serviceContextRootName, pathInfo, null, null, null, null, null) } @@ -63,16 +63,16 @@ } Object callService(String route, String serviceHost, String serviceContextRootName, String pathInfo, String queryString, - theBody, Map additionalHeaders, theMethod, Class theReturnType) { + theBody, Map additionalHeaders, theMethod, Class theReturnType) { Map reqHeaders = requestHeaders() ?: [:] if (additionalHeaders) { reqHeaders += additionalHeaders } Class returnType = theReturnType ?: String reqHeaders.response = RequestContextHolder.currentRequestAttributes().currentResponse def request = RequestContextHolder.requestAttributes.request reqHeaders.request = request - String dm = mediationUtilService.findDomain(request) + String dm = mediationUtilService.findDomain(request, false) reqHeaders.dm = dm - + def method = theMethod ?: request.method def body = postOrPutWithoutBody(theBody, method) ? request.reader?.text : theBody if (log.isDebugEnabled() && body) { log.debug "[body]: $body" } @@ -83,10 +83,10 @@ reqHeaders[Exchange.HTTP_METHOD] = method logEndpoint(reqHeaders, method) addAuditHeaders(reqHeaders) - + invokeServiceEndpoint(route, body, reqHeaders, returnType) } - + private void addEndpointHeader(Map reqHeaders, String serviceHost, String serviceContextRootName, String pathInfo) { if (reqHeaders.endPointHeader == null) { String shouldThrowExceptionStr = reqHeaders.shouldThrowException @@ -126,25 +126,25 @@ endPoint << "&httpClient.soTimeout=${reqHeaders?.get(RequestHelperService.SO_TIMEOUT) ?: 30000}" } - private Map requestHeaders() { - def req = RequestContextHolder.requestAttributes.request - Map reqHeaders = [:] - req.headerNames.each { headerName -> - if (!headerName.equalsIgnoreCase('accept-encoding')) { - reqHeaders[headerName] = req.getHeader(headerName) - } - } - reqHeaders - } + private Map requestHeaders() { + def req = RequestContextHolder.requestAttributes.request + Map reqHeaders = [:] + req.headerNames.each { headerName -> + if (!headerName.equalsIgnoreCase('accept-encoding')) { + reqHeaders[headerName] = req.getHeader(headerName) + } + } + reqHeaders + } - Map addAuditHeaders(Map headers) { - Map reqHeaders = headers ?: [:] - def request = RequestContextHolder.requestAttributes.request - reqHeaders.loggedInDomain = mediationUtilService.findDomain(request) - reqHeaders.loggedInDealerCode = mediationUtilService.findDealerCode(request) - reqHeaders.loggedInUserName = mediationUtilService.findUserName(request) - reqHeaders.loggedInUserId = mediationUtilService.findUserId() - reqHeaders.put('loggedInUserTypeId', mediationUtilService.findUserTypeId()?.toString()) - reqHeaders - } + Map addAuditHeaders(Map headers) { + Map reqHeaders = headers ?: [:] + def request = RequestContextHolder.requestAttributes.request + reqHeaders.loggedInDomain = mediationUtilService.findDomain(request, false) + reqHeaders.loggedInDealerCode = mediationUtilService.findDealerCode(request) + reqHeaders.loggedInUserName = mediationUtilService.findUserName(request) + reqHeaders.loggedInUserId = mediationUtilService.findUserId() + reqHeaders.put('loggedInUserTypeId', mediationUtilService.findUserTypeId()?.toString()) + reqHeaders + } } Index: mediator-service/branches/DS-801_JSON_Login/src/java/com/lemanscorp/mediation/LemansSimpleUrlAuthenticationSuccessHandler.java =================================================================== diff -u -r8645 -r8649 --- mediator-service/branches/DS-801_JSON_Login/src/java/com/lemanscorp/mediation/LemansSimpleUrlAuthenticationSuccessHandler.java (.../LemansSimpleUrlAuthenticationSuccessHandler.java) (revision 8645) +++ mediator-service/branches/DS-801_JSON_Login/src/java/com/lemanscorp/mediation/LemansSimpleUrlAuthenticationSuccessHandler.java (.../LemansSimpleUrlAuthenticationSuccessHandler.java) (revision 8649) @@ -3,17 +3,15 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +import com.lemanscorp.MediationUserDetails; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; - import com.lemanscorp.mediator.modules.login.LoginHelperService; /** @@ -23,12 +21,12 @@ */ public class LemansSimpleUrlAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { - protected final Log logger = LogFactory.getLog(this.getClass()); - - @Autowired - LoginHelperService loginHelperService; + protected final Log logger = LogFactory.getLog(this.getClass()); - public LemansSimpleUrlAuthenticationSuccessHandler() { + @Autowired + LoginHelperService loginHelperService; + + public LemansSimpleUrlAuthenticationSuccessHandler() { } /** @@ -38,23 +36,27 @@ */ protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { + MediationUserDetails mediationUserDetails = (MediationUserDetails) authentication.getPrincipal(); Map criteria = new HashMap(); - criteria.put("userName", request.getParameterValues("userName")[0]); - criteria.put("dealerCode", request.getParameterValues("dealerCode")[0]); - criteria.put("dm", request.getParameterValues("dm")[0]); + criteria.put("userName", mediationUserDetails.getUsername()); + criteria.put("dealerCode", mediationUserDetails.getDealerCode()); + criteria.put("dm", mediationUserDetails.getDomain()); criteria.put("userActionTypeId", "1"); - loginHelperService.logUserAction(criteria); - - response.setContentType("simple/text"); - response.getWriter().write("{\"message\": \"login is successful\"}"); + loginHelperService.logUserAction(criteria); + if ("application/json".equals(request.getContentType())) { + response.setContentType("application/json"); + } else { + response.setContentType("simple/text"); + } + response.getWriter().write("{\"message\": \"login is successful\"}"); } /** * Calls the parent class {@code handle()} method to forward or redirect to the target URL, and * then calls {@code clearAuthenticationAttributes()} to remove any leftover session data. */ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, - Authentication authentication) throws IOException, ServletException { + Authentication authentication) throws IOException, ServletException { handle(request, response, authentication); clearAuthenticationAttributes(request); Index: mediator-service/branches/DS-801_JSON_Login/grails-app/services/com/lemanscorp/mediation/utils/MediationUtilService.groovy =================================================================== diff -u -r8645 -r8649 --- mediator-service/branches/DS-801_JSON_Login/grails-app/services/com/lemanscorp/mediation/utils/MediationUtilService.groovy (.../MediationUtilService.groovy) (revision 8645) +++ mediator-service/branches/DS-801_JSON_Login/grails-app/services/com/lemanscorp/mediation/utils/MediationUtilService.groovy (.../MediationUtilService.groovy) (revision 8649) @@ -28,17 +28,17 @@ final static Pattern DM_PATTERN = Pattern.compile(/^.*(\bdm)\/(\d+).*$/) - String byteArray2Hex(byte[] bytes) { - char[] hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] - StringBuilder sb = new StringBuilder(bytes.length * 2) - for (final byte b : bytes) { - sb.append(hex[(b & 0xF0) >> 4]) - sb.append(hex[b & 0x0F]) - } - sb - } + String byteArray2Hex(byte[] bytes) { + char[] hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] + StringBuilder sb = new StringBuilder(bytes.length * 2) + for (final byte b : bytes) { + sb.append(hex[(b & 0xF0) >> 4]) + sb.append(hex[b & 0x0F]) + } + sb + } - private Map generateTokenAsMap(domainId) { + private Map generateTokenAsMap(domainId) { MessageDigest md = MessageDigest.getInstance('SHA1') String token= UUID.randomUUID() def secretKey @@ -57,80 +57,80 @@ byte[] clientHashByte=md.digest() String hashCode=byteArray2Hex(clientHashByte) ['token': token, 'hashCode': hashCode, 'utc': utc ] - } + } - String generateToken(domainId) { - def map = generateTokenAsMap(domainId) - map.collect { k, v -> "$k=$v" }.join('&') - } + String generateToken(domainId) { + def map = generateTokenAsMap(domainId) + map.collect { k, v -> "$k=$v" }.join('&') + } - Object readConfig(String input) { - def result - if (input) { - def configData = Holders.flatConfig["mediation.services.${input}"] - result = configData - } - if (!result) { - throw new IllegalStateException("Configuration Not found for end point ${input}") - } - result - } + Object readConfig(String input) { + def result + if (input) { + def configData = Holders.flatConfig["mediation.services.${input}"] + result = configData + } + if (!result) { + throw new IllegalStateException("Configuration Not found for end point ${input}") + } + result + } - //This method is called by re-delivery processor. It can not be in the requestHelper as producerTemplate is being referred there. - /** - * This method creates query string based on various parameters. - * For internal request it does not consider query string. - * Only for external requests it use queryString and append other query parameters to it - * Camel HTTP_QUERY header does not expect query string to start with query string. - * So return value should never return string starting with ? - * If this method is used by methods to form the query string and needs ? in the beginning then add it in the caller method. - * If mediator service calling self then mark the call as 'internal' to avoid sending service tokens twice in the request. - * @param additionalQueryString - * @param domainId - * @param isInternalRequest - * @return - */ - String processQueryString(addQueryString, domainId, boolean isInternalRequest) { - def request = RequestContextHolder.requestAttributes.request - String reqString = '' - if (!isInternalRequest) { reqString = stripSqBrackets(request.queryString) } - if (addQueryString) { - String additionalQueryString = stripSqBrackets(addQueryString) - if (reqString) { - if (additionalQueryString.startsWith('?')) { - additionalQueryString = additionalQueryString.replaceFirst('\\?', '') - } - if (additionalQueryString.startsWith('&')) { - additionalQueryString = additionalQueryString.replaceFirst('&', '') - } - reqString += '&' + additionalQueryString - } else { reqString = additionalQueryString } - } + //This method is called by re-delivery processor. It can not be in the requestHelper as producerTemplate is being referred there. + /** + * This method creates query string based on various parameters. + * For internal request it does not consider query string. + * Only for external requests it use queryString and append other query parameters to it + * Camel HTTP_QUERY header does not expect query string to start with query string. + * So return value should never return string starting with ? + * If this method is used by methods to form the query string and needs ? in the beginning then add it in the caller method. + * If mediator service calling self then mark the call as 'internal' to avoid sending service tokens twice in the request. + * @param additionalQueryString + * @param domainId + * @param isInternalRequest + * @return + */ + String processQueryString(addQueryString, domainId, boolean isInternalRequest) { + def request = RequestContextHolder.requestAttributes.request + String reqString = '' + if (!isInternalRequest) { reqString = stripSqBrackets(request.queryString) } + if (addQueryString) { + String additionalQueryString = stripSqBrackets(addQueryString) + if (reqString) { + if (additionalQueryString.startsWith('?')) { + additionalQueryString = additionalQueryString.replaceFirst('\\?', '') + } + if (additionalQueryString.startsWith('&')) { + additionalQueryString = additionalQueryString.replaceFirst('&', '') + } + reqString += '&' + additionalQueryString + } else { reqString = additionalQueryString } + } - if (reqString) { reqString += '&' + generateToken(domainId) } - else { reqString = generateToken(domainId) } - reqString - } + if (reqString) { reqString += '&' + generateToken(domainId) } + else { reqString = generateToken(domainId) } + reqString + } - def valueMasked(value) { + def valueMasked(value) { if (value) { - return value.replaceAll('((token|utc|hashCode|password)[^&?]+)') { match -> - ''.padLeft(match.size(), '*') - } + return value.replaceAll('((token|utc|hashCode|password)[^&?]+)') { match -> + ''.padLeft(match.size(), '*') + } } '' - } + } - /** - * This function strip the square brackets around the query parameters and replace it with plain query parameters. - * This is done to support build in feature of PHP of sending query parameter with same name. - * e.g. br=1&br=2 is sent as br[0]=1&br[1]=2. This function cnovert the string to br=1&br=2 - * another example with encoding br%5B0%5D%3D1%26br%5B1%5D%3D2 is converted to br=1&br=2 as well. - * For encoded string it decodes it first so that square brackets '[' and ']' can be identify to apply regex expression. - * It encode the query string again after the swapping is done. - * @param queryString - * @return - */ + /** + * This function strip the square brackets around the query parameters and replace it with plain query parameters. + * This is done to support build in feature of PHP of sending query parameter with same name. + * e.g. br=1&br=2 is sent as br[0]=1&br[1]=2. This function cnovert the string to br=1&br=2 + * another example with encoding br%5B0%5D%3D1%26br%5B1%5D%3D2 is converted to br=1&br=2 as well. + * For encoded string it decodes it first so that square brackets '[' and ']' can be identify to apply regex expression. + * It encode the query string again after the swapping is done. + * @param queryString + * @return + */ String stripSqBrackets(qs) { String queryString = qs if (queryString) { @@ -143,15 +143,15 @@ queryString } - List toList(String value) { + List toList(String value) { [value] - } + } - def toList(value) { - value ?: [] - } + def toList(value) { + value ?: [] + } - Map queryStringToMap(queryString) { + Map queryStringToMap(queryString) { if (queryString == null) { return [:] } @@ -160,173 +160,173 @@ map[key] = value map //note map is returned in the closure } - } + } - String extractLoginToken(HttpServletRequest request) { - String cookieName = 'loginToken' - String loginToken = null - loginToken = request.getHeader(cookieName) - if (!StringUtils.hasLength(loginToken)) { - loginToken = request.getParameter('loginToken') - } - if (!StringUtils.hasLength(loginToken)) { - loginToken = extractRememberMeCookie(request) - } - loginToken - } + String extractLoginToken(HttpServletRequest request) { + String cookieName = 'loginToken' + String loginToken = null + loginToken = request.getHeader(cookieName) + if (!StringUtils.hasLength(loginToken)) { + loginToken = request.getParameter('loginToken') + } + if (!StringUtils.hasLength(loginToken)) { + loginToken = extractRememberMeCookie(request) + } + loginToken + } - String extractRememberMeCookie(HttpServletRequest request) { - String cookieName = 'loginToken' - Cookie[] cookies = request.cookies - if ((cookies == null) || (cookies.length == 0)) { - return null - } + String extractRememberMeCookie(HttpServletRequest request) { + String cookieName = 'loginToken' + Cookie[] cookies = request.cookies + if ((cookies == null) || (cookies.length == 0)) { + return null + } - for (int i = 0; i < cookies.length; i++) { - if (cookieName == cookies[i].name) { - return cookies[i].value - } - } - null - } + for (int i = 0; i < cookies.length; i++) { + if (cookieName == cookies[i].name) { + return cookies[i].value + } + } + null + } - String[] decodeCookie(String cookie) throws InvalidCookieException { - String cookieValue = cookie - for (int j = 0; j < cookieValue.length() % 4; j++) { - cookieValue = cookieValue + '=' - } - def cookieBytes = cookieValue.bytes + String[] decodeCookie(String cookie) throws InvalidCookieException { + String cookieValue = cookie + for (int j = 0; j < cookieValue.length() % 4; j++) { + cookieValue = cookieValue + '=' + } + def cookieBytes = cookieValue.bytes - if (!Base64.isBase64(cookieBytes)) { - throw new InvalidCookieException( "Cookie token was not Base64 encoded; value was '" + cookieValue + "'") - } + if (!Base64.isBase64(cookieBytes)) { + throw new InvalidCookieException( "Cookie token was not Base64 encoded; value was '" + cookieValue + "'") + } - String cookieAsPlainText = new String(Base64.decodeBase64(cookieBytes)) + String cookieAsPlainText = new String(Base64.decodeBase64(cookieBytes)) - String[] tokens = StringUtils.delimitedListToStringArray(cookieAsPlainText, ':') + String[] tokens = StringUtils.delimitedListToStringArray(cookieAsPlainText, ':') - if ((tokens[0].equalsIgnoreCase('http') || tokens[0].equalsIgnoreCase('https')) && tokens[1].startsWith('//')) { - // Assume we've accidentally split a URL (OpenID identifier) - String[] newTokens = new String[tokens.length - 1] - newTokens[0] = tokens[0] + ':' + tokens[1] - System.arraycopy(tokens, 2, newTokens, 1, newTokens.length - 1) - tokens = newTokens - } - tokens - } + if ((tokens[0].equalsIgnoreCase('http') || tokens[0].equalsIgnoreCase('https')) && tokens[1].startsWith('//')) { + // Assume we've accidentally split a URL (OpenID identifier) + String[] newTokens = new String[tokens.length - 1] + newTokens[0] = tokens[0] + ':' + tokens[1] + System.arraycopy(tokens, 2, newTokens, 1, newTokens.length - 1) + tokens = newTokens + } + tokens + } - /** - * - * Sequence is important - * Sample string : - * @param request - * @return - */ - Map decodeCookieAsMap(HttpServletRequest request) { - def map = [:] - String cookieValue = extractLoginToken(request) - if (cookieValue) { - String[] values = decodeCookie(cookieValue) + /** + * + * Sequence is important + * Sample string : + * @param request + * @return + */ + Map decodeCookieAsMap(HttpServletRequest request) { + def map = [:] + String cookieValue = extractLoginToken(request) + if (cookieValue) { + String[] values = decodeCookie(cookieValue) if (values && values.length == 6) { - map['userName'] = values[0] - map['expiryTime'] = values[1] - map['signature'] = values[2] - map['dealerCode'] = values[3] - map['dm'] = values[4] - map['userId'] = values[5] + map['userName'] = values[0] + map['expiryTime'] = values[1] + map['signature'] = values[2] + map['dealerCode'] = values[3] + map['dm'] = values[4] + map['userId'] = values[5] } - } - map - } + } + map + } - String findDomain(request) { - def dm = findInToken(request, 'dm') - if (dm == null) { - dm = request.getParameter('dm') - if (dm == null) { - def requestURI = request.forwardURI - Matcher matcher = DM_PATTERN.matcher(requestURI) - if (matcher.find()) { - dm = matcher.group(2) - } - } - } - if (!dm) { - throw new IllegalArgumentException('domainId is not sent') - } - dm - } + String findDomain(request, boolean failOnNull = true ) { + def dm = findInToken(request, 'dm') + if (dm == null) { + dm = request.getParameter('dm') + if (dm == null) { + def requestURI = request.forwardURI + Matcher matcher = DM_PATTERN.matcher(requestURI) + if (matcher.find()) { + dm = matcher.group(2) + } + } + } + if (!dm && failOnNull) { + throw new IllegalArgumentException('domainId is not sent') + } + dm + } - String findDealerCode(request) { - def dealerCode - MediationUserDetails mediationUserDetails = MediatorSecurityHelperService.principal - if (mediationUserDetails != null) { - dealerCode = mediationUserDetails?.dealerCode - } else { - dealerCode = findInToken(request, 'dealerCode') - } - dealerCode - } + String findDealerCode(request) { + def dealerCode + MediationUserDetails mediationUserDetails = MediatorSecurityHelperService.principal + if (mediationUserDetails != null) { + dealerCode = mediationUserDetails?.dealerCode + } else { + dealerCode = findInToken(request, 'dealerCode') + } + dealerCode + } - String findUserName(request) { - def userName - MediationUserDetails mediationUserDetails = MediatorSecurityHelperService.principal - if (mediationUserDetails != null) { - userName = mediationUserDetails.username - } else { - userName = findInToken(request, 'userName') - } - userName - } + String findUserName(request) { + def userName + MediationUserDetails mediationUserDetails = MediatorSecurityHelperService.principal + if (mediationUserDetails != null) { + userName = mediationUserDetails.username + } else { + userName = findInToken(request, 'userName') + } + userName + } - String findUserId() { - def userId - MediationUserDetails mediationUserDetails = MediatorSecurityHelperService.principal - if (mediationUserDetails != null) { - userId = mediationUserDetails.userId - } - userId - } + String findUserId() { + def userId + MediationUserDetails mediationUserDetails = MediatorSecurityHelperService.principal + if (mediationUserDetails != null) { + userId = mediationUserDetails.userId + } + userId + } Integer findUserTypeId() { MediationUserDetails mediationUserDetails = MediatorSecurityHelperService.principal if (mediationUserDetails != null) { mediationUserDetails.userTypeId } } - String findInToken(request, field) { - def tokenMap = decodeCookieAsMap(request) - String fieldValue = tokenMap[(field)] - if (fieldValue == null) { - fieldValue = request.getParameter(field) - } - fieldValue - } + String findInToken(request, field) { + def tokenMap = decodeCookieAsMap(request) + String fieldValue = tokenMap[(field)] + if (fieldValue == null) { + fieldValue = request.getParameter(field) + } + fieldValue + } - void addToCache(cacheName, cacheKey, object) { - def cache = ehCacheManager?.getCache(cacheName) - if (cache.isKeyInCache(cacheKey) == false) { + void addToCache(cacheName, cacheKey, object) { + def cache = ehCacheManager?.getCache(cacheName) + if (cache.isKeyInCache(cacheKey) == false) { log.debug "adding to cache ${cacheKey}" cache.put(new Element(cacheKey, object)) - } else { - log.debug "Already exists... ${cacheKey}" - } - } + } else { + log.debug "Already exists... ${cacheKey}" + } + } - Object getObjectFromCache(cacheName, cacheKey) { - def cache = ehCacheManager?.getCache(cacheName) - if (cache?.isKeyInCache(cacheKey)) { - return cache?.get(cacheKey)?.objectValue - } - null - } + Object getObjectFromCache(cacheName, cacheKey) { + def cache = ehCacheManager?.getCache(cacheName) + if (cache?.isKeyInCache(cacheKey)) { + return cache?.get(cacheKey)?.objectValue + } + null + } - String createUserCacheKey(dm, dealerCode, userName) { - "${dm}_${dealerCode?.toUpperCase()}_${userName?.toUpperCase()}" - } - - String getLoggedInDealerCode() { MediatorSecurityHelperService.principal.dealerCode.toString() } - - Integer getLoggedInUserId() { MediatorSecurityHelperService.principal.userId.toInteger() } - - Integer getLoggedInDomain() { MediatorSecurityHelperService.principal.domain.toInteger() } + String createUserCacheKey(dm, dealerCode, userName) { + "${dm}_${dealerCode?.toUpperCase()}_${userName?.toUpperCase()}" + } + + String getLoggedInDealerCode() { MediatorSecurityHelperService.principal.dealerCode.toString() } + + Integer getLoggedInUserId() { MediatorSecurityHelperService.principal.userId.toInteger() } + + Integer getLoggedInDomain() { MediatorSecurityHelperService.principal.domain.toInteger() } }