Пример #1
0
  public void setEmail(String email) {
    if (UserManager.getUserProvider().isReadOnly()) {
      throw new UnsupportedOperationException("User provider is read-only.");
    }

    if (email != null && email.matches("\\s*")) {
      email = null;
    }

    if (UserManager.getUserProvider().isEmailRequired()
        && !StringUtils.isValidEmailAddress(email)) {
      throw new IllegalArgumentException("User provider requires email address.");
    }

    try {
      String originalEmail = this.email;
      UserManager.getUserProvider().setEmail(username, email);
      this.email = email;
      // Fire event.
      Map<String, Object> params = new HashMap<String, Object>();
      params.put("type", "emailModified");
      params.put("originalValue", originalEmail);
      UserEventDispatcher.dispatchEvent(this, UserEventDispatcher.EventType.user_modified, params);
    } catch (UserNotFoundException unfe) {
      Log.error(unfe.getMessage(), unfe);
    }
  }
Пример #2
0
 /**
  * 得到开始菜单.
  *
  * @param userId 用户ID
  */
 public List<Menu> getMenusByUserId(Long userId) {
   List<Menu> menus = Lists.newArrayList();
   List<Resource> rootResources = Lists.newArrayList();
   User user = userManager.loadById(userId);
   User superUser = userManager.getSuperUser();
   if (user != null && superUser != null && user.getId() == superUser.getId()) { // 超级用户
     rootResources = getByParentId(null, StatusState.normal.getValue());
   } else if (user != null) {
     rootResources = getResourcesByUserId(userId, null);
     // 去除非菜单资源
     Iterator<Resource> iterator = rootResources.iterator();
     while (iterator.hasNext()) {
       if (!ResourceState.menu.getValue().equals(iterator.next().getType())) {
         iterator.remove();
       }
     }
   }
   for (Resource parentResource : rootResources) {
     Menu menu = resourceToMenu(parentResource, true);
     if (menu != null) {
       menus.add(menu);
     }
   }
   return menus;
 }
Пример #3
0
  public void testAddAndRemoveUser() throws Exception {
    user = new User();

    // call populate method in super class to populate test data
    // from a properties file matching this class name
    user = (User) populate(user);

    user.addRole(roleManager.getRole(Constants.USER_ROLE));

    user = mgr.saveUser(user);
    assertEquals("john", user.getUsername());
    assertEquals(1, user.getRoles().size());

    log.debug("removing user...");

    mgr.removeUser(user.getId().toString());

    try {
      user = mgr.getUserByUsername("john");
      fail("Expected 'Exception' not thrown");
    } catch (Exception e) {
      log.debug(e);
      assertNotNull(e);
    }
  }
Пример #4
0
  // 使用缓存
  @Cacheable(
      value = {CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE},
      key = "#userId +'getResourceTreeByUserId'")
  public List<TreeNode> getResourceTreeByUserId(Long userId)
      throws DaoException, SystemException, ServiceException {
    // Assert.notNull(userId, "参数[userId]为空!");
    List<TreeNode> nodes = Lists.newArrayList();
    List<Resource> userResources = Lists.newArrayList();
    User user = userManager.loadById(userId);
    User superUser = userManager.getSuperUser();
    if (user != null && superUser != null && user.getId() == superUser.getId()) { // 超级用户
      userResources = this.getByParentId(null, StatusState.normal.getValue());
    } else if (user != null) {
      userResources = this.getResourcesByUserId(userId, null);
    }
    for (Resource resource : userResources) {
      TreeNode node = this.resourceToTreeNode(resource, null, true);
      if (node != null) {
        nodes.add(node);
      }
    }

    logger.debug(
        "缓存:{}", CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE + " 参数:userId=" + userId);
    return nodes;
  }
Пример #5
0
  public void createGame(
      String name,
      String description,
      ArrayList<Calendar> gameSessions,
      int turnTime,
      int defTime,
      int negTime)
      throws RemoteException, InvalidGameInfoException, InvalidSessionException {

    if (name == null) throw new NullPointerException();
    if (description == null) throw new NullPointerException();
    if (gameSessions == null) throw new NullPointerException();
    if (name.isEmpty()) throw new EmptyStringException();
    if (turnTime <= 0) throw new NegativeValueException();
    if (defTime <= 0) throw new NegativeValueException();
    if (negTime <= 0) throw new NegativeValueException();

    final ArrayList<String> listPlayer = new ArrayList<String>();
    listPlayer.add(usrMgr.getSession().getUser());
    srvAdapter.createGame(
        usrMgr.getSession(),
        new GameInfo(
            UUID.randomUUID(),
            name,
            description,
            listPlayer,
            gameSessions,
            42,
            turnTime,
            defTime,
            negTime));
    this.updateGameList();
  }
