Search in sources :

Example 1 with User

use of org.openmrs.User in project openmrs-module-pihcore by PIH.

the class UpdateProviderRetiredStatesBasedOnAssociatedUserAccountsTest method shouldNotRetireProviderIfAnyUserAccountActiveLessThanAMonthAgo.

@Test
public void shouldNotRetireProviderIfAnyUserAccountActiveLessThanAMonthAgo() {
    // retire first account more than a month ago
    User user = userService.getUser(1002);
    user.setRetired(true);
    user.setRetiredBy(userService.getUser(1));
    user.setRetireReason("test");
    user.setDateRetired(new DateTime(2015, 1, 1, 0, 0, 0).toDate());
    // retire second account on current date
    user = userService.getUser(1003);
    user.setRetired(true);
    user.setRetiredBy(userService.getUser(1));
    user.setRetireReason("test");
    user.setDateRetired(new Date());
    new UpdateProviderRetiredStatesBasedOnAssociatedUserAccounts().execute();
    assertFalse(providerService.getProvider(1002).isRetired());
    // sanity check other providers (should maintain whatever retired state was set in the test dataset)
    assertTrue(providerService.getProvider(1001).isRetired());
    assertTrue(providerService.getProvider(1005).isRetired());
    assertTrue(providerService.getProvider(1005).isRetired());
    assertFalse(providerService.getProvider(1003).isRetired());
    assertFalse(providerService.getProvider(1004).isRetired());
}
Also used : User(org.openmrs.User) DateTime(org.joda.time.DateTime) Date(java.util.Date) BaseModuleContextSensitiveTest(org.openmrs.test.BaseModuleContextSensitiveTest) Test(org.junit.Test)

Example 2 with User

use of org.openmrs.User in project openmrs-core by openmrs.

the class HibernateContextDAO method authenticate.

/**
 * @see org.openmrs.api.db.ContextDAO#authenticate(java.lang.String, java.lang.String)
 */
