Пример #1
0
  /**
   * Is the user configured to use this credential type
   *
   * @return
   */
  public boolean configuredForCredentialType(String type, RealmModel realm, UserModel user) {
    UserFederationProvider link = getFederationLink(realm, user);
    if (link != null) {
      Set<String> supportedCredentialTypes = link.getSupportedCredentialTypes(user);
      if (supportedCredentialTypes.contains(type)) return true;
    }
    if (UserCredentialModel.isOtp(type)) {
      if (!user.isOtpEnabled()) return false;
    }

    List<UserCredentialValueModel> creds = user.getCredentialsDirectly();
    for (UserCredentialValueModel cred : creds) {
      if (cred.getType().equals(type)) {
        if (UserCredentialModel.isOtp(type)) {
          OTPPolicy otpPolicy = realm.getOTPPolicy();
          if (!cred.getAlgorithm().equals(otpPolicy.getAlgorithm())
              || cred.getDigits() != otpPolicy.getDigits()) {
            return false;
          }
          if (type.equals(UserCredentialModel.TOTP) && cred.getPeriod() != otpPolicy.getPeriod()) {
            return false;
          }
        }
        return true;
      }
    }
    return false;
  }
  private void getSysUserSource() {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
    // 一种方法
    /*WebVisitor sor = AbstractConfig.getWebApplication().getVisitorsOper().getVisitors().get(session.getId());
    String sorw =sor.getUser().getUserCode();
    System.out.println("ssssssssssssssssssssss"+sorw);*/
    // 另一种方法
    java.lang.Object obj = session.getAttribute("webVisitor");
    WebVisitor visitorObj = (WebVisitor) obj;
    UserModel userObj = visitorObj.getUser();

    ExeSQL sysUserExe = new ExeSQL();
    String sysUserSQL = "select userdescription from ledsysuser where usercode = ? ";

    ArrayList<String[]> list = new ArrayList<String[]>();
    String[] arr = new String[2];
    arr[0] = "String";
    arr[1] = userObj.getUserCode();
    list.add(arr);

    String userSourceValue = sysUserExe.getOneValue(sysUserSQL, list);
    System.out.println(userSourceValue);
    this.setSysUserSourceT(userSourceValue);
    System.out.println("fffffffffffffffffffffff" + userObj.getUserCode());
  }
Пример #3
0
 protected UserFederationProvider getFederationLink(RealmModel realm, UserModel user) {
   if (user.getFederationLink() == null) return null;
   for (UserFederationProviderModel fed : realm.getUserFederationProviders()) {
     if (fed.getId().equals(user.getFederationLink())) {
       return getFederationProvider(fed);
     }
   }
   return null;
 }
Пример #4
0
 protected UserModel registerWithFederation(RealmModel realm, UserModel user) {
   for (UserFederationProviderModel federation : realm.getUserFederationProviders()) {
     UserFederationProvider fed = getFederationProvider(federation);
     if (fed.synchronizeRegistrations()) {
       user.setFederationLink(federation.getId());
       UserModel registered = fed.register(realm, user);
       managedUsers.put(registered.getId(), registered);
       return registered;
     }
   }
   return user;
 }
 private User addJabberUserToUserModelOrUpdateInfo(RosterEntry rosterEntry) {
   //    System.out.println("rosterEntry.getName() = " + rosterEntry.getName());
   //    System.out.println("rosterEntry.getUser() = " + rosterEntry.getUser());
   User user = myUserModel.createUser(getSimpleId(rosterEntry.getUser()), getName());
   String newGroup = getUserGroup(rosterEntry);
   if (newGroup != null) {
     user.setGroup(newGroup, myUserModel);
   }
   user.setDisplayName(rosterEntry.getName(), myUserModel);
   myUserModel.addUser(user);
   String jabberId = getCurrentJabberID(user, rosterEntry);
   updateIsIDEtalkClient(jabberId, user);
   return user;
 }
