Example #1
0
  @Override
  public void serialize(IResult value, JsonGenerator jgen, SerializerProvider provider)
      throws IOException {
    // output the custom Json
    jgen.writeStartObject();

    // jgen.writeFieldName("rcode");
    jgen.writeFieldName("resultCode");
    jgen.writeNumber(value.getErrcode());

    //		jgen.writeFieldName("errmsg");
    //		jgen.writeString(value.toString());

    String msg;
    if (value.getErrmsg() != null && value.getErrmsg().equals("") == false) {
      msg = value.getErrmsg();
    } else {
      if (value.getErrcode() == 0) {
        msg = succMessages.getMessage(value.toString(), value.getArgs(), value.toString());
      } else {
        msg = failMessages.getMessage(value.toString(), value.getArgs(), value.toString());
      }
    }
    if (msg != null && msg.equals("") == false) {
      jgen.writeFieldName("resultMsg");
      jgen.writeString(msg);
    }

    // end tag
    jgen.writeEndObject();
  }
  /**
   * This is the main method of this class, calling authentication, authorization and user details
   * mapping.
   *
   * @param authentication object to populate
   * @return Populated authentication object
   * @throws AuthenticationException
   */
  public Authentication authenticate(final Authentication authentication)
      throws AuthenticationException {
    Assert.isInstanceOf(
        UsernamePasswordAuthenticationToken.class,
        authentication,
        messages.getMessage(
            "AbstractUserDetailsAuthenticationProvider.onlySupports",
            "Only UsernamePasswordAuthenticationToken is supported"));

    logger.finest("CustomLdapAuthenticationProvider: authenticate");

    final UsernamePasswordAuthenticationToken userToken =
        (UsernamePasswordAuthenticationToken) authentication;

    String username = userToken.getName();
    String password = (String) authentication.getCredentials();

    logger.fine("Processing authentication request for user: "******"LdapAuthenticationProvider.emptyUsername", "Empty Username"));
    }

    Assert.notNull(password, "Null password was supplied in authentication token");

    try {
      DirContextOperations userData = getAuthenticator().authenticate(authentication);

      Collection<GrantedAuthority> extraAuthorities =
          loadUserAuthorities(userData, username, password);

      Collection<String> userAuthGroups = loadUserAuthGroups(userData, username, password);

      ExtendedLdapUserDetailsImpl extendedUserDetails =
          userDetailsContextMapper.mapUserFromContext(
              userData, username, extraAuthorities, userAuthGroups);

      return createSuccessfulAuthentication(userToken, extendedUserDetails);

    } catch (PasswordPolicyException ppe) {
      // The only reason a ppolicy exception can occur during a bind is that the account is locked.
      throw new LockedException(
          messages.getMessage(ppe.getStatus().getErrorCode(), ppe.getStatus().getDefaultMessage()));
    } catch (UsernameNotFoundException notFound) {
      if (hideUserNotFoundExceptions) {
        throw new BadCredentialsException(
            messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials"));
      } else {
        throw notFound;
      }
    } catch (NamingException ldapAccessFailure) {
      throw new AuthenticationServiceException(ldapAccessFailure.getMessage(), ldapAccessFailure);
    }
  }
  // SEC-3013
  @Test
  public void germanSystemLocaleWithEnglishLocaleContextHolder() {
    Locale beforeSystem = Locale.getDefault();
    Locale.setDefault(Locale.GERMAN);

    Locale beforeHolder = LocaleContextHolder.getLocale();
    LocaleContextHolder.setLocale(Locale.US);

    MessageSourceAccessor msgs = SpringSecurityMessageSource.getAccessor();
    assertThat("Access is denied")
        .isEqualTo(msgs.getMessage("AbstractAccessDecisionManager.accessDenied", "Ooops"));

    // Revert to original Locale
    Locale.setDefault(beforeSystem);
    LocaleContextHolder.setLocale(beforeHolder);
  }
Example #4
0
  public String save() {
    try {
      // before check
      roleChecker.check(model);

      // after invoke
      Role dest = null;

      if (id > 0) {
        dest = roleManager.get(id);
        beanMapper.copy(model, dest);
      } else {
        dest = model;
      }

      if (id == 0) {
        dest.setGlobalId(scopeConnector.findGlobalId(ScopeHolder.getGlobalCode()));
        dest.setLocalId(
            scopeConnector.findLocalId(ScopeHolder.getGlobalCode(), ScopeHolder.getLocalCode()));
      }

      dest.setName(roleDefManager.get(roleDefId).getName());
      dest.setRoleDef(roleDefManager.get(roleDefId));

      roleManager.save(dest);

      addActionMessage(messages.getMessage("core.success.save", "保存成功"));
    } catch (CheckRoleException ex) {
      addActionMessage(ex.getMessage());

      return INPUT;
    }

    return RELOAD;
  }
