Beispiel #1
0
  @Test
  public void testAuthenticateValidAuthInHeaderAndUserInDataStore() throws Exception {
    UserObjectifyDAOImpl userDAO = new UserObjectifyDAOImpl();

    User dbuser = new User();
    dbuser.setLogin("bob");
    dbuser.setToken("smith");
    dbuser.setPermissions(Permission.LIST_ALL_JOBS);
    dbuser = userDAO.insert(dbuser);

    AuthenticatorImpl auth = new AuthenticatorImpl();
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getRemoteAddr()).thenReturn("192.168.1.1");
    when(request.getHeader(AuthenticatorImpl.AUTHORIZATION_HEADER))
        .thenReturn("Basic " + encodeString("bob:smith"));

    User u = auth.authenticate(request);
    assertTrue(u != null);
    assertTrue(u.getLogin().equals("bob"));
    assertTrue(u.getToken().equals("smith"));
    assertTrue(u.getPermissions() == Permission.LIST_ALL_JOBS);
    assertTrue(u.getIpAddress().equals("192.168.1.1"));
    assertTrue(u.getId() == dbuser.getId().longValue());

    verify(request).getHeader(AuthenticatorImpl.AUTHORIZATION_HEADER);
  }
Beispiel #2
0
 @Test
 public void testShowBulk() {
   { // a small bulk!
     Twitter tw = TwitterTest.newTestTwitter();
     List<User> users = tw.users().show(Arrays.asList("mcfc", "winterstein"));
     for (User user : users) {
       System.out.println(
           user.getScreenName()
               + "\t"
               + user.getLocation()
               + "\t"
               + user.getPlace()
               + "\t"
               + user.getId());
     }
   }
   { // anonymous -- only in version 1
     Twitter tw = new Twitter();
     tw.setAPIRootUrl("http://api.twitter.com/1");
     List<User> users = tw.users().show(Arrays.asList("joehalliwell", "winterstein"));
     for (User user : users) {
       System.out.println(
           user.getScreenName()
               + "\t"
               + user.getLocation()
               + "\t"
               + user.getPlace()
               + "\t"
               + user.getId());
     }
   }
 }
