@RequestMapping(
      value = {"/pay_success_url"},
      method = RequestMethod.POST)
  public void successURL(
      @RequestParam(value = "OutSum", required = true) String outSum,
      @RequestParam(value = "InvId", required = true) String invId,
      @RequestParam(value = "SignatureValue", required = true) String signatureValue,
      @RequestParam(value = "Culture", required = false) String culture)
      throws Exception {

    double _money = Double.parseDouble(outSum);
    long _id = Long.parseLong(invId);

    String md5String = md5SignatureValue(_money, _id, password2, ":Shp_item=" + shp_item);
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetail = (UserDetails) auth.getPrincipal();
    Users u = userService.getRepository().findUsersByLogin(userDetail.getUsername());

    PaymentSystems ps =
        (PaymentSystems) paymentService.getRepository().findPaymentSystemsByUserId(u.getId());
    if (md5String.equals(ps.getKey())) {
      u.setSummaryCash(u.getSummaryCash() + _money);
      userService.getRepository().save(u);
    }
    HttpGet method = new HttpGet(url.concat("?OK").concat(invId));
    HttpClient client = new DefaultHttpClient();
    client.execute(method);
  }
Exemple #2
0
  @ResponseBody
  @RequestMapping("noLogin")
  public String noLogin(@RequestParam("uname") String uname) {

    if (ValidateUtil.isValid(uname)) {
      AdminUser result = adminUserService.noLogin(uname);
      // 用户不存在
      if (!ValidateUtil.isValid(result.getId())) {
        adminUserService.saveOrUpdateEntiry(result);
      }

      UserDetailsService detail = (UserDetailsService) SpringContextUtil.getBean("myUserDetail");
      UserDetails details = null;
      try {

        details = detail.loadUserByUsername(result.getName());
      } catch (Exception e) {
        return "用户未找到";
      }

      UsernamePasswordAuthenticationToken authenticationToken =
          new UsernamePasswordAuthenticationToken(details, null, details.getAuthorities());

      SecurityContextHolder.getContext().setAuthentication(authenticationToken);

      HttpSession session = getRequest().getSession(true); //
      session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());
    }
    return "redirect:/user";
  }
  public void removeUserFromCache(UserDetails user) {
    if (logger.isDebugEnabled()) {
      logger.debug("Cache remove: " + user.getUsername());
    }

    this.removeUserFromCache(user.getUsername());
  }
  /** {@inheritDoc} */
  @Override
  public User saveExistingUser(final User user) {
    // Existing user, check password in DB
    UserDetails existingUser = null;

    try {
      existingUser = dao.loadUserByUsername(user.getUsername());
    } catch (final UsernameNotFoundException e) {
      // username could not be found
    }

    String currentPassword = "";
    if (existingUser == null) {
      // lowercase userId
      ((UserImpl) user).setUsername(user.getUsername().toLowerCase());
    } else {
      currentPassword = existingUser.getPassword();
    }

    // if new user or changed password, encrypt the password
    if (StringUtils.isBlank(currentPassword) || !currentPassword.equals(user.getPassword())) {
      ((UserImpl) user).setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
    }

    return dao.save(user);
  }
  @RequestMapping(
      value = {"/welcome"},
      method = RequestMethod.GET)
  public ModelAndView defaultPage(Locale locale, HttpServletRequest request) {
    logger.info("Welcome to welcome Page. The client locale is {}.", locale);
    Contact contact = new Contact();
    // check if user is login
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth instanceof UsernamePasswordAuthenticationToken) {
      UserDetails userDetail = (UserDetails) auth.getPrincipal();

      String username = userDetail.getUsername();
      logger.info("username taken from SecurityContext " + username);
      User user = userService.getUserByUsername(username);
      if (user != null) {
        Utils.populateContact(user, contact);
      }
      logger.info("Contact object populated with username " + contact.getUsername());
    }
    ModelAndView mav = new ModelAndView("userMain");
    mav.addObject("countriesMap", Utils.getCountriesMap());
    mav.addObject("command", contact);
    mav.addObject(
        DashboardSessionManagmentFilter.SESSION_AUTHENTICATION_PARAM_NAME,
        filter.generateSecurityToken(request, encoder));

    return mav;
  }
 @Override
 public void updateUser(UserDetails user) {
   inMemManager.updateUser(user);
   User userToUpdate = userRepository.findFirstByUsername(user.getUsername());
   userToUpdate.setPassword(user.getPassword());
   for (GrantedAuthority authority : user.getAuthorities()) {
     StringTokenizer stringTokenizer = new StringTokenizer(authority.getAuthority(), ":");
     String rl = stringTokenizer.nextToken();
     String pj = stringTokenizer.nextToken();
     boolean found = false;
     for (Role role : userToUpdate.getRoles()) {
       if (role.getProject().equals(pj)) {
         role.setRole(Role.RoleEnum.valueOf(rl));
         found = true;
       }
     }
     if (!found) {
       Role role = new Role();
       role.setRole(Role.RoleEnum.valueOf(rl));
       role.setProject(pj);
       userToUpdate.getRoles().add(role);
     }
   }
   userRepository.save(userToUpdate);
 }
  protected UserDetails createUserDetails(
      String username, UserDetails userFromUserQuery, List<GrantedAuthority> combinedAuthorities) {
    String returnUsername = userFromUserQuery.getUsername();

    if (!isUsernameBasedPrimaryKey()) {
      returnUsername = username;
    }
    System.out.println(
        "HERE2>>>LOGGING IN...**********username: "******" userFromUserQuery.getPassword(): "
            + userFromUserQuery.getPassword()
            + " (CustomUser)userFromUserQuery).getKtn(): "
            + ((CustomUser) userFromUserQuery).getKtn().toString());

    return new CustomUser(
        ((CustomUser) userFromUserQuery).getKtn(),
        returnUsername,
        userFromUserQuery.getPassword(),
        userFromUserQuery.isEnabled(),
        true,
        true,
        true,
        combinedAuthorities);
  }
  @RequestMapping(value = "/group/create/invite", method = RequestMethod.POST)
  public String grpCrtInvite(
      @ModelAttribute("rootData") RootBean bean, Model model, Principal principal)
      throws Exception {

    initilize.exec();

    // ログインアカウントのUserNameを取得
    Authentication authentication = (Authentication) principal;
    UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    String userName = userDetails.getUsername();

    /*グループを新規作成(MEMBERには、ログインアカウントのみをセット)し、
    ログインアカウント以外のーザを取得*/
    grpCrtInviteCommand.preProc(bean);
    grpCrtInviteCommand.exec(userName);
    this.bean = grpCrtInviteCommand.postProc();

    // ログインアカウント以外のユーザを画面にセット
    model.addAttribute("rootData", bean);

    finalize.exec(bean, CommonConstants.VIEW_INVITE_MEMBER);

    return "groupInviteMember";
  }
  //    @Override
  public List<Capture> getAllCaptures() {
    UserDetails userDetails = JarvisContextHolder.getContext().getUserDetails();
    if (userDetails == null) {
      ResponseBuilderImpl builder = new ResponseBuilderImpl();
      builder.status(Response.Status.UNAUTHORIZED);
      Response response = builder.build();
      throw new WebApplicationException(response);
    }

    List<Capture> result = Lists.newArrayList();
    for (final Annotation annotation :
        annotatorDao.getAnnotationsByUsername(userDetails.getUsername())) {
      Capture capture = new Capture();
      capture.setAnnotator_schema_version(annotation.getAnnotatorSchemaVersion());
      capture.setCreated(new Date(annotation.getCreated()));
      capture.setId(annotation.getId());
      capture.setOfflineId(annotation.getOfflineId());
      capture.setQuote(annotation.getQuote());
      capture.setRanges(annotation.getRanges());
      capture.setResearchSession(annotation.getResearchSession());
      capture.setText(annotation.getText());
      capture.setUri(annotation.getUri());
      result.add(capture);
    }
    return result;
  }
 @RequestMapping(value = "account/current", method = RequestMethod.GET)
 @ResponseStatus(value = HttpStatus.OK)
 @ResponseBody
 public Account accounts(UserDetails userDetails) {
   LOG.info(userDetails.toString());
   return userRepository.findByEmail(userDetails.getUsername());
 }