Example #5
0
  public String removeAll() {
    List<ScopeGlobal> scopeGlobals = scopeGlobalManager.findByIds(selectedItem);

    scopeGlobalManager.removeAll(scopeGlobals);
    addActionMessage(messages.getMessage("core.success.delete", "删除成功"));

    return RELOAD;
  }
Example #6
0
  public String removeAll() {
    List<DocInfo> docInfos = docInfoManager.findByIds(selectedItem);

    docInfoManager.removeAll(docInfos);
    addActionMessage(messages.getMessage("core.success.delete", "删除成功"));

    return RELOAD;
  }
Example #7
0
  public String removeAll() {
    List<AclSid> aclSids = aclSidManager.findByIds(selectedItem);

    aclSidManager.removeAll(aclSids);
    addActionMessage(messages.getMessage("core.success.delete", "删除成功"));

    return RELOAD;
  }
Example #8
0
  @CacheEvict(value = "users", allEntries = true)
  public List<UserInvitation> inviteUsers(
      UserInvitationCreateRequest form, BindingResult result, AuthorizedUser authorizedUser)
      throws MessagingException {
    String[] recipients = StringUtils.commaDelimitedListToStringArray(form.getInvitees());

    LocalDateTime now = LocalDateTime.now();

    List<UserInvitation> invitations = new ArrayList<>();
    for (String recipient : recipients) {
      UserInvitation invitation = new UserInvitation();
      invitation.setEmail(recipient);
      invitation.setMessage(form.getMessage());
      invitation.setExpiredAt(now.plusHours(72));
      invitation.setCreatedAt(now);
      invitation.setCreatedBy(authorizedUser.toString());
      invitation.setUpdatedAt(now);
      invitation.setUpdatedBy(authorizedUser.toString());
      invitation = userInvitationRepository.saveAndFlush(invitation);
      invitations.add(invitation);
    }

    Blog blog = blogService.readBlogById(Blog.DEFAULT_ID);
    for (UserInvitation invitation : invitations) {
      String websiteTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());
      String signupLink =
          ServletUriComponentsBuilder.fromCurrentContextPath()
              .path("/_admin/signup")
              .queryParam("token", invitation.getToken())
              .buildAndExpand()
              .toString();

      final Context ctx = new Context(LocaleContextHolder.getLocale());
      ctx.setVariable("websiteTitle", websiteTitle);
      ctx.setVariable("authorizedUser", authorizedUser);
      ctx.setVariable("signupLink", signupLink);
      ctx.setVariable("invitation", invitation);

      final MimeMessage mimeMessage = mailSender.createMimeMessage();
      final MimeMessageHelper message =
          new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
      message.setSubject(
          MessageFormat.format(
              messageSourceAccessor.getMessage(
                  "InvitationMessageTitle", LocaleContextHolder.getLocale()),
              authorizedUser.toString(),
              websiteTitle));
      message.setFrom(authorizedUser.getEmail());
      message.setTo(invitation.getEmail());

      final String htmlContent = templateEngine.process("user-invite", ctx);
      message.setText(htmlContent, true); // true = isHtml

      mailSender.send(mimeMessage);
    }

    return invitations;
  }