Beispiel #3
0
  @PUT
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  @RolesAllowed({ADMIN, USER})
  public User modify(@NotNull User user) {

    User existingUser = null;
    if (sessionContext.isCallerInRole(USER) && !sessionContext.isCallerInRole(ADMIN)) {
      existingUser = userFinder.findByLogin(sessionContext.getCallerPrincipal().getName());

      if (!existingUser.getId().equals(user.getId())
          || !existingUser.getLogin().equals(user.getLogin())) {
        throw new WebApplicationException(Response.Status.UNAUTHORIZED);
      }

      user.setActivated(existingUser.getActivated());
      user.setDisabled(existingUser.getDisabled());
      user.setActionToken(existingUser.getActionToken());
    }

    if (existingUser == null) {
      existingUser = entityManager.find(User.class, user.getId());
    }
    checkNotNull(existingUser);
    user.setPassword(existingUser.getPassword());
    user.setCreationDate(existingUser.getCreationDate());
    user.setRoles(existingUser.getRoles());
    return entityManager.merge(user);
  }
  @RequestMapping(value = "/remove-userpic.jsp", method = RequestMethod.POST)
  public ModelAndView removeUserpic(ServletRequest request, @RequestParam("id") User user)
      throws Exception {
    Template tmpl = Template.getTemplate(request);

    if (!tmpl.isSessionAuthorized()) {
      throw new AccessViolationException("Not autorized");
    }

    User currentUser = tmpl.getCurrentUser();

    if (!currentUser.isModerator() && currentUser.getId() != user.getId()) {
      throw new AccessViolationException("Not permitted");
    }

    if (user.isModerator()) {
      throw new AccessViolationException(
          "Пользователю " + user.getNick() + " нельзя удалить картинку");
    }

    if (user.getPhoto() == null) {
      throw new AccessViolationException("Пользователь " + user.getNick() + " картинки не имеет");
    }

    if (userDao.removePhoto(user, currentUser)) {
      logger.info("Clearing " + user.getNick() + " userpic by " + currentUser.getNick());
    } else {
      logger.debug("SKIP Clearing " + user.getNick() + " userpic by " + currentUser.getNick());
    }

    return redirectToProfile(user);
  }
 private void refreshTimeoutOnEvade(User user, Server server) {
   ServerTimeout timeout =
       SafeNav.of(serverStorage.get(server.getId()))
           .next(TempServerConfig::getServerTimeouts)
           .next(ServerTimeoutStorage::getTimeouts)
           .next(timeouts -> timeouts.get(user.getId()))
           .get();
   if (timeout == null) {
     LOGGER.warn(
         "Attempted to refresh a timeout on a user who was not timed out! {} ({})",
         user.getUsername(),
         user.getId());
     return;
   }
   LOGGER.info(
       "User {} ({}) attempted to evade a timeout on {} ({})!",
       user.getUsername(),
       user.getId(),
       server.getName(),
       server.getId());
   Channel channel = apiClient.getChannelById(server.getId(), server);
   apiClient.sendMessage(
       loc.localize(
           "listener.mod.timeout.on_evasion",
           user.getId(),
           formatDuration(Duration.between(Instant.now(), timeout.getEndTime())),
           formatInstant(timeout.getEndTime())),
       channel);
   applyTimeoutRole(user, server, channel);
 }
 public void onTimeoutExpire(User user, Server server) {
   String serverId = server.getId();
   TempServerConfig serverConfig = serverStorage.get(serverId);
   if (serverConfig == null) {
     serverConfig = new TempServerConfig(serverId);
     serverStorage.put(serverId, serverConfig);
   }
   ServerTimeoutStorage storage = serverConfig.getServerTimeouts();
   if (storage != null) {
     ServerTimeout timeout = storage.getTimeouts().remove(user.getId());
     if (timeout != null) {
       saveServerConfig(serverConfig);
       LOGGER.info(
           "Expiring timeout for {} ({}) in {} ({})",
           user.getUsername(),
           user.getId(),
           server.getName(),
           server.getId());
       if (apiClient.getUserById(user.getId(), server) != NO_USER) {
         apiClient.sendMessage(
             loc.localize("message.mod.timeout.expire", user.getId()), server.getId());
       }
       removeTimeoutRole(user, server, apiClient.getChannelById(server.getId()));
       return;
     }
   }
   LOGGER.warn(
       "Unable to expire: find server or timeout entry for {} ({}) in {} ({})",
       user.getUsername(),
       user.getId(),
       server.getName(),
       server.getId());
 }
  public void testShowUser() throws Exception {
    User user = twitter1.showUser(id1.screenName);
    assertEquals(id1.screenName, user.getScreenName());
    assertNotNull(user.getLocation());
    assertNotNull(user.getDescription());
    assertNotNull(user.getProfileImageURL());
    assertNotNull(user.getURL());
    assertFalse(user.isProtected());

    assertTrue(0 <= user.getFavouritesCount());
    assertTrue(0 <= user.getFollowersCount());
    assertTrue(0 <= user.getFriendsCount());
    assertNotNull(user.getCreatedAt());
    assertNotNull(user.getTimeZone());
    assertNotNull(user.getProfileBackgroundImageUrl());

    assertTrue(0 <= user.getStatusesCount());
    assertNotNull(user.getProfileBackgroundColor());
    assertNotNull(user.getProfileTextColor());
    assertNotNull(user.getProfileLinkColor());
    assertNotNull(user.getProfileSidebarBorderColor());
    assertNotNull(user.getProfileSidebarFillColor());
    assertNotNull(user.getProfileTextColor());

    assertTrue(1 < user.getFollowersCount());
    if (user.getStatus() != null) {
      assertNotNull(user.getStatus().getCreatedAt());
      assertNotNull(user.getStatus().getText());
      assertNotNull(user.getStatus().getSource());
      assertFalse(user.getStatus().isFavorited());
      assertEquals(-1, user.getStatus().getInReplyToStatusId());
      assertEquals(-1, user.getStatus().getInReplyToUserId());
      assertFalse(user.getStatus().isFavorited());
      assertNull(user.getStatus().getInReplyToScreenName());
    }

    assertTrue(1 <= user.getListedCount());
    assertFalse(user.isFollowRequestSent());

    // test case for TFJ-91 null pointer exception getting user detail on users with no statuses
    // http://yusuke.homeip.net/jira/browse/TFJ-91
    twitter1.showUser("twit4jnoupdate");
    user = twitter1.showUser("tigertest");
    User previousUser = user;
    assertNotNull(DataObjectFactory.getRawJSON(user));

    user = twitter1.showUser(numberId);
    assertEquals(numberIdId, user.getId());
    assertNull(DataObjectFactory.getRawJSON(previousUser));
    assertNotNull(DataObjectFactory.getRawJSON(user));
    assertEquals(user, DataObjectFactory.createUser(DataObjectFactory.getRawJSON(user)));

    previousUser = user;
    user = twitter1.showUser(numberIdId);
    assertEquals(numberIdId, user.getId());
    assertNotNull(DataObjectFactory.getRawJSON(user));
    assertEquals(user, DataObjectFactory.createUser(DataObjectFactory.getRawJSON(user)));
  }
