List of usage examples for org.springframework.security.core GrantedAuthority getAuthority
String getAuthority();
GrantedAuthority
can be represented as a String
and that String
is sufficient in precision to be relied upon for an access control decision by an AccessDecisionManager (or delegate), this method should return such a String
. From source file:org.schedoscope.metascope.service.MetascopeUserService.java
/** * Get the user object for the logged in user * * @return/*from w w w .j a v a 2 s .co m*/ * @throws NamingException */ public MetascopeUser getUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { return null; } Object principal = authentication.getPrincipal(); if (principal instanceof LdapUserDetailsImpl) { LdapUserDetailsImpl ldapUser = (LdapUserDetailsImpl) principal; MetascopeUser userEntity = metascopeUserRepository.findByUsername(ldapUser.getUsername()); if (userEntity == null) { createUser(ldapUser.getUsername(), "", "", sha256("" + System.currentTimeMillis()), false, null); } // sync user with ldap userEntity = metascopeUserRepository.findByUsername(ldapUser.getUsername()); DirContextAdapter dca = (DirContextAdapter) ldap.lookup(ldapUser.getDn()); Attributes attr = dca.getAttributes(); String mail = ""; String fullname = ""; try { mail = (String) attr.get("mail").get(); fullname = (String) attr.get("displayName").get(); } catch (NamingException e) { // if not found, ignore .. } boolean admin = false; for (GrantedAuthority authoritiy : ldapUser.getAuthorities()) { for (String adminGroup : config.getAdminGroups().split(",")) { String role = "ROLE_" + adminGroup.toUpperCase(); if (authoritiy.getAuthority().equalsIgnoreCase(role)) { admin = true; } } } boolean changes = false; if (userEntity.getEmail() == null || !userEntity.getEmail().equals(mail)) { userEntity.setEmail(mail); changes = true; } if (userEntity.getFullname() == null || !userEntity.getFullname().equals(fullname)) { userEntity.setFullname(fullname); changes = true; } if (admin) { if (!userEntity.isAdmin()) { changes = true; } userEntity.setUserrole(Role.ROLE_ADMIN); } else { if (userEntity.isAdmin()) { changes = true; } userEntity.setUserrole(Role.ROLE_USER); } if (changes) { metascopeUserRepository.save(userEntity); } return userEntity; } else if (principal instanceof User) { User userDetails = (User) principal; MetascopeUser user = metascopeUserRepository.findByUsername(userDetails.getUsername()); if (user == null) { LOG.warn("User from session not found. username={}", userDetails.getUsername()); return null; } return user; } return null; }
From source file:org.azrul.langkuik.framework.webgui.BeanView.java
@Override public void enter(final ViewChangeListener.ViewChangeEvent vcevent) { setCurrentView(vcevent.getViewName()); //reset form//from w w w . jav a2 s .c o m this.removeAllComponents(); //determine user details UserDetails userDetails = null; Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!(auth instanceof AnonymousAuthenticationToken)) { userDetails = (UserDetails) auth.getPrincipal(); } else { return; } final Set<String> currentUserRoles = new HashSet<>(); for (GrantedAuthority grantedAuth : userDetails.getAuthorities()) { currentUserRoles.add(grantedAuth.getAuthority()); } //determine entity rights EntityRight entityRight = null; EntityUserMap[] entityUserMaps = ((WebEntity) currentBean.getClass().getAnnotation(WebEntity.class)) .userMap(); for (EntityUserMap e : entityUserMaps) { if (currentUserRoles.contains(e.role()) || ("*").equals(e.role())) { entityRight = e.right(); break; } } if (entityRight == null) { //if entityRight=EntityRight.NONE, still allow to go through because field level might be accessible //Not accessible return; } //create bean utils final BeanUtils beanUtils = new BeanUtils(); //rebuild pageParameter.getBreadcrumb() BreadCrumbBuilder.buildBreadCrumb(vcevent.getNavigator(), pageParameter.getBreadcrumb(), pageParameter.getHistory()); //rebuild components if (currentBean == null) { return; } //refresh current item C newBean = dao.refresh(currentBean); if (newBean != null) { currentBean = newBean; } final BeanFieldGroup fieldGroup = new BeanFieldGroup(currentBean.getClass()); fieldGroup.setItemDataSource(currentBean); final FormLayout form = new FormLayout(); Map<String, Map<Integer, FieldContainer>> groups = beanUtils.createGroupsFromBean(currentBean.getClass()); //render form according to tab if (groups.size() == 1) { createForm(entityRight, currentUserRoles, groups, fieldGroup, pageParameter.getCustomTypeDaos(), vcevent.getNavigator(), form); } else { TabSheet tabSheet = new TabSheet(); for (String group : groups.keySet()) { if (("All").equals(group)) { createForm(entityRight, currentUserRoles, groups, group, fieldGroup, pageParameter.getCustomTypeDaos(), vcevent.getNavigator(), form); } else { FormLayout tab = new FormLayout(); createForm(entityRight, currentUserRoles, groups, group, fieldGroup, pageParameter.getCustomTypeDaos(), vcevent.getNavigator(), tab); tabSheet.addTab(tab, group); } } form.addComponent(tabSheet); } //Navigation and actions HorizontalLayout navButtons = new HorizontalLayout(); navButtons.setSpacing(true); Button saveAndBackBtn = new Button("Save and back", new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { try { fieldGroup.commit(); currentBean = (C) fieldGroup.getItemDataSource().getBean(); currentBean = saveBean(currentBean, parentBean, beanUtils, currentUserRoles); if (!pageParameter.getHistory().isEmpty()) { String currentView = pageParameter.getHistory().pop().getViewHandle(); String lastView = pageParameter.getHistory().peek().getViewHandle(); vcevent.getNavigator().removeView(currentView); vcevent.getNavigator().navigateTo(lastView); } } catch (FieldGroup.CommitException ex) { handleFieldsError(fieldGroup); } } }); navButtons.addComponent(saveAndBackBtn); saveAndBackBtn.setId(saveAndBackBtn.getCaption()); form.addComponent(navButtons); form.setMargin(new MarginInfo(true)); this.addComponent(form); }
From source file:fr.univlorraine.mondossierweb.controllers.UserController.java
public boolean userCanAccessAdminView() { //On parcourt les droits for (GrantedAuthority ga : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) { //Si a l'autorisation de consulter la vue adminView if (MdwUserDetailsService.CONSULT_ADMINVIEW_AUTORISE.equals(ga.getAuthority())) { return true; }//from w w w . j a va 2 s . c o m } return false; }
From source file:org.azrul.langkuik.framework.webgui.PlainTableView.java
@Override public void enter(final ViewChangeListener.ViewChangeEvent vcevent) { setCurrentView(vcevent.getViewName()); this.removeAllComponents(); //determine user details UserDetails userDetails = null;/*from ww w . j a v a 2 s.c om*/ Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!(auth instanceof AnonymousAuthenticationToken)) { userDetails = (UserDetails) auth.getPrincipal(); } else { return; } final Set<String> currentUserRoles = new HashSet<>(); for (GrantedAuthority grantedAuth : userDetails.getAuthorities()) { currentUserRoles.add(grantedAuth.getAuthority()); } //determine entity rights EntityRight entityRight = null; EntityUserMap[] entityUserMaps = classOfBean.getAnnotation(WebEntity.class).userMap(); for (EntityUserMap e : entityUserMaps) { if (currentUserRoles.contains(e.role()) || ("*").equals(e.role())) { entityRight = e.right(); break; } } if (entityRight == null) { //if entityRight=EntityRight.NONE, still allow to go through because field level might be accessible //Not accessible return; } //Build bread crumb BreadCrumbBuilder.buildBreadCrumb(vcevent.getNavigator(), pageParameter.getBreadcrumb(), pageParameter.getHistory()); FindAnyEntityParameter<C> searchQuery = new FindAnyEntityParameter<>(classOfBean); //set form FormLayout form = new FormLayout(); final SearchDataTableLayout<C> dataTable = new SearchDataTableLayout<>(searchQuery, classOfBean, dao, noBeansPerPage, pageParameter.getCustomTypeDaos(), pageParameter.getConfig(), currentUserRoles, entityRight); form.addComponent(dataTable); //Handle navigations and actions HorizontalLayout buttonLayout = new HorizontalLayout(); // Button addNewBtn = new Button("Add new", // new Button.ClickListener() { // @Override // public void buttonClick(Button.ClickEvent event // ) { // C currentBean = dao.createAndSave(); // BeanView<Object, C> beanView = new BeanView<Object, C>(currentBean,null, pageParameter.getRelationManagerFactory(), pageParameter.getEntityManagerFactory(), pageParameter.getHistory(), pageParameter.getBreadcrumb(), pageParameter.getConfig(), pageParameter.getCustomTypeDaos()); // String targetView = "CHOOSE_ONE_TABLE_VIEW_" + UUID.randomUUID().toString(); // WebEntity myObject = (WebEntity) currentBean.getClass().getAnnotation(WebEntity.class); // History his = new History(targetView, "Add new " + myObject.name()); // pageParameter.getHistory().push(his); // vcevent.getNavigator().addView(targetView, beanView); // vcevent.getNavigator().navigateTo(targetView); // // } // }); // buttonLayout.addComponent(addNewBtn); // addNewBtn.setId(addNewBtn.getCaption()); Button manageBtn = new Button("Manage", new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { Collection<C> currentBeans = (Collection<C>) dataTable.getTableValues(); if (!currentBeans.isEmpty()) { C currentBean = currentBeans.iterator().next(); if (currentBean != null) { BeanView<Object, C> beanView = new BeanView<>(currentBean, null, null, pageParameter); String targetView = "CHOOSE_ONE_TABLE_VIEW_" + UUID.randomUUID().toString(); WebEntity myObject = (WebEntity) currentBean.getClass().getAnnotation(WebEntity.class); History his = new History(targetView, "Manage " + myObject.name()); pageParameter.getHistory().push(his); vcevent.getNavigator().addView(targetView, beanView); vcevent.getNavigator().navigateTo(targetView); } } } }); buttonLayout.addComponent(manageBtn); manageBtn.setId(manageBtn.getCaption()); Button deleteBtn = new Button("Delete", new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { final Collection<C> currentBeans = (Collection<C>) dataTable.getTableValues(); if (!currentBeans.isEmpty()) { ConfirmDialog.show(PlainTableView.this.getUI(), "Please Confirm:", "Are you really sure you want to delete these entries?", "I am", "Not quite", new ConfirmDialog.Listener() { public void onClose(ConfirmDialog dialog) { if (dialog.isConfirmed()) { // dao.delete(currentBeans); // Collection<C> data = dao.search(searchTerms, classOfBean, currentTableDataIndex, noBeansPerPage); // if (data.isEmpty()) { // data = new ArrayList<C>(); // data.add(dao.createNew()); // } // tableDataIT.setBeans(data); // tableDataIT.refreshItems(); // totalTableData = dao.countSearch(searchTerms, classOfBean); // final Label pageLabel = new Label(); // int lastPage = (int) Math.floor(totalTableData / noBeansPerPage); // if (totalTableData % noBeansPerPage == 0) { // lastPage--; // } // int currentUpdatedPage = currentTableDataIndex / noBeansPerPage; // pageLabel.setCaption(" " + (currentUpdatedPage + 1) + " of " + (lastPage + 1) + " "); } } }); } } }); buttonLayout.addComponent(deleteBtn); deleteBtn.setId(deleteBtn.getCaption()); buttonLayout.setSpacing(true); form.addComponent(buttonLayout); Button backBtn = new Button("Back", new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { if (!pageParameter.getHistory().isEmpty()) { String currentView = pageParameter.getHistory().pop().getViewHandle(); String lastView = pageParameter.getHistory().peek().getViewHandle(); vcevent.getNavigator().removeView(currentView); vcevent.getNavigator().navigateTo(lastView); } } }); form.addComponent(backBtn); backBtn.setId(backBtn.getCaption()); this.addComponent(form); }
From source file:com.bac.accountserviceapp.data.mysql.MysqlAccountServiceAppSpringAuthenticationTest.java
private String[] getAuthorityArray(Collection<? extends GrantedAuthority> authorities) { String[] authoritiesArray = new String[authorities.size()]; int index = 0; for (GrantedAuthority authority : authorities) { authoritiesArray[index++] = authority.getAuthority(); }//from w w w. j a v a2s . c om return authoritiesArray; }
From source file:com.traffitruck.web.HtmlController.java
@RequestMapping(value = "/resetPassword", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) ModelAndView resetPassword(@RequestParam("password") String password, @RequestParam("confirm_password") String confirm_password) { if (password == null || !password.equals(confirm_password)) { throw new RuntimeException("Failed resetting the password"); }//from w ww .j a va 2 s. co m Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String username = authentication.getName(); LoadsUser user = dao.getUser(username); user.setPassword(password); dao.storeUser(user); String resetPasswordId = null; for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) { if (grantedAuthority.getAuthority().startsWith("resetPassword-")) resetPasswordId = grantedAuthority.getAuthority().substring("resetPassword-".length()); dao.deleteResetPassword(resetPasswordId, username); } return new ModelAndView("redirect:" + user.getRoles().get(0).getLandingUrl()); }
From source file:com.traffitruck.web.HtmlController.java
private void updateModelWithRoles(Map<String, Object> model) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); boolean isLoadsOwner = false; boolean isTruckOwner = false; for (GrantedAuthority auth : authentication.getAuthorities()) { if (Role.LOAD_OWNER.toString().equals(auth.getAuthority())) { isLoadsOwner = true;//from www. ja va2s. com } if (Role.TRUCK_OWNER.toString().equals(auth.getAuthority())) { isTruckOwner = true; } } model.put("isLoadsOwner", isLoadsOwner); model.put("isTruckOwner", isTruckOwner); }
From source file:com.traffitruck.web.HtmlController.java
@RequestMapping(value = { "/menu", "/" }) ModelAndView menu() {/*from w w w . j a v a 2 s . c o m*/ Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Map<String, Object> model = new HashMap<>(); boolean isLoadsOwner = false; boolean isTruckOwner = false; for (GrantedAuthority auth : authentication.getAuthorities()) { if (Role.LOAD_OWNER.toString().equals(auth.getAuthority())) { isLoadsOwner = true; } if (Role.TRUCK_OWNER.toString().equals(auth.getAuthority())) { isTruckOwner = true; } } String username = authentication.getName(); if (isLoadsOwner && !isTruckOwner) { return new ModelAndView("redirect:/myLoads", model); } List<Truck> trucks = dao.getTrucksForUserAndRegistration(username, TruckRegistrationStatus.APPROVED); if (trucks != null && trucks.size() > 0) { return new ModelAndView("redirect:/findTrucksForLoad", model); } else { return new ModelAndView("redirect:/myTrucks", model); } }
From source file:com.ewcms.content.document.service.ArticleMainService.java
@Override public Map<Channel, Long> findBeApprovalArticleMain(String userName) { Map<Channel, Long> result = new HashMap<Channel, Long>(); List<String> groupNames = new ArrayList<String>(); UserDetails user = userService.loadUserByUsername(userName); if (user != null) { Collection<GrantedAuthority> authorites = user.getAuthorities(); for (GrantedAuthority auth : authorites) { if (StringUtils.startsWith(auth.getAuthority(), GroupServiceable.GROUP_NAME_PERFIX)) { groupNames.add(auth.getAuthority()); }/*from ww w . j a v a2 s . c om*/ } } Map<Integer, Long> map = articleMainDAO.findBeApprovalArticleMain(userName, groupNames); if (!map.isEmpty()) { Set<Integer> keySets = map.keySet(); for (Integer key : keySets) { Channel channel = channelDAO.get(key); Long count = map.get(key); result.put(channel, count); } } return result; }
From source file:com.ewcms.content.document.service.ArticleMainService.java
@Override public void submitReviewArticleMain(List<Long> articleMainIds, Integer channelId) throws BaseException { for (Long articleMainId : articleMainIds) { ArticleMain articleMain = articleMainDAO.findArticleMainByArticleMainAndChannel(articleMainId, channelId);//w ww.j a v a 2s.co m Assert.notNull(articleMain); Article article = articleMain.getArticle(); Assert.notNull(article); if (article.getStatus() == Status.DRAFT || article.getStatus() == Status.REEDIT) { ReviewProcess reviewProcess = reviewProcessDAO.findFirstReviewProcessByChannel(channelId); if (reviewProcess == null) { operateTrackService.addOperateTrack(articleMainId, article.getStatusDescription(), "?", ""); article.setStatus(Status.PRERELEASE); article.setReviewProcess(null); } else { UserDetails userDetails = EwcmsContextUtil.getUserDetails(); Collection<GrantedAuthority> authorities = userDetails.getAuthorities(); Boolean isAdmin = false; for (GrantedAuthority ga : authorities) { if (ga.getAuthority().toUpperCase().equals("ROLE_ADMIN")) { operateTrackService.addOperateTrack(articleMainId, article.getStatusDescription(), "???", ""); article.setStatus(Status.PRERELEASE); article.setReviewProcess(null); isAdmin = true; } } if (!isAdmin) { operateTrackService.addOperateTrack(articleMainId, article.getStatusDescription(), "???" + reviewProcess.getName() + "", ""); article.setStatus(Status.REVIEW); article.setReviewProcess(reviewProcess); } } if (article.getPublished() == null) { article.setPublished(new Date(Calendar.getInstance().getTime().getTime())); } articleMain.setArticle(article); articleMainDAO.merge(articleMain); // }else{ // throw new BaseException("","???????"); } } }