@Observer(value = KiWiEvents.CONTENT_UPDATED)
 public void onContentUpdated(ContentItem item) {
   User currentUser = (User) Component.getInstance("currentUser");
   Events.instance()
       .raiseAsynchronousEvent(
           KiWiEvents.CONTENT_UPDATED + "AsyncIE", item, currentUser, Identity.instance());
 }
Пример #2
0
  public void init() {
    if (!isInitialized) {

      if (getFileId() == null)
        throw new InvalidWikiRequestException("Missing filedId request parameter");

      log.debug("initializing document history with file id: " + getFileId());

      if (currentFile == null) {
        log.debug("loading current file: " + getFileId());
        currentFile = wikiNodeDAO.findWikiDocument(getFileId());

        if (currentFile == null) {
          throw new org.jboss.seam.framework.EntityNotFoundException(
              getFileId(), WikiDocument.class);
        }

        if (!Identity.instance().hasPermission("Node", "read", currentFile)) {
          throw new AuthorizationException("You don't have permission for this operation");
        }
      }

      initializeHistoricalFileList();
    }

    isInitialized = true;
  }
Пример #3
0
  private void processBasicAuth(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    Identity identity = Identity.instance();

    if (identity == null) {
      throw new ServletException(
          "Identity not found - please ensure that the Identity component is created on startup.");
    }

    Credentials credentials = identity.getCredentials();

    boolean requireAuth = false;

    String header = request.getHeader("Authorization");
    if (header != null && header.startsWith("Basic ")) {
      String base64Token = header.substring(6);
      String token = new String(Base64.decode(base64Token));

      String username = "";
      String password = "";
      int delim = token.indexOf(":");

      if (delim != -1) {
        username = token.substring(0, delim);
        password = token.substring(delim + 1);
      }

      // Only reauthenticate if username doesn't match Identity.username and user isn't
      // authenticated
      if (!username.equals(credentials.getUsername()) || !identity.isLoggedIn()) {
        try {
          credentials.setPassword(password);
          authenticate(request, username);
        } catch (Exception ex) {
          log.warn("Error authenticating: " + ex.getMessage());
          requireAuth = true;
        }
      }
    }

    if (!identity.isLoggedIn() && !credentials.isSet()) {
      requireAuth = true;
    }

    try {
      if (!requireAuth) {
        chain.doFilter(request, response);
        return;
      }
    } catch (NotLoggedInException ex) {
      requireAuth = true;
    }

    if ((requireAuth && !identity.isLoggedIn())) {
      response.addHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not authorized");
    }
  }
Пример #4
0
 private void handleLoadRuleAssetException(RuleAsset asset) {
   if (asset.metaData.categories.length == 0) {
     Identity.instance().checkPermission(new CategoryPathType(null), RoleTypes.ANALYST_READ);
   } else {
     RuntimeException exception = null;
     boolean passed = false;
     for (String cat : asset.metaData.categories) {
       try {
         Identity.instance().checkPermission(new CategoryPathType(cat), RoleTypes.ANALYST_READ);
         passed = true;
       } catch (RuntimeException re) {
         exception = re;
       }
     }
     if (!passed) {
       throw exception;
     }
   }
 }
 @Create
 public void create() {
   String userName = READ_ONLY_USER;
   if (Contexts.isApplicationContextActive()) {
     userName = Identity.instance().getCredentials().getUsername();
   }
   if (userName == null) {
     userName = READ_ONLY_USER;
   }
   repository = new RulesRepository(repositoryConfiguration.newSession(userName));
 }
 @Observer(value = KiWiEvents.ACTIVITY_REMOVETAG)
 public void onRemoveTag(User taggingUser, Tag tag) {
   User currentUser = (User) Component.getInstance("currentUser");
   Events.instance()
       .raiseAsynchronousEvent(
           KiWiEvents.ACTIVITY_REMOVETAG + "AsyncIE",
           taggingUser,
           tag,
           currentUser,
           Identity.instance());
 }
Пример #7
0
 @SuppressWarnings("unchecked")
 public void loadMemberPictures() {
   memberImages =
       (List<MemberImage>)
           entityManager
               .createQuery(
                   "select i from MemberImage i where i.member.memberName = :name and not i = i.member.picture")
               .setParameter("name", memberName)
               .getResultList();
   Identity.instance().filterByPermission(memberImages, "view");
 }