Beispiel #8
0
  public void testMapAndElementCollection() throws Exception {
    Session session = openSession();
    Transaction tx = session.beginTransaction();
    Address home = new Address();
    home.setCity("Paris");
    Address work = new Address();
    work.setCity("San Francisco");
    User user = new User();
    user.getAddresses().put("home", home);
    user.getAddresses().put("work", work);
    user.getNicknames().add("idrA");
    user.getNicknames().add("day[9]");
    session.persist(home);
    session.persist(work);
    session.persist(user);
    User user2 = new User();
    user2.getNicknames().add("idrA");
    user2.getNicknames().add("day[9]");
    session.persist(user2);
    tx.commit();

    session.clear();

    tx = session.beginTransaction();
    user = (User) session.get(User.class, user.getId());
    assertThat(user.getNicknames()).as("Should have 2 nick1").hasSize(2);
    assertThat(user.getNicknames()).as("Should contain nicks").contains("idrA", "day[9]");
    user.getNicknames().remove("idrA");
    tx.commit();

    session.clear();

    tx = session.beginTransaction();
    user = (User) session.get(User.class, user.getId());
    // TODO do null value
    assertThat(user.getAddresses()).as("List should have 2 elements").hasSize(2);
    assertThat(user.getAddresses().get("home").getCity())
        .as("home address should be under home")
        .isEqualTo(home.getCity());
    assertThat(user.getNicknames()).as("Should have 1 nick1").hasSize(1);
    assertThat(user.getNicknames()).as("Should contain nick").contains("day[9]");
    session.delete(user);
    session.delete(session.load(Address.class, home.getId()));
    session.delete(session.load(Address.class, work.getId()));

    user2 = (User) session.get(User.class, user2.getId());
    assertThat(user2.getNicknames()).as("Should have 2 nicks").hasSize(2);
    assertThat(user2.getNicknames()).as("Should contain nick").contains("idrA", "day[9]");
    session.delete(user2);

    tx.commit();

    session.close();

    checkCleanCache();
  }
  @RequestMapping(value = "/show-topics.jsp", method = RequestMethod.GET)
  public ModelAndView showUserTopics(
      @RequestParam("nick") String nick,
      @RequestParam(value = "offset", required = false) Integer offset,
      @RequestParam(value = "output", required = false) String output,
      HttpServletResponse response)
      throws Exception {
    Connection db = null;

    Map<String, Object> params = new HashMap<String, Object>();

    try {
      response.setDateHeader("Expires", System.currentTimeMillis() + 60 * 1000);
      response.setDateHeader("Last-Modified", System.currentTimeMillis());

      db = LorDataSource.getConnection();

      User user = User.getUser(db, nick);

      params.put("ptitle", "Сообщения " + user.getNick());
      params.put("navtitle", "Сообщения " + user.getNick());

      params.put("user", user);

      NewsViewer newsViewer = new NewsViewer();

      offset = fixOffset(offset);

      newsViewer.setLimit("LIMIT 20" + (offset > 0 ? (" OFFSET " + offset) : ""));

      newsViewer.setCommitMode(NewsViewer.CommitMode.ALL);

      if (user.getId() == 2) {
        throw new UserErrorException("Лента для пользователя anonymous не доступна");
      }

      newsViewer.setUserid(user.getId());

      params.put("messages", newsViewer.getMessagesCached(db));

      params.put("offsetNavigation", true);
      params.put("offset", offset);

      params.put("rssLink", "show-topics.jsp?nick=" + nick + "&output=rss");

      if (output != null && output.equals("rss")) {
        return new ModelAndView("section-rss", params);
      } else {
        return new ModelAndView("view-news", params);
      }
    } finally {
      if (db != null) {
        db.close();
      }
    }
  }