Example #9
0
  public PasswordResetToken createPasswordResetToken(PasswordResetTokenCreateRequest request) {
    User user = userRepository.findByEmail(request.getEmail());
    if (user == null) {
      throw new EmailNotFoundException();
    }

    LocalDateTime now = LocalDateTime.now();
    PasswordResetToken passwordResetToken = new PasswordResetToken();
    passwordResetToken.setUser(user);
    passwordResetToken.setEmail(user.getEmail());
    passwordResetToken.setExpiredAt(now.plusHours(24));
    passwordResetToken.setCreatedAt(now);
    passwordResetToken.setCreatedBy(user.toString());
    passwordResetToken.setUpdatedAt(now);
    passwordResetToken.setUpdatedBy(user.toString());
    passwordResetToken = passwordResetTokenRepository.saveAndFlush(passwordResetToken);

    try {
      Blog blog = blogService.readBlogById(Blog.DEFAULT_ID);
      String blogTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());

      ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
      if (blog.isMultiLanguage()) {
        builder.path("/{language}");
      }
      builder.path("/password-reset");
      builder.path("/{token}");

      Map<String, Object> urlVariables = new LinkedHashMap<>();
      urlVariables.put("language", request.getLanguage());
      urlVariables.put("token", passwordResetToken.getToken());
      String resetLink = builder.buildAndExpand(urlVariables).toString();

      Context ctx = new Context(LocaleContextHolder.getLocale());
      ctx.setVariable("passwordResetToken", passwordResetToken);
      ctx.setVariable("resetLink", resetLink);

      MimeMessage mimeMessage = mailSender.createMimeMessage();
      MimeMessageHelper message =
          new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
      message.setSubject(
          MessageFormat.format(
              messageSourceAccessor.getMessage(
                  "PasswordResetSubject", LocaleContextHolder.getLocale()),
              blogTitle));
      message.setFrom(mailProperties.getProperties().get("mail.from"));
      message.setTo(passwordResetToken.getEmail());

      String htmlContent = templateEngine.process("password-reset", ctx);
      message.setText(htmlContent, true); // true = isHtml

      mailSender.send(mimeMessage);
    } catch (MessagingException e) {
      throw new ServiceException(e);
    }

    return passwordResetToken;
  }
  /**
   * The onSubmit function receives the form/command object that was modified by the input form and
   * saves it to the db
   *
   * @see
   *     org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse, java.lang.Object,
   *     org.springframework.validation.BindException)
   */
  protected ModelAndView onSubmit(
      HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors)
      throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();
    if (Context.isAuthenticated()) {
      String[] reportObjectList = request.getParameterValues("reportObjectId");

      String success = "";
      String error = "";
      int numDeleted = 0;

      MessageSourceAccessor msa = getMessageSourceAccessor();
      String deleted = msa.getMessage("general.deleted");
      String notDeleted = msa.getMessage("general.cannot.delete");
      String textReport = msa.getMessage("reportingcompatibility.ReportObject.reportObject");
      String noneDeleted = msa.getMessage("reportingcompatibility.ReportObject.nonedeleted");
      if (reportObjectList != null) {
        for (String p : reportObjectList) {
          try {
            Context.getService(ReportingCompatibilityService.class)
                .deleteReportObject(Integer.valueOf(p));
            if (!success.equals("")) success += "<br/>";
            success += textReport + " " + p + " " + deleted;
            numDeleted++;
          } catch (APIException e) {
            log.warn("Error deleting report object", e);
            if (!error.equals("")) error += "<br/>";
            error += textReport + " " + p + " " + notDeleted;
          }
        }

        if (numDeleted > 3) success = numDeleted + " " + deleted;
      } else {
        success += noneDeleted;
      }
      view = getSuccessView();
      if (!success.equals("")) httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success);
      if (!error.equals("")) httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error);
    }

    return new ModelAndView(new RedirectView(view));
  }
  @Test
  public void testReplacableLookup() {
    // Change Locale to English
    Locale before = LocaleContextHolder.getLocale();
    LocaleContextHolder.setLocale(Locale.FRENCH);

    // Cause a message to be generated
    MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
    assertThat("Le jeton nonce est compromis FOOBAR")
        .isEqualTo(
            messages.getMessage(
                "DigestAuthenticationFilter.nonceCompromised",
                new Object[] {"FOOBAR"},
                "ERROR - FAILED TO LOOKUP"));

    // Revert to original Locale
    LocaleContextHolder.setLocale(before);
  }
Example #12
0
 private void accountincative(Boolean active, String username, Integer userid) {
   if (!active) {
     // log user for inactive account
     saveUserAccessLog(
         "139002",
         messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled"),
         username,
         userid);
   }
 }
 @Override
 public User findUserById(Long userId) {
   User user = userDAO.findByPK(userId);
   if (user == null) {
     throw new ValidationException(
         CustomError.ErrorCode.USER_NOT_FOUND.getErrorCode(),
         messageSourceAccessor.getMessage("error.user.not.found"));
   }
   return user;
 }
