Search in sources :

Example 21 with User

use of org.hisp.dhis.user.User in project dhis2-core by dhis2.

the class MobileClientController method getOrgUnitsForUser2_8.

@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public OrgUnits getOrgUnitsForUser2_8(HttpServletRequest request) throws NotAllowedException {
    User user = currentUserService.getCurrentUser();
    if (user == null) {
        throw NotAllowedException.NO_USER;
    }
    Collection<OrganisationUnit> units = user.getOrganisationUnits();
    List<MobileOrgUnitLinks> unitList = new ArrayList<>();
    for (OrganisationUnit unit : units) {
        unitList.add(getOrgUnit(unit, request));
    }
    OrgUnits orgUnits = new OrgUnits(unitList);
    orgUnits.setClientVersion(DataStreamSerializable.TWO_POINT_EIGHT);
    return orgUnits;
}
Also used : OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) MobileOrgUnitLinks(org.hisp.dhis.api.mobile.model.MobileOrgUnitLinks) User(org.hisp.dhis.user.User) ArrayList(java.util.ArrayList) OrgUnits(org.hisp.dhis.api.mobile.model.OrgUnits) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 22 with User

use of org.hisp.dhis.user.User in project dhis2-core by dhis2.

the class UserRoleController method removeUserFromRole.

@RequestMapping(value = "/{id}/users/{userId}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void removeUserFromRole(@PathVariable(value = "id") String pvId, @PathVariable("userId") String pvUserId, HttpServletResponse response) throws WebMessageException {
    UserAuthorityGroup userAuthorityGroup = userService.getUserAuthorityGroup(pvId);
    if (userAuthorityGroup == null) {
        throw new WebMessageException(WebMessageUtils.notFound("UserRole does not exist: " + pvId));
    }
    User user = userService.getUser(pvUserId);
    if (user == null || user.getUserCredentials() == null) {
        throw new WebMessageException(WebMessageUtils.notFound("User does not exist: " + pvId));
    }
    if (!aclService.canUpdate(currentUserService.getCurrentUser(), userAuthorityGroup)) {
        throw new DeleteAccessDeniedException("You don't have the proper permissions to delete this object.");
    }
    if (user.getUserCredentials().getUserAuthorityGroups().contains(userAuthorityGroup)) {
        user.getUserCredentials().getUserAuthorityGroups().remove(userAuthorityGroup);
        userService.updateUserCredentials(user.getUserCredentials());
    }
}
Also used : User(org.hisp.dhis.user.User) UserAuthorityGroup(org.hisp.dhis.user.UserAuthorityGroup) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) DeleteAccessDeniedException(org.hisp.dhis.hibernate.exception.DeleteAccessDeniedException) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 23 with User

use of org.hisp.dhis.user.User in project dhis2-core by dhis2.

the class DefaultPushAnalysisService method runPushAnalysis.