Beispiel #10
0
 public static void testUpdateAndFind() {
   User user = new User();
   user = getSession().insert(user);
   user.setName("name12");
   getSession().update(user);
   User user1 = getSession().find(User.class, user.getId());
   System.out.println(user1.getId() == user.getId());
   System.out.println(user1.getName().equals(user.getName()));
   System.out.println(user1.getAge() == user.getAge());
   System.out.println(user.getId());
 }
Beispiel #11
0
 /** Test positive creation of User instances. */
 @Test
 public final void testCreation() {
   User user1 = new User(TEST_USER1);
   Assert.assertEquals(TEST_USER1, user1.getUsername());
   Assert.assertNull(user1.getId());
   Assert.assertTrue(user1.isNew());
   user1 = new User(TEST_USER2, TEST_PASSWORD);
   Assert.assertEquals(TEST_USER2, user1.getUsername());
   Assert.assertEquals(TEST_PASSWORD, user1.getPassword());
   Assert.assertNull(user1.getId());
   Assert.assertTrue(user1.isNew());
 }
Beispiel #12
0
 public void registerAdmin() {
   this.isAdmin = true;
   User user = UserManager.getInstance().createUser("Admin", host);
   if (user == null) {
     user = UserManager.getInstance().findUser("Admin");
   }
   user.setUserData(
       new UserData(UserGroup.ADMIN, 0, false, false, false, null, "world.png", false));
   if (!UserManager.getInstance().connectToSession(sessionId, user.getId())) {
     logger.info("Error connecting Admin!");
   }
   this.userId = user.getId();
 }
  /**
   * Un boolean qui permet de dire si la requête a été envoyé ou reçue et qui permet d'initialiser
   * l'utilisateur user
   */
  public FriendRequest(User sender, User receiver, boolean isReceived) {

    received = isReceived;
    setSent(!received);

    if (received) user = receiver;
    else user = sender;

    senderID = sender.getId();
    receiverID = receiver.getId();
    senderName = sender.getFirstName() + " " + sender.getLastName();
    receiverName = receiver.getFirstName() + " " + receiver.getLastName();
  }
  @Test
  public void findByCheckId() {
    Set<Role> roles =
        Sets.newHashSet(
            roleRepository.save(
                Sets.newHashSet(
                    Role.builder().name("admin").build(),
                    Role.builder().name("verified").build(),
                    Role.builder().name("registered").build())));

    User parent =
        userRepository.save(
            User.builder()
                .accessToken("testAccessToken")
                .email("*****@*****.**")
                .name("testUser")
                .password("testPassword")
                .resetToken("testResetToken")
                .roles(roles)
                .build());

    Check parentCheck =
        checkRepository.save(
            Check.builder()
                .probe("testProbe")
                .interval(1)
                .name("testCheck")
                .state(State.ELECTED)
                .status(Status.UP)
                .user(parent)
                .url("http://www.test.com")
                .build());

    resultRepository.save(
        Result.builder()
            .probe("testProbe")
            .changed(true)
            .confirmation(true)
            .check(parentCheck)
            .responseTime(15)
            .status(Status.UP)
            .statusCode(200)
            .build());

    Page<Result> results = resultRepository.findByCheckId(parent.getId(), null);
    Assert.assertEquals(parent.getId(), results.getContent().get(0).getCheck().getId());
    userRepository.delete(parent);
  }
