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:de.tudarmstadt.ukp.csniper.webapp.page.ApplicationPageBase.java

@SuppressWarnings({ "serial" })
private void commonInit() {
    getSession().setLocale(Locale.ENGLISH);

    logInOutPanel = new LogInOutPanel("logInOutPanel");
    helpPanel = new InfoPanel("helpPanel", "page.help");
    macroPanel = new InfoPanel("macroPanel", "page.macros") {
        @Override/*from   w  ww .ja  va2 s  . c o  m*/
        protected void initialize() {
            super.initialize();
            Map<String, String> macros = new HashMap<String, String>();
            for (CqpMacro macro : CqpEngine.getMacros()) {
                macros.put(macro.getName(), macro.getBodyAsHtml());
            }
            infoPanel.replaceWith(new ExpandableList("infoPanel", macros));
        }
    };
    openHelp = new AjaxLink<Void>("openHelp") {
        @Override
        public void onClick(AjaxRequestTarget aTarget) {
            helpPanel.setVisible(!helpPanel.isVisible());
            aTarget.add(helpPanel);
        }
    };
    openMacros = new AjaxLink<Void>("openMacros") {
        @Override
        public void onClick(AjaxRequestTarget aTarget) {
            macroPanel.setVisible(!macroPanel.isVisible());
            aTarget.add(macroPanel);
        }
    };
    feedbackPanel = new FeedbackPanel("feedbackPanel");
    feedbackPanel.setOutputMarkupId(true);
    feedbackPanel.setFilter(new IFeedbackMessageFilter() {
        @Override
        public boolean accept(FeedbackMessage aMessage) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String username = auth != null ? auth.getName() : "UNKNOWN";
            if (aMessage.isFatal()) {
                LOG.fatal(username + ": " + aMessage.getMessage());
            } else if (aMessage.isError()) {
                LOG.error(username + ": " + aMessage.getMessage());
            } else if (aMessage.isWarning()) {
                LOG.warn(username + ": " + aMessage.getMessage());
            } else if (aMessage.isInfo()) {
                LOG.info(username + ": " + aMessage.getMessage());
            } else if (aMessage.isDebug()) {
                LOG.debug(username + ": " + aMessage.getMessage());
            }
            return true;
        }
    });

    Properties props = getVersionProperties();
    versionLabel = new Label("version",
            props.getProperty("version") + " (" + props.getProperty("timestamp") + ")");

    add(openHelp);
    add(openMacros);
    add(helpPanel);
    add(macroPanel);
    add(logInOutPanel);
    add(feedbackPanel);
    add(versionLabel);
}

From source file:fr.xebia.monitoring.demo.payment.CreditCardServiceAuditingImpl.java

@Override
public PaymentTransaction purchase(MonetaryAmount total, Order order, String requestId) {
    StringBuilder auditMessage = new StringBuilder("creditcardservice.purchase(" + requestId + ", "
            + order.getAccount().getEmail() + ", " + total + ") by ");
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        auditMessage.append("anonymous");
    } else {/*from  w  w  w .  ja v  a 2s .c  o m*/
        auditMessage.append(authentication.getName());
        if (authentication.getDetails() instanceof WebAuthenticationDetails) {
            WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
            auditMessage.append(" coming from " + details.getRemoteAddress());
        }
    }

    long nanosBefore = System.nanoTime();
    try {
        PaymentTransaction paymentTransaction = creditCardService.purchase(total, order, requestId);

        auditMessage.append(" SUCCESS ").append(paymentTransaction.getTransactionId());
        auditMessage.append(" in ")
                .append(TimeUnit.MILLISECONDS.convert(System.nanoTime() - nanosBefore, TimeUnit.NANOSECONDS))
                .append(" ms");
        auditLogger.info(auditMessage.toString());
        return paymentTransaction;
    } catch (RuntimeException e) {
        auditMessage.append(" FAILURE ").append(Joiner.on(", ").join(Throwables.getCausalChain(e)));
        auditMessage.append(" in ")
                .append(TimeUnit.MILLISECONDS.convert(System.nanoTime() - nanosBefore, TimeUnit.NANOSECONDS))
                .append(" ms");
        auditLogger.warn(auditMessage.toString());
        throw e;
    }

}