Exemple #11
0
  /** Get the login of the current user. */
  public static String getCurrentLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    UserDetails springSecurityUser =
        (UserDetails) securityContext.getAuthentication().getPrincipal();

    return springSecurityUser.getUsername();
  }
  @Override
  public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
    User user = userManager.getUser(userName);

    if (user == null) {
      throw new UsernameNotFoundException("用户" + userName + "不存在");
    }

    HashSet<GrantedAuthority> grantedAuthoritySet = getUserAuthority(user);

    boolean enabled = true;
    boolean accountNonExpired = true;
    boolean credentialsNonExpired = true;
    boolean accountNonLocked = true;

    UserDetails userDetails =
        new org.springframework.security.core.userdetails.User(
            user.getUserName(),
            user.getPassword(),
            enabled,
            accountNonExpired,
            credentialsNonExpired,
            accountNonLocked,
            grantedAuthoritySet);
    System.out.println(userDetails.getPassword());
    return userDetails;
  }
  @RequestMapping(
      value = {"/", "/welcome**"},
      method = RequestMethod.GET)
  public ModelAndView defaultPage() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    ModelAndView model = new ModelAndView();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
      UserDetails userDetail = (UserDetails) auth.getPrincipal();
      model.addObject("nextBeers", nextBeerDAO.getBeers(userDetail.getUsername()));
      model.addObject(
          "hasBeersWithoutDate", nextBeerDAO.hasBeersWithoutDate(userDetail.getUsername()));
      model.setViewName("homeLogged");
    } else {
      model.setViewName("home");
    }
    NextBeer nextestBeer = nextBeerDAO.getNextBeer();
    Calendar today = Calendar.getInstance();
    today.set(Calendar.HOUR_OF_DAY, 23);
    today.set(Calendar.MINUTE, 59);
    if (nextestBeer != null && today.before(nextestBeer.getDateToPay())) {
      model.addObject("dateToPayNextBeers", nextestBeer.getDateToPay());
    }
    model.addObject("allNextBeers", nextBeerDAO.getAllNextBeers());

    return model;
  }
  //    @Override
  public Capture saveCapture(final String sessionId, final Capture capture) {
    UserDetails userDetails = JarvisContextHolder.getContext().getUserDetails();
    if (userDetails == null) {
      ResponseBuilderImpl builder = new ResponseBuilderImpl();
      builder.status(Response.Status.UNAUTHORIZED);
      Response response = builder.build();
      throw new WebApplicationException(response);
    }

    Annotation annotation = new Annotation();
    annotation.setAuthor(userDetails.getUsername());
    annotation.setAnnotatorSchemaVersion(capture.getAnnotator_schema_version());
    annotation.setCreated(new Date().getTime());
    annotation.setOfflineId(capture.getOfflineId());
    annotation.setQuote(capture.getQuote());
    annotation.setRanges(capture.getRanges());
    annotation.setResearchSession(capture.getResearchSession());
    annotation.setText(capture.getText());
    annotation.setUri(capture.getUri());

    annotatorDao.insertAnnotation(annotation);

    capture.setId(annotation.getId());
    capture.setCreated(new Date(annotation.getCreated()));

    return capture;
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    if (!(request instanceof HttpServletRequest)) {
      throw new RuntimeException("Expecting a HTTP request");
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authToken = httpRequest.getHeader("X-Auth-Token");

    String userName = TokenUtils.getUserNameFromToken(authToken);

    if (userName != null) {
      UserDetails userDetails = this.userService.loadUserByUsername(userName);
      if (TokenUtils.validateToken(authToken, userDetails)) {
        UsernamePasswordAuthenticationToken authentication =
            new UsernamePasswordAuthenticationToken(
                userDetails, null, userDetails.getAuthorities());
        authentication.setDetails(
            new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
        SecurityContextHolder.getContext().setAuthentication(authentication);
      }
    }

    chain.doFilter(request, response);
  }
 @Override
 public void setCurrentUser(SiteUser user) {
   UserDetails userDetails = userDetailsService.loadUserByUsername(user.getName());
   Authentication authentication =
       new UsernamePasswordAuthenticationToken(
           userDetails, user.getPassword(), userDetails.getAuthorities());
   SecurityContextHolder.getContext().setAuthentication(authentication);
 }
  @Test
  public void nullPopulatorConstructorReturnsEmptyAuthoritiesList() throws Exception {
    DirContextAdapter userData = new DirContextAdapter(new DistinguishedName("uid=joe"));

    LdapUserDetailsService service = new LdapUserDetailsService(new MockUserSearch(userData));
    UserDetails user = service.loadUserByUsername("doesntmatterwegetjoeanyway");
    assertThat(user.getAuthorities()).isEmpty();
  }
  public User getCurrentUser() {
    SecurityContext securityContext = SecurityContextHolder.getContext();

    UserDetails springSecurityUser =
        (UserDetails) securityContext.getAuthentication().getPrincipal();

    return userRepository.findUserByLogin(springSecurityUser.getUsername());
  }
Exemple #19
0
 public static String getUserName() {
   String userName = null;
   Authentication auth = SecurityContextHolder.getContext().getAuthentication();
   if (!(auth instanceof AnonymousAuthenticationToken)) {
     UserDetails userDetail = (UserDetails) auth.getPrincipal();
     userName = userDetail.getUsername();
   }
   return userName;
 }
 @Override
 public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
   for (UserDetails detail : this.details) {
     if (detail.getUsername().equalsIgnoreCase(userName)) {
       return detail;
     }
   }
   return null;
 }
 Authentication getAuthentication() {
   if (adminAuthentication == null) {
     UserDetails user = userDetailsService.loadUserByUsername("user");
     adminAuthentication =
         new TestingAuthenticationToken(
             user, user.getPassword(), (List<GrantedAuthority>) user.getAuthorities());
   }
   return adminAuthentication;
 }
 /**
  * If the current user has a specific authority (security role).
  *
  * <p>The name of this method comes from the isUserInRole() method in the Servlet API
  */
 public static boolean isUserInRole(String authority) {
   SecurityContext securityContext = SecurityContextHolder.getContext();
   Authentication authentication = securityContext.getAuthentication();
   if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
     UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
     return springSecurityUser.getAuthorities().contains(new SimpleGrantedAuthority(authority));
   }
   return false;
 }
  @Override
  public ItemDetails getItem(int itemNumber) throws RegistryException, LoginException {
    UsernamePasswordAuthenticationToken token =
        (UsernamePasswordAuthenticationToken) webServiceContext.getUserPrincipal();
    UserDetails user = userDetailsService.loadUserByUsername(token.getName());

    terminalSession.getModule(Login.class).login(user.getUsername(), user.getPassword());
    return terminalSession.getEntity(ItemDetails.class, itemNumber);
  }
 /**
  * {@inheritDoc}.
  *
  * @param arg0 the user name
  * @return S security user details.
  */
 @Override
 public UserDetails loadUserByUsername(final String arg0) throws UsernameNotFoundException {
   for (final UserDetails details : RepositoryUserDetailsService.users) {
     if (details.getUsername().equals(arg0)) {
       return details;
     }
   }
   throw new UsernameNotFoundException("no user with this pseudo");
 }
  public static String userName() {

    UserDetails user = SecurityUtils.getUser();

    if (user != null) {
      return user.getUsername();
    }

    return null;
  }