Example #14
0
  @CacheEvict(value = "users", allEntries = true)
  public User updatePassword(PasswordUpdateRequest request, PasswordResetToken passwordResetToken) {
    User user = userRepository.findByIdForUpdate(request.getUserId());
    if (user == null) {
      throw new IllegalArgumentException("The user does not exist");
    }
    PasswordEncoder passwordEncoder = new StandardPasswordEncoder();
    user.setLoginPassword(passwordEncoder.encode(request.getPassword()));
    user.setUpdatedAt(LocalDateTime.now());
    user.setUpdatedBy(passwordResetToken.getUser().toString());
    user = userRepository.saveAndFlush(user);

    passwordResetTokenRepository.delete(passwordResetToken);

    try {
      Blog blog = blogService.readBlogById(Blog.DEFAULT_ID);
      String blogTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());

      ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
      if (blog.isMultiLanguage()) {
        builder.path("/{language}");
      }
      builder.path("/login");

      Map<String, Object> urlVariables = new LinkedHashMap<>();
      urlVariables.put("language", request.getLanguage());
      urlVariables.put("token", passwordResetToken.getToken());
      String loginLink = builder.buildAndExpand(urlVariables).toString();

      Context ctx = new Context(LocaleContextHolder.getLocale());
      ctx.setVariable("passwordResetToken", passwordResetToken);
      ctx.setVariable("resetLink", loginLink);

      MimeMessage mimeMessage = mailSender.createMimeMessage();
      MimeMessageHelper message =
          new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
      message.setSubject(
          MessageFormat.format(
              messageSourceAccessor.getMessage(
                  "PasswordChangedSubject", LocaleContextHolder.getLocale()),
              blogTitle));
      message.setFrom(mailProperties.getProperties().get("mail.from"));
      message.setTo(passwordResetToken.getEmail());

      String htmlContent = templateEngine.process("password-changed", ctx);
      message.setText(htmlContent, true); // true = isHtml

      mailSender.send(mimeMessage);
    } catch (MessagingException e) {
      throw new ServiceException(e);
    }

    return user;
  }
  /**
   * Allows subclasses to customise behaviour when too many sessions are detected.
   *
   * @param request
   * @param sessions either <code>null</code> or all unexpired sessions associated with the
   *     principal
   * @param allowableSessions the number of concurrent sessions the user is allowed to have
   * @param registry an instance of the <code>SessionRegistry</code> for subclass use
   */
  protected void allowableSessionsExceeded(
      HttpServletRequest request,
      List<SessionInformation> sessions,
      int allowableSessions,
      SessionRegistry registry)
      throws SessionAuthenticationException {
    String logoutLeastRecentlyUsed = request.getParameter(LOGOUT_LEAST_RECENTLY_USED);

    if (logoutLeastRecentlyUsed == null) {
      throw new SessionAuthenticationConfirmationException(
          messages.getMessage(
              "ConcurrentSessionControlAuthenticationStrategy.exceededAllowed",
              new Object[] {Integer.valueOf(allowableSessions)},
              "Maximum sessions of {0} for this principal exceeded"));
    } else {
      exceptionIfMaximumExceeded = (Boolean.parseBoolean(logoutLeastRecentlyUsed)) ? false : true;
    }

    // ----- original code
    if (exceptionIfMaximumExceeded || (sessions == null)) {
      throw new SessionAuthenticationException(
          messages.getMessage(
              "ConcurrentSessionControlAuthenticationStrategy.exceededAllowed",
              new Object[] {Integer.valueOf(allowableSessions)},
              "Maximum sessions of {0} for this principal exceeded"));
    }

    // Determine least recently used session, and mark it for invalidation
    SessionInformation leastRecentlyUsed = null;

    for (SessionInformation session : sessions) {
      if ((leastRecentlyUsed == null)
          || session.getLastRequest().before(leastRecentlyUsed.getLastRequest())) {
        leastRecentlyUsed = session;
      }
    }

    leastRecentlyUsed.expireNow();
  }
  /**
   * The onSubmit function receives the form/command object that was modified by the input form and
   * saves it to the db
   *
   * @see
   *     org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse, java.lang.Object,
   *     org.springframework.validation.BindException)
   */
  protected ModelAndView onSubmit(
      HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors)
      throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();
    if (Context.isAuthenticated()) {
      String success = "";
      String error = "";

      MessageSourceAccessor msa = getMessageSourceAccessor();

      String[] conceptClassList = request.getParameterValues("conceptClassId");
      if (conceptClassList != null) {
        ConceptService cs = Context.getConceptService();

        String deleted = msa.getMessage("general.deleted");
        String notDeleted = msa.getMessage("ConceptClass.cannot.delete");
        for (String cc : conceptClassList) {
          try {
            cs.purgeConceptClass(cs.getConceptClass(Integer.valueOf(cc)));
            if (!success.equals("")) success += "<br/>";
            success += cc + " " + deleted;
          } catch (DataIntegrityViolationException e) {
            error = handleConceptClassIntegrityException(e, error, notDeleted);
          } catch (APIException e) {
            error = handleConceptClassIntegrityException(e, error, notDeleted);
          }
        }
      } else error = msa.getMessage("ConceptClass.select");

      view = getSuccessView();
      if (!success.equals("")) httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success);
      if (!error.equals("")) httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error);
    }

    return new ModelAndView(new RedirectView(view));
  }
  private String resolveMessage(ResourceDescription description) {

    if (!description.isDefault()) {
      return description.getMessage();
    }

    try {
      return messageSource.getMessage(description);
    } catch (NoSuchMessageException o_O) {
      return configuration.metadataConfiguration().omitUnresolvableDescriptionKeys()
          ? null
          : description.getMessage();
    }
  }