Пример #6
0
  public void execute() throws Exception {
    super.execute();
    String condition = "";
    // getTab().setTabName("Other");

    if (true) return;

    System.out.println(
        "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n The SQL ==="
            + condition
            + " The propertie name here ====="
            + getTab().getPropertiesNamesAsString());

    Long corporateId =
        UserManager.getCorporateOfLoginUser() == null
            ? 0L
            : UserManager.getCorporateOfLoginUser().getId();
    if (getTab().getPropertiesNamesAsString() != null
        && getTab().getPropertiesNamesAsString().indexOf("terminalId") >= 0) {
      condition = "${corporate.id}=" + corporateId;
    }

    System.out.println(
        "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n The SQL ==="
            + condition
            + " The propertie name here ====="
            + getTab().getPropertiesNamesAsString());

    getTab().setBaseCondition(condition);
  }
Пример #7
0
 public boolean saveUser(BeanFieldGroup<User> fieldGroup, String clearPass)
     throws FieldGroup.CommitException, BLException {
   fieldGroup.commit();
   BeanItem<User> item = fieldGroup.getItemDataSource();
   try {
     return (boolean)
         DB.execWithTransaction(
             (db) -> {
               User u = item.getBean();
               db.save(u);
               if (clearPass != null && !clearPass.isEmpty()) {
                 UserManager mgr = new UserManager(db);
                 try {
                   mgr.setPassword(u, clearPass);
                 } catch (BLException e) {
                   return false;
                 }
                 addRevisionCreated(
                     db, getEntityName(), item.getItemProperty("id").getValue().toString());
                 u.setForcePasswordChange(true);
                 db.session().update(u);
                 return true;
               }
               return false;
             });
   } catch (Exception e) {
     getApp().getLog().error(e);
     return false;
   }
 }
Пример #8
0
  /** Save the bowl picks */
  public void saveBowlPicks(Integer userId, List<BowlPickBo> bowlPicks) {
    UserManager userMgr = new UserManager();
    User user = userMgr.getUserById(userId);

    Transaction saveTransaction = session.beginTransaction();
    for (BowlPickBo bowlPickBo : bowlPicks) {
      BowlMatchup matchup = getMatchupById(bowlPickBo.getBowlMatchupId());
      if (matchup.getLockFlag() == true) {
        continue;
      }

      BowlPick pick = null;
      if (bowlPickBo.getBowlPickId() != null) {
        pick = getBowlPickById(bowlPickBo.getBowlPickId());
      } else {
        pick = new BowlPick();
      }
      pick.setBowlMatchup(getMatchupById(bowlPickBo.getBowlMatchupId()));
      pick.setSelectedTeam(getCfbTeamById(bowlPickBo.getSelectedTeamId()));
      pick.setUser(user);
      pick.setLastEditTimestamp(new Date());
      pick.setCreateTimestamp(new Date());
      user.getBowlPicks().add(pick);

      if (pick.getBowlMatchup().getLockFlag() == true) {
        continue;
      }

      session.saveOrUpdate(pick);
    }
    saveTransaction.commit();
    session.flush();
  }
Пример #9
0
  public void updateGameList() throws RemoteException, InvalidSessionException {
    final String user = usrMgr.getSession().getUser();
    final ArrayList<GameInfo> fullList = srvAdapter.fetchGameList(usrMgr.getSession());
    final ArrayList<GameInfo> currentList = new ArrayList<GameInfo>();
    final ArrayList<GameInfo> openList = new ArrayList<GameInfo>();
    final Calendar now = Calendar.getInstance();
    final Calendar now2h = Calendar.getInstance();
    now2h.add(Calendar.HOUR, -2);

    for (final GameInfo info : fullList) {
      if (info.getPlayers().contains(user)) {
        for (final Calendar c : info.getGameSessions()) {
          if (c.before(now) && c.after(now2h)) {
            currentList.add(info);
            break;
          }
        }
      } else if (info.getnFreeTerritories() > 0) {
        for (final Calendar c : info.getGameSessions()) {
          if (c.after(now2h)) {
            openList.add(info);
            break;
          }
        }
      }
    }

    mCurrentGameListModel.setData(currentList);
    mOpenGameListModel.setData(openList);
  }