Beispiel #15
0
  public QueryResponse performSearch(SolrServer search) throws SolrServerException {
    SolrQuery params = new SolrQuery();
    // set search query params
    params.set("q", query.getQ());
    params.set("rows", SEARCH_ROWS);
    params.set("start", query.getOffset());

    params.set("qt", "edismax");

    if (query.getRange().getParam() != null) {
      params.add("fq", query.getRange().getParam());
    }

    if (query.getInterval().getRange() != null) {
      params.add("fq", query.getInterval().getRange());
    }

    params.setFacetMinCount(1);
    params.setFacet(true);

    if (query.getSection() != 0) {
      params.add("fq", "{!tag=dt}section_id:" + query.getSection());
      params.addFacetField("{!ex=dt}section_id");

      params.addFacetField("{!ex=dt}group_id");
    } else {
      params.addFacetField("section_id");
      params.addFacetField("group_id");
    }

    if (query.getUser() != null) {
      User user = query.getUser();

      if (query.isUsertopic()) {
        params.add("fq", "topic_user_id:" + user.getId());
      } else {
        params.add("fq", "user_id:" + user.getId());
      }
    }

    if (query.getGroup() != 0) {
      params.add("fq", "{!tag=dt}group_id:" + query.getGroup());
    }

    params.set("sort", query.getSort().getParam());

    return search.query(params);
  }
Beispiel #16
0
  @RequestMapping(
      value = "/memories.jsp",
      params = {"remove"},
      method = RequestMethod.POST)
  public @ResponseBody void remove(ServletRequest request, @RequestParam("id") int id)
      throws Exception {
    Template tmpl = Template.getTemplate(request);

    if (!tmpl.isSessionAuthorized()) {
      throw new AccessViolationException("Not authorized");
    }

    User user = tmpl.getCurrentUser();
    user.checkBlocked();
    user.checkAnonymous();

    MemoriesListItem m = memoriesDao.getMemoriesListItem(id);

    if (m != null) {
      if (m.getUserid() != user.getId()) {
        throw new AccessViolationException("Нельзя удалить чужую запись");
      }

      memoriesDao.delete(id);
    }
  }
Beispiel #17
0
  private void doDeleteComment(int msgid, String reason, User user, int scoreBonus)
      throws SQLException, ScriptErrorException {
    if (!getReplys(msgid).isEmpty()) {
      throw new ScriptErrorException("Нельзя удалить комментарий с ответами");
    }

    deleteComment.clearParameters();
    insertDelinfo.clearParameters();

    deleteComment.setInt(1, msgid);
    insertDelinfo.setInt(1, msgid);
    insertDelinfo.setInt(2, user.getId());
    insertDelinfo.setString(3, reason + " (" + scoreBonus + ')');

    updateScore.setInt(1, scoreBonus);
    updateScore.setInt(2, msgid);

    deleteComment.executeUpdate();
    insertDelinfo.executeUpdate();
    updateScore.executeUpdate();

    logger.info(
        "Удалено сообщение "
            + msgid
            + " пользователем "
            + user.getNick()
            + " по причине `"
            + reason
            + '\'');
  }
Beispiel #18
0
 public int create(User user) {
   try {
     Statement stat = conn.createStatement();
     ResultSet rs = stat.executeQuery("Select ID FROM USERS ");
     int i = user.getId();
     String n = user.getName();
     String pass = user.getPassword();
     Date d = user.getDate();
     System.out.println("i= " + i);
     stat.execute(
         "INSERT INTO USERS VALUES("
             + i
             + ",'"
             + n
             + "', '"
             + pass
             + "', TO_DATE('"
             + d
             + "','YYYY-MM-DD'))");
   } catch (SQLException e) {
     e.printStackTrace();
     System.out.println("Alarm in addUser");
   }
   return 1;
 }