@Override
@Transactional(noRollbackFor = ContextAuthenticationException.class)
public User authenticate(String login, String password) throws ContextAuthenticationException {
    String errorMsg = "Invalid username and/or password: " + login;
    Session session = sessionFactory.getCurrentSession();
    User candidateUser = null;
    if (login != null) {
        // if username is blank or white space character(s)
        if (StringUtils.isEmpty(login) || StringUtils.isWhitespace(login)) {
            throw new ContextAuthenticationException(errorMsg);
        }
        // loginWithoutDash is used to compare to the system id
        String loginWithDash = login;
        if (login.matches("\\d{2,}")) {
            loginWithDash = login.substring(0, login.length() - 1) + "-" + login.charAt(login.length() - 1);
        }
        try {
            candidateUser = (User) session.createQuery("from User u where (u.username = ? or u.systemId = ? or u.systemId = ?) and u.retired = '0'").setString(0, login).setString(1, login).setString(2, loginWithDash).uniqueResult();
        } catch (HibernateException he) {
            log.error("Got hibernate exception while logging in: '" + login + "'", he);
        } catch (Exception e) {
            log.error("Got regular exception while logging in: '" + login + "'", e);
        }
    }
    // only continue if this is a valid username and a nonempty password
    if (candidateUser != null && password != null) {
        if (log.isDebugEnabled()) {
            log.debug("Candidate user id: " + candidateUser.getUserId());
        }
        String lockoutTimeString = candidateUser.getUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP, null);
        Long lockoutTime = null;
        if (lockoutTimeString != null && !"0".equals(lockoutTimeString)) {
            try {
                // putting this in a try/catch in case the admin decided to put junk into the property
                lockoutTime = Long.valueOf(lockoutTimeString);
            } catch (NumberFormatException e) {
                log.debug("bad value stored in " + OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP + " user property: " + lockoutTimeString);
            }
        }
        // if they've been locked out, don't continue with the authentication
        if (lockoutTime != null) {
            // to now and make them wait another 5 mins
            if (System.currentTimeMillis() - lockoutTime > 300000) {
                candidateUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOGIN_ATTEMPTS, "0");
                candidateUser.removeUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP);
                saveUserProperties(candidateUser);
            } else {
                candidateUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP, String.valueOf(System.currentTimeMillis()));
                throw new ContextAuthenticationException("Invalid number of connection attempts. Please try again later.");
            }
        }
        String passwordOnRecord = (String) session.createSQLQuery("select password from users where user_id = ?").addScalar("password", StandardBasicTypes.STRING).setInteger(0, candidateUser.getUserId()).uniqueResult();
        String saltOnRecord = (String) session.createSQLQuery("select salt from users where user_id = ?").addScalar("salt", StandardBasicTypes.STRING).setInteger(0, candidateUser.getUserId()).uniqueResult();
        // if the username and password match, hydrate the user and return it
        if (passwordOnRecord != null && Security.hashMatches(passwordOnRecord, password + saltOnRecord)) {
            // hydrate the user object
            candidateUser.getAllRoles().size();
            candidateUser.getUserProperties().size();
            candidateUser.getPrivileges().size();
            // only clean up if the were some login failures, otherwise all should be clean
            Integer attempts = getUsersLoginAttempts(candidateUser);
            if (attempts > 0) {
                candidateUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOGIN_ATTEMPTS, "0");
                candidateUser.removeUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP);
                saveUserProperties(candidateUser);
            }
            // to indicate that this is the valid user
            return candidateUser;
        } else {
            // the user failed the username/password, increment their
            // attempts here and set the "lockout" timestamp if necessary
            Integer attempts = getUsersLoginAttempts(candidateUser);
            attempts++;
            Integer allowedFailedLoginCount = 7;
            try {
                allowedFailedLoginCount = Integer.valueOf(Context.getAdministrationService().getGlobalProperty(OpenmrsConstants.GP_ALLOWED_FAILED_LOGINS_BEFORE_LOCKOUT).trim());
            } catch (Exception ex) {
                log.error("Unable to convert the global property " + OpenmrsConstants.GP_ALLOWED_FAILED_LOGINS_BEFORE_LOCKOUT + "to a valid integer. Using default value of 7");
            }
            if (attempts > allowedFailedLoginCount) {
                // set the user as locked out at this exact time
                candidateUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP, String.valueOf(System.currentTimeMillis()));
            } else {
                candidateUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOGIN_ATTEMPTS, String.valueOf(attempts));
            }
            saveUserProperties(candidateUser);
        }
    }
    // throw this exception only once in the same place with the same
    // message regardless of username/pw combo entered
    log.info("Failed login attempt (login=" + login + ") - " + errorMsg);
    throw new ContextAuthenticationException(errorMsg);
}
Also used : ContextAuthenticationException(org.openmrs.api.context.ContextAuthenticationException) User(org.openmrs.User) HibernateException(org.hibernate.HibernateException) ContextAuthenticationException(org.openmrs.api.context.ContextAuthenticationException) HibernateException(org.hibernate.HibernateException) FullTextSession(org.hibernate.search.FullTextSession) Session(org.hibernate.Session) Transactional(org.springframework.transaction.annotation.Transactional)

Example 3 with User

use of org.openmrs.User in project openmrs-core by openmrs.

the class Context method becomeUser.

/**
 * Become a different user. (You should only be able to do this as a superuser.)
 *
 * @param systemId
 * @throws ContextAuthenticationException
 * @should change locale when become another user
 */
public static void becomeUser(String systemId) throws ContextAuthenticationException {
    if (log.isInfoEnabled()) {
        log.info("systemId: " + systemId);
    }
    User user = getUserContext().becomeUser(systemId);
    // if assuming identity procedure finished successfully, we should change context locale parameter
    Locale locale = null;
    if (user.getUserProperties().containsKey(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE)) {
        String localeString = user.getUserProperty(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE);
        locale = LocaleUtility.fromSpecification(localeString);
    }
    // when locale parameter is not valid or does not exist
    if (locale == null) {
        locale = LocaleUtility.getDefaultLocale();
    }
    Context.setLocale(locale);
}
Also used : Locale(java.util.Locale) User(org.openmrs.User)