Пример #10
0
  /**
   * Validates the login. Writes the isValid flag into the session along with the current user.
   *
   * @return true if OK, false if there's a problem
   */
  private boolean validateLogin(
      HttpSession session, HttpServletRequest req, HttpServletResponse res) throws Exception {

    // Creates a user database access bean.
    UserManager userManager = new UserManager();
    // (no setSession() here, since user may not exist yet)

    // Validates the login
    String username = req.getParameter("Username");
    String password = req.getParameter("Password");
    boolean isValid = userManager.isValidUser(username, password);
    boolean isAdmin = userManager.isAdmin(username);

    // To allow bootstrapping the system, if there are no users
    // yet, set this session valid, and grant admin privileges.
    if (userManager.getRecords().isEmpty()) {
      isValid = true;
      isAdmin = true;
    }

    if (isValid) {
      // Writes User object and validity flag to the session
      session.setAttribute("user", new User(username, password, isAdmin));
      session.setAttribute("isValid", new Boolean(isValid));
    } else {
      Util.putMessagePage(res, "Invalid user or password");
      return false;
    }
    return isValid;
  }
 @Test
 public void should_check_login_with_userName_and_password() throws Exception {
   addUsers(userManager);
   assertThat(userManager.checkLogin("user1", "p123"), is(true));
   assertThat(userManager.checkLogin("user2", "p321"), is(false));
   assertThat(userManager.checkLogin("user3", "b312"), is(true));
 }
Пример #12
0
  @Override
  public String advancedPut(Session s, String[] args, String content) throws WPISuiteException {
    Project p = getEntity(args[2])[0];
    String[] names = null;

    try {
      names = gson.fromJson(content, String[].class);
    } catch (JsonSyntaxException j) {
      throw new BadRequestException("Could not parse JSON");
    }

    ArrayList<String> success = new ArrayList<String>();

    UserManager u = ManagerLayer.getInstance().getUsers();

    if (args.length > 3) {
      if ("add".equals(args[3])) {
        for (String person : names) {
          if (p.addTeamMember(u.getEntity(s, person)[0])) success.add(person);
        }
      } else if ("remove".equals(args[3])) {
        for (String person : names) {
          if (p.removeTeamMember(u.getEntity(s, person)[0])) success.add(person);
        }
      }
    }

    return gson.toJson(success.toArray(names), String[].class);
  }
  @Override
  public Authentication authenticate(final Authentication authentication)
      throws AuthenticationException {

    Optional<User> u = Optional.absent();
    u = userManager.getInternalUser(authentication.getPrincipal().toString());

    if (!u.isPresent()) {
      throw new UsernameNotFoundException(
          "user not found: " + authentication.getPrincipal().toString());
    }
    boolean b =
        userManager.authenticate(
            authentication.getPrincipal().toString(), authentication.getCredentials().toString());
    if (!b) {
      throw new BadCredentialsException("invalid credentials");
    }

    List<GrantedAuthority> gaList = Lists.newArrayList();
    for (String role : u.get().getRoles()) {

      GrantedAuthority ga = new SimpleGrantedAuthority(role);
      gaList.add(ga);
    }

    UsernamePasswordAuthenticationToken upt =
        new UsernamePasswordAuthenticationToken(
            authentication.getPrincipal().toString(),
            authentication.getCredentials().toString(),
            gaList);
    return upt;
  }
Пример #14
0
 /** @see org.olat.core.id.User#setProperty(java.lang.String, java.lang.String) */
 @Override
 public void setProperty(final String propertyName, final String propertyValue) {
   final UserManager um = UserManager.getInstance();
   final UserPropertyHandler propertyHandler =
       um.getUserPropertiesConfig().getPropertyHandler(propertyName);
   propertyHandler.setUserProperty(this, propertyValue);
 }
Пример #15
0
  public void setName(String name) {
    if (UserManager.getUserProvider().isReadOnly()) {
      throw new UnsupportedOperationException("User provider is read-only.");
    }

    if (name != null && name.matches("\\s*")) {
      name = null;
    }

    if (name == null && UserManager.getUserProvider().isNameRequired()) {
      throw new IllegalArgumentException("User provider requires name.");
    }

    try {
      String originalName = this.name;
      UserManager.getUserProvider().setName(username, name);
      this.name = name;

      // Fire event.
      Map<String, Object> params = new HashMap<String, Object>();
      params.put("type", "nameModified");
      params.put("originalValue", originalName);
      UserEventDispatcher.dispatchEvent(this, UserEventDispatcher.EventType.user_modified, params);
    } catch (UserNotFoundException unfe) {
      Log.error(unfe.getMessage(), unfe);
    }
  }
