List of usage examples for org.springframework.security.core Authentication isAuthenticated
boolean isAuthenticated();
AuthenticationManager
. From source file:org.yes.cart.bulkjob.bulkimport.LocalFileShareImportListenerImpl.java
private void runShopRootScan(final Logger defaultLog, final File shopDir, final String importDirPath, final Set<String> importGroupNames) { final Shop shop = shopService.getShopByCode(shopDir.getName()); if (shop != null) { ShopCodeContext.setShopCode(shop.getCode()); ShopCodeContext.setShopId(shop.getShopId()); final Logger shopLog = ShopCodeContext.getLog(this); try {/*w ww. j a v a 2 s . c o m*/ defaultLog.info("Scanning processed directory for shop {}", shop.getCode()); shopLog.info("Scanning processed directory"); final File config = ensureDirectoryExists(defaultLog, shopLog, shopDir, shop, "config"); final File configProps = new File(config, "config.properties"); if (!configProps.exists()) { defaultLog.info("Configuration file is missing for shop {} ... skipping", shop.getCode()); shopLog.info("Configuration file is missing ... skipping"); return; } final Map<Pattern, Map<String, String>> patternGroupMap = loadShopAutoImportConfigurations(shopLog, configProps, importGroupNames); final File processed = ensureDirectoryExists(defaultLog, shopLog, shopDir, shop, "processed"); final File[] readyForImport = processed.listFiles(); if (readyForImport == null || readyForImport.length == 0) { defaultLog.info("No new files to import for shop {}", shop.getCode()); shopLog.info("No new files to import for shop {}", shop.getCode()); return; } final SimpleDateFormat format = new SimpleDateFormat("_yyyy-MMM-dd-hh-mm-ss-SSS"); for (final File toImport : prioritiseProcessedFiles(readyForImport)) { final String timestamp = format.format(new Date()); final File targetDirectory = new File(importDirPath + File.separator + PRINCIPAL + timestamp); targetDirectory.mkdirs(); defaultLog.info("Moving files to '{}' for shop {}", targetDirectory.getAbsolutePath(), shop.getCode()); shopLog.info("Moving files to '{}' for shop {}", targetDirectory.getAbsolutePath(), shop.getCode()); Map<String, String> groupData = null; for (final Map.Entry<Pattern, Map<String, String>> group : patternGroupMap.entrySet()) { if (group.getKey().matcher(toImport.getName()).matches()) { groupData = group.getValue(); break; } } if (groupData == null) { defaultLog.warn("Importing '{}' for shop {} ... skipping (no valid import group)", toImport.getAbsolutePath(), shop.getCode()); shopLog.warn("Importing '{}' for shop {} ... skipping (no valid import group)", toImport.getAbsolutePath(), shop.getCode()); continue; } final String groupName = groupData.get("group"); defaultLog.info("Importing '{}' for shop {} using group {}", new Object[] { toImport.getAbsolutePath(), shop.getCode(), groupName }); shopLog.info("Importing '{}' for shop {} using group {}", new Object[] { toImport.getAbsolutePath(), shop.getCode(), groupName }); final String destination = moveFileToImportDirectory(toImport, targetDirectory); try { final String user = groupData.get("user"); final String pass = groupData.get("pass"); final Authentication shopAuth = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(user, pass)); if (shopAuth.isAuthenticated()) { SecurityContextHolder.getContext().setAuthentication( new RunAsUserAuthentication(user, pass, shopAuth.getAuthorities())); // Make this synchronous since we are already in async process final String importToken = importDirectorService.doImport(groupName, destination, false); final JobStatus importStatus = importDirectorService.getImportStatus(importToken); defaultLog.info("Importing '{}' for shop {} using group {} ... completed [{}]", new Object[] { toImport.getAbsolutePath(), shop.getCode(), groupName, importStatus.getCompletion() }); shopLog.info("Importing '{}' for shop {} using group {} ... completed [{}]", new Object[] { toImport.getAbsolutePath(), shop.getCode(), groupName, importStatus.getCompletion() }); remoteDevService.evictAllCache(); if (importStatus.getCompletion() == JobStatus.Completion.OK) { final boolean reindex = Boolean.valueOf(groupData.get("reindex")); if (reindex) { defaultLog.info("Re-indexed products for shop {} using group {} ... starting", new Object[] { shop.getCode(), groupName }); shopLog.info("Re-indexed products for shop {} using group {} ... starting", new Object[] { shop.getCode(), groupName }); Thread.sleep(INDEX_GET_READY_TIMEOUT); // let cache invalidation run before index final String indexToken = reindexService .reindexShopProducts(ShopCodeContext.getShopId()); while (true) { Thread.sleep(INDEX_PING_INTERVAL); JobStatus reindexStatus = reindexService.getIndexAllStatus(indexToken); if (reindexStatus.getState() == JobStatus.State.FINISHED) { defaultLog.info( "Re-indexed products for shop {} using group {} ... completed [{}]", new Object[] { shop.getCode(), groupName, reindexStatus.getCompletion() }); shopLog.info( "Re-indexed products for shop {} using group {} ... completed [{}]", new Object[] { shop.getCode(), groupName, reindexStatus.getCompletion() }); remoteDevService.evictAllCache(); Thread.sleep(WARMUP_GET_READY_TIMEOUT); remoteDevService.warmUp(); break; } } } } } else { defaultLog.warn("Invalid credentials for '{}' for shop {} using group {}", new Object[] { user, shop.getCode(), groupName }); shopLog.warn("Invalid credentials for '{}' for shop {} using group {}", new Object[] { user, shop.getCode(), groupName }); } } finally { // Reinstate global context of AutoImport SecurityContextHolder.getContext().setAuthentication(global); } } } catch (Exception exp) { defaultLog.error("Failed import configuration " + shop.getCode(), exp); shopLog.error("Failed import configuration " + shop.getCode(), exp); } finally { ShopCodeContext.clear(); } } }
From source file:org.yes.cart.domain.interceptor.AdminInterceptor.java
private Runnable createEvictCacheRunnable(final String op, final String entityName, final Long pk) { final AsyncContext jobContext = ThreadLocalAsyncContextUtils.getContext(); final Authentication auth = SecurityContextHolder.getContext() != null ? SecurityContextHolder.getContext().getAuthentication() : null;// w ww. j a va 2 s.c om final String username = auth != null && auth.isAuthenticated() ? auth.getName() : null; return new Runnable() { @Override public void run() { try { final AsyncContext threadContext; if (StringUtils.isBlank(username)) { threadContext = jobContext; } else { SecurityContextHolder.getContext().setAuthentication( new RunAsUserAuthentication(username, "", Collections.EMPTY_LIST)); final Map<String, Object> params = new HashMap<String, Object>(); params.put(AsyncContext.TIMEOUT_KEY, AttributeNamesKeys.System.SYSTEM_BACKDOOR_CACHE_TIMEOUT_MS); threadContext = asyncContextFactory.getInstance(params); } if (threadContext == null) { LOG.debug("Cannot invalidate cache for entity [" + entityName + "] pk value = [" + pk + "] - no async context "); return; } final List<Node> cluster = nodeService.getSfNodes(); final List<String> targets = new ArrayList<String>(); for (final Node node : cluster) { targets.add(node.getId()); } final HashMap<String, Object> payload = new HashMap<String, Object>(); payload.put("entityOperation", op); payload.put("entityName", entityName); payload.put("pkValue", pk); final RspMessage message = new ContextRspMessageImpl(nodeService.getCurrentNodeId(), targets, "CacheDirector.onCacheableChange", payload, threadContext); nodeService.broadcast(message); } catch (Exception exp) { LOG.error("Unable to perform cache eviction: " + exp.getMessage(), exp); } finally { SecurityContextHolder.clearContext(); } } }; }
From source file:ro.nextreports.server.security.ExternalAuthenticationProvider.java
public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!canResolve(authentication)) { return null; // it's ok to return null to ignore/skip the provider (see ProviderManager javadocs) }/*from www .ja v a2s. c o m*/ String username = authentication.getName(); if (LOG.isDebugEnabled()) { LOG.debug("Trying to authenticate user '{}' via {}", username, realm); } try { authentication = doAuthenticate(authentication); } catch (AuthenticationException e) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to authenticate user {} via {}: {}", new Object[] { username, realm, e.getMessage() }); } throw e; } catch (Exception e) { String message = "Unexpected exception in " + realm + " authentication:"; LOG.error(message, e); throw new AuthenticationServiceException(message, e); } if (!authentication.isAuthenticated()) { return authentication; } // user authenticated if (LOG.isDebugEnabled()) { LOG.debug("'{}' authenticated successfully by {}.", username, realm); } User user = (User) authentication.getPrincipal(); applyPatch(user); createOrUpdateUser(user); /* // create new authentication response containing the user and it's authorities NextServerAuthentication authenticationToken = new NextServerAuthentication(user, authentication.getCredentials()); return authenticationToken; */ return authentication; }
From source file:ubc.pavlab.aspiredb.server.security.authentication.UserManagerImpl.java
@Override public String getCurrentUsername() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth == null || !auth.isAuthenticated()) { throw new IllegalStateException("Not authenticated!"); }/*from www .j av a2 s. c o m*/ if (auth.getPrincipal() instanceof UserDetails) { return ((UserDetails) auth.getPrincipal()).getUsername(); } return auth.getPrincipal().toString(); }
From source file:ubic.gemma.web.controller.common.auditAndSecurity.UserFormMultiActionController.java
/** * AJAX entry point. Loads a user./*from w w w .j ava 2 s. c o m*/ */ @RequestMapping("/loadUser.html") public void loadUser(HttpServletRequest request, HttpServletResponse response) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); boolean isAuthenticated = authentication.isAuthenticated(); if (!isAuthenticated) { log.error("User not authenticated. Cannot populate user data."); return; } Object o = authentication.getPrincipal(); String username; if (o instanceof UserDetails) { username = ((UserDetails) o).getUsername(); } else { username = o.toString(); } User user = userManager.findByUserName(username); JSONUtil jsonUtil = new JSONUtil(request, response); String jsonText = null; try { if (user == null) { // this shouldn't happen. jsonText = "{success:false,message:'No user with name " + username + "}"; } else { jsonText = "{success:true, data:{username:" + "\"" + username + "\"" + ",email:" + "\"" + user.getEmail() + "\"" + "}}"; } } catch (Exception e) { jsonText = "{success:false,message:" + e.getLocalizedMessage() + "}"; } finally { try { jsonUtil.writeToResponse(jsonText); } catch (IOException e) { e.printStackTrace(); } } }