Пример #6
0
 protected void deleteInvalidUser(RealmModel realm, UserModel user) {
   KeycloakSession tx = session.getKeycloakSessionFactory().create();
   try {
     tx.getTransaction().begin();
     RealmModel realmModel = tx.realms().getRealm(realm.getId());
     if (realmModel == null) return;
     UserModel deletedUser = tx.userStorage().getUserById(user.getId(), realmModel);
     tx.userStorage().removeUser(realmModel, deletedUser);
     logger.infof("Removed invalid user '%s'", user.getUsername());
     tx.getTransaction().commit();
   } finally {
     tx.close();
   }
 }
 private boolean hasJabberContacts() {
   User[] users = myUserModel.getAllUsers();
   for (User user : users) {
     if (user.getTransportCode().equals(getName())) return true;
   }
   return false;
 }
  private void updateJabberUsers(boolean removeUsersNotInRoster) {
    LOG.debug("Roster changed - update user model");
    Set<User> currentUsers = new HashSet<>(Arrays.asList(myUserModel.getAllUsers()));
    for (RosterEntry rosterEntry : getRoster().getEntries()) {
      User user = addJabberUserToUserModelOrUpdateInfo(rosterEntry);
      currentUsers.remove(user);
    }

    if (removeUsersNotInRoster) {
      removeUsers(currentUsers);
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug("Roster synchronized: " + Arrays.asList(myUserModel.getAllUsers()));
    }
  }
  public static boolean needsToRenew(UserModel u) {
    if (u.isMember("Associate")) {
      return true;
    }

    GregorianCalendar cal = new GregorianCalendar();
    cal.set(Calendar.MONTH, Calendar.JANUARY);
    cal.set(Calendar.DAY_OF_MONTH, 20);
    cal.set(Calendar.YEAR, 2009);
    cal.set(Calendar.HOUR_OF_DAY, 1);
    cal.set(Calendar.MINUTE, 0);

    GregorianCalendar exp = new GregorianCalendar();
    exp.setTime(u.getExpiry());
    return exp.before(cal);
  }
Пример #10
0
 public void updateCredential(RealmModel realm, UserModel user, UserCredentialModel credential) {
   if (credential.getType().equals(UserCredentialModel.PASSWORD)) {
     if (realm.getPasswordPolicy() != null) {
       PasswordPolicy.Error error =
           realm.getPasswordPolicy().validate(user, credential.getValue());
       if (error != null) throw new ModelException(error.getMessage(), error.getParameters());
     }
   }
   user.updateCredential(credential);
 }
Пример #11
0
  protected UserModel validateAndProxyUser(RealmModel realm, UserModel user) {
    UserModel managed = managedUsers.get(user.getId());
    if (managed != null) {
      return managed;
    }

    UserFederationProvider link = getFederationLink(realm, user);
    if (link != null) {
      UserModel validatedProxyUser = link.validateAndProxy(realm, user);
      if (validatedProxyUser != null) {
        managedUsers.put(user.getId(), validatedProxyUser);
        return validatedProxyUser;
      } else {
        deleteInvalidUser(realm, user);
        return null;
      }
    }
    return user;
  }
Пример #12
0
            @Override
            public void config(
                RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
              UserModel user = appRealm.getUser("test-user@localhost");
              ApplicationModel accountApp =
                  appRealm
                      .getApplicationNameMap()
                      .get(org.keycloak.models.Constants.ACCOUNT_APPLICATION);
              for (String r : accountApp.getDefaultRoles()) {
                accountApp.grantRole(user, accountApp.getRole(r));
              }

              UserModel user2 = appRealm.addUser("test-user-no-access@localhost");
              user2.setEnabled(true);
              UserCredentialModel creds = new UserCredentialModel();
              creds.setType(CredentialRepresentation.PASSWORD);
              creds.setValue("password");
              appRealm.updateCredential(user2, creds);
            }