Пример #16
0
 public int preReference(
     SessionContext ctx,
     DatabaseConnection conn,
     FormInstance instance,
     ErrorMessages msgs,
     EventManager manager,
     String reffldnm,
     SqlWhereUtil sqlWhereUtil) {
   UserManager um = (UserManager) ctx.getAttribute(SystemAttributeNames.USER_INFO_NAME);
   //    if (reffldnm.equals("APPBRHID") || reffldnm.equals("CLIENTMGR") ||
   // reffldnm.equals("UNIONNO")) {
   if (reffldnm.equals("APPBRHID") || reffldnm.equals("CLIENTMGR")) {
     // BRHID(用户网点)
     String BRHID = SCUser.getBrhId(um.getUserName());
     if (BRHID == null || BRHID.length() < 1) {
       msgs.add("用户网点不存在!");
       return -1;
     }
     // SUBBRHIDs(用户网点下的所有实网点,包括自己)
     String SUBBRHIDs = SCBranch.getSubBranchAll(BRHID);
     if (SUBBRHIDs == null || SUBBRHIDs.length() < 1) {
       msgs.add("下属网点不存在!");
       return -1;
     } else {
       SUBBRHIDs = "'" + SUBBRHIDs.replaceAll(",", "','") + "'";
     }
     // sqlWhereUtil
     if (reffldnm.equals("APPBRHID")) {
       sqlWhereUtil.addWhereField(
           "SCBRANCH",
           "BRHID",
           SUBBRHIDs,
           SqlWhereUtil.DataType_Sql,
           sqlWhereUtil.OperatorType_In);
     }
     if (reffldnm.equals("CLIENTMGR")) {
       sqlWhereUtil.addWhereField(
           "SCUSER",
           "BRHID",
           SUBBRHIDs,
           SqlWhereUtil.DataType_Sql,
           sqlWhereUtil.OperatorType_In,
           sqlWhereUtil.RelationOperator_And);
       sqlWhereUtil.addWhereField(
           "SCUSER",
           "USERTYPE",
           "3",
           //                                   SqlWhereUtil.DataType_Number,
           SqlWhereUtil.DataType_Character,
           sqlWhereUtil.OperatorType_Not_Equals);
     }
     //      if (reffldnm.equals("UNIONNO")) {
     //        sqlWhereUtil.addWhereField("CMFAMILYUNION", "BRHID", SUBBRHIDs,
     //                                   SqlWhereUtil.DataType_Sql,
     //                                   sqlWhereUtil.OperatorType_In);
     //      }
   }
   return 0;
 }
Пример #17
0
 @Test
 public void testExists() throws Exception {
   UserManager um = new UserManager();
   User u = new User();
   u.setUsername("a");
   boolean exists = um.exists(u);
   Assert.assertEquals(true, exists); // 第一个值是你想得到的结果
 }
Пример #18
0
 @Test
 public void testDelete1() {
   User user = userManager.get(1);
   Assert.assertNotNull(user);
   userManager.remove(1);
   sessionFactory.getCurrentSession().flush();
   user = userManager.get(1);
   Assert.assertNull(user);
 }
Пример #19
0
  // Test fix to http://issues.appfuse.org/browse/APF-96
  public void testUpdateUserWithUserRole() throws Exception {
    UserManager userManager = makeInterceptedTarget();
    User user = new User("user");
    user.setId(1L);
    user.getRoles().add(new Role(Constants.USER_ROLE));

    userDao.expects(once()).method("saveUser");
    userManager.saveUser(user);
  }
Пример #20
0
 public static Map<String, String> getHeaders() {
   HashMap<String, String> headers = new HashMap<>();
   headers.put("Content-Type", "application/json");
   headers.put("Accept", "application/json");
   if (UserManager.getInstance().getAuthToken() != null) {
     headers.put("Authorization", "Token " + UserManager.getInstance().getAuthToken());
   }
   return headers;
 }