From source file:co.com.carpco.altablero.spring.web.controller.ClassRoomController.java

@RequestMapping(value = "/admin/cursos/edicion", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView classRoomEdit(@RequestParam(value = "classroomId", required = false) Integer idClassRoom) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (!(auth instanceof AnonymousAuthenticationToken)) {
        ModelAndView model = roleUtils.createModelWithUserDetails(auth.getName());
        UserBO user = userBll.getUserByDocumentNumber(auth.getName());
        List<GradeBO> gradeList = new ArrayList<>(gradeBll.getGradeSet());
        List<YearBO> yearList = new ArrayList<>(yearBll.getYearSet());
        List<UserBO> teacherList = new ArrayList<>(userBll.getTeacherSet(user.getSchool().getId()));
        Collections.sort(gradeList);
        Collections.sort(yearList);
        Collections.sort(teacherList);

        if (idClassRoom != null) {
            ClassRoomBO classRoomBO = classRoomBll.getClassRoom(idClassRoom, user.getSchool().getId());
            model.addObject("classroom", classRoomBO);
        }//  ww  w.  ja  v a2s  . com

        model.addObject("years", yearList);
        model.addObject("grades", gradeList);
        model.addObject("teachers", teacherList);
        model.setViewName("admin/classroom/edit");
        return model;
    } else {
        return new ModelAndView("redirect:/login");
    }
}

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

@Override
public List<AppelOffre> getThemComplete() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    final Role userConnected = roleDao.retrieveAUser(auth.getName()); // get the current logged user
    List<Caution> cautions = new ArrayList<>();
    List<AppelOffre> appelOffres = offreDao.findAll();
    if (userConnected.getRole().equals("ROLE_COMMERCIAL")) {
        for (AppelOffre appelOffre : appelOffres) {
            appelOffre.setCautions(dao.filterByAppelOffreAndUser(appelOffre.getId(), userConnected.getId()));
            appelOffre.setLigneAppels(ligneAppelDao.filterByAppelOffre(appelOffre.getId()));
        }//from   ww  w  . j  a  v  a  2s . c o m
        return appelOffres;
    } else {
        for (AppelOffre appelOffre : appelOffres) {
            System.out.println("gnration de la page pour une user admin ou tresorier ");
            appelOffre.setCautions(dao.filterByAppelOffre(appelOffre.getId()));
            appelOffre.setLigneAppels(ligneAppelDao.filterByAppelOffre(appelOffre.getId()));
        }
        return appelOffres;
    }
}

From source file:cherry.sqlapp.controller.sqltool.clause.SqltoolClauseIdControllerImpl.java

@Override
public SqltoolMetadataForm getMetadata(int id, Authentication auth) {
    SqltoolMetadata md = metadataService.findById(id, auth.getName());
    shouldExist(md, SqltoolMetadata.class, id, auth.getName());
    return mdFormUtil.getMdForm(md);
}

From source file:com.qpark.eip.core.spring.security.EipAffirmativeBased.java

/**
 * @see org.springframework.security.access.vote.AffirmativeBased#decide(org.springframework.security.core.Authentication,
 *      java.lang.Object, java.util.Collection)
 *//*ww w.j  av  a  2 s.  c  o  m*/
@Override
public void decide(final Authentication authentication, final Object object,
        final Collection<ConfigAttribute> configAttributes) throws AccessDeniedException {
    String channelName = EipRoleVoter.getChannelName(object);
    this.logger.debug("+decide {} {}", channelName, authentication.getName());
    try {
        super.decide(authentication, object, configAttributes);
    } catch (AccessDeniedException e) {
        for (AccessDecisionVoter<?> voter : this.getDecisionVoters()) {
            if (EipRoleVoter.class.isInstance(voter)) {
                this.logger.warn(" decide - vote failed {} {}: required  [{}]", channelName,
                        authentication.getName(), ((EipRoleVoter) voter).getRequiredRoles(configAttributes));
                this.logger.warn(" decide - vote failed {} {}: userroles [{}]", channelName,
                        authentication.getName(), ((EipRoleVoter) voter).getGrantedRoles(authentication));
                break;
            }
        }
        this.logger.info(" decide {} {}: {}", channelName, authentication.getName(), e.getMessage());
        throw e;
    } finally {
        this.logger.debug("-decide {} {}", channelName, authentication.getName());
    }
}

From source file:com.epam.cme.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  ww .  ja  v a2  s  . c  o  m
            final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(username));
            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"));
        }
    }
    checkUserCart(username);
    return super.authenticate(authentication);
}

From source file:controller.PaymentController.java

@RequestMapping(value = "/process", method = RequestMethod.GET)
public ModelAndView processPayment(Authentication authen, HttpServletRequest req, @RequestParam int month) {
    ModelAndView model = new ModelAndView();
    try {/*from  w w w. java2 s . c  o m*/
        model.setViewName("processPayment");
        Customer cus = cusModel.find(authen.getName(), "username", false).get(0);
        int orderID = orderModel.getOrderIDByCustomerNonActive(cus.getCustomerId());
        int orderIDActive = orderModel.getOrderIDByCustomer(cus.getCustomerId());
        Order order = orderModel.getByID(orderID);
        Order orderActive = orderModel.getByID(orderIDActive);
        if (order.getStatus() == 1) {
            order.setOderId(0);
            Calendar ca = Calendar.getInstance();
            ca.setTime(orderActive.getOrderExpiredDate());
            ca.add(Calendar.MONTH, month);
            order.setOrderExpiredDate(new Date(ca.getTimeInMillis()));
        } else {
            Calendar ca = Calendar.getInstance();
            ca.setTime(orderActive.getOrderExpiredDate());
            ca.add(Calendar.MONTH, month);
            order.setOrderExpiredDate(ca.getTime());
        }
        order.setOrderPaymentDate(new Date());

        order.setStatus((byte) 0);
        Set<OderDetail> listOrderDetail = order.getOderDetails();
        orderModel.addOrUpdate(order);

        for (OderDetail orderdetail : listOrderDetail) {
            orderdetail.setId(new OderDetailId(order.getOderId(), orderdetail.getId().getPackageId()));
        }
        model.addObject("check", orderModel.addOrUpdate(order));
        model.addObject("alert", "Send request success");
        model.addObject("link", req.getContextPath() + "/index.html");
    } catch (Exception ex) {
        ex.printStackTrace();
        model.addObject("alert", "Error: " + ex.getMessage());
    }
    return model;
}

From source file:com.acc.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 {// w  w  w.ja v  a  2s. co  m
            final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(username));
            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"));
        }
    }

    checkCartForUser(username);
    return super.authenticate(authentication);

}

From source file:com.orchestra.portale.controller.UserInfoController.java

@RequestMapping(value = "/userInfo")
@Secured("ROLE_USER")
public ModelAndView getUserInfo(HttpServletRequest request) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    ModelAndView model = new ModelAndView("userInfo");
    ModelAndView model2 = new ModelAndView("index");
    if (auth != null) {
        User user = pm.findUserByUsername(auth.getName());
        HttpSession session = request.getSession();
        ServletContext sc = session.getServletContext();
        File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "user" + File.separator + "img"
                + File.separator + user.getId() + File.separator + "avatar.jpg");
        if (dir.exists()) {
            model.addObject("avatar", "./dist/user/img/" + user.getId() + "/avatar.jpg");
        } else {//from  w  ww.j  a va 2 s .  com
            model.addObject("avatar", "./dist/img/default_avatar.png");
        }

        model.addObject("user", user);

        if (request.isUserInRole("ROLE_FB")) {
            Object categories = fbprofiler.getFBCategories();
            if (categories != null) {
                model.addObject("categories", categories);
            }
        }
    } else {
        return model2;
    }
    return model;
}