public async Task <ActionResult> Get(
            [FromRoute] string org,
            [FromRoute] string app,
            [FromQuery] string dataType)
        {
            if (string.IsNullOrEmpty(dataType))
            {
                return(BadRequest($"Invalid dataType {dataType} provided. Please provide a valid dataType as query parameter."));
            }

            string classRef = _appResourcesService.GetClassRefForLogicDataType(dataType);

            if (string.IsNullOrEmpty(classRef))
            {
                return(BadRequest($"Invalid dataType {dataType} provided. Please provide a valid dataType as query parameter."));
            }

            if (GetPartyHeader(HttpContext).Count > 1)
            {
                return(BadRequest($"Invalid party. Only one allowed"));
            }

            InstanceOwner owner = await GetInstanceOwner(HttpContext);

            if (string.IsNullOrEmpty(owner.PartyId))
            {
                return(StatusCode((int)HttpStatusCode.Forbidden));
            }

            EnforcementResult enforcementResult = await AuthorizeAction(org, app, Convert.ToInt32(owner.PartyId), "read");

            if (!enforcementResult.Authorized)
            {
                return(Forbidden(enforcementResult));
            }

            object appModel = _altinnApp.CreateNewAppModel(classRef);

            // runs prefill from repo configuration if config exists
            await _prefillService.PrefillDataModel(owner.PartyId, dataType, appModel);

            Instance virutalInstance = new Instance()
            {
                InstanceOwner = owner
            };
            await _altinnApp.RunProcessDataRead(virutalInstance, null, appModel);

            return(Ok(appModel));
        }
Beispiel #2
0
        /// <inheritdoc />
        public async Task OnStartProcessTask(string taskId, Instance instance)
        {
            _logger.LogInformation($"OnStartProcessTask for {instance.Id}");

            foreach (DataType dataType in _appMetadata.DataTypes.Where(dt => dt.TaskId == taskId && dt.AppLogic?.AutoCreate == true))
            {
                _logger.LogInformation($"Auto create data element: {dataType.Id}");

                DataElement dataElement = instance.Data.Find(d => d.DataType == dataType.Id);

                if (dataElement == null)
                {
                    dynamic data = CreateNewAppModel(dataType.AppLogic.ClassRef);

                    // runs prefill from repo configuration if config exists
                    await _prefillService.PrefillDataModel(instance.InstanceOwner.PartyId, dataType.Id, data);
                    await RunDataCreation(instance, data);

                    Type type = GetAppModelType(dataType.AppLogic.ClassRef);

                    DataElement createdDataElement = await _dataService.InsertFormData(instance, dataType.Id, data, type);

                    instance.Data.Add(createdDataElement);

                    _logger.LogInformation($"Created data element: {createdDataElement.Id}");
                }
            }
        }
        public async Task <ActionResult> Post([FromQuery] string dataType)
        {
            if (string.IsNullOrEmpty(dataType))
            {
                return(BadRequest($"Invalid dataType {dataType} provided. Please provide a valid dataType as query parameter."));
            }

            string classRef = _appResourcesService.GetClassRefForLogicDataType(dataType);

            if (string.IsNullOrEmpty(classRef))
            {
                return(BadRequest($"Invalid dataType {dataType} provided. Please provide a valid dataType as query parameter."));
            }

            object appModel = _altinnApp.CreateNewAppModel(classRef);

            int?partyId = HttpContext.User.GetPartyIdAsInt();

            if (partyId.HasValue)
            {
                // runs prefill from repo configuration if config exists
                await _prefillService.PrefillDataModel(partyId.ToString(), dataType, appModel);
            }

            await _altinnApp.RunCalculation(appModel);

            return(Ok(appModel));
        }
Beispiel #4
0
        private async Task StorePrefillParts(Instance instance, Application appInfo, List <RequestPart> parts)
        {
            Guid   instanceGuid         = Guid.Parse(instance.Id.Split("/")[1]);
            int    instanceOwnerIdAsInt = int.Parse(instance.InstanceOwner.PartyId);
            string org = instance.Org;
            string app = instance.AppId.Split("/")[1];

            foreach (RequestPart part in parts)
            {
                DataType dataType = appInfo.DataTypes.Find(d => d.Id == part.Name);

                DataElement dataElement;
                if (dataType.AppLogic != null)
                {
                    _logger.LogInformation($"Storing part {part.Name}");

                    Type type;
                    try
                    {
                        type = _altinnApp.GetAppModelType(dataType.AppLogic.ClassRef);
                    }
                    catch (Exception altinnAppException)
                    {
                        throw new ServiceException(HttpStatusCode.InternalServerError, $"App.GetAppModelType failed: {altinnAppException.Message}", altinnAppException);
                    }

                    ModelDeserializer deserializer = new ModelDeserializer(_logger, type);
                    object            data         = await deserializer.DeserializeAsync(part.Stream, part.ContentType);

                    if (!string.IsNullOrEmpty(deserializer.Error))
                    {
                        throw new InvalidOperationException(deserializer.Error);
                    }

                    await _prefillService.PrefillDataModel(instance.InstanceOwner.PartyId, part.Name, data);

                    await _altinnApp.RunDataCreation(instance, data);

                    dataElement = await _dataService.InsertFormData(
                        data,
                        instanceGuid,
                        type,
                        org,
                        app,
                        instanceOwnerIdAsInt,
                        part.Name);
                }
                else
                {
                    dataElement = await _dataService.InsertBinaryData(instance.Id, part.Name, part.ContentType, part.FileName, part.Stream);
                }

                if (dataElement == null)
                {
                    throw new ServiceException(HttpStatusCode.InternalServerError, $"Data service did not return a valid instance metadata when attempt to store data element {part.Name}");
                }
            }
        }
