Example usage for org.springframework.security.core Authentication getName

List of usage examples for org.springframework.security.core Authentication getName

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getName.

Prototype

public String getName();

Source Link

Document

Returns the name of this principal.

Usage

From source file:com.cami.persistence.service.impl.CautionService.java

@Override
public Page<Caution> filter(long banque, long typeCaution, Date debutEcheance, Date finEcheance, int page,
        Integer size) {/*  www .j  ava2s. c o m*/
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    final Role userConnected = roleDao.retrieveAUser(auth.getName()); // get the current logged user
    if (userConnected.getRole().equals("ROLE_COMMERCIAL")) {

        if (banque == -1 && typeCaution > -1) {
            return dao.filterByTypeCautionAndUser(typeCaution, debutEcheance, finEcheance,
                    userConnected.getId(), new PageRequest(page, size, Sort.Direction.DESC, "dateFin"));

        }

        if (banque > 1 && typeCaution == -1) {
            return dao.filterByBanqueAndUser(banque, debutEcheance, finEcheance, userConnected.getId(),
                    new PageRequest(page, size, Sort.Direction.DESC, "dateFin"));
        }

        if (banque > -1 && typeCaution > -1) {

            return dao.filterByTypeCautionBanqueAndUser(banque, typeCaution, debutEcheance, finEcheance,
                    userConnected.getId(), new PageRequest(page, size, Sort.Direction.DESC, "dateFin"));
        }

        if (banque == -1 && typeCaution == -1) {
            return dao.filterByUser(debutEcheance, finEcheance, userConnected.getId(),
                    new PageRequest(page, size, Sort.Direction.DESC, "dateFin"));

        }
    } else {
        if (banque == -1 && typeCaution > -1) {
            System.out.println("filtre-1");
            return dao.filterByTypeCaution(typeCaution, debutEcheance, finEcheance,
                    new PageRequest(page, size, Sort.Direction.DESC, "dateFin"));
        }

        if (banque > -1 && typeCaution == -1) {
            System.out.println("filtre-2");
            return dao.filterByBanque(banque, debutEcheance, finEcheance,
                    new PageRequest(page, size, Sort.Direction.DESC, "dateFin"));
        }

        if (banque > -1 && typeCaution > -1) {
            System.out.println("filtre-3");
            return dao.filterByTypeCautionAndBanque(banque, typeCaution, debutEcheance, finEcheance,
                    new PageRequest(page, size, Sort.Direction.DESC, "dateFin"));
        }

        if (banque == -1 && typeCaution == -1) {
            System.out.println("filtre-4");
            return dao.filter(debutEcheance, finEcheance,
                    new PageRequest(page, size, Sort.Direction.DESC, "dateFin"));
        }

    }
    return null;

}

From source file:fr.mcc.ginco.rest.services.SuggestionRestService.java

/**
 * Public method used to create new suggestions
 *///  w ww.j a  va2 s.  c  om
@GET
@Path("/getUserSuggestions")
@Produces({ MediaType.APPLICATION_JSON })
public ExtJsonFormLoadData<List<MySuggestionView>> getUserSuggestions(@QueryParam("start") Integer startIndex,
        @QueryParam("limit") Integer limit) {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String currentUser = auth.getName();

    List<Suggestion> suggestions = suggestionService.getSuggestionPaginatedListByRecipient(currentUser,
            startIndex, limit);

    List<MySuggestionView> resultSuggestions = new ArrayList<MySuggestionView>();

    for (Suggestion suggestion : suggestions) {
        SuggestionView view = suggestionViewConverter.convert(suggestion);

        MySuggestionView myView = new MySuggestionView(view);

        if (suggestion.getConcept() != null) {
            myView.setObjectIdentifier(suggestion.getConcept().getIdentifier());
            myView.setObjectValue(
                    thesaurusConceptService.getConceptLabel(suggestion.getConcept().getIdentifier()));
            myView.setThesaurusTitle(suggestion.getConcept().getThesaurus().getTitle());

        } else {
            myView.setObjectIdentifier(suggestion.getTerm().getIdentifier());
            myView.setObjectValue(suggestion.getTerm().getLexicalValue());
            myView.setThesaurusTitle(suggestion.getTerm().getThesaurus().getTitle());

        }

        resultSuggestions.add(myView);
    }

    ExtJsonFormLoadData<List<MySuggestionView>> result = new ExtJsonFormLoadData<List<MySuggestionView>>(
            resultSuggestions);
    result.setTotal(suggestionService.getSuggestionByRecipientCount(currentUser));
    return result;
}