Пример #21
0
 /** @see org.olat.core.id.User#getProperty(java.lang.String, java.util.Locale) */
 @Override
 public String getProperty(final String propertyName, final Locale locale) {
   final UserManager um = UserManager.getInstance();
   final UserPropertyHandler propertyHandler =
       um.getUserPropertiesConfig().getPropertyHandler(propertyName);
   if (propertyHandler == null) {
     return null;
   }
   return propertyHandler.getUserProperty(this, locale);
 }
Пример #22
0
  private UserManager makeInterceptedTarget() {
    ctx = new ClassPathXmlApplicationContext("/applicationContext-test.xml");

    UserManager userManager = (UserManager) ctx.getBean("targeted");

    // Mock the userDao
    userDao = new Mock(UserDao.class);
    userManager.setUserDao((UserDao) userDao.proxy());
    return userManager;
  }
Пример #23
0
  public void testSaveUser() throws Exception {
    user = mgr.getUserByUsername("user");
    user.setPhoneNumber("303-555-1212");

    log.debug("saving user with updated phone number: " + user);

    user = mgr.saveUser(user);
    assertEquals("303-555-1212", user.getPhoneNumber());
    assertEquals(1, user.getRoles().size());
  }
Пример #24
0
  @SuppressWarnings("unused")
  private static void printCurrentUser(UserManager mgr) throws Exception {
    User currentUser = mgr.getCurrentUser();
    logger.debug("user="******"*****@*****.**");
    mgr.update(currentUser);
    logger.debug("updated user");

    User currentUser2 = mgr.getCurrentUser();
    logger.debug("updated user's mail: " + currentUser2.getMail());
  }
Пример #25
0
 /** @return */
 public List<BowlPickScoreBo> getAllUsersBowlPickScores() {
   List<BowlPickScoreBo> results = new ArrayList<BowlPickScoreBo>();
   UserManager usrMgr = new UserManager();
   for (User user : usrMgr.getAllUsers()) {
     if (user.getBowlPicks().isEmpty()) {
       continue;
     }
     BowlPickScoreBo pickScore = new BowlPickScoreBo(user);
     results.add(pickScore);
   }
   return results;
 }
 public void add() {
   studentFacade.create(this.student);
   if (!userManager.loggedIn()) userManager.setStudent(student);
   else
     try {
       FacesContext.getCurrentInstance()
           .getExternalContext()
           .dispatch("studentList.xhtml?add=" + student.getStudentId());
     } catch (IOException ex) {
       Logger.getLogger(StudentManager.class.getName()).log(Level.SEVERE, null, ex);
     }
 }
  @Test
  public void testZeroInteractionsWithMock() throws Exception {

    User user = new User("user1", new Date());

    // call method where no call to userService will be made
    userManager.getUserLastLogin(user);
    Mockito.verifyZeroInteractions(userService);

    // Another way to check zero interactions
    userManager.getUserLastLogin(user);
    Mockito.verify(userService, Mockito.never());
  }
Пример #28
0
 @Test
 public void testUpdate() {
   User user = userManager.get(1);
   Assert.assertNotNull(user);
   Assert.assertEquals(new Integer(0), user.getLoginOk());
   Assert.assertEquals(new Integer(0), user.getLoginKo());
   user.incrementLoginOk();
   userManager.update(user, true);
   sessionFactory.getCurrentSession().flush();
   user = userManager.get(1);
   Assert.assertEquals(new Integer(1), user.getLoginOk());
   Assert.assertEquals(new Integer(0), user.getLoginKo());
 }
Пример #29
0
  @Override
  public Object invoke(MethodInvocation invocation) throws Throwable {

    Role requiredRole = invocation.getMethod().getAnnotation(RequiresRole.class).value();

    if (userManager.getCurrentUser() == null
        || !userManager.getCurrentUser().getRoles().contains(requiredRole)) {

      throw new IllegalStateException("User requires role " + requiredRole);
    }

    return invocation.proceed();
  }
Пример #30
0
  // Test fix to http://issues.appfuse.org/browse/APF-96
  public void testChangeToAdminRoleFromUserRole() throws Exception {
    UserManager userManager = makeInterceptedTarget();
    User user = new User("user");
    user.setId(1L);
    user.getRoles().add(new Role(Constants.ADMIN_ROLE));

    try {
      userManager.saveUser(user);
      fail("AccessDeniedException not thrown");
    } catch (AccessDeniedException expected) {
      assertNotNull(expected);
      assertEquals(expected.getMessage(), UserSecurityAdvice.ACCESS_DENIED);
    }
  }