Beispiel #5
0
        private async Task <ActionResult> CreateAppModelData(
            string org,
            string app,
            Instance instance,
            string dataType)
        {
            Guid instanceGuid = Guid.Parse(instance.Id.Split("/")[1]);

            object appModel;

            string classRef = _appResourcesService.GetClassRefForLogicDataType(dataType);

            if (Request.ContentType == null)
            {
                appModel = _altinnApp.CreateNewAppModel(classRef);
            }
            else
            {
                ModelDeserializer deserializer = new ModelDeserializer(_logger, _altinnApp.GetAppModelType(classRef));
                appModel = await deserializer.DeserializeAsync(Request.Body, Request.ContentType);

                if (!string.IsNullOrEmpty(deserializer.Error))
                {
                    return(BadRequest(deserializer.Error));
                }
            }

            // runs prefill from repo configuration if config exists
            await _prefillService.PrefillDataModel(instance.InstanceOwner.PartyId, dataType, appModel);

            // send events to trigger application business logic
            await _altinnApp.RunDataCreation(instance, appModel);

            Dictionary <string, string> updatedValues =
                DataHelper.GetUpdatedDataValues(
                    _appResourcesService.GetApplication().PresentationFields,
                    instance.PresentationTexts,
                    dataType,
                    appModel);

            if (updatedValues.Count > 0)
            {
                await _instanceService.UpdatePresentationTexts(
                    int.Parse(instance.InstanceOwner.PartyId),
                    Guid.Parse(instance.Id.Split("/")[1]),
                    new PresentationTexts { Texts = updatedValues });
            }

            int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId);

            DataElement dataElement = await _dataService.InsertFormData(appModel, instanceGuid, _altinnApp.GetAppModelType(classRef), org, app, instanceOwnerPartyId, dataType);

            SelfLinkHelper.SetDataAppSelfLinks(instanceOwnerPartyId, instanceGuid, dataElement, Request);

            return(Created(dataElement.SelfLinks.Apps, dataElement));
        }
Beispiel #6
0
        /// <inheritdoc />
        public async Task OnStartProcessTask(string taskId, Instance instance)
        {
            _logger.LogInformation($"OnStartProcessTask for {instance.Id}");

            foreach (DataType dataType in _appMetadata.DataTypes.Where(dt => dt.TaskId == taskId && dt.AppLogic?.AutoCreate == true))
            {
                _logger.LogInformation($"Auto create data element: {dataType.Id}");

                DataElement dataElement = instance.Data.Find(d => d.DataType == dataType.Id);

                if (dataElement == null)
                {
                    dynamic data = CreateNewAppModel(dataType.AppLogic.ClassRef);

                    // runs prefill from repo configuration if config exists
                    await _prefillService.PrefillDataModel(instance.InstanceOwner.PartyId, dataType.Id, data);
                    await RunDataCreation(instance, data);

                    Type type = GetAppModelType(dataType.AppLogic.ClassRef);

                    DataElement createdDataElement = await _dataService.InsertFormData(instance, dataType.Id, data, type);

                    instance.Data.Add(createdDataElement);

                    Dictionary <string, string> updatedValues =
                        DataHelper.GetUpdatedDataValues(_appMetadata.PresentationFields, instance.PresentationTexts, dataType.Id, data);

                    if (updatedValues.Count > 0)
                    {
                        Instance updatedInstance = await _instanceService.UpdatePresentationTexts(
                            int.Parse(instance.Id.Split("/")[0]),
                            Guid.Parse(instance.Id.Split("/")[1]),
                            new PresentationTexts { Texts = updatedValues });

                        instance.PresentationTexts = updatedInstance.PresentationTexts;
                    }

                    _logger.LogInformation($"Created data element: {createdDataElement.Id}");
                }
            }
        }
