/**
   * 验证用户
   *
   * @param request
   * @param response
   * @param model
   * @return
   */
  @RequestMapping("/checkLogin.do")
  public String checkLogin(
      HttpServletRequest request,
      HttpServletResponse response,
      @RequestParam("userName") String userName,
      @RequestParam("passWord") String passWord,
      Model model) {
    logger.debug("logon request: {username={}, password={}}", userName, passWord);
    boolean checkPassword = identityService.checkPassword(userName, passWord);

    HttpSession session = request.getSession(true);

    if (checkPassword) {
      User user = identityService.createUserQuery().userId(userName).singleResult();
      session.setAttribute("user", user);
      GroupQuery groupQuery = identityService.createGroupQuery();
      List<Group> groupList = groupQuery.groupMember(userName).list();

      session.setAttribute("groups", groupList);

      String[] groupNames = new String[groupList.size()];

      for (int i = 0; i < groupNames.length; i++) {
        groupNames[i] = groupList.get(i).getName();
      }

      session.setAttribute("groupNames", ArrayUtils.toString(groupNames));
      return "redirect:/simple/index.do";
    } else {
      return "redirect:/simple/login.do";
    }
  }
  /* ------------------------------------------------------------ */
  public void logout(Authentication.User user) {
    LOG.debug("logout {}", user);
    LoginService login_service = getLoginService();
    if (login_service != null) {
      login_service.logout(user.getUserIdentity());
    }

    IdentityService identity_service = getIdentityService();
    if (identity_service != null) {
      // TODO recover previous from threadlocal (or similar)
      Object previous = null;
      identity_service.disassociate(previous);
    }
  }
  @SuppressWarnings("unchecked")
  @Test
  public void givenInvalidIdentityTokenProvideEmpty() {
    when(identityLoader.find(BAD_IDENTITY_TOKEN)).thenThrow(IdentityNotFound.class);

    Optional<Identity> result = identityService.isIdentifiable(BAD_IDENTITY_TOKEN);

    assertFalse(result.isPresent());
  }
  @Test
  public void givenValidIdentityTokenProvideIdentity() {
    Identity identity = new Identity(UUID.randomUUID());
    when(identityLoader.find(IDENTITY_TOKEN)).thenReturn(Optional.of(identity));

    Optional<Identity> result = identityService.isIdentifiable(IDENTITY_TOKEN);

    assertTrue(result.isPresent());
    assertEquals(identity, result.get());
  }
 /**
  * Starts new {@link CandidateSession} for the current thread's {@link User} on the given {@link
  * Delivery}
  *
  * <p>NB: No checks are made on whether the {@link User} should be allowed to start a session on
  * this {@link Delivery}.
  */
 public CandidateSession launchCandidateSession(
     final Delivery delivery,
     final boolean authorMode,
     final String lisOutcomeServiceUrl,
     final String lisResultSourcedid)
     throws CandidateException {
   Assert.notNull(delivery, "delivery");
   final User candidate = identityService.assertCurrentThreadUser();
   return launchCandidateSession(
       candidate, delivery, authorMode, lisOutcomeServiceUrl, lisResultSourcedid);
 }
  /**
   * Put user into realm.
   *
   * @param userName The user to add
   * @param credential The users Credentials
   * @param roles The users roles
   * @return UserIdentity
   */
  public synchronized UserIdentity putUser(String userName, Credential credential, String[] roles) {
    Principal userPrincipal = new KnownUser(userName, credential);
    Subject subject = new Subject();
    subject.getPrincipals().add(userPrincipal);
    subject.getPrivateCredentials().add(credential);

    if (roles != null)
      for (String role : roles) subject.getPrincipals().add(new RolePrincipal(role));

    subject.setReadOnly();
    UserIdentity identity = _identityService.newUserIdentity(subject, userPrincipal, roles);
    _users.put(userName, identity);
    return identity;
  }
  /**
   * 开始流程
   *
   * @return
   */
  @RequestMapping(value = "/start.do")
  public String startProcessDefinition(
      HttpServletRequest request,
      @RequestParam("processDefId") String processDefId,
      @RequestParam("userId") String userId) {

    // 用来设置启动流程的人员ID,引擎会自动把用户ID保存到activiti:initiator中
    identityService.setAuthenticatedUserId(userId);

    Map map = new HashMap();
    map.put("owner", userId);
    runtimeService.startProcessInstanceById(processDefId, map);

    return "redirect:/simple/index.do";
  }
  /**
   * Put user into realm. Called by implementations to put the user data loaded from file/db etc
   * into the user structure.
   *
   * @param userName User name
   * @param info a UserIdentity instance, or a String password or Credential instance
   * @return User instance
   */
  protected synchronized UserIdentity putUser(String userName, Object info) {
    final UserIdentity identity;
    if (info instanceof UserIdentity) identity = (UserIdentity) info;
    else {
      Credential credential =
          (info instanceof Credential)
              ? (Credential) info
              : Credential.getCredential(info.toString());

      Principal userPrincipal = new KnownUser(userName, credential);
      Subject subject = new Subject();
      subject.getPrincipals().add(userPrincipal);
      subject.getPrivateCredentials().add(credential);
      subject.setReadOnly();
      identity = _identityService.newUserIdentity(subject, userPrincipal, IdentityService.NO_ROLES);
    }

    _users.put(userName, identity);
    return identity;
  }
  @Test
  public void givenNullIdentityTokenProvideEmpty() {
    Optional<Identity> result = identityService.isIdentifiable(null);

    assertFalse(result.isPresent());
  }