Пример #13
0
  protected void validateUser(RealmModel realm, UserModel user) {
    if (managedUsers.containsKey(user.getId())) {
      return;
    }

    UserFederationProvider link = getFederationLink(realm, user);
    if (link != null && !link.isValid(realm, user)) {
      deleteInvalidUser(realm, user);
      throw new IllegalStateException("Federated user no longer valid");
    }
  }
  private void updateUserPresence(String jabberId) {
    LOG.debug("Presence changed for " + jabberId);
    final User user = myUserModel.findUser(getSimpleId(jabberId), getName());
    if (user != null) {
      updateIsIDEtalkClient(jabberId, user);

      final UserPresence presence = _getUserPresence(user);
      IDEtalkEvent event = createPresenceChangeEvent(user, presence);
      if (event != null) {
        getBroadcaster().doChange(event, () -> myUser2Presence.put(user, presence));
      }
    }
  }
  public static ConferenceRegistrationModel newRegistration(
      UserModel user,
      String type,
      int prevConfs,
      int prevRetreats,
      boolean headset,
      String foodPrefs,
      String emergName,
      String emergPhone,
      String specialNeeds,
      String code,
      String receiptNum,
      boolean africafund) {
    ConferenceRegistrationModel reg = new ConferenceRegistrationModel();
    reg.setUser(user);
    reg.setType(type);
    reg.setDate(new Date());
    reg.setReceiptNum(receiptNum);
    reg.setAmountPaid(costs.get(type));
    reg.setChapter(user.getChapter());
    reg.setSubsidized(type.contains("sub"));

    reg.setCancelled(false);

    if (type.contains("reg0")) reg.setRoomSize(0);
    if (type.contains("reg1")) reg.setRoomSize(1);
    if (type.contains("reg2")) reg.setRoomSize(2);
    if (type.contains("reg4")) reg.setRoomSize(4);

    reg.setEmergName(emergName);
    reg.setEmergPhone(emergPhone);
    reg.setSpecialNeeds(specialNeeds);
    reg.setHeadset(headset);
    reg.setFoodPrefs(foodPrefs);
    reg.setPrevConfs(prevConfs);
    reg.setPrevRetreats(prevRetreats);
    reg.setCode(code);

    reg.setAfricafund(africafund);

    HibernateUtil.currentSession().save(reg);
    return reg;
  }
Пример #16
0
 @Override
 public boolean removeUser(RealmModel realm, UserModel user) {
   UserFederationProvider link = getFederationLink(realm, user);
   if (link != null) {
     boolean fedRemoved = link.removeUser(realm, user);
     if (fedRemoved) {
       boolean localRemoved = session.userStorage().removeUser(realm, user);
       managedUsers.remove(user.getId());
       if (!localRemoved) {
         logger.warn(
             "User removed from federation provider, but failed to remove him from keycloak model");
       }
       return localRemoved;
     } else {
       logger.warn("Failed to remove user from federation provider");
       return false;
     }
   }
   return session.userStorage().removeUser(realm, user);
 }
Пример #17
0
  public PostModel reply(UserModel currentUser, String body, String tags) {
    if (!hasActiveWhiteboard()) {
      Session hibernateSession = HibernateUtil.currentSession();
      PostModel p = new PostModel();
      hibernateSession.save(p);
      AjaxServlet.invalidateFrontPageCache(getGroup().getId());

      p.setBody(body);
      addReply(p); // sets group on reply

      Logger.getLogger(this.getClass())
          .info("Post " + this.getId() + " has " + this.getReplies().size() + " replies.");

      if (this.getReplies().size() == Post.RepliesToFeature) {
        this.feature();
      }

      if (this.isFeatured()) {
        p.feature();
      }

      for (String tag : TagLogic.extractTagNames(tags)) {
        addTag(TagModel.getOrCreateTag(tag));
      }

      currentUser.addPost(p);

      setLastReply(new Date());

      hibernateSession.flush();
      Helpers.currentDailyStats().logReply();

      p.setSearchable(SearchableModel.newSearchable(p, null, null));

      return p;
    } else {
      Logger.getLogger(this.getClass()).debug("Tried to reply to a post that has a whiteboard.");
      return null;
    }
  }
Пример #18
0
  public static PostModel newPost(
      UserModel currentUser,
      GroupModel targetGroup,
      String subject,
      String intro,
      String body,
      String unsplitTags,
      boolean whiteboard) {
    Session hibernateSession = HibernateUtil.currentSession();
    PostModel p = new PostModel();
    hibernateSession.save(p);
    AjaxServlet.invalidateFrontPageCache(targetGroup.getId());

    p.setSubject(subject);
    p.setIntro(intro);

    if (!body.trim().equals("")) {
      p.setBody(body);
    }

    targetGroup.addPost(p);

    for (String tag : TagLogic.extractTagNames(unsplitTags)) {
      p.addTag(TagModel.getOrCreateTag(tag));
    }

    currentUser.addPost(p);

    hibernateSession.flush();

    if (whiteboard) {
      p.setWhiteboard(WhiteboardModel.newWhiteboard(null, p, null));
    }
    Helpers.currentDailyStats().logPost();

    p.setSearchable(SearchableModel.newSearchable(p, null, null));

    return p;
  }
 private void removeUsers(Set<User> currentUsers) {
   for (User user : currentUsers) {
     myUserModel.removeUser(user);
   }
 }
 boolean isUserInMyContactListAndActive(String userName) {
   User user = myUserModel.findUser(getSimpleId(userName), getName());
   return user != null && user.isOnline();
 }
 private EventBroadcaster getBroadcaster() {
   return myUserModel.getBroadcaster();
 }