Beispiel #19
0
  public static HashMap<Integer, Integer> getUnseenTopics(User user) {

    HashMap<Integer, Integer> unseenHash = new HashMap<Integer, Integer>();
    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    try {
      tx = session.getTransaction();
      Query q =
          session.createQuery(
              "select location, count(*) from Topic as t"
                  + " where t.topicID not in ("
                  + "		select topicID from LastseenTopic as l where l.userID = :userid and l.lasttime >= t.lastedit"
                  + "       )"
                  + " group by location");
      q.setInteger("userid", user.getId());

      List<Object[]> lsts = q.list();
      for (Object[] o : lsts) {
        unseenHash.put(new Integer("" + o[0]), new Integer("" + o[1]));
      }

    } catch (HibernateException e) {
      e.printStackTrace();
      if (tx != null && tx.isActive()) tx.rollback();
    }
    return unseenHash;
  }
 private void stopTimeout(MessageContext context, String args) {
   if (args.isEmpty()) {
     apiClient.sendMessage(
         loc.localize("commands.mod.stoptimeout.response.invalid"), context.getChannel());
     return;
   }
   String uid = args;
   if (uid.length() > 4) {
     if (uid.startsWith("<@")) {
       uid = uid.substring(2, uid.length() - 1);
     }
     Server server = context.getServer();
     User user = apiClient.getUserById(uid, server);
     if (user == NO_USER) {
       user = new User("UNKNOWN", uid, "", null);
     }
     LOGGER.info(
         "{} ({}) is attempting to cancel timeout for {} ({}) in {} ({})",
         context.getAuthor().getUsername(),
         context.getAuthor().getId(),
         user.getUsername(),
         user.getId(),
         server.getName(),
         server.getId());
     cancelTimeout(user, server, context.getChannel());
   } else {
     apiClient.sendMessage(
         loc.localize("commands.mod.stoptimeout.response.invalid"), context.getChannel());
   }
 }
  @Test
  public void testJSONDeserializer() throws IOException, URISyntaxException {
    User user = new User(new RestClient(null, new URI("/123/asd")), getTestJSON());
    assertEquals(user.getName(), username);
    assertEquals(user.getDisplayName(), displayName);
    assertEquals(user.getEmail(), email);
    assertEquals(user.getId(), userID);

    Map<String, String> avatars = user.getAvatarUrls();

    assertEquals(
        "https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=16",
        avatars.get("16x16"));
    assertEquals(
        "https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=24",
        avatars.get("24x24"));
    assertEquals(
        "https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=32",
        avatars.get("32x32"));
    assertEquals(
        "https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=48",
        avatars.get("48x48"));

    assertTrue(user.isActive());
  }
 public void deleteMessageFor(final Long id, final User user) {
   final Query query =
       entityManager.createNativeQuery(
           "update MESSAGES SET deleted_by=:user_id where ID=:id and deleted_by IS NULL and receiver_id <> sender_id and (receiver_id=:user_id or sender_id=:user_id)");
   query.setParameter("user_id", user.getId());
   query.setParameter("id", id);
   final int updated = query.executeUpdate();
   if (updated == 0) {
     final Query query2 =
         entityManager.createNativeQuery(
             "delete from MESSAGES where ID=:id and (receiver_id=:user_id or sender_id=:user_id)");
     query2.setParameter("id", id);
     query2.setParameter("user_id", user.getId());
     query2.executeUpdate();
   }
 }
Beispiel #23
0
 @Test
 public void testFind() throws Exception {
   User foundUser = h2User.find(user.getId());
   assertEquals(email, foundUser.getEmail());
   assertEquals(password, foundUser.getPassword());
   assertEquals(type, foundUser.getType());
 }
 public void setUser(User user) {
   synchronized (this) {
     this.user = user;
     userId = user == null ? null : user.getId();
     user__resolvedKey = userId;
   }
 }
 private String userToResult(User user) {
   return loc.localize(
       "commands.admin.find.response.entry",
       user.getUsername(),
       user.getId(),
       user.getDiscriminator());
 }
  public void testDefaultConfigurationModeIsInherited() throws Exception {
    User john = new User();
    john.setFirstname("John");
    john.setLastname("Doe");
    List<User> friends = new ArrayList<User>();
    User friend = new User();
    friend.setFirstname("Jane");
    friend.setLastname("Doe");
    friends.add(friend);
    john.setFriends(friends);

    Session s = openSession();
    s.persist(john);
    Transaction tx = s.beginTransaction();
    tx.commit();
    s.clear();
    tx = s.beginTransaction();
    john = (User) s.get(User.class, john.getId());
    assertEquals("Wrong number of friends", 1, john.getFriends().size());
    assertNull(john.firstname);

    s.delete(john);
    tx.commit();
    s.close();
  }
 @RequestMapping(value = "/login", method = RequestMethod.POST)
 public void login(
     @ModelAttribute("user") User user,
     HttpSession session,
     HttpServletRequest request,
     HttpServletResponse response,
     @RequestParam(value = "userId", required = true) String userId,
     @RequestParam(value = "passwd", required = true) String passwd)
     throws Exception {
   user = this.userService.getUser(userId, passwd);
   PrintWriter pw = response.getWriter();
   if (user != null) {
     Cookie cookie = new Cookie(Constants.BRUSERID, user.getId());
     cookie.setPath("/");
     cookie.setMaxAge(10 * 365 * 24 * 3600);
     response.addCookie(cookie);
     WebContextThreadLocal.setCurrentUser(user);
     LoggerUtil.info(this.getClass(), "当前登录用户为:" + user.getUserName());
     AuthenticateRole.authenticate(request, user, (String) request.getAttribute("userIdRuleReg"));
     request.setAttribute("user", user);
     session.setAttribute("user", user);
     this.userService.flush();
     pw.write(
         "{\"login\" : true ,\"user\":\""
             + user.getUserName()
             + "\",\"isTeacher\":\""
             + request.getAttribute("isTeacher")
             + "\"}");
   } else {
     LoggerUtil.debug(this.getClass(), "用户名或密码错误!");
     pw.write("{\"login\":false}");
   }
   pw.close();
 }