Example #18
0
  @SuppressWarnings("deprecation")
  @Override
  public boolean validateUser(
      String userId, String password, String encPass, Object encoder, Object salt) {
    if (!((PasswordEncoder) encoder).isPasswordValid(encPass, password, salt)) {
      LOG.debug("Authentication failed: password does not match stored value");

      throw new BadCredentialsException(
          messages.getMessage(
              "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"),
          userId);
    }
    return true;
  }
Example #19
0
  public String removeAll() {
    try {
      List<Role> roles = roleManager.findByIds(selectedItem);

      for (Role role : roles) {
        roleChecker.check(role);
      }

      roleManager.removeAll(roles);
      addActionMessage(messages.getMessage("core.success.delete", "删除成功"));
    } catch (CheckRoleException ex) {
      addActionMessage(ex.getMessage());
    }

    return RELOAD;
  }
Example #20
0
  public String save() {
    ScopeGlobal dest = null;

    if (id > 0) {
      dest = scopeGlobalManager.get(id);
      beanMapper.copy(model, dest);
    } else {
      dest = model;
    }

    scopeGlobalManager.save(dest);

    addActionMessage(messages.getMessage("core.success.save", "保存成功"));

    return RELOAD;
  }
Example #21
0
  public String getMessage(final String[] messageCodes, final Object[] args) {
    MessageSourceResolvable resolvable =
        new MessageSourceResolvable() {
          public String[] getCodes() {
            return messageCodes;
          }

          public Object[] getArguments() {
            return args;
          }

          public String getDefaultMessage() {
            return messageCodes[0];
          }
        };
    return messageSourceAccessor.getMessage(resolvable, Locale.getDefault());
  }
Example #22
0
  public String save() throws Exception {
    DocInfo dest = null;

    if (id > 0) {
      dest = docInfoManager.get(id);
      beanMapper.copy(model, dest);
    } else {
      dest = model;

      String userId =
          userConnector
              .findByUsername(
                  SpringSecurityUtils.getCurrentUsername(), ScopeHolder.getUserRepoRef())
              .getId();
      dest.setUserId(Long.parseLong(userId));
    }

    new File("target/uploaded").mkdirs();

    File targetFile = new File("target/uploaded", attachment.getName());
    InputStream is = null;
    OutputStream os = null;

    try {
      is = new FileInputStream(attachment);
      os = new FileOutputStream(targetFile);
      IoUtils.copyStream(is, os);
    } finally {
      if (is != null) {
        is.close();
      }

      if (os != null) {
        os.close();
      }
    }

    dest.setPath(targetFile.getName());
    docInfoManager.save(dest);

    addActionMessage(messages.getMessage("core.success.save", "保存成功"));

    return RELOAD;
  }
  @RequestMapping(method = RequestMethod.GET)
  public ModelAndView handleRequest(HttpServletRequest request) throws Exception {
    log.debug("entering 'handleRequest' method...");

    String username = request.getParameter("username");
    MessageSourceAccessor text = new MessageSourceAccessor(messageSource, request.getLocale());

    // ensure that the username has been sent
    if (username == null) {
      log.warn("Username not specified, notifying user that it's a required field.");
      request.setAttribute(
          "error", text.getMessage("errors.required", text.getMessage("user.username")));
      return new ModelAndView("login");
    }

    log.debug("Processing Password Hint...");

    // look up the user's information
    try {
      User user = userManager.getUserByUsername(username);

      StringBuffer msg = new StringBuffer();
      msg.append("Your password hint is: ").append(user.getPasswordHint());
      msg.append("\n\nLogin at: ").append(RequestUtil.getAppURL(request));

      message.setTo(user.getEmail());
      String subject =
          '[' + text.getMessage("webapp.name") + "] " + text.getMessage("user.passwordHint");
      message.setSubject(subject);
      message.setText(msg.toString());
      mailEngine.send(message);

      saveMessage(
          request,
          text.getMessage("login.passwordHint.sent", new Object[] {username, user.getEmail()}));
    } catch (UsernameNotFoundException e) {
      log.warn(e.getMessage());
      saveError(request, text.getMessage("login.passwordHint.error", new Object[] {username}));
    } catch (MailException me) {
      log.warn(me.getMessage());
      saveError(request, me.getCause().getLocalizedMessage());
    }

    return new ModelAndView(new RedirectView(request.getContextPath()));
  }