From source file:com.castlemock.war.config.SecurityInterceptor.java

/**
 * The method will check if the logged in user is still valid.
 * @param request The incoming request.//from w w w. j a  v  a 2 s.  c om
 * @param response The outgoing response
 * @param handler The handler contains information about the method and controller that will process the incoming request
 * @return Returns true if the logged in users information is still valid. Returns false if the user is not valid
 * @throws IOException Upon unable to send a redirect as a response
 * @throws ServletException Upon unable to logout the user
 */
@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler) throws IOException, ServletException {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || !authentication.isAuthenticated()) {
        return true;
    }

    final String loggedInUsername = authentication.getName();
    if (ANONYMOUS_USER.equals(loggedInUsername)) {
        return true;
    }

    final ReadUserByUsernameInput readUserByUsernameInput = new ReadUserByUsernameInput(loggedInUsername);
    final ReadUserByUsernameOutput readUserByUsernameOutput = serviceProcessor.process(readUserByUsernameInput);
    final UserDto loggedInUser = readUserByUsernameOutput.getUser();
    if (loggedInUser == null) {
        LOGGER.info("The following logged in user is not valid anymore: " + loggedInUsername);
        request.logout();
        response.sendRedirect(request.getContextPath());
        return false;
    } else if (!Status.ACTIVE.equals(loggedInUser.getStatus())) {
        LOGGER.info("The following logged in user is not active anymore: " + loggedInUsername);
        request.logout();
        response.sendRedirect(request.getContextPath());
        return false;
    } else {
        for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
            Role role = Role.valueOf(grantedAuthority.getAuthority());
            if (!loggedInUser.getRole().equals(role)) {
                LOGGER.info("The following logged in user's authorities has been updated: " + loggedInUsername);
                final UserDetails userDetails = userDetailSecurityService.loadUserByUsername(loggedInUsername);
                final Authentication newAuthentication = new UsernamePasswordAuthenticationToken(userDetails,
                        userDetails.getPassword(), userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(newAuthentication);
            }
        }
        return true;
    }
}

From source file:com.sentinel.config.StatelessLoginFilter.java

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        FilterChain chain, Authentication authentication) throws IOException, ServletException {
    // Lookup the complete User object from the database and create an Authentication for it
    final org.springframework.security.core.userdetails.User authenticatedUser = userProfileService
            .loadUserByUsername(authentication.getName());
    final UserAuthentication userAuthentication = new UserAuthentication(authenticatedUser);
    // Add the custom token as HTTP header to the response
    tokenAuthenticationService.addAuthentication(response, userAuthentication);
    // Add the authentication to the Security context
    SecurityContextHolder.getContext().setAuthentication(userAuthentication);
}

From source file:cherry.sqlman.tool.statement.SqlStatementControllerImpl.java

private void initializeForm(SqlStatementForm form, Integer ref, Authentication auth) {
    if (ref == null) {
        form.setDatabaseName(dataSourceDef.getDefaultName());
        return;// ww w. ja v  a  2  s  . c  o  m
    }
    SqlMetadataForm mdForm = metadataService.findById(ref, auth.getName());
    if (mdForm != null) {
        SqlStatementForm f = statementService.findById(ref);
        shouldExist(f, SqlStatementForm.class, ref);
        form.setDatabaseName(f.getDatabaseName());
        form.setSql(f.getSql());
        form.setParamMap(f.getParamMap());
        form.setLockVersion(f.getLockVersion());
    }
}

From source file:net.solarnetwork.central.dras.aop.SecurityAspectSupport.java

/**
 * Get the ID of the acting user.//  ww  w.  j  a  v a 2s .  c o  m
 * 
 * @return ID, or <em>null</em> if not available
 */
protected final Long getCurrentUserId() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth == null) {
        log.info("No Authentication available, cannot tell current user ID");
        return null;
    }
    String currentUserName = auth.getName();
    SimpleUserFilter filter = new SimpleUserFilter();
    filter.setUniqueId(currentUserName);
    FilterResults<Match> results = userDao.findFiltered(filter, null, null, null);
    if (results.getReturnedResultCount() < 1) {
        log.debug("User not found for username {}", currentUserName);
        return null;
    }
    return results.getResults().iterator().next().getId();
}

From source file:com.alehuo.wepas2016projekti.controller.ImageController.java

/**
 * Kuvasta tykkys/*ww  w .jav a2  s.c o  m*/
 *
 * @param a Autentikointi
 * @param imageUuid Kuvan UUID
 * @param redirect Uudelleenohjaus
 * @param req HTTP Request
 * @return Onnistuiko pyynt vai ei (sek sen tyyppi; unlike vai like).
 */
@RequestMapping(value = "/like", method = RequestMethod.POST)
public ResponseEntity<String> likeImage(Authentication a, @RequestParam String imageUuid,
        @RequestParam int redirect, HttpServletRequest req) {
    //Kyttjn autentikoiminen
    UserAccount u = userService.getUserByUsername(a.getName());
    final HttpHeaders h = new HttpHeaders();
    //Jos kyttjtili ei ole tyhj
    if (u != null) {
        //Haetaan kuva
        Image i = imageService.findOneImageByUuid(imageUuid);

        //Jos kuva ei ole tyhj
        if (i != null && i.isVisible()) {
            //Lis / poista tykkys tilanteen mukaan
            if (i.getLikedBy().contains(u)) {
                LOG.log(Level.INFO, "Kayttaja ''{0}'' poisti tykkayksen kuvasta ''{1}''",
                        new Object[] { a.getName(), imageUuid });
                i.removeLike(u);
                imageService.saveImage(i);
                h.add("LikeType", "unlike");
            } else {
                i.addLike(u);
                LOG.log(Level.INFO, "Kayttaja ''{0}'' tykkasi kuvasta ''{1}''",
                        new Object[] { a.getName(), imageUuid });
                imageService.saveImage(i);
                h.add("LikeType", "like");
            }
            //Uudelleenohjaus
            if (redirect == 1) {
                h.add("Location", req.getHeader("Referer"));
                return new ResponseEntity<>(h, HttpStatus.FOUND);
            }
            return new ResponseEntity<>(h, HttpStatus.OK);
        } else {
            //Jos kuvaa ei ole olemassa mutta yritetn silti tykt
            LOG.log(Level.WARNING, "Kayttaja ''{0}'' yritti tykata kuvaa, mita ei ole olemassa. ({1})",
                    new Object[] { a.getName(), imageUuid });
            return new ResponseEntity<>(h, HttpStatus.BAD_REQUEST);
        }
    }
    //Jos ei olla kirjauduttu sisn ja yritetn tykt kuvasta
    LOG.log(Level.WARNING, "Yritettiin tykata kuvaa kirjautumatta sisaan ({0})", a.getName());
    return new ResponseEntity<>(h, HttpStatus.UNAUTHORIZED);
}

From source file:com.auditbucket.helper.SecurityHelper.java

public SystemUser getSysUser(boolean exceptionOnNull) {
    Authentication a = SecurityContextHolder.getContext().getAuthentication();
    if (a == null)
        if (exceptionOnNull)
            throw new SecurityException("User is not authenticated");
        else/*from  www .  ja v a2  s.  c  om*/
            return null;

    return sysUserService.findByName(a.getName());
}

From source file:architecture.user.security.spring.authentication.ExtendedAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    try {//from   w  ww.j av  a2  s . c o  m
        return super.authenticate(authentication);
    } catch (AuthenticationException e) {
        if (log.isInfoEnabled())
            log.info(L10NUtils.format("005012", authentication != null ? authentication.getName() : "<unknown>",
                    e.getMessage()));
        if (log.isTraceEnabled())
            log.trace(L10NUtils.getMessage("005013"), e);
        throw e;
    } catch (RuntimeException e) {
        log.warn(L10NUtils.format("005014", authentication != null ? authentication.getName() : "<unknown>"),
                e);
        throw e;
    }
}

From source file:com.epam.storefront.security.AcceleratorAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
            : authentication.getName();

    if (getBruteForceAttackCounter().isAttack(username)) {
        try {/*from  w w w .  j a v  a  2  s .c  o m*/
            final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(username));

            if (userModel instanceof CustomerModel) {
                final CustomerModel customerModel = (CustomerModel) userModel;

                customerModel.setLoginDisabled(true);
                customerModel.setStatus(Boolean.TRUE);
                customerModel.setAttemptCount(Integer.valueOf(0));

                getModelService().save(customerModel);
            } else {
                userModel.setLoginDisabled(true);
                getModelService().save(userModel);
            }

            bruteForceAttackCounter.resetUserCounter(userModel.getUid());
        } catch (final UnknownIdentifierException e) {
            LOG.warn("Brute force attack attempt for non existing user name " + username);
        } finally {
            throw new BadCredentialsException(
                    messages.getMessage("CoreAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    }

    return doAuth(authentication, username);
}