Пример #22
0
  public void testSaveUser() {
    Session session = sessionFactory.openSession();
    Transaction transaction = session.getTransaction();
    transaction.begin();

    UserModel user = new UserModel();
    user.setEmail("*****@*****.**");
    user.setUsername("diennm");
    user.setDateOfBirth(new Date(1988, 06, 15));
    user.setEncryptedPassword(false);
    user.setPassword("dien123");
    user.setFirstName("Dien");
    user.setLastName("Nguyen");
    user.setGender(Gender.Male);
    user.setWebsite("https://github.com/DienNM");

    session.save(user);
    transaction.commit();

    // Find User
    Query query = session.createQuery("from UserModel u where u.username = :uname ");
    query.setParameter("uname", "diennm");

    UserModel uniqueUser = (UserModel) query.uniqueResult();
    System.out.println("Loaded user: " + uniqueUser.getEmail());

    session.close();
  }
 private User self() {
   return myUserModel.createUser(myFacade.getMyAccount().getJabberId(), getName());
 }
Пример #24
0
  // 根据用户ID找该用户的粉丝对象
  public Set<String> getFansUserByUid(String uid, int pageNumber) {

    System.out.println("进入查找用户的粉丝用户");

    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
    connectionManager.setMaxTotal(2000);
    connectionManager.setDefaultMaxPerRoute(1000);

    HttpClient httpClient_fans = new DefaultHttpClient(connectionManager);

    // 伪装成Firefox 5,
    httpClient_fans
        .getParams()
        .setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    httpClient_fans
        .getParams()
        .setParameter(
            ClientPNames.COOKIE_POLICY,
            CookiePolicy.BROWSER_COMPATIBILITY); // 一定要有,否则会生成多个Cookie header送给web server
    httpClient_fans.getParams().setParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, true); //
    httpClient_fans
        .getParams()
        .setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); // 这个是和目标网站的编码有关;
    httpClient_fans.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "UTF-8");
    List<BasicHeader> headerList_fans = new ArrayList<BasicHeader>();

    headerList_fans.add(new BasicHeader("Accept", "*/*"));
    headerList_fans.add(new BasicHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3"));
    headerList_fans.add(new BasicHeader("Accept-Language", "zh-CN,zh;q=0.8"));
    headerList_fans.add(new BasicHeader("Cache-Control", "no-cache"));
    headerList_fans.add(new BasicHeader("Connection", "keep-alive"));
    headerList_fans.add(
        new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"));
    headerList_fans.add(new BasicHeader("X-Requested-With", "XMLHttpRequest"));
    headerList_fans.add(new BasicHeader("Cookie", CookieData.CookieNow));

    httpClient_fans
        .getParams()
        .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(300000));
    httpClient_fans.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(300000));
    httpClient_fans
        .getParams()
        .setParameter(ClientPNames.CONN_MANAGER_TIMEOUT, new Long(300000)); // second;
    // 伪装成Firefox
    httpClient_fans
        .getParams()
        .setParameter(
            CoreProtocolPNames.USER_AGENT,
            "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/17.0 Firefox/17.0");

    headerList_fans.add(new BasicHeader("Host", "weibo.com"));
    headerList_fans.add(new BasicHeader("Origin", "weibo.com"));

    GetFollowOrFansPageNumber page = new GetFollowOrFansPageNumber();
    int number = page.getFollowOrFansPage("http://weibo.com/" + uid + "/fans");

    //		QueryNumberManager queryNumber = QueryNumberManager.getInstance();

    Set<String> uidList = new HashSet<String>();

    for (int u = pageNumber; u < number; u++) {

      System.out.println("粉丝第" + (u + 1) + "页");
      String url_fans = "http://weibo.com/" + uid + "/fans" + "?page=" + (u + 1);
      System.out.println(url_fans);

      headerList_fans.add(new BasicHeader("Referer", url_fans));
      httpClient_fans.getParams().setParameter(ClientPNames.DEFAULT_HEADERS, headerList_fans);

      // 设置代理对象 ip/代理名称,端口
      //			ProxyManager proxyManager = ProxyManager.getInstance();
      //			ProxyBean proxy = new ProxyBean();
      //			proxy = proxyManager.getOneProxy();
      //			System.out.println("拿到代理IP" + proxy.getIp());
      //			httpClient_fans.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new
      // HttpHost(proxy.getIp(), proxy.getPort()));

      HttpPost httpPost_fans = new HttpPost(url_fans);

      HttpResponse httpResponseFans = null;
      try {
        httpResponseFans = httpClient_fans.execute(httpPost_fans);
      } catch (ClientProtocolException e1) {
        PshLogger.logger.error(e1.getMessage());
      } catch (IOException e1) {
        PshLogger.logger.error(e1.getMessage());
        System.out.println("重新执行找关注");
        return getFansUserByUid(uid, u);
      }

      if (httpResponseFans == null) {

        return getFansUserByUid(uid, u + 1);
      }

      HttpEntity httpEntityFans = httpResponseFans.getEntity();

      if (httpEntityFans == null) {

        return getFansUserByUid(uid, u);
      }

      BufferedReader in_fans = null;
      try {
        in_fans = new BufferedReader(new InputStreamReader(httpEntityFans.getContent(), "UTF-8"));
      } catch (UnsupportedEncodingException e1) {
        PshLogger.logger.error(e1.getMessage());
      } catch (IllegalStateException e1) {
        PshLogger.logger.error(e1.getMessage());
      } catch (IOException e1) {
        PshLogger.logger.error(e1.getMessage());
      }

      String result_fans = "";
      String item_fans = "";

      try {
        while ((item_fans = in_fans.readLine()) != null) {
          if (item_fans.trim().indexOf("cnfList") != -1) {
            System.out.println("找到一行html符合");
            result_fans = item_fans.trim();
          }
        }
      } catch (IOException e1) {
        PshLogger.logger.error(e1.getMessage());
      } finally {
        try {
          in_fans.close();
        } catch (IOException e) {
          PshLogger.logger.error(e.getMessage());
        }
      }

      if (result_fans.trim().equals("")) {

        System.out.println("新浪微博提示行为异常follow");
        // 换代理IP重新获取该页
        return getFansUserByUid(uid, u);
      }

      System.out.println("已获取到 html_fans");

      try {

        result_fans =
            result_fans.substring(
                result_fans.indexOf("<div"), result_fans.lastIndexOf("/div>") + 5);
        result_fans = result_fans.replace('\\', '`');
        result_fans = result_fans.replaceAll("`n", "");
        result_fans = result_fans.replaceAll("`t", "");
        result_fans = result_fans.replaceAll("`r", "");
        result_fans = result_fans.replaceAll("`", "");
        result_fans = "<html><body>" + result_fans + "</body></html>";
      } catch (Exception e) {
        PshLogger.logger.error(e.getMessage());
        return getFansUserByUid(uid, u + 1);
      }

      Document doc_fans = Jsoup.parse(result_fans);

      Elements elements_fans = doc_fans.getElementsByAttributeValue("class", "W_f14 S_func1");
      System.out.println(elements_fans.size());

      for (int x = 0; x < elements_fans.size(); x++) {
        System.out.println("遍历粉丝第" + (u + 1) + "页,第" + (x + 1) + "个用户");
        String uidString = elements_fans.get(x).attr("usercard");
        System.out.println("uridString------" + uidString);
        String uid_fans = uidString.substring(3);
        System.out.println(uid_fans);

        UserModel userModel = new UserModel();

        if (userModel.checkUserIsExsit(uid_fans)) {
          continue;
        }

        // 获取该用户详细信息
        UserBean user = new UserBean();
        GetPersonInfo personInfo = new GetPersonInfo();
        Elements element_followNum =
            elements_fans
                .get(x)
                .parent()
                .parent()
                .getElementsByAttributeValue("href", "/" + uid_fans + "/follow");
        Elements element_fansNum =
            elements_fans
                .get(x)
                .parent()
                .parent()
                .getElementsByAttributeValue("href", "/" + uid_fans + "/fans");
        String fans = "";
        String follow = "";
        for (int y = 0; y < element_followNum.size(); y++) {
          follow = element_followNum.get(y).text();
        }
        for (int y = 0; y < element_fansNum.size(); y++) {
          fans = element_fansNum.get(y).text();
        }
        // 将该用户信息加入数据库
        user = personInfo.getUserInfoFromWeibo(uid_fans, fans, follow);
        if (user == null) {
          continue;
        }
        System.out.println("用户查找完" + user.getUck());

        // 进行2级遍历
        uidList.add(uid_fans);
      }
    }

    //		queryNumber.executeFollowAndFans(uidList, queryTaskID,level);
    return uidList;
  }