/** * Adds a user in the user map * * @param user */ public void putUser(User user) { checkUserMap(); if (userMap.containsKey(user.getUsername())) throw new IllegalArgumentException("The user " + user.getUsername() + " already exists"); else userMap.put(user.getUsername(), user); }
@Override public UserProfile getUser(Authentication authentication) { Object userName = authentication.getPrincipal(); String login; User auth = null; if (userName instanceof String) login = (String) userName; else { login = ((User) authentication.getPrincipal()).getUsername(); auth = (User) authentication.getPrincipal(); } UserProfile userProfile = new UserProfile(); userProfile.setUserId(login); userProfile.setStatus("ENABLED"); if (auth != null && !auth.getAuthorities().isEmpty()) { for (GrantedAuthority grantedAuthority : auth.getAuthorities()) { userProfile.addUserRole(grantedAuthority.getAuthority()); } } if (auth != null) { SystemUser sysUser = systemUserService.findByLogin(login); if (sysUser != null) { userProfile.setApiKey(sysUser.getApiKey()); userProfile.setCompany(sysUser.getCompany().getName()); } } return userProfile; }
/** * Stores the provided user map into a properties object * * @param userMap * @return */ Properties storeUsersToProperties(Map<String, User> userMap) { Properties p = new Properties(); for (User user : userMap.values()) { p.setProperty(user.getUsername(), serializeUser(user)); } return p; }
@Override public void savePayrolls(EmployeePayrollList payrolls) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); User user = (User) auth.getPrincipal(); String savePayrollsQuery = "insert into employee_payroll(reg_no, emp_name, date, basic_salary, gross_pay, loan_deduction, other_deduction, created_by, created_on, net_salary, last_updated_by, last_updated_on) values(?,?,?,?,?,?,?,?,?,?,?,?)"; System.out.println(payrolls.getMonth() + " " + payrolls.getYear()); for (int i = 0; i < payrolls.getPayrolls().size(); i++) { EmployeePayroll payroll = payrolls.getPayrolls().get(i); jdbcTemplate.update( savePayrollsQuery, new Object[] { payroll.getRegNum(), payroll.getName(), payrolls.getMonth() + " " + payrolls.getYear(), payroll.getBasicSalary(), payroll.getGrossPay(), payroll.getLoanDeduction(), payroll.getOtherDeduction(), payroll.getCreatedBy(), payroll.getCreatedOn(), payroll.getNetSalary(), user.getUsername(), user.getUsername() }); } }
public boolean canDeleteBooking(User user, long bookingId) { Booking booking = bookings.findOne(bookingId); return booking != null && ((booking.getGuest() != null && user.getUsername().equals(booking.getGuest().getEmail())) || (booking.getHotel() != null && booking.getHotel().getManager() != null && user.getUsername().equals(booking.getHotel().getManager().getEmail()))); }
@RequestMapping(value = "/home/luis", method = RequestMethod.GET) public String luis(Model model) { Util.loginUsuario("*****@*****.**", "garbage1"); User user = Util.getUserLogged(); model.addAttribute("usuario", user.getUsername()); model.addAttribute("password", user.getPassword()); return "home"; }
/** * Presents user with an iframe whose access is controlled by Shibboleth. IT IS IMPERATIVE THAT * THIS URL BE ACCESSIBLE ONLY TO AUTHENTICATED USERS. Accessing this URL will log the user into * the system so care must be taken that it is accessible only after the user has already * authenticated. */ @RequestMapping("/login") public String login() { User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); logger.debug("Logged in user: "******"shiblogin"; }
@Override public UserInfo getAuthenticatedUserInfo() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.getPrincipal() != null) { User user = (User) authentication.getPrincipal(); return userService.findByUsername(user.getUsername()); } return null; }
@Override public void onLogoutSuccess( HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { User user = (User) authentication.getPrincipal(); log.info(user.getUsername() + " logout "); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().flush(); }
@Test public void testRemoveSessionInformationByUsername() { EwcmsSessionRegistryImpl sessionRegistry = initSessionRegistry(); User user = new User("Pertty", "123456", true, true, true, true, new ArrayList<GrantedAuthority>()); sessionRegistry.removeSessionInformationByUsername(user.getUsername()); List<SessionInformation> sessionInformations = sessionRegistry.getAllSessions(user, true); assertTrue(sessionInformations.isEmpty()); }
@Override public void enter(ViewChangeListener.ViewChangeEvent event) { User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); List<String> roles = new ArrayList<String>(); for (GrantedAuthority grantedAuthority : user.getAuthorities()) { roles.add(grantedAuthority.getAuthority()); } usernameLabel.setValue(user.getUsername()); rolesLabel.setValue(StringUtils.join(roles, ",")); }
/** * Turns the users password, granted authorities and enabled state into a property file value * * @param user * @return */ String serializeUser(User user) { StringBuffer sb = new StringBuffer(); sb.append(user.getPassword()); sb.append(","); for (GrantedAuthority ga : user.getAuthorities()) { sb.append(ga.getAuthority()); sb.append(","); } sb.append(user.isEnabled() ? "enabled" : "disabled"); return sb.toString(); }
/** * Get the list of roles currently known by users (there's guarantee the well known * ROLE_ADMINISTRATOR will be part of the lot) */ public List<String> getRoles() { checkUserMap(); Set<String> roles = new TreeSet<String>(); roles.add("ROLE_ADMINISTRATOR"); for (User user : getUsers()) { for (GrantedAuthority ga : user.getAuthorities()) { roles.add(ga.getAuthority()); } } return new ArrayList<String>(roles); }
@RequestMapping(value = "/adminpanel/{postid}/updatepost", method = RequestMethod.GET) public ModelAndView updatePost(@PathVariable(value = "postid") int id) { ModelAndView model = new ModelAndView("updatepost"); User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); slf4jLogger.info("User <{}> updated post.", user.getUsername()); Post post = daoPost.getPost(id); model.addObject("post", post); return model; }
/** * Login a user manually/programmatically. * * @param user the user' object */ @Transactional public void login(User user) { org.springframework.security.core.userdetails.User authUser = new org.springframework.security.core.userdetails.User( user.getUsername(), user.getPassword(), AuthorityUtils.createAuthorityList("ROLE_USER")); Authentication auth = new UsernamePasswordAuthenticationToken( authUser, authUser.getPassword(), authUser.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(auth); LOGGER.info("Programmatically logged in user={}", user); }
public AdminUser getPersistentAdminUser() { SecurityContext ctx = SecurityContextHolder.getContext(); if (ctx != null) { Authentication auth = ctx.getAuthentication(); if (auth != null && !auth.getName().equals(ANONYMOUS_USER_NAME)) { User temp = (User) auth.getPrincipal(); AdminUser adminUser = securityService.readAdminUserByUserName(temp.getUsername()); return adminUser; } } return null; }
@RequestMapping(value = "/dataSocial", method = RequestMethod.GET) public ResponseEntity<Usuario> dataSocial(HttpServletRequest request) { logger.info("Requested current user logged"); User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String username = user.getUsername(); Usuario usuario = null; if (username != null && !username.equals("")) { usuario = usuarioRepository.findByUsername(username); } if (usuario != null) { return new ResponseEntity<>(usuario, HttpStatus.ACCEPTED); } else { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }
@RequestMapping("/adminpanel") public ModelAndView adminPanel(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("adminpanel"); User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); slf4jLogger.info("User <{}> is online.", user.getUsername()); List<Post> list = daoPost.getPosts(0, 10); model.addObject("posts", list); model.addObject("numOfPages", (daoPost.getNumberOfPosts() / 10) + 1); return model; }
@Test public void handleRequest() { org.springframework.security.core.userdetails.User principal = mock(org.springframework.security.core.userdetails.User.class); String mockOpenId = new String("open_id"); UserDto mockUserDto = new UserDto(1L); when(mockAuthentication.getPrincipal()).thenReturn(principal); when(principal.getUsername()).thenReturn(mockOpenId); when(userFacade.findUserByOpenid(mockOpenId)).thenReturn(mockUserDto); securityFilter.handleRequest(null, null); verify(mockAuthentication).getPrincipal(); verify(principal).getUsername(); verify(userFacade).findUserByOpenid(mockOpenId); }
/** * Creates a new tweet and stores it. * * @return authenticated 'user object */ public User getUser() { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof String) { return null; } org.springframework.security.core.userdetails.User userDetails = (org.springframework.security.core.userdetails.User) principal; User user = userRepository.findByUsername(userDetails.getUsername()); if (user == null) { LOGGER.warn("User from session not found. username={}.", userDetails.getUsername()); return null; } return user; }
private Authentication fresh(Authentication authentication, ServletRequest req) { HttpServletRequest request = (HttpServletRequest) req; HttpSession session = request.getSession(false); if (session != null) { SessionRegistry sessionRegistry = (SessionRegistry) SpringBeanUtil.getBeanByName("sessionRegistry"); SessionInformation info = sessionRegistry.getSessionInformation(session.getId()); if (info != null) { // Non-expired - update last request date/time Object principal = info.getPrincipal(); if (principal instanceof org.springframework.security.core.userdetails.User) { org.springframework.security.core.userdetails.User userRefresh = (org.springframework.security.core.userdetails.User) principal; ServletContext sc = session.getServletContext(); HashSet<String> unrgas = springSecurityService.getUsersNeedRefreshGrantedAuthorities(); if (unrgas.size() > 0) { HashSet<String> loginedUsernames = new HashSet<String>(); List<Object> loggedUsers = sessionRegistry.getAllPrincipals(); for (Object lUser : loggedUsers) { if (lUser instanceof org.springframework.security.core.userdetails.User) { org.springframework.security.core.userdetails.User u = (org.springframework.security.core.userdetails.User) lUser; loginedUsernames.add(u.getUsername()); } } // 清除已经下线的但需要刷新的username for (Iterator iterator = unrgas.iterator(); iterator.hasNext(); ) { String unrgs = (String) iterator.next(); if (!loginedUsernames.contains(unrgs)) { iterator.remove(); } } if (unrgas.contains(userRefresh.getUsername())) { // 如果需要刷新权限的列表中有当前的用户,刷新登录用户权限 // FIXME:与springSecurityServiceImpl中的功能,相重复,需重构此方法和springSecurityServiceImpl MyJdbcUserDetailsManager mdudm = (MyJdbcUserDetailsManager) SpringBeanUtil.getBeanByType(MyJdbcUserDetailsManager.class); SecurityContextHolder.getContext() .setAuthentication( new UsernamePasswordAuthenticationToken( userRefresh, userRefresh.getPassword(), mdudm.getUserAuthorities(userRefresh.getUsername()))); session.setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); unrgas.remove(userRefresh.getUsername()); return SecurityContextHolder.getContext().getAuthentication(); } } } } } return authentication; }
@Override public Map<String, Object> update(PendingMergeParent obj, Integer transactionId) { User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); SqlParameterSource in = new MapSqlParameterSource() .addValue("p_trans_id", transactionId) .addValue("p_stuPidm", obj.getStudentPidm()) .addValue("p_stuPpid", obj.getStudentPpid()) .addValue("p_parPpid", obj.getParentPpid()) .addValue("p_parPidm", obj.getPidm()) .addValue("p_peciAdminUserId", user.getUsername()) .addValue("p_peciAdminDataOrigin", "ADMIN INTERFACE"); Map<String, Object> out = this.updateParent.execute(in); // if ( this.hasOutputErrors(out) ) { // throw new StoredProcedureDAOException("There was an error(s) when attempting to update the // existing parent", obj, transactionId); // } return out; }
/** Simply selects the home view to render by returning its name. */ @RequestMapping(value = "/home/client", method = RequestMethod.GET) public String home(Locale locale, Model model) { Date date = new Date(); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); String formattedDate = dateFormat.format(date); User user = Util.getUserLogged(); logger.info("usuario " + user.getUsername()); logger.info("password " + user.getPassword()); model.addAttribute("usuario", user.getUsername()); model.addAttribute("password", user.getPassword()); model.addAttribute("serverTime", formattedDate); return "home"; }
public String createTokenForUser(User user) { logger.debug("create token for user : {}", user.toString()); byte[] userBytes = toJSON(user).getBytes(); byte[] hash = createHmac(userBytes); final StringBuilder sb = new StringBuilder(170); sb.append(toBase64(userBytes)); sb.append(SEPARATOR); sb.append(toBase64(hash)); logger.debug("generated token : {}", sb.toString()); return sb.toString(); }
@RequestMapping("/adminpanel/{pageNum}") public ModelAndView adminPanelNextPage( HttpServletRequest request, HttpServletResponse response, @PathVariable(value = "pageNum") int pageNum) throws Exception { ModelAndView model = new ModelAndView("adminpanel"); User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); slf4jLogger.info("User <{}> is online.", user.getUsername()); int firstResult = (pageNum - 1) * 10; int maxResults = 10; List<Post> list = daoPost.getPosts(firstResult, maxResults); model.addObject("posts", list); model.addObject("numOfPages", (daoPost.getNumberOfPosts() / 10) + 1); return model; }
public User parseUserFromToken(String token) { logger.debug("parseToken from : {}", token); final String[] parts = token.split(SEPARATOR_SPLITTER); if (parts.length == 2 && parts[0].length() > 0 && parts[1].length() > 0) { logger.debug("split token : {}", parts.toString()); try { final byte[] userBytes = fromBase64(parts[0]); final byte[] hash = fromBase64(parts[1]); logger.debug("retrieve userBytes={} and hash={}", new String(userBytes), new String(hash)); boolean validHash = Arrays.equals(createHmac(userBytes), hash); logger.debug("is valid hash : {}", validHash); if (validHash) { final User user = fromJSON(userBytes); logger.debug("return user : {}", user.toString()); return user; } } catch (IllegalArgumentException e) { // log tempering attempt here } } return null; }
/** * Check creating new article with get user auth context * * @throws Exception */ @Test @PrepareForTest({SecurityContextHolder.class}) public void testCreateArticle() throws Exception { Article article = new Article(); PowerMockito.mockStatic(SecurityContextHolder.class); PowerMockito.when(SecurityContextHolder.getContext()).thenReturn(securityContext); Mockito.when(securityContext.getAuthentication()).thenReturn(authentication); Mockito.when(authentication.getPrincipal()).thenReturn(userDetail); Mockito.when(userDetail.getUsername()).thenReturn("userName"); Mockito.when(userService.getAuthorizedUser()).thenReturn(user); articleService.createArticle(article); ArgumentCaptor<Article> argument = ArgumentCaptor.forClass(Article.class); Mockito.verify(articleDao, Mockito.times(1)).createArticle(argument.capture()); Assert.assertEquals(argument.getValue().getUserOwner(), user); }
public AppUser( final Office office, final User user, final Set<Role> roles, final String email, final String firstname, final String lastname) { this.office = office; this.email = email.trim(); this.username = user.getUsername().trim(); this.firstname = firstname.trim(); this.lastname = lastname.trim(); this.password = user.getPassword().trim(); this.accountNonExpired = user.isAccountNonExpired(); this.accountNonLocked = user.isAccountNonLocked(); this.credentialsNonExpired = user.isCredentialsNonExpired(); this.enabled = user.isEnabled(); this.roles = roles; this.firstTimeLoginRemaining = true; }
@RequestMapping("/landing") public String landing(@CurrentUser User user, Model model) { model.addAttribute("username", user.getUsername()); return "landing"; }
public AuthenticationUserDetails(User user) { this.login = user.getUsername(); this.passwordHash = user.getPassword(); this.enabled = user.isEnabled(); this.grantedAuthorities.addAll(user.getAuthorities()); }