Example 4 with User

use of org.openmrs.User in project openmrs-core by openmrs.

the class UserContext method becomeUser.

/**
 * Change current authentication to become another user. (You can only do this if you're already
 * authenticated as a superuser.)
 *
 * @param systemId
 * @return The new user that this context has been set to. (null means no change was made)
 * @throws ContextAuthenticationException
 */
public User becomeUser(String systemId) throws ContextAuthenticationException {
    if (!Context.getAuthenticatedUser().isSuperUser()) {
        throw new APIAuthenticationException("You must be a superuser to assume another user's identity");
    }
    if (log.isDebugEnabled()) {
        log.debug("Turning the authenticated user into user with systemId: " + systemId);
    }
    User userToBecome = Context.getUserService().getUserByUsername(systemId);
    if (userToBecome == null) {
        throw new ContextAuthenticationException("User not found with systemId: " + systemId);
    }
    // hydrate the user object
    if (userToBecome.getAllRoles() != null) {
        userToBecome.getAllRoles().size();
    }
    if (userToBecome.getUserProperties() != null) {
        userToBecome.getUserProperties().size();
    }
    if (userToBecome.getPrivileges() != null) {
        userToBecome.getPrivileges().size();
    }
    this.user = userToBecome;
    // update the user's location
    setUserLocation();
    if (log.isDebugEnabled()) {
        log.debug("Becoming user: " + user);
    }
    return userToBecome;
}
Also used : User(org.openmrs.User) APIAuthenticationException(org.openmrs.api.APIAuthenticationException)

Example 5 with User

use of org.openmrs.User in project openmrs-core by openmrs.

the class PersonServiceTest method voidRelationship_shouldVoidRelationshipAndSetVoidedByToGivenUserIfGivenRelationshipIsNotVoided.

@Test
public void voidRelationship_shouldVoidRelationshipAndSetVoidedByToGivenUserIfGivenRelationshipIsNotVoided() {
    Relationship relationship = personService.getRelationship(1);
    assertFalse("We need an unvoided relationship to test the method", relationship.getVoided());
    String voidReason = "Something";
    User user = Context.getUserService().getUser(501);
    assertNotNull("need a user to void", user);
    relationship.setVoidedBy(user);
    // TODO - voiding is done by the BaseVoidHandler called via AOP before voidRelationship
    // is executed. Coverage of voidRelationship is low because relationship.getVoided() is true
    // when entering voidRelationship
    // Documented at TRUNK-5151
    personService.voidRelationship(relationship, voidReason);
    Relationship voidedRelationship = personService.getRelationship(1);
    assertTrue(voidedRelationship.getVoided());
    assertThat(voidedRelationship.getVoidReason(), is(voidReason));
    assertNotNull(voidedRelationship.getDateVoided());
    assertEquals(voidedRelationship.getVoidedBy(), user);
}
Also used : User(org.openmrs.User) Relationship(org.openmrs.Relationship) Test(org.junit.Test) BaseContextSensitiveTest(org.openmrs.test.BaseContextSensitiveTest)

Aggregations

User (org.openmrs.User)201 Test (org.junit.Test)150 BaseContextSensitiveTest (org.openmrs.test.BaseContextSensitiveTest)132 Date (java.util.Date)38 Person (org.openmrs.Person)33 Encounter (org.openmrs.Encounter)21 Patient (org.openmrs.Patient)18 PersonName (org.openmrs.PersonName)17 Role (org.openmrs.Role)13 GlobalProperty (org.openmrs.GlobalProperty)11 Location (org.openmrs.Location)11 ArrayList (java.util.ArrayList)10 EncounterType (org.openmrs.EncounterType)10 Locale (java.util.Locale)7 UserService (org.openmrs.api.UserService)7 PatientServiceImplTest (org.openmrs.api.impl.PatientServiceImplTest)7 BindException (org.springframework.validation.BindException)7 Errors (org.springframework.validation.Errors)7 EncounterRole (org.openmrs.EncounterRole)6 PatientIdentifier (org.openmrs.PatientIdentifier)6