Beispiel #28
0
  public static boolean needsHighlight(Topic t, User u) {
    boolean highlight = true;
    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    try {
      tx = session.getTransaction();
      Query q =
          session.createQuery(
              "select ls "
                  + "  from LastseenTopic as ls "
                  + " where ls.userID = :userID "
                  + "   and ls.topicID = :topicID "
                  + "   and ls.lasttime > :lastedit");
      q.setInteger("userID", u.getId());
      q.setInteger("topicID", t.getTopicID());
      q.setDate("lastedit", t.getLastedit());
      List<LastseenTopic> lsts = q.list();
      if (lsts.size() > 0) {
        highlight = lsts.get(0).getLasttime().before(t.getLastedit());
      }

    } catch (HibernateException e) {
      e.printStackTrace();
      if (tx != null && tx.isActive()) tx.rollback();
    }
    return highlight;
  }
 private Collection<GroupData> fetchGroupDataForUser(
     final User user, final boolean restrictToSuscribed) {
   final String ifConnectedColumns =
       "max(ifnull(USER_ID=:userId, false))>0, sum(ifnull(USER_ID=:userId AND LAST_VISIT<PUBLIC_MESSAGES.`DATE`, false))";
   final Query query =
       entityManager.createNativeQuery(
           "select GROUPS.ID, name, count(DISTINCT GROUP_USER.USER_ID), "
               + (user != null ? ifConnectedColumns : " 0,0")
               + " from GROUPS left join  GROUP_USER on GROUP_ID=ID "
               + " left join PUBLIC_MESSAGES on PUBLIC_MESSAGES.GROUP_ID=GROUP_USER.GROUP_ID "
               + (restrictToSuscribed ? " where GROUP_USER.USER_ID=:userId" : "")
               + " group by GROUPS.ID order by CREATION_DATE");
   if (user != null) query.setParameter("userId", user.getId());
   final List<Object[]> list = query.getResultList();
   final Collection<GroupData> result = new ArrayList<GroupData>(list.size());
   for (final Object[] o : list)
     result.add(
         new GroupData(
             ((Number) o[0]).longValue(),
             UserStringImpl.valueOf(String.valueOf(o[1])),
             ((Number) o[2]).longValue(),
             ((Number) o[3]).intValue() != 0,
             ((Number) o[4]).intValue()));
   return result;
 }
  private void ban(MessageContext context, String args) {
    if (args.isEmpty()) {
      return;
    }
    String[] split = args.split(" ");
    List<String> banned = new ArrayList<>();
    List<String> failed = new ArrayList<>();
    Channel channel = context.getChannel();
    for (String userStr : split) {
      User user = findUser(context, userStr);
      String userId = user.getId();
      if (user == NO_USER) {
        userId = userStr;
      }

      if (banChecked(channel, context.getAuthor(), user, context.getServer())) {
        banned.add(userId + " " + user.getUsername());
      } else {
        failed.add(userId + " " + user.getUsername());
      }
    }

    if (channel.getId() != null) {
      StringJoiner joiner = new StringJoiner("\n");
      for (String s : banned) {
        String[] pair = s.split(" ", 2);
        joiner.add(loc.localize("commands.mod.ban.response", pair[1], pair[0]));
      }
      apiClient.sendMessage(joiner.toString(), channel);
    }
  }