Example #24
0
  public String save() {
    AclSid dest = null;

    if (id > 0) {
      dest = aclSidManager.get(id);
      beanMapper.copy(model, dest);
    } else {
      dest = model;
    }

    if (id == 0) {
      dest.setScopeId(ScopeHolder.getScopeId());
    }

    aclSidManager.save(dest);

    addActionMessage(messages.getMessage("core.success.save", "保存成功"));

    return RELOAD;
  }
Example #25
0
 private Boolean isAccountExpired(
     Timestamp accessStartDate, Timestamp accessExpiryDate, String username, Integer userid) {
   Timestamp currentDttm = new Timestamp(System.currentTimeMillis());
   if (accessExpiryDate != null && accessStartDate != null) {
     // Checking if Current Date is between Access StartDate and ExpiryDate
     if (currentDttm.after(accessStartDate) && currentDttm.before(accessExpiryDate)) {
       return false;
     }
   }
   // unlimited access
   else if (currentDttm.after(accessStartDate) && accessExpiryDate == null) {
     return false;
   }
   // log user for account expire
   saveUserAccessLog(
       "139004",
       messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired"),
       username,
       userid);
   return true;
 }
Example #26
0
 private Boolean isAccountLocked(
     Boolean accountLocked, Timestamp accountLockExpiryDttm, String username, Integer userid) {
   Timestamp currentDttm = new Timestamp(System.currentTimeMillis());
   if (accountLocked) {
     // If current date time is less than Account lock expire date time
     // then the account is locked hence return true
     if (currentDttm.before(accountLockExpiryDttm)) {
       // log user for account locked
       saveUserAccessLog(
           "139003",
           messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked"),
           username,
           userid);
       return true;
     } else {
       // call stored proc "ExpiredLockAccount"
       String url = expired_user_lock_account + "/" + username;
       LOGGER.debug(url);
       restTemplate.getForObject(url, Boolean.class);
       return false;
     }
   }
   return false;
 }
  /**
   * The onSubmit function receives the form/command object that was modified by the input form and
   * saves it to the db
   *
   * @see
   *     org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse, java.lang.Object,
   *     org.springframework.validation.BindException)
   */
  @Override
  protected ModelAndView onSubmit(
      HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors)
      throws Exception {

    HttpSession httpSession = request.getSession();
    String view = getFormView();

    if (Context.isAuthenticated()) {
      Form form = (Form) obj;
      MessageSourceAccessor msa = getMessageSourceAccessor();
      String action = request.getParameter("action");
      if (action == null) {
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Form.not.saved");
      } else {
        if (action.equals(msa.getMessage("Form.save"))) {
          try {
            // save form
            form = Context.getFormService().saveForm(form);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Form.saved");
          } catch (Exception e) {
            log.error("Error while saving form " + form.getFormId(), e);
            errors.reject(e.getMessage());
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Form.not.saved");
            return showForm(request, response, errors);
          }
        } else if (action.equals(msa.getMessage("Form.delete"))) {
          try {
            Context.getFormService().purgeForm(form);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Form.deleted");
          } catch (DataIntegrityViolationException e) {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Form.cannot.delete");
            return new ModelAndView(new RedirectView("formEdit.form?formId=" + form.getFormId()));
          } catch (Exception e) {
            log.error("Error while deleting form " + form.getFormId(), e);
            errors.reject(e.getMessage());
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Form.cannot.delete");
            return showForm(request, response, errors);
            // return new ModelAndView(new RedirectView(getSuccessView()));
          }
        } else if (action.equals(msa.getMessage("Form.updateSortOrder"))) {

          FormService fs = Context.getFormService();

          TreeMap<Integer, TreeSet<FormField>> treeMap = FormUtil.getFormStructure(form);
          for (Map.Entry<Integer, TreeSet<FormField>> entry : treeMap.entrySet()) {
            Integer parentFormFieldId = entry.getKey();
            float sortWeight = 0;
            for (FormField formField : entry.getValue()) {
              formField.setSortWeight(sortWeight);
              fs.saveFormField(formField);
              sortWeight += 50;
            }
          }

        } else {
          try {
            Context.getFormService().duplicateForm(form);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Form.duplicated");
          } catch (Exception e) {
            log.error("Error while duplicating form " + form.getFormId(), e);
            errors.reject(e.getMessage());
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Form.cannot.duplicate");
            return showForm(request, response, errors);
          }
        }

        view = getSuccessView();
      }
    }

    return new ModelAndView(new RedirectView(view));
  }
  /*
   * (non-Javadoc)
   * @see org.springframework.core.convert.converter.GenericConverter#convert(java.lang.Object, org.springframework.core.convert.TypeDescriptor, org.springframework.core.convert.TypeDescriptor)
   */
  @Override
  public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {

    PersistentEntity<?, ?> persistentEntity = repositories.getPersistentEntity((Class<?>) source);
    final ResourceMetadata metadata = mappings.getMappingFor(persistentEntity.getType());
    final JsonSchema jsonSchema =
        new JsonSchema(
            persistentEntity.getName(), accessor.getMessage(metadata.getItemResourceDescription()));

    persistentEntity.doWithProperties(
        new SimplePropertyHandler() {

          /*
           * (non-Javadoc)
           * @see org.springframework.data.mapping.PropertyHandler#doWithPersistentProperty(org.springframework.data.mapping.PersistentProperty)
           */
          @Override
          public void doWithPersistentProperty(PersistentProperty<?> persistentProperty) {

            Class<?> propertyType = persistentProperty.getType();
            String type = uncapitalize(propertyType.getSimpleName());

            ResourceMapping propertyMapping = metadata.getMappingFor(persistentProperty);
            ResourceDescription description = propertyMapping.getDescription();
            String message = accessor.getMessage(description);

            Property property =
                persistentProperty.isCollectionLike()
                    ? //
                    new ArrayProperty("array", message, false)
                    : new Property(type, message, false);

            jsonSchema.addProperty(persistentProperty.getName(), property);
          }
        });

    final List<Link> links = new ArrayList<Link>();

    persistentEntity.doWithAssociations(
        new SimpleAssociationHandler() {

          /*
           * (non-Javadoc)
           * @see org.springframework.data.mapping.AssociationHandler#doWithAssociation(org.springframework.data.mapping.Association)
           */
          @Override
          public void doWithAssociation(Association<? extends PersistentProperty<?>> association) {

            PersistentProperty<?> persistentProperty = association.getInverse();

            if (!metadata.isExported(persistentProperty)) {
              return;
            }

            RepositoryLinkBuilder builder =
                new RepositoryLinkBuilder(metadata, config.getBaseUri()).slash("{id}");
            maybeAddAssociationLink(builder, mappings, persistentProperty, links);
          }
        });

    jsonSchema.add(links);

    return jsonSchema;
  }
 /**
  * Convenience method for getting a i18n key's value with arguments.
  *
  * @param msgKey
  * @param args
  * @param locale the current locale
  * @return
  */
 public String getText(String msgKey, Object[] args, Locale locale) {
   return messages.getMessage(msgKey, args, locale);
 }
 /**
  * Convenience method for getting a i18n key's value. Calling getMessageSourceAccessor() is used
  * because the RequestContext variable is not set in unit tests b/c there's no DispatchServlet
  * Request.
  *
  * @param msgKey
  * @param locale the current locale
  * @return
  */
 public String getText(String msgKey, Locale locale) {
   return messages.getMessage(msgKey, locale);
 }