Exemple #26
0
 @Override
 public void createUser(UserDetails userDetails) {
   if (!userExists(userDetails.getUsername())) {
     String password = userDetails.getPassword();
     String hashedPassword = PasswordEncoderGenerator.generateHashedPassword(password);
     User user = (User) userDetails;
     user.setPassword(hashedPassword);
     mongoOperations.save((User) userDetails);
   }
 }
  @RequestMapping(value = "/403", method = RequestMethod.GET)
  public String access(ModelMap model) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (!(authentication instanceof AnonymousAuthenticationToken)) {
      UserDetails userDetails = (UserDetails) authentication.getPrincipal();
      model.addAttribute("username", userDetails.getUsername());
    }
    return "403";
  }
  @Test
  public void loadUserByUsername_usesSecurityContext() {
    when(userRepository.findOne(USER_A_NAME)).thenReturn(null);
    when(securityContext.getAuthentication()).thenReturn(authentication);
    when(authentication.getPrincipal()).thenReturn(userA);

    UserDetails result = communityServiceImpl.loadUserByUsername(USER_A_NAME);
    verify(securityContext, times(1)).getAuthentication();
    verify(authentication, times(1)).getPrincipal();
    assertEquals(USER_A_NAME, result.getUsername());
  }
Exemple #29
0
  /**
   * Check if current user has specified role.
   *
   * @param privilege the role to check if user has.
   * @return true if user has specified role, otherwise false.
   */
  public static boolean hasPrivilege(final String privilege) {
    final UserDetails userDetails = SpringSecurityUtil.getCurrentUserDetails();
    if (userDetails != null) {
      for (final GrantedAuthority each : userDetails.getAuthorities()) {
        if (each.getAuthority().equals(privilege)) {
          return true;
        }
      }
    }

    return false;
  }
Exemple #30
0
 /**
  * 重新加载UserDetails
  *
  * @param username
  * @param request
  */
 public static void reloadUserDetails(String username, HttpServletRequest request) {
   UserDetailServiceImpl userDetailServiceImpl =
       ContextManager.getApplicationContext().getBean(UserDetailServiceImpl.class);
   UserDetails userDetails = userDetailServiceImpl.loadUserByUsername(username);
   PreAuthenticatedAuthenticationToken authentication =
       new PreAuthenticatedAuthenticationToken(
           userDetails, userDetails.getPassword(), userDetails.getAuthorities());
   if (request != null) {
     authentication.setDetails(new WebAuthenticationDetails(request));
   }
   SecurityContextHolder.getContext().setAuthentication(authentication);
 }