Пример #8
0
  /**
   * This actually does the hard work of loading up an asset based on its format.
   *
   * <p>Role-based Authorization check: This method can be accessed if user has following
   * permissions: 1. The user has a ANALYST_READ role or higher (i.e., ANALYST) and this role has
   * permission to access the category which the asset belongs to. Or. 2. The user has a
   * package.readonly role or higher (i.e., package.admin, package.developer) and this role has
   * permission to access the package which the asset belongs to.
   */
  @WebRemote
  @Restrict("#{identity.loggedIn}")
  public RuleAsset loadRuleAsset(String uuid) throws SerializationException {

    long time = System.currentTimeMillis();

    AssetItem item = getRulesRepository().loadAssetByUUID(uuid);
    RuleAsset asset = new RuleAsset();

    asset.uuid = item.getUUID();
    asset.name = item.getName();
    asset.description = item.getDescription();
    asset.lastModified = item.getLastModified().getTime();
    asset.lastContributor = item.getLastContributor();
    asset.state = (item.getState() != null) ? item.getState().getName() : "";
    asset.dateCreated = item.getCreatedDate().getTime();
    asset.checkinComment = item.getCheckinComment();
    asset.versionNumber = item.getVersionNumber();

    // load standard meta data
    asset.metaData = repositoryAssetOperations.populateMetaData(item);

    // Verify if the user has permission to access the asset through package
    // based permission.
    // If failed, then verify if the user has permission to access the asset
    // through category
    // based permission
    if (Contexts.isSessionContextActive()) {

      try {
        Identity.instance()
            .checkPermission(
                new PackageNameType(asset.metaData.packageName), RoleTypes.PACKAGE_READONLY);
      } catch (RuntimeException e) {
        handleLoadRuleAssetException(asset);
      }
    }

    PackageItem pkgItem = handlePackageItem(item, asset);

    log.debug(
        "Package: "
            + pkgItem.getName()
            + ", asset: "
            + item.getName()
            + ". Load time taken for asset: "
            + (System.currentTimeMillis() - time));
    UserInbox.recordOpeningEvent(item);
    return asset;
  }
 @Override
 public void validerAuthorisation() {
   // On valide pour l'édition que l'utilisateur connecté est bien
   // propriétaire du bateau.
   if (getInstance().getUtilisateur() != null
       && utilisateurCourant != null
       && !getInstance()
           .getUtilisateur()
           .getPseudonyme()
           .equals(utilisateurCourant.getPseudonyme())
       && !Identity.instance().hasRole(Role.ADMIN)) {
     ResourceBundle messages = SeamResourceBundle.getBundle();
     throw new AuthorizationException(messages.getString("annonce.propriorequis"));
   }
 }
Пример #10
0
  @WebRemote
  @Restrict("#{identity.loggedIn}")
  public void promoteAssetToGlobalArea(String uuid) {
    if (Contexts.isSessionContextActive()) {
      Identity.instance()
          .checkPermission(
              new PackageNameType(RulesRepository.RULE_GLOBAL_AREA), RoleTypes.PACKAGE_DEVELOPER);
    }

    log.info(
        "USER:"******" CHANGING PACKAGE OF asset: ["
            + uuid
            + "] to [ globalArea ]");
    getRulesRepository()
        .moveRuleItemPackage(RulesRepository.RULE_GLOBAL_AREA, uuid, "promote asset to globalArea");
  }
  @WebRemote
  @Restrict("#{identity.loggedIn}")
  public AnalysisReport analysePackage(String packageUUID) throws SerializationException {
    if (Contexts.isSessionContextActive()) {
      Identity.instance()
          .checkPermission(new PackageUUIDType(packageUUID), RoleType.PACKAGE_DEVELOPER.getName());
    }

    PackageItem packageItem = getAssetService().getRulesRepository().loadPackageByUUID(packageUUID);

    VerifierRunner runner = new VerifierRunner(defaultVerifier);

    AnalysisReport report =
        runner.verify(
            packageItem,
            new ScopesAgendaFilter(true, ScopesAgendaFilter.VERIFYING_SCOPE_KNOWLEDGE_PACKAGE));

    defaultVerifier.flushKnowledgeSession();

    return report;
  }
  @Test
  public void testLoginComponent() throws Exception {
    Identity identity = Identity.instance();

    assertFalse(identity.isLoggedIn());
    identity.setUsername("gavin");
    identity.setPassword("foobar");
    identity.login();

    User user = (User) Component.getInstance("user");
    assertEquals("Gavin King", user.getName());
    assertEquals("gavin", user.getUsername());
    assertEquals("foobar", user.getPassword());
    assertTrue(identity.isLoggedIn());
    identity.logout();
    assertFalse(identity.isLoggedIn());
    identity.setUsername("gavin");
    identity.setPassword("tiger");
    identity.login();
    assertFalse(identity.isLoggedIn());
  }
  private AnalysisReport performAssetVerification(
      RuleAsset asset, boolean useVerifierDefaultConfig, Set<String> activeWorkingSets)
      throws SerializationException {
    long startTime = System.currentTimeMillis();

    if (Contexts.isSessionContextActive()) {
      Identity.instance()
          .checkPermission(
              new PackageNameType(asset.getMetaData().getPackageName()),
              RoleType.PACKAGE_DEVELOPER.getName());
    }

    PackageItem packageItem =
        getAssetService().getRulesRepository().loadPackage(asset.getMetaData().getPackageName());

    List<String> constraintRules = applyWorkingSets(activeWorkingSets);

    Verifier verifierToBeUsed = null;
    if (useVerifierDefaultConfig) {
      verifierToBeUsed = defaultVerifier;
    } else {
      verifierToBeUsed = getWorkingSetVerifier(constraintRules);
    }

    log.debug("constraints rules: " + constraintRules);

    try {
      VerifierRunner runner = new VerifierRunner(verifierToBeUsed);
      AnalysisReport report = runner.verify(packageItem, chooseScopesAgendaFilterFor(asset));

      verifierToBeUsed.flushKnowledgeSession();

      log.debug("Asset verification took: " + (System.currentTimeMillis() - startTime));

      return report;

    } catch (Throwable t) {
      throw new SerializationException(t.getMessage());
    }
  }
  @Test
  public void testLogin() throws Exception {
    Identity identity = Identity.instance();

    assertFalse(identity.isLoggedIn());

    identity.setUsername("gavin");
    identity.setPassword("foobar");
    identity.login();

    User user = (User) Component.getInstance("user");
    assertEquals("Gavin King", user.getName());
    assertEquals("gavin", user.getUsername());
    assertEquals("foobar", user.getPassword());
    assertFalse(Manager.instance().isLongRunningConversation());
    assertTrue(identity.isLoggedIn());

    identity.logout();
    assertTrue(Session.instance().isInvalid());

    assertFalse(identity.isLoggedIn());
  }