Beispiel #7
0
        public async Task <dynamic> InstantiateApp(StartServiceModel startServiceModel)
        {
            // Dependency Injection: Getting the Service Specific Implementation based on the app parameter data store
            // Will compile code and load DLL in to memory for AltinnCore
            bool startService = true;
            IServiceImplementation serviceImplementation = _execution.GetServiceImplementation(startServiceModel.Org, startServiceModel.Service, startService);

            // Get the service context containing metadata about the app
            ServiceContext serviceContext = _execution.GetServiceContext(startServiceModel.Org, startServiceModel.Service, startService);

            // Create and populate the RequestContext object and make it available for the service implementation so
            // app developer can implement logic based on information about the request and the user performing
            // the request
            RequestContext requestContext = RequestHelper.GetRequestContext(Request.Query, Guid.Empty);

            requestContext.UserContext = await _userHelper.GetUserContext(HttpContext);

            // Populate the reportee information
            requestContext.UserContext.Party = await _register.GetParty(startServiceModel.PartyId);

            requestContext.Party = requestContext.UserContext.Party;

            // Checks if the reportee is allowed to instantiate the application
            Application application = await _application.GetApplication(startServiceModel.Org, startServiceModel.Service);

            if (application == null || (application != null && !InstantiationHelper.IsPartyAllowedToInstantiate(requestContext.UserContext.Party, application.PartyTypesAllowed)))
            {
                return(new StatusCodeResult(403));
            }

            // Create platform service and assign to service implementation making it possible for the service implementation
            // to use platform services. Also make it available in ViewBag so it can be used from Views
            serviceImplementation.SetPlatformServices(_platformSI);

            // Assign the different context information to the service implementation making it possible for
            // the app developer to take use of this information
            serviceImplementation.SetContext(requestContext, serviceContext, null, ModelState);

            object serviceModel = null;

            if (!string.IsNullOrEmpty(startServiceModel.PrefillKey))
            {
                _form.GetPrefill(
                    startServiceModel.Org,
                    startServiceModel.Service,
                    serviceImplementation.GetServiceModelType(),
                    startServiceModel.PartyId,
                    startServiceModel.PrefillKey);
            }

            if (serviceModel == null)
            {
                // If the service model was not loaded from prefill.
                serviceModel = serviceImplementation.CreateNewServiceModel();
            }

            // Assign service model to the implementation
            serviceImplementation.SetServiceModel(serviceModel);

            // Run prefill
            PrefillContext prefillContext = new PrefillContext
            {
                Organization = requestContext.UserContext.Party.Organization,
                Person       = requestContext.UserContext.Party.Person,
                UserId       = requestContext.UserContext.UserId,
                Org          = startServiceModel.Org,
                App          = startServiceModel.Service,
            };
            await _prefill.PrefillDataModel(prefillContext, serviceModel);

            // Run Instansiation event
            await serviceImplementation.RunServiceEvent(ServiceEventType.Instantiation);

            // Run validate Instansiation event where
            await serviceImplementation.RunServiceEvent(ServiceEventType.ValidateInstantiation);

            // If ValidateInstansiation event has not added any errors the new form is saved and user is redirercted to the correct
            if (ModelState.IsValid)
            {
                if (serviceContext.WorkFlow.Any() && serviceContext.WorkFlow[0].StepType.Equals(StepType.Lookup))
                {
                    return(JsonConvert.SerializeObject(
                               new
                    {
                        org = startServiceModel.Org,
                        service = startServiceModel.Service
                    }));
                }

                int instanceOwnerId = requestContext.UserContext.PartyId;

                // Create a new instance document
                Instance instance = await _instance.InstantiateInstance(startServiceModel, serviceModel, serviceImplementation);

                // Create and store the instance created event
                InstanceEvent instanceEvent = new InstanceEvent
                {
                    AuthenticationLevel = requestContext.UserContext.AuthenticationLevel,
                    EventType           = InstanceEventType.Created.ToString(),
                    InstanceId          = instance.Id,
                    InstanceOwnerId     = instanceOwnerId.ToString(),
                    UserId      = requestContext.UserContext.UserId,
                    ProcessInfo = instance.Process,
                };

                Enum.TryParse <WorkflowStep>(instance.Process.CurrentTask.Name, out WorkflowStep currentStep);

                return(JsonConvert.SerializeObject(
                           new
                {
                    instanceId = instance.Id,
                }));
            }

            startServiceModel.PartyList = _authorization.GetPartyList(requestContext.UserContext.UserId)
                                          .Select(x => new SelectListItem
            {
                Text  = (x.PartyTypeName == PartyType.Person) ? x.SSN + " " + x.Name : x.OrgNumber + " " + x.Name,
                Value = x.PartyId.ToString(),
            }).ToList();

            HttpContext.Response.Cookies.Append(_generalSettings.GetAltinnPartyCookieName, startServiceModel.PartyId.ToString());

            return(JsonConvert.SerializeObject(
                       new
            {
                redirectUrl = View(startServiceModel),
            }));
        }