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.auditbucket.helper.SecurityHelper.java

public String getLoggedInUser() {
    Authentication a = SecurityContextHolder.getContext().getAuthentication();
    if (a == null)
        throw new SecurityException("User is not authenticated");
    return a.getName();
}

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

@RequestMapping(value = "/get", method = GET, produces = APPLICATION_JSON_UTF8_VALUE)
@ResponseBody/* ww w. ja v  a  2s.co  m*/
public UserAccountTO getAccount() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    LOG.debug("Get account for {}", auth.getName());
    try {

        UserAccountTO userAccount = userAccountService.get(auth.getName());
        if (userAccount == null) {
            LOG.error("Someone tried to access an account with an invalid username: {}", auth);
            mailService.sendAdminMail("Wrong Account?",
                    "Someone tried to access an account with an invalid username: " + auth);
            return null;
        }
        LOG.debug("Get account success for {}", auth.getName());
        return userAccount;
    } catch (Exception e) {
        LOG.error("User create error", e);
        return new UserAccountTO().type(Type.SERVER_ERROR).message(e.getMessage());
    }
}

From source file:com.kcs.core.actions.LoginAction.java

@Override
public String success() throws Exception {
    try {/* w  w w  .  ja  va 2 s  .  c o  m*/
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        logger.debug("auth : " + auth);
        setCurrentUser(authorizeService.authenticateUser(auth.getName(),
                convertPasswordBase64(auth.getCredentials().toString())));
        if (null != getCurrentUser()) {
            logger.debug("login success!");
            getCurrentUser().setMenuList(authorizeService.authorizeMenuUser(getCurrentUser().getEmpNo()));
            session.put(DmsConstant.SESSION.LOGIN_KEY, getCurrentUser());
            session.put(DmsConstant.SESSION.LOGIN_ID, getCurrentUser().getEmpNo());
        } else {
            logger.debug("login fail!");
            return FAIL;
        }

        //            UserData cur = new UserData();
        //            cur.setEmpNo("0000");
        //            setCurrentUser(cur);
        //            session.put(DmsConstant.SESSION.LOGIN_KEY, getCurrentUser());
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    return SUCCESS;
}

From source file:ru.codemine.ccms.service.EmployeeService.java

@Transactional
public Employee getCurrentUser() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        return employeeDAO.getByUsername(auth.getName());
    }//from   w w  w .ja v a 2 s  .c  o  m

    return new Employee();
}

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

@RequestMapping(value = "/delete", method = PATCH, produces = APPLICATION_JSON_UTF8_VALUE)
@ResponseBody//  w w w .  j  a  va 2s . c  om
public UserAccountStatusTO deleteAccount() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    LOG.debug("Delete account for {}", auth.getName());
    try {
        UserAccountStatusTO status = userAccountService.delete(auth.getName());
        if (!status.isSuccess()) {
            LOG.error("Someone tried a delete account with an invalid username: {}/{}", auth,
                    status.type().name());
            mailService.sendAdminMail("Wrong Delete Account?",
                    "Someone tried a delete account with an invalid username: " + auth + "/"
                            + status.type().name());
        }
        LOG.debug("Delete account success for {}", auth.getName());
        return status;

    } catch (Exception e) {
        LOG.error("User create error", e);
        return new UserAccountStatusTO().type(Type.SERVER_ERROR).message(e.getMessage());
    }
}

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

@RequestMapping(value = "/change-password", method = POST, produces = APPLICATION_JSON_UTF8_VALUE, consumes = APPLICATION_JSON_UTF8_VALUE)
public UserAccountStatusTO changePassword(@RequestBody UserAccountTO to, HttpServletRequest request,
        HttpServletResponse response) {//from  w  w  w  .  j av  a 2 s . c o  m
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    LOG.debug("Change password account for {}", auth.getName());
    if (auth != null) {
        UserAccountStatusTO status = userAccountService.changePassword(auth.getName(), to.password());
        return status;
    } else {
        return new UserAccountStatusTO().type(Type.ACCOUNT_ERROR);
    }

}