Пример #15
0
  private void doWork(HttpServletRequest request, HttpServletResponse response) throws IOException {

    if (!Identity.instance().isLoggedIn()) {
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
      return;
    }

    Enumeration<?> e = request.getParameterNames();
    while (e.hasMoreElements()) {
      log.info("parameter: #0", e.nextElement());
    }

    EntityManager em = (EntityManager) Component.getInstance("entityManager");

    if (em != null) {
      Long tfId = saveParseLong(request.getParameter(PARAM_TFID));
      log.info("trying to serve up serialized version of trialform with id #0", tfId);
      try {
        if (tfId != null) {

          Transaction.instance().begin();
          TrialForm tf = em.find(TrialForm.class, tfId);

          if (tf == null) {
            log.warn("requested trialform was not found (id: #0)", tfId);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            Transaction.instance().commit();
            return;
          }

          Identity.instance().checkPermission(tf.getTrial(), SpicsPermissions.EXPORT_TRIAL_FORMS);

          String filename =
              ((tf.getName() == null || "".equals(tf.getName()))
                  ? "formular"
                  : tf.getName() + ".zip");

          response.setContentType("application/zip");
          response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
          /*
           * the following three header elements are needed in order
           * for the downloads to work properly under IE (at least
           * version 7)
           */
          response.addHeader("Pragma", "public");
          response.addDateHeader("Expires", 0);
          response.addHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");

          response.setStatus(HttpServletResponse.SC_OK);

          ServletOutputStream os = response.getOutputStream();
          IXMLImportExport xmlExport = new XMLImportExport();
          xmlExport.writeTrialFormToZip(tf, os);

          Transaction.instance().commit();
          os.flush();

        } else {
          // insufficient parameters specified
          log.warn("insufficient parameters specified!");
          response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
      } catch (AuthorizationException e2) {
        log.warn("AuthorizationException #0", e2.getMessage());
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
      } catch (Exception e1) {
        e1.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      }
    } else {
      log.error("injected entitymanager was null, could not proceed");
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }
Пример #16
0
 private void authenticate(HttpServletRequest request, final String username)
     throws ServletException, IOException, LoginException {
   Identity identity = Identity.instance();
   identity.getCredentials().setUsername(username);
   identity.authenticate();
 }
Пример #17
0
  private void processDigestAuth(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    Identity identity = Identity.instance();

    if (identity == null) {
      throw new ServletException(
          "Identity not found - please ensure that the Identity component is created on startup.");
    }

    Credentials credentials = identity.getCredentials();

    boolean requireAuth = false;
    boolean nonceExpired = false;

    String header = request.getHeader("Authorization");
    if (header != null && header.startsWith("Digest ")) {
      String section212response = header.substring(7);

      String[] headerEntries = section212response.split(",");
      Map<String, String> headerMap = new HashMap<String, String>();
      for (String entry : headerEntries) {
        String[] vals = split(entry, "=");
        headerMap.put(vals[0].trim(), vals[1].replace("\"", "").trim());
      }

      DigestRequest digestRequest = new DigestRequest();
      digestRequest.setHttpMethod(request.getMethod());
      digestRequest.setSystemRealm(realm);
      digestRequest.setRealm(headerMap.get("realm"));
      digestRequest.setKey(key);
      digestRequest.setNonce(headerMap.get("nonce"));
      digestRequest.setUri(headerMap.get("uri"));
      digestRequest.setClientDigest(headerMap.get("response"));
      digestRequest.setQop(headerMap.get("qop"));
      digestRequest.setNonceCount(headerMap.get("nc"));
      digestRequest.setClientNonce(headerMap.get("cnonce"));

      try {
        digestRequest.validate();
        request.getSession().setAttribute(DigestRequest.DIGEST_REQUEST, digestRequest);
        authenticate(request, headerMap.get("username"));
      } catch (DigestValidationException ex) {
        log.warn(
            String.format(
                "Digest validation failed, header [%s]: %s", section212response, ex.getMessage()));
        requireAuth = true;

        if (ex.isNonceExpired()) nonceExpired = true;
      } catch (Exception ex) {
        log.warn("Error authenticating: " + ex.getMessage());
        requireAuth = true;
      }
    }

    if (!identity.isLoggedIn() && !credentials.isSet()) {
      requireAuth = true;
    }

    try {
      if (!requireAuth) {
        chain.doFilter(request, response);
        return;
      }
    } catch (NotLoggedInException ex) {
      requireAuth = true;
    }

    if ((requireAuth && !identity.isLoggedIn())) {
      long expiryTime = System.currentTimeMillis() + (nonceValiditySeconds * 1000);

      String signatureValue = DigestUtils.md5Hex(expiryTime + ":" + key);
      String nonceValue = expiryTime + ":" + signatureValue;
      String nonceValueBase64 = Base64.encodeBytes(nonceValue.getBytes());

      // qop is quality of protection, as defined by RFC 2617.
      // we do not use opaque due to IE violation of RFC 2617 in not
      // representing opaque on subsequent requests in same session.
      String authenticateHeader =
          "Digest realm=\"" + realm + "\", " + "qop=\"auth\", nonce=\"" + nonceValueBase64 + "\"";

      if (nonceExpired) authenticateHeader = authenticateHeader + ", stale=\"true\"";

      response.addHeader("WWW-Authenticate", authenticateHeader);
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
  }
Пример #18
0
  /**
   * Role-based Authorization check: This method can be accessed if user has following permissions:
   * 1. The user has a Analyst role and this role has permission to access the category which the
   * asset belongs to. Or. 2. The user has a package.developer role or higher (i.e., package.admin)
   * and this role has permission to access the package which the asset belongs to.
   */
  @WebRemote
  @Restrict("#{identity.loggedIn}")
  public void changeState(String uuid, String newState) {
    AssetItem asset = getRulesRepository().loadAssetByUUID(uuid);

    // Verify if the user has permission to access the asset through
    // package based permission.
    // If failed, then verify if the user has permission to access the
    // asset through category
    // based permission
    if (Contexts.isSessionContextActive()) {
      boolean passed = false;

      try {
        Identity.instance()
            .checkPermission(
                new PackageUUIDType(asset.getPackage().getUUID()), RoleTypes.PACKAGE_DEVELOPER);
      } catch (RuntimeException e) {
        if (asset.getCategories().size() == 0) {
          Identity.instance().checkPermission(new CategoryPathType(null), RoleTypes.ANALYST);
        } else {
          RuntimeException exception = null;

          for (CategoryItem cat : asset.getCategories()) {
            try {
              Identity.instance()
                  .checkPermission(new CategoryPathType(cat.getName()), RoleTypes.ANALYST);
              passed = true;
            } catch (RuntimeException re) {
              exception = re;
            }
          }
          if (!passed) {
            throw exception;
          }
        }
      }
    }

    log.info(
        "USER:"******" CHANGING ASSET STATUS. Asset name, uuid: "
            + "["
            + asset.getName()
            + ", "
            + asset.getUUID()
            + "]"
            + " to ["
            + newState
            + "]");
    String oldState = asset.getStateDescription();
    asset.updateState(newState);

    push("statusChange", oldState);
    push("statusChange", newState);

    addToDiscussionForAsset(asset.getUUID(), oldState + " -> " + newState);

    getRulesRepository().save();
  }