@Override
public void runPushAnalysis(int id, TaskId taskId) {
    //----------------------------------------------------------------------
    // Set up
    //----------------------------------------------------------------------
    PushAnalysis pushAnalysis = pushAnalysisStore.get(id);
    Set<User> receivingUsers = new HashSet<>();
    notifier.clear(taskId);
    //----------------------------------------------------------------------
    // Pre-check
    //----------------------------------------------------------------------
    log(taskId, NotificationLevel.INFO, "Starting pre-check on PushAnalysis", false, null);
    if (!setPushAnalysisIsRunningFlag(pushAnalysis, true)) {
        log(taskId, NotificationLevel.ERROR, "PushAnalysis with id '" + id + "' is already running. Terminating new PushAnalysis job.", true, null);
        return;
    }
    if (pushAnalysis == null) {
        log(taskId, NotificationLevel.ERROR, "PushAnalysis with id '" + id + "' was not found. Terminating PushAnalysis", true, null);
        return;
    }
    if (pushAnalysis.getRecipientUserGroups().size() == 0) {
        log(taskId, NotificationLevel.ERROR, "PushAnalysis with id '" + id + "' has no userGroups assigned. Terminating PushAnalysis.", true, null);
        return;
    }
    if (pushAnalysis.getDashboard() == null) {
        log(taskId, NotificationLevel.ERROR, "PushAnalysis with id '" + id + "' has no dashboard assigned. Terminating PushAnalysis.", true, null);
        return;
    }
    if (systemSettingManager.getInstanceBaseUrl() == null) {
        log(taskId, NotificationLevel.ERROR, "Missing system setting '" + SettingKey.INSTANCE_BASE_URL.getName() + "'. Terminating PushAnalysis.", true, null);
        return;
    }
    log(taskId, NotificationLevel.INFO, "pre-check completed successfully", false, null);
    //----------------------------------------------------------------------
    // Compose list of users that can receive PushAnalysis
    //----------------------------------------------------------------------
    log(taskId, NotificationLevel.INFO, "Composing list of receiving users", false, null);
    for (UserGroup userGroup : pushAnalysis.getRecipientUserGroups()) {
        for (User user : userGroup.getMembers()) {
            if (!user.hasEmail()) {
                log(taskId, NotificationLevel.WARN, "Skipping user: User '" + user.getUsername() + "' is missing a valid email.", false, null);
                continue;
            }
            receivingUsers.add(user);
        }
    }
    log(taskId, NotificationLevel.INFO, "List composed. " + receivingUsers.size() + " eligible users found.", false, null);
    //----------------------------------------------------------------------
    // Generating reports
    //----------------------------------------------------------------------
    log(taskId, NotificationLevel.INFO, "Generating and sending reports", false, null);
    for (User user : receivingUsers) {
        try {
            String title = pushAnalysis.getTitle();
            String html = generateHtmlReport(pushAnalysis, user, taskId);
            // TODO: Better handling of messageStatus; Might require refactoring of EmailMessageSender
            @SuppressWarnings("unused") OutboundMessageResponse status = messageSender.sendMessage(title, html, "", null, Sets.newHashSet(user), true);
        } catch (Exception e) {
            log(taskId, NotificationLevel.ERROR, "Could not create or send report for PushAnalysis '" + pushAnalysis.getName() + "' and User '" + user.getUsername() + "': " + e.getMessage(), false, e);
        }
    }
    // Update lastRun date
    pushAnalysis.setLastRun(new Date());
    pushAnalysisStore.update(pushAnalysis);
    setPushAnalysisIsRunningFlag(pushAnalysis, false);
}
Also used : User(org.hisp.dhis.user.User) OutboundMessageResponse(org.hisp.dhis.outboundmessage.OutboundMessageResponse) IOException(java.io.IOException) Date(java.util.Date) HashSet(java.util.HashSet) UserGroup(org.hisp.dhis.user.UserGroup)

Example 24 with User

use of org.hisp.dhis.user.User in project dhis2-core by dhis2.

the class PreheatServiceTest method testPreheatAllMetadataUID.

@Test
public void testPreheatAllMetadataUID() {
    DataElementGroup dataElementGroup = new DataElementGroup("DataElementGroupA");
    dataElementGroup.setAutoFields();
    DataElement de1 = createDataElement('A');
    DataElement de2 = createDataElement('B');
    DataElement de3 = createDataElement('C');
    manager.save(de1);
    manager.save(de2);
    manager.save(de3);
    User user = createUser('A');
    manager.save(user);
    dataElementGroup.addDataElement(de1);
    dataElementGroup.addDataElement(de2);
    dataElementGroup.addDataElement(de3);
    dataElementGroup.setUser(user);
    manager.save(dataElementGroup);
    PreheatParams params = new PreheatParams();
    params.setPreheatMode(PreheatMode.ALL);
    preheatService.validate(params);
    Preheat preheat = preheatService.preheat(params);
    assertFalse(preheat.isEmpty());
    assertFalse(preheat.isEmpty(PreheatIdentifier.UID));
    assertFalse(preheat.isEmpty(PreheatIdentifier.UID, DataElement.class));
    assertFalse(preheat.isEmpty(PreheatIdentifier.UID, DataElementGroup.class));
    assertFalse(preheat.isEmpty(PreheatIdentifier.UID, User.class));
    assertTrue(preheat.containsKey(PreheatIdentifier.UID, DataElement.class, de1.getUid()));
    assertTrue(preheat.containsKey(PreheatIdentifier.UID, DataElement.class, de2.getUid()));
    assertTrue(preheat.containsKey(PreheatIdentifier.UID, DataElement.class, de3.getUid()));
    assertTrue(preheat.containsKey(PreheatIdentifier.UID, DataElementGroup.class, dataElementGroup.getUid()));
    assertTrue(preheat.containsKey(PreheatIdentifier.UID, User.class, user.getUid()));
}
Also used : DataElement(org.hisp.dhis.dataelement.DataElement) User(org.hisp.dhis.user.User) DataElementGroup(org.hisp.dhis.dataelement.DataElementGroup) Test(org.junit.Test) DhisSpringTest(org.hisp.dhis.DhisSpringTest)