From source file:com.pokerweb.Area.CheckBetArea.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// ww  w  .j av a  2s.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 {
    String Token = "";
    for (Cookie object : request.getCookies())
        if (object.getName().equals("JSESSIONID"))
            Token = object.getValue();
    if (Token.length() <= 0)
        return;
    JSONObject js = new JSONObject();
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    long UserId = DBManager.GetInstance().GetCurrentUserId(auth.getName());
    for (Map.Entry<Long, StatisticBet> object : TableStatus.GetInstance().RequestStatisticBet.entrySet())
        if (object.getValue().ToketUserRequest.equals(Token) && object.getKey() == UserId)
            if (TableStatus.GetInstance().StatisticBetCurrentUser.containsKey(object.getValue().IdBet)) {
                try {
                    Game GMData = new Game();
                    String data = data = GMData.GetDateFromBet(object.getValue().IdBet);
                    TableStatus.GetInstance().StatisticBetCurrentUser.get(object.getValue().IdBet).put("date",
                            data);
                    TableStatus.GetInstance().StatisticBetCurrentUser.get(object.getValue().IdBet).put("round",
                            GMData.GetRoundFromBet(object.getValue().IdBet));
                    js.put("StatisticCurrentUser",
                            TableStatus.GetInstance().StatisticBetCurrentUser.get(object.getValue().IdBet));
                    TableStatus.GetInstance().StatisticBetCurrentUser.remove(object.getValue().IdBet);
                    TableStatus.GetInstance().RequestStatisticBet.remove(
                            TableStatus.GetInstance().StatisticBetCurrentUser.get(object.getValue().IdBet));
                } catch (JSONException ex) {
                    Logger.getLogger(CheckBetArea.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
    response.setContentType("application/json; charset=utf-8");
    response.setHeader("Cache-Control", "no-cache");
    response.getWriter().write(js.toString());
}

From source file:com.traffitruck.web.JsonController.java

@RequestMapping(value = "/alertFromFilter", method = RequestMethod.POST)
String newAlert(@RequestParam("source") String source, @RequestParam("sourceLat") Double sourceLat,
        @RequestParam("sourceLng") Double sourceLng, @RequestParam("destination") String destination,
        @RequestParam("destinationLat") Double destinationLat,
        @RequestParam("destinationLng") Double destinationLng) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication.getName();
    Alert alert = new Alert();
    alert.setUsername(username);/* w  w w.ja va2  s  .c o m*/
    if (source != null && sourceLat != null && sourceLng != null) {
        alert.setSource(source);
        alert.setSourceLocation(new Location(new double[] { sourceLng, sourceLat }));
    }
    if (destination != null && destinationLat != null && destinationLng != null) {
        alert.setDestination(destination);
        alert.setDestinationLocation(new Location(new double[] { destinationLng, destinationLat }));
    }
    dao.storeAlert(alert);
    return "Success!";
}

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

@RequestMapping("/")
public String welcome(ModelMap aMap) throws IOException {
    // model.put("time", new Date());
    // model.put("message", this.message);

    /*/*from w w w .jav a  2s. c  om*/
     * LotusNotesManager lotusNotesManager = new LotusNotesManager(); Calendar now = Calendar.getInstance();
     * now.add(Calendar.DATE, 30 * -1); // Clear out the time portion now.set(Calendar.HOUR_OF_DAY, 0);
     * now.set(Calendar.MINUTE, 0); now.set(Calendar.SECOND, 0); Date startDate = now.getTime(); now =
     * Calendar.getInstance(); now.add(Calendar.DATE, 30); // Set the time portion now.set(Calendar.HOUR_OF_DAY,
     * 23); now.set(Calendar.MINUTE, 59); now.set(Calendar.SECOND, 59); Date endDate = now.getTime(); // Date
     * startDate = call.getTime(); LOGGER.info("run date is: {}", startDate); LOGGER.info("end date is: {}",
     * endDate); lotusNotesManager.setServer("LN1-BRS1"); //
     * lotusNotesManager.setServerDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
     * lotusNotesManager.setServerDateFormat("Detect"); lotusNotesManager.setMailFile("mail\\vvai.nsf");
     * lotusNotesManager.setPassword(""); lotusNotesManager.setMinStartDate(startDate);
     * lotusNotesManager.setMaxEndDate(endDate); lotusNotesManager.setDiagnosticMode(false);
     * lotusNotesManager.setRequiresAuth(true); LOGGER.info("before get calendar entries"); final
     * ArrayList<LotusNotesCalendarEntry> calendarEntries = lotusNotesManager.getCalendarEntries(); for
     * (LotusNotesCalendarEntry eachCalendarEntry : calendarEntries) {
     * LOGGER.info("entry subject: {}, startDate: {}, endDate: {}", eachCalendarEntry.getSubject(),
     * eachCalendarEntry.getStartDateTime(), eachCalendarEntry.getEndDateTime()); }
     * LOGGER.info("after get calendar entries, size: {}", calendarEntries.size());
     */

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String name = auth.getName();
    LOGGER.info("user is {}", name);

    final User user = userDAO.getUser(name);
    aMap.addAttribute("user", user);
    if (user != null) {
        final List<Event> userEvents = userDAO.getUserEvents(user);
        Collections.sort(userEvents);
        aMap.addAttribute("events", userEvents);
    }

    return "index";
}

From source file:eu.freme.broker.tools.ratelimiter.RateLimitingFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    if (rateLimiterEnabled) {

        HttpServletRequest request = (HttpServletRequest) req;
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        username = auth.getName();
        if (username.equals("anonymousUser")) {
            username = req.getRemoteAddr();
        } else {/*from   w w  w .  j ava2s  . com*/
            User user = ((User) auth.getPrincipal());
            username = user.getName();
        }

        userRole = ((SimpleGrantedAuthority) auth.getAuthorities().toArray()[0]).getAuthority();

        long size = req.getContentLength();
        if (size == 0) {
            try {
                size = request.getHeader("input").length();
            } catch (NullPointerException e) {
                //Then the size is truly 0
            }
        }
        try {
            rateLimiterInMemory.addToStoredRequests(username, new Date().getTime(), size,
                    request.getRequestURI(), userRole);
        } catch (TooManyRequestsException e) {
            HttpServletResponse response = (HttpServletResponse) res;
            exceptionHandlerService.writeExceptionToResponse(request, response, e);
            return;
        }
    }

    chain.doFilter(req, res);

}