Exemplo n.º 10
0
 /**
  * @param taskId
  * @param processInstanceId
  * @param message
  */
 @Override
 public void saveComment(String taskId, String processInstanceId, String message) {
   identityService.setAuthenticatedUserId(UserUtils.getUserFromSession().getNatrualkey());
   taskService.addComment(taskId, processInstanceId, message);
 }
  /*
   * @see org.eclipse.jetty.server.Handler#handle(java.lang.String,
   *      javax.servlet.http.HttpServletRequest,
   *      javax.servlet.http.HttpServletResponse, int)
   */
  @Override
  public void handle(
      String pathInContext,
      Request baseRequest,
      HttpServletRequest request,
      HttpServletResponse response)
      throws IOException, ServletException {
    final Response base_response = baseRequest.getResponse();
    final Handler handler = getHandler();

    if (handler == null) return;

    final Authenticator authenticator = _authenticator;

    if (checkSecurity(baseRequest)) {
      // See Servlet Spec 3.1 sec 13.6.3
      if (authenticator != null) authenticator.prepareRequest(baseRequest);

      RoleInfo roleInfo = prepareConstraintInfo(pathInContext, baseRequest);

      // Check data constraints
      if (!checkUserDataPermissions(pathInContext, baseRequest, base_response, roleInfo)) {
        if (!baseRequest.isHandled()) {
          response.sendError(HttpServletResponse.SC_FORBIDDEN);
          baseRequest.setHandled(true);
        }
        return;
      }

      // is Auth mandatory?
      boolean isAuthMandatory = isAuthMandatory(baseRequest, base_response, roleInfo);

      if (isAuthMandatory && authenticator == null) {
        LOG.warn("No authenticator for: " + roleInfo);
        if (!baseRequest.isHandled()) {
          response.sendError(HttpServletResponse.SC_FORBIDDEN);
          baseRequest.setHandled(true);
        }
        return;
      }

      // check authentication
      Object previousIdentity = null;
      try {
        Authentication authentication = baseRequest.getAuthentication();
        if (authentication == null || authentication == Authentication.NOT_CHECKED)
          authentication =
              authenticator == null
                  ? Authentication.UNAUTHENTICATED
                  : authenticator.validateRequest(request, response, isAuthMandatory);

        if (authentication instanceof Authentication.Wrapped) {
          request = ((Authentication.Wrapped) authentication).getHttpServletRequest();
          response = ((Authentication.Wrapped) authentication).getHttpServletResponse();
        }

        if (authentication instanceof Authentication.ResponseSent) {
          baseRequest.setHandled(true);
        } else if (authentication instanceof Authentication.User) {
          Authentication.User userAuth = (Authentication.User) authentication;
          baseRequest.setAuthentication(authentication);
          if (_identityService != null)
            previousIdentity = _identityService.associate(userAuth.getUserIdentity());

          if (isAuthMandatory) {
            boolean authorized =
                checkWebResourcePermissions(
                    pathInContext,
                    baseRequest,
                    base_response,
                    roleInfo,
                    userAuth.getUserIdentity());
            if (!authorized) {
              response.sendError(HttpServletResponse.SC_FORBIDDEN, "!role");
              baseRequest.setHandled(true);
              return;
            }
          }

          handler.handle(pathInContext, baseRequest, request, response);
          if (authenticator != null)
            authenticator.secureResponse(request, response, isAuthMandatory, userAuth);
        } else if (authentication instanceof Authentication.Deferred) {
          DeferredAuthentication deferred = (DeferredAuthentication) authentication;
          baseRequest.setAuthentication(authentication);

          try {
            handler.handle(pathInContext, baseRequest, request, response);
          } finally {
            previousIdentity = deferred.getPreviousAssociation();
          }

          if (authenticator != null) {
            Authentication auth = baseRequest.getAuthentication();
            if (auth instanceof Authentication.User) {
              Authentication.User userAuth = (Authentication.User) auth;
              authenticator.secureResponse(request, response, isAuthMandatory, userAuth);
            } else authenticator.secureResponse(request, response, isAuthMandatory, null);
          }
        } else {
          baseRequest.setAuthentication(authentication);
          if (_identityService != null) previousIdentity = _identityService.associate(null);
          handler.handle(pathInContext, baseRequest, request, response);
          if (authenticator != null)
            authenticator.secureResponse(request, response, isAuthMandatory, null);
        }
      } catch (ServerAuthException e) {
        // jaspi 3.8.3 send HTTP 500 internal server error, with message
        // from AuthException
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      } finally {
        if (_identityService != null) _identityService.disassociate(previousIdentity);
      }
    } else handler.handle(pathInContext, baseRequest, request, response);
  }