Example 25 with User

use of org.hisp.dhis.user.User in project dhis2-core by dhis2.

the class DhisConvenienceTest method createUserAndInjectSecurityContext.

/**
     * Creates a user and injects into the security context with username
     * "username". Requires <code>identifiableObjectManager</code> and
     * <code>userService</code> to be injected into the test.
     *
     * @param organisationUnits         the organisation units of the user.
     * @param dataViewOrganisationUnits user's data view organisation units.
     * @param allAuth                   whether to grant the ALL authority.
     * @param auths                     authorities to grant to user.
     * @return the user.
     */
protected User createUserAndInjectSecurityContext(Set<OrganisationUnit> organisationUnits, Set<OrganisationUnit> dataViewOrganisationUnits, boolean allAuth, String... auths) {
    Assert.notNull(userService, "UserService must be injected in test");
    Set<String> authorities = new HashSet<>();
    if (allAuth) {
        authorities.add(UserAuthorityGroup.AUTHORITY_ALL);
    }
    if (auths != null) {
        authorities.addAll(Lists.newArrayList(auths));
    }
    UserAuthorityGroup userAuthorityGroup = new UserAuthorityGroup();
    userAuthorityGroup.setName("Superuser");
    userAuthorityGroup.getAuthorities().addAll(authorities);
    userService.addUserAuthorityGroup(userAuthorityGroup);
    User user = createUser('A');
    if (organisationUnits != null) {
        user.setOrganisationUnits(organisationUnits);
    }
    if (dataViewOrganisationUnits != null) {
        user.setDataViewOrganisationUnits(dataViewOrganisationUnits);
    }
    user.getUserCredentials().getUserAuthorityGroups().add(userAuthorityGroup);
    userService.addUser(user);
    user.getUserCredentials().setUserInfo(user);
    userService.addUserCredentials(user.getUserCredentials());
    Set<GrantedAuthority> grantedAuths = authorities.stream().map(a -> new SimpleGrantedAuthority(a)).collect(Collectors.toSet());
    UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUserCredentials().getUsername(), user.getUserCredentials().getPassword(), grantedAuths);
    Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, "", grantedAuths);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    return user;
}
Also used : UniqunessType(org.hisp.dhis.program.UniqunessType) AopUtils(org.springframework.aop.support.AopUtils) ProgramStageDataElement(org.hisp.dhis.program.ProgramStageDataElement) ProgramMessage(org.hisp.dhis.program.message.ProgramMessage) SqlView(org.hisp.dhis.sqlview.SqlView) Autowired(org.springframework.beans.factory.annotation.Autowired) TrackedEntityAttributeValue(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue) ProgramRuleVariableSourceType(org.hisp.dhis.programrule.ProgramRuleVariableSourceType) UserCredentials(org.hisp.dhis.user.UserCredentials) MonthlyPeriodType(org.hisp.dhis.period.MonthlyPeriodType) ValidationRuleGroup(org.hisp.dhis.validation.ValidationRuleGroup) NamespaceContext(javax.xml.namespace.NamespaceContext) DataElementCategoryService(org.hisp.dhis.dataelement.DataElementCategoryService) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) IndicatorGroup(org.hisp.dhis.indicator.IndicatorGroup) PrintWriter(java.io.PrintWriter) OrganisationUnitGroup(org.hisp.dhis.organisationunit.OrganisationUnitGroup) UserGroup(org.hisp.dhis.user.UserGroup) TrackedEntityInstance(org.hisp.dhis.trackedentity.TrackedEntityInstance) CacheStrategy(org.hisp.dhis.common.cache.CacheStrategy) Set(java.util.Set) ProgramRuleActionType(org.hisp.dhis.programrule.ProgramRuleActionType) DataElementCategoryOption(org.hisp.dhis.dataelement.DataElementCategoryOption) Operator(org.hisp.dhis.expression.Operator) GrantedAuthority(org.springframework.security.core.GrantedAuthority) DimensionalObject(org.hisp.dhis.common.DimensionalObject) Predictor(org.hisp.dhis.predictor.Predictor) ProgramType(org.hisp.dhis.program.ProgramType) LogFactory(org.apache.commons.logging.LogFactory) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Legend(org.hisp.dhis.legend.Legend) DataDimensionType(org.hisp.dhis.common.DataDimensionType) XPath(javax.xml.xpath.XPath) Advised(org.springframework.aop.framework.Advised) DataSet(org.hisp.dhis.dataset.DataSet) ProgramStageInstance(org.hisp.dhis.program.ProgramStageInstance) Attribute(org.hisp.dhis.attribute.Attribute) Lists(com.google.common.collect.Lists) ProgramNotificationRecipient(org.hisp.dhis.program.notification.ProgramNotificationRecipient) DataElementCategoryCombo(org.hisp.dhis.dataelement.DataElementCategoryCombo) LegendSet(org.hisp.dhis.legend.LegendSet) Indicator(org.hisp.dhis.indicator.Indicator) DataElementGroupSet(org.hisp.dhis.dataelement.DataElementGroupSet) IndicatorType(org.hisp.dhis.indicator.IndicatorType) NotificationTrigger(org.hisp.dhis.program.notification.NotificationTrigger) CategoryOptionGroupSet(org.hisp.dhis.dataelement.CategoryOptionGroupSet) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) StringWriter(java.io.StringWriter) AggregationType(org.hisp.dhis.analytics.AggregationType) CategoryOptionGroup(org.hisp.dhis.dataelement.CategoryOptionGroup) IOException(java.io.IOException) OrganisationUnitGroupSet(org.hisp.dhis.organisationunit.OrganisationUnitGroupSet) SqlViewType(org.hisp.dhis.sqlview.SqlViewType) File(java.io.File) OptionSet(org.hisp.dhis.option.OptionSet) StringReader(java.io.StringReader) TrackedEntity(org.hisp.dhis.trackedentity.TrackedEntity) ProgramTrackedEntityAttribute(org.hisp.dhis.program.ProgramTrackedEntityAttribute) DataValue(org.hisp.dhis.datavalue.DataValue) PeriodType(org.hisp.dhis.period.PeriodType) CodeGenerator(org.hisp.dhis.common.CodeGenerator) Expression(org.hisp.dhis.expression.Expression) DataElementGroup(org.hisp.dhis.dataelement.DataElementGroup) OrganisationUnitLevel(org.hisp.dhis.organisationunit.OrganisationUnitLevel) IndicatorGroupSet(org.hisp.dhis.indicator.IndicatorGroupSet) XPathExpressionException(javax.xml.xpath.XPathExpressionException) ProgramTrackedEntityAttributeGroup(org.hisp.dhis.program.ProgramTrackedEntityAttributeGroup) ValueType(org.hisp.dhis.common.ValueType) Date(java.util.Date) RenderService(org.hisp.dhis.render.RenderService) Constant(org.hisp.dhis.constant.Constant) Method(java.lang.reflect.Method) Period(org.hisp.dhis.period.Period) DataEntryForm(org.hisp.dhis.dataentryform.DataEntryForm) UserService(org.hisp.dhis.user.UserService) Chart(org.hisp.dhis.chart.Chart) ProgramNotificationTemplate(org.hisp.dhis.program.notification.ProgramNotificationTemplate) Collection(java.util.Collection) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) DataElementCategoryOptionCombo(org.hisp.dhis.dataelement.DataElementCategoryOptionCombo) ProgramRule(org.hisp.dhis.programrule.ProgramRule) List(java.util.List) UserAuthorityGroup(org.hisp.dhis.user.UserAuthorityGroup) PostConstruct(javax.annotation.PostConstruct) ValidationCriteria(org.hisp.dhis.validation.ValidationCriteria) ProgramIndicator(org.hisp.dhis.program.ProgramIndicator) Authentication(org.springframework.security.core.Authentication) TrackedEntityAttribute(org.hisp.dhis.trackedentity.TrackedEntityAttribute) ProgramMessageStatus(org.hisp.dhis.program.message.ProgramMessageStatus) AttributeValue(org.hisp.dhis.attribute.AttributeValue) LocationManager(org.hisp.dhis.external.location.LocationManager) ValidationNotificationTemplate(org.hisp.dhis.validation.notification.ValidationNotificationTemplate) ClassPathResource(org.springframework.core.io.ClassPathResource) ProgramRuleVariable(org.hisp.dhis.programrule.ProgramRuleVariable) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) ProgramDataElementDimensionItem(org.hisp.dhis.program.ProgramDataElementDimensionItem) ProgramRuleAction(org.hisp.dhis.programrule.ProgramRuleAction) Program(org.hisp.dhis.program.Program) DataElement(org.hisp.dhis.dataelement.DataElement) HashSet(java.util.HashSet) ProgramMessageRecipients(org.hisp.dhis.program.message.ProgramMessageRecipients) RelationshipType(org.hisp.dhis.relationship.RelationshipType) User(org.hisp.dhis.user.User) UserDetails(org.springframework.security.core.userdetails.UserDetails) XMLConstants(javax.xml.XMLConstants) InputSource(org.xml.sax.InputSource) DataElementCategory(org.hisp.dhis.dataelement.DataElementCategory) Iterator(java.util.Iterator) DataElementDomain(org.hisp.dhis.dataelement.DataElementDomain) DateTime(org.joda.time.DateTime) ValidationRule(org.hisp.dhis.validation.ValidationRule) ProgramStage(org.hisp.dhis.program.ProgramStage) ProgramStageSection(org.hisp.dhis.program.ProgramStageSection) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) XPathFactory(javax.xml.xpath.XPathFactory) Option(org.hisp.dhis.option.Option) DeliveryChannel(org.hisp.dhis.common.DeliveryChannel) Log(org.apache.commons.logging.Log) Collections(java.util.Collections) ChartType(org.hisp.dhis.chart.ChartType) Assert(org.springframework.util.Assert) User(org.hisp.dhis.user.User) GrantedAuthority(org.springframework.security.core.GrantedAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetails(org.springframework.security.core.userdetails.UserDetails) UserAuthorityGroup(org.hisp.dhis.user.UserAuthorityGroup) Authentication(org.springframework.security.core.Authentication) HashSet(java.util.HashSet)

Aggregations

User (org.hisp.dhis.user.User)715 Test (org.junit.jupiter.api.Test)254 TransactionalIntegrationTest (org.hisp.dhis.TransactionalIntegrationTest)168 OrganisationUnit (org.hisp.dhis.organisationunit.OrganisationUnit)132 DataElement (org.hisp.dhis.dataelement.DataElement)85 ArrayList (java.util.ArrayList)79 List (java.util.List)78 IdentifiableObject (org.hisp.dhis.common.IdentifiableObject)63 HashSet (java.util.HashSet)62 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)59 UserGroup (org.hisp.dhis.user.UserGroup)53 Date (java.util.Date)51 Transactional (org.springframework.transaction.annotation.Transactional)49 HashMap (java.util.HashMap)46 Program (org.hisp.dhis.program.Program)44 DataSet (org.hisp.dhis.dataset.DataSet)43 UserAuthorityGroup (org.hisp.dhis.user.UserAuthorityGroup)43 ClassPathResource (org.springframework.core.io.ClassPathResource)41 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)38 Set (java.util.Set)37