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.github.dbourdette.otto.service.logs.Logs.java

private void store(String message) {
    BasicDBObject log = new BasicDBObject();

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null) {
        log.put("user", "system");
    } else {//from w  w w . j  av a 2 s  .c o m
        Object principal = authentication.getPrincipal();

        if (principal instanceof User) {
            log.put("user", ((User) principal).getUsername());
        } else {
            log.put("user", authentication.getName());
        }
    }

    log.put("date", new Date());
    log.put("message", message);

    logs().insert(log);
}

From source file:com.siacra.beans.PermanenciaDocBean.java

public Docente getPrincipal() {
    try {/* w ww  . j a v  a 2  s  . c om*/
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        User user = getUserService().getUserLogin(name);
        if (!getDocenteService().existDocente(user.getIdUsuario())) {
            principal = getDocenteService().getDocenteByUser(user.getIdUsuario());
        }
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
    return principal;
}

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

/**
 * Imports a list of terms/*from   w ww  . j  a  va2 s .  com*/
 *
 * @param body
 * @param thesaurusId
 * @param request
 * @return
 * @throws IOException
 */
@POST
@Path("/importSandBoxTerms")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_HTML)
@PreAuthorize("hasPermission(#thesaurusId, '0') or hasPermission(#thesaurusId, '1')")
public String importSandBoxTerms(MultipartBody body, @QueryParam("thesaurusId") String thesaurusId,
        @Context HttpServletRequest request) throws IOException {

    Attachment file = body.getAttachment(ATTACHMENT_NAME);
    String content = file.getObject(String.class);

    if (content.contains("<?xml")) {
        throw new BusinessException("Unable to import XML file as sandbox terms", "import-unable-to-read-file");
    } else {

        String[] termsSplit = content.split("\n|\r\n");
        List<String> termsLines = Arrays.asList(termsSplit);
        Map<String, Language> terms = new HashMap<String, Language>();
        List<String> termsInError = new ArrayList<String>();

        for (String termLine : termsLines) {
            String[] termSplitted = termLine.split("@");
            if (termSplitted.length == 2) {
                String lexValue = termSplitted[0];
                if (StringUtils.isNotEmpty(lexValue)) {
                    Language lang = languageService.getLanguageById(termSplitted[1]);
                    if (lang == null) {
                        lang = languageService.getLanguageByPart1(termSplitted[1]);
                    }
                    if (lang != null) {
                        terms.put(lexValue, lang);
                    } else {
                        termsInError.add(termLine);
                    }
                } else {
                    termsInError.add(termLine);
                }
            } else {
                String lexValue = termLine;
                Language lang = languageService.getLanguageById(defaultLang);
                terms.put(lexValue, lang);
            }
        }

        int defaultStatus = TermStatusEnum.VALIDATED.getStatus();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();

        if (userRoleService.hasRole(username, thesaurusId, Role.EXPERT)) {
            defaultStatus = TermStatusEnum.CANDIDATE.getStatus();
        }

        List<ThesaurusTerm> sandboxedTerms = thesaurusTermService.importSandBoxTerms(terms, thesaurusId,
                defaultStatus);
        for (ThesaurusTerm sandboxedTerm : sandboxedTerms) {
            termIndexerService.addTerm(sandboxedTerm);
        }

        ImportedTermsResponse response = new ImportedTermsResponse();
        response.setTermsInError(termsInError);
        ObjectMapper mapper = new ObjectMapper();
        String serialized = mapper.writeValueAsString(new ExtJsonFormLoadData(response));

        //Update vocabulary date
        Thesaurus thesaurus = thesaurusService.getThesaurusById(thesaurusId);
        thesaurusService.updateThesaurusDate(thesaurus);

        return serialized;
    }
}

From source file:de.interseroh.report.services.BirtReportServiceBean.java

private String documentFileName(String reportName) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String name = (authentication != null) ? authentication.getName() : UUID.randomUUID().toString();

    return reportName + '_' + name + '_' + DOCUMENT_FILE_SUFFIX;
}

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

/**
 * Lis uusi kommentti//from   ww  w .j a v  a 2 s .com
 *
 * @param a Autentikointi
 * @param imageUuid Kuvan UUID
 * @param comment Kommentin sislt
 * @param request HTTP Request
 * @return Uudelleenohjaa aikaisemmalle sivulle
 */
@RequestMapping(method = RequestMethod.POST)
public String addComment(Authentication a, @RequestParam String imageUuid, @RequestParam String comment,
        HttpServletRequest request) {
    //Validoidaan syte tss
    if (comment.length() > 0 && comment.length() <= 40) {
        Image img = imageService.findOneImageByUuid(imageUuid);
        if (img != null && img.isVisible()) {
            UserAccount u = userService.getUserByUsername(a.getName());
            Comment comm = commentService.addComment(comment, u);
            img.addComment(comm);
            u.addComment(comm);
            LOG.log(Level.INFO, "Kayttaja ''{0}'' kommentoi kuvaan ''{1}'' viestin sisallolla \"{2}\"",
                    new Object[] { a.getName(), imageUuid, comment });
            userService.saveUser(u);
            imageService.saveImage(img);
        } else {
            LOG.log(Level.WARNING,
                    "Kayttaja ''{0}'' yritti kommentoida kuvaa ''{1}'' viestin sisallolla \"{2}\", mutta kuvaa ei lytynyt.",
                    new Object[] { a.getName(), imageUuid, comment });
            return "redirect:/";
        }

    } else {
        LOG.log(Level.WARNING,
                "Kayttaja ''{0}'' yritti kommentoida kuvaa ''{1}'' viestin sisallolla \"{2}\", mutta viesti oli liian pitk.",
                new Object[] { a.getName(), imageUuid, comment });
    }
    return "redirect:/photo/" + imageUuid;
}

From source file:com.hp.autonomy.frontend.configuration.authentication.DefaultLoginAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final com.hp.autonomy.frontend.configuration.authentication.Authentication<?> authenticationConfig = configService
            .getConfig().getAuthentication();

    if (!LoginTypes.DEFAULT.equalsIgnoreCase(authenticationConfig.getMethod())) {
        return null;
    }/*from   w w  w  . java 2 s .com*/

    final UsernameAndPassword defaultLogin = authenticationConfig.getDefaultLogin();

    final String username = authentication.getName();
    final String password = authentication.getCredentials().toString();

    if (defaultLogin.getUsername().equals(username) && defaultLogin.getPassword().equals(password)) {
        return new UsernamePasswordAuthenticationToken(username, password,
                Arrays.asList(new SimpleGrantedAuthority(roleDefault)));
    } else {
        throw new BadCredentialsException("Access is denied");
    }
}

From source file:eu.openanalytics.rsb.security.JmxSecurityAuthenticator.java

@Override
public Subject authenticate(final Object credentials) {
    try {/*from   w  w  w . ja  v a 2  s.c o  m*/
        final String[] info = (String[]) credentials;

        final Authentication authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(info[0], info[1]));

        final User authenticatedUser = (User) authentication.getPrincipal();

        if ((isRsbAdminPrincipal(authenticatedUser)) || (isRsbAdminRole(authenticatedUser))) {
            final Subject s = new Subject();
            s.getPrincipals().add(new JMXPrincipal(authentication.getName()));
            return s;
        } else {
            throw new SecurityException("Authenticated user " + authenticatedUser + " is not an RSB admin");
        }
    } catch (final Exception e) {
        LOGGER.error("Error when trying to authenticate JMX credentials of type: " + credentials.getClass(), e);

        throw new SecurityException(e);
    }
}

From source file:com.devicehive.auth.JwtPermissionEvaluator.java

@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
    if (authentication != null && authentication instanceof HiveAuthentication) {
        HiveAuthentication hiveAuthentication = (HiveAuthentication) authentication;
        HivePrincipal hivePrincipal = (HivePrincipal) hiveAuthentication.getPrincipal();
        HiveAction action = HiveAction.valueOf(permission.toString().trim());
        logger.debug("Checking {} for permissions {}", authentication.getName(), hivePrincipal.getActions());
        boolean permissionAllowed = jwtCheckPermissionsHelper.checkPermissions(hivePrincipal, action,
                targetDomainObject);/*  w w  w  . ja  va 2s .c  om*/
        if (!permissionAllowed) {
            logger.warn("Principal doesn't have required permission {}. Access denied", permission);
            return false;
        }
        logger.info("Successfully checked for permission {}", permission);
        return true;
    }
    logger.error("Can't check access key permission for jwt '{}'", authentication.getClass().getName());
    return true;
}

From source file:net.solarnetwork.central.dras.biz.alert.SimpleAlertBiz.java

private Long getCurrentUserId() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth == null) {
        log.info("No Authentication available, cannot tell current user ID");
        return null;
    }/*from ww  w  .j  a  v a  2  s.c o  m*/
    String currentUserName = auth.getName();
    SimpleUserFilter filter = new SimpleUserFilter();
    filter.setUniqueId(currentUserName);
    FilterResults<Match> results = userDao.findFiltered(filter, null, null, null);
    if (results.getReturnedResultCount() < 1) {
        return null;
    }
    return results.getResults().iterator().next().getId();
}

From source file:com.nec.harvest.servlet.interceptor.BackOriginGroupInterceptor.java

@Override
@SuppressWarnings("unchecked")
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    final User userPricipal = AuthenticatedUserDetails.getUserPrincipal();
    if (userPricipal == null || userPricipal.getOrganization() == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Please login again with right permission");
        }// ww  w  .j  a  v  a 2s.co  m
        logger.info("Sorry, you don't have permission to access this url");

        // Sorry, you don't have permission to access this url. Please login again with right permission
        response.setContentType(HttpServletContentType.PLAN_TEXT);
        response.sendRedirect(request.getContextPath() + "/logout");
        response.flushBuffer();
        return false;
    }

    final HandlerMethod handlerMethod = (org.springframework.web.method.HandlerMethod) handler;
    final Object controller = handlerMethod.getBean();
    if (controller instanceof MenuController) {
        return super.preHandle(request, response, handler);
    }

    final Map<String, Object> pathVariables = (Map<String, Object>) request
            .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);

    final String PRO_GROUP_NO = "proGNo";
    final String proGroupNo = (String) pathVariables.get(PRO_GROUP_NO);
    final boolean hasMenuGroups = menuGroupService
            .hasMenuGroupByUserRoleAndSpecificGroup(userPricipal.getUsrKbn(), proGroupNo);
    if (!hasMenuGroups) {
        logger.info("Sorry, you don't have permission to access this url");

        // Sorry, you don't have permission to access this url. Please login again with right permission
        response.setContentType(HttpServletContentType.PLAN_TEXT);
        response.sendRedirect(request.getContextPath() + "/logout");
        response.flushBuffer();
        return false;
    }

    final String ORG_CODE = "orgCode";
    final HttpSession session = request.getSession();

    // Get active original code
    String orgCode = (String) pathVariables.get(ORG_CODE);
    if (StringUtils.isNotEmpty(orgCode)) {
        final String userOrgCode = (String) session.getAttribute(Constants.SESS_ORGANIZATION_CODE);
        if (!userOrgCode.equals(orgCode)) {
            logger.info("Sorry, you don't have permission to access this url");

            // Sorry, you don't have permission to access this url. Please login again with right permission
            response.setContentType(HttpServletContentType.PLAN_TEXT);
            response.sendRedirect(request.getContextPath() + "/logout");
            response.flushBuffer();
            return false;
        }
    }

    // All of original groups
    String[] processGroupNumbers = null;
    if (controller instanceof DailyReportingProGroup) {
        processGroupNumbers = ((DailyReportingProGroup) controller).getProcessGroupNumber();
    } else if (controller instanceof MasterManagementProGroup) {
        processGroupNumbers = ((MasterManagementProGroup) controller).getProcessGroupNumber();
    } else if (controller instanceof ProfitAndLossManagementProGroup) {
        processGroupNumbers = ((ProfitAndLossManagementProGroup) controller).getProcessGroupNumber();
    }

    // If the end-user already logged in into Harvest system, but have an error occurred 
    // when trying to set some information into SESSION then we can reset again that 
    // information into SESSION
    orgCode = (String) session.getAttribute(Constants.SESS_ORGANIZATION_CODE);
    if (orgCode == null) {
        session.setAttribute(Constants.SESS_ORGANIZATION_CODE, userPricipal.getOrganization().getStrCode());
    }

    final Object businessDay = session.getAttribute(Constants.SESS_BUSINESS_DAY);
    if (businessDay == null) {
        BusinessDayService businessDayService = ContextAwareContainer.getInstance()
                .getComponent(BusinessDayService.class);
        final BusinessDay businessDate = businessDayService.findLatest();

        // 
        session.setAttribute(Constants.SESS_BUSINESS_DAY, businessDate.getEigDate());
    }

    // Granted authority of user logged-in
    final String grantedAuthority = userPricipal.getUsrKbn();
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    for (GrantedAuthority authority : authentication.getAuthorities()) {
        logger.info("User {} was logged-in with granted role {}", authentication.getName(),
                authority.getAuthority());
    }

    /**
     * ?
     * 
     * 1?2?3??4
     */
    logger.info(
            "Granted authority of logged user: {}, NOTE: 1?2?3??4",
            grantedAuthority);

    // 
    if (StringUtils.isNotEmpty(grantedAuthority)) {
        if (ArrayUtils.isNotEmpty(processGroupNumbers)) {
            // Trying to store the original group menu into the REQUEST
            final String processGroupNumber = processGroupNumbers[Integer.valueOf(grantedAuthority) - 1];
            request.setAttribute(Constants.SESS_ORIGINAL_GROUP, processGroupNumber);

            // 
            logger.info("Were are trying to handle the sub-menu of group {}", processGroupNumber);
        }
    }

    return super.preHandle(request, response, handler);
}