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:business.security.CustomAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication == null || authentication.getName() == null) {
        log.error("Empty authentication.");
        return null;
    }/*from  w  ww  . j  av  a  2  s .c  o m*/
    String username = authentication.getName().toLowerCase();
    log.info("username: " + username);
    User user = userRepository.findByUsernameAndActiveTrueAndEmailValidatedTrueAndDeletedFalse(username);
    if (user != null) {
        if (user.isAccountTemporarilyBlocked()) {
            Date now = new Date();
            long interval = now.getTime() - user.getAccountBlockStartTime().getTime();
            if (interval > ACCOUNT_BLOCKING_PERIOD * 1000) {
                // unblock account
                log.info("Unblocking blocked account for user " + user.getUsername());
                user.resetFailedLoginAttempts();
                user.setAccountTemporarilyBlocked(false);
                user = userRepository.save(user);
            } else {
                // account is temporarily blocked, deny access.
                log.info("Account still blocked for user " + user.getUsername() + ". Access denied.");
                throw new UserAccountBlocked();
            }
        }
        if (passwordService.getEncoder().matches(authentication.getCredentials().toString(),
                user.getPassword())) {
            log.info("AuthenticationProvider: OK");
            if (user.getFailedLoginAttempts() > 0) {
                user.resetFailedLoginAttempts();
                user = userRepository.save(user);
            }
            UserAuthenticationToken token = new UserAuthenticationToken(user, getAuthorityList(user));
            log.info("Token: " + token);
            return token;
        }
        // failed login attempt
        user.incrementFailedLoginAttempts();
        log.info("Login failed for user " + user.getUsername() + ". Failed attempt number "
                + user.getFailedLoginAttempts() + ".");
        if (user.getFailedLoginAttempts() >= MAX_FAILED_LOGIN_ATTEMPTS) {
            // block account
            user.setAccountTemporarilyBlocked(true);
            user.setAccountBlockStartTime(new Date());
            userRepository.save(user);
            throw new UserAccountBlocked();
        }
        userRepository.save(user);
    }
    return null;
}

From source file:ch.astina.hesperid.web.services.users.impl.UserServiceImpl.java

public User getCurrentUser() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth.isAuthenticated() == false) {
        return null;
    }/* www  . ja  v a  2  s  .c  om*/
    String username = auth.getName();
    if (username.isEmpty()) {
        return null;
    }
    return userDao.getUserByName(username);
}

From source file:com.pokerweb.servlets.holdem.ExitUserTable.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w w w .  j  a  va  2  s . c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        StringBuilder jb = new StringBuilder();
        String line = null;
        BufferedReader reader = request.getReader();
        DBManager DBM = DBManager.GetInstance();
        while ((line = reader.readLine()) != null)
            jb.append(line);
        JSONObject jsonObject = new JSONObject(jb.toString());
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        TableStatus.GetInstance().ExitTable(jsonObject.getInt("IdTable"), auth.getName());
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write("{error:null}");
    } catch (JSONException ex) {
        Logger.getLogger(GetTableInfo.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.pokerweb.servlets.holdem.SitThisUser.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w  w  w  .  ja  va2 s . c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        StringBuilder jb = new StringBuilder();
        String line = null;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
            jb.append(line);
        JSONObject jsonObject = new JSONObject(jb.toString());
        int IdTable = jsonObject.getInt("IdTable");
        int plaseId = jsonObject.getInt("plaseId");
        double summ = jsonObject.getDouble("summ");
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        TableStatus.GetInstance().SendSitThisRequest(IdTable, plaseId, summ, auth.getName());
    } catch (JSONException ex) {
        Logger.getLogger(SitThisUser.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:fr.mycellar.interfaces.web.security.CurrentUserService.java

/**
 * @return/* ww w.  j av a  2  s.  c  o m*/
 */
public String getCurrentUserEmail() {
    String email = null;
    SecurityContext context = SecurityContextHolder.getContext();
    if (context != null) {
        Authentication auth = context.getAuthentication();
        if ((auth != null) && auth.isAuthenticated() && !(auth instanceof AnonymousAuthenticationToken)) {
            email = auth.getName();
        }
    }
    return email;
}

From source file:com.healthcit.cacure.security.AuthenticationProcessingFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException {

    try {//from  w  ww  .  j  av a  2s. c  o m
        //call to daoAuthenticationProvider
        Authentication auth = super.attemptAuthentication(request, response);

        //store currentUser in HttpSession
        UserCredentials currentUser = userService.findByName(auth.getName());
        request.getSession().setAttribute(Constants.CURRENT_USER, currentUser);

        //display info about currentUser
        Collection<GrantedAuthority> gs = auth.getAuthorities();
        StringBuilder sb = new StringBuilder("===== Authentification Succesful : userName = " + auth.getName());
        sb.append(" with roles: ");
        for (GrantedAuthority x : gs) {
            sb.append(x.getAuthority()).append(",");
        }
        log.info(sb);
        return auth;
    } catch (AuthenticationException e) {
        log.info("Login wasn't successful for " + obtainUsername(request));
        throw e;
    }
}

From source file:gr.brid.castamuv.infrastructure.security.SocialConfig.java

/**
 * Request-scoped data access object providing access to the current user's
 * connections./*from  w  w  w. j  a v  a 2  s  .  co  m*/
 */
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public ConnectionRepository connectionRepository() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    return usersConnectionRepository().createConnectionRepository(auth.getName());
}

From source file:com.ericpol.notifier.web.MainController.java

@RequestMapping(value = "/new-event", method = RequestMethod.POST)
public String newEvent(@RequestParam(value = "description", defaultValue = "none") String aDescription,
        @RequestParam(value = "date-time") String aDate, Map<String, Object> model) throws ParseException {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String name = auth.getName();
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(aDate);

    final User user = userDAO.getUser(name);
    final Event newEvent = new Event();
    newEvent.setUID("custom");
    newEvent.setDescription(aDescription);
    newEvent.setDate(date);/* w ww .ja v  a  2  s  . c  o m*/
    newEvent.setNotified(true);
    newEvent.setCustom(true);
    newEvent.setIdUser(user.getId());
    userDAO.createEvent(newEvent);

    LOGGER.info("new event {}, date {}", aDescription, aDate);

    return "redirect:/";
}

From source file:io.github.autsia.crowly.security.CrowlyAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    try {//from  ww w .  j  av a2  s .c o m
        CrowlyUser dbUser = userRepository.findByEmail(authentication.getName());
        if (bCryptPasswordEncoder.matches(authentication.getCredentials().toString(), dbUser.getPassword())) {
            return new UsernamePasswordAuthenticationToken(authentication.getName(),
                    authentication.getCredentials(), getAuthorities(dbUser));
        }
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
    throw new BadCredentialsException(authentication.getName());
}

From source file:com.coinblesk.server.controller.UserControllerAuthenticated.java

@RequestMapping(value = "/logout", method = GET, produces = APPLICATION_JSON_UTF8_VALUE)
public UserAccountStatusTO logout(HttpServletRequest request, HttpServletResponse response) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    LOG.debug("Logout account for {}", auth.getName());
    if (auth != null) {
        new SecurityContextLogoutHandler().logout(request, response, auth);
    }//from   www .  java2 s. c o m
    return new UserAccountStatusTO().setSuccess();
}