public UserFormAccessList GetAuthorisedForms(SecureSession session, RoleList roleList)
        {
            IEnumerable<string> keys = AssemblyResourceReader.GetResourceKeys();
            string pattern = string.Format("Test_Data.ApplicationPermissions.FORM-([a-z0-9-]*)-USER-{0}", session.AuthenticatedUser.Id);
            Dictionary<string, List<string>> forms = new Dictionary<string, List<string>>();

            foreach (string key in keys)
            {
                Match match = Regex.Match(key, pattern, RegexOptions.IgnoreCase);
                if (!match.Success)
                {
                    continue;
                }

                string content = AssemblyResourceReader.ReadAsString(key);
                string formId = match.Groups[1].Value;

                ApplicationEntitlementList applicationEntitlements = JsonConvert.DeserializeObject<ApplicationEntitlementList>(content);
                foreach (ApplicationEntitlement entitlement in applicationEntitlements)
                {
                    if (entitlement.AccessLevel > AccessLevel.NoAccess)
                    {
                        if (!forms.ContainsKey(formId))
                        {
                            forms.Add(formId, new List<string>());
                        }

                        forms[formId].Add(entitlement.StateName);
                    }
                }
            }

            return new UserFormAccessList(forms.Select(kvp => new UserFormAccess(kvp.Key, kvp.Value.ToList())));
        }
        /// <summary>
        /// Gets the base <see cref="AccessLevel" /> applicable for a combination of user &amp; application.
        /// </summary>
        /// <param name="session">Contains session and user information used to determine access rights.</param>
        /// <param name="application">The application.</param>
        /// <param name="roleList">The list of roles.</param>
        /// <param name="versionNumber">The version number of the form being accessed.</param>
        /// <returns>The base <see cref="AccessLevel" /> applicable for a combination of user &amp; application.</returns>
        public virtual AccessLevel GetApplicationAccess(SecureSession session, Application application, RoleList roleList, int versionNumber)
        {
            if (this.IsAdministrator(session))
            {
                return AccessLevel.Write;
            }

            if (!this.IsOrganisationEntitled(session, application))
            {
                return AccessLevel.NoAccess;
            }

            string userId = this.GetSessionUserId(session);
            bool viewAllDrafts = session.AuthenticatedUser != null && this.GetSystemEntitlements(userId)[SystemEntitlementAccess.VIEW_DRAFT_APPLICATIONS] > AccessLevel.NoAccess;
            if (application.Draft && application.AssignedTo != userId && !viewAllDrafts)
            {
                return AccessLevel.NoAccess;
            }

            var systemEntitlements = this.GetSystemEntitlements(session.AuthenticatedUser != null ? session.AuthenticatedUser.Id : null);

            if (application.Draft && application.AssignedTo != userId && systemEntitlements[SystemEntitlementAccess.VIEW_DRAFT_APPLICATIONS] == AccessLevel.NoAccess)
            {
                return AccessLevel.NoAccess;
            }

            Dictionary<string, string> userRoles = this.DetermineRolesForUser(session, roleList, application);
            ApplicationEntitlementList applicationEntitlements = this.securityService.GetApplicationEntitlements(application.FormId, versionNumber, application.WorkflowState, userRoles.Keys);
            return applicationEntitlements.Any() ? applicationEntitlements.Max(e => e.AccessLevel) : AccessLevel.NoAccess;
        }
        /// <summary>
        /// Gets the base <see cref="AccessLevel" /> applicable for a combination of user &amp; application.
        /// </summary>
        /// <param name="session">Contains session and user information used to determine access rights.</param>
        /// <param name="application">The application.</param>
        /// <param name="roleList">The list of roles.</param>
        /// <param name="versionNumber">The version number of the form being accessed.</param>
        /// <returns>The base <see cref="AccessLevel" /> applicable for a combination of user &amp; application.</returns>
        public AccessLevel GetApplicationAccess(SecureSession session, Application application, RoleList roleList, int versionNumber)
        {
            if (this.ImpersonatedSession != null && string.IsNullOrWhiteSpace(application.Id))
            {
                this.ImpersonateEntitlements(session);
            }

            return this.wrappedProvider.GetApplicationAccess(session, application, roleList, versionNumber);
        }
        /// <summary>
        /// Find all eligible applications and perform system transitions.
        /// </summary>
        /// <param name="session">A secure session.</param>
        public void DoWork(SecureSession session)
        {
            List<SystemTransitionWorkflowStateList> stateTransitionList = this.GetStateTransitions(session);

            foreach (var stateList in stateTransitionList)
            {
                foreach (WorkflowState state in stateList)
                {
                    UnitOfWorkList<ApplicationWorkItem> work = this.FindWork(session, stateList.FormId, state);
                    foreach (UnitOfWork<ApplicationWorkItem> workItem in work)
                    {
                        ApplicationWorkflowItem workflowItem = this.GetWorkflowItem(session, workItem);

                        if (!string.IsNullOrWhiteSpace(workItem.Item.EmailAddress))
                        {
                            workflowItem.UserEmail = workItem.Item.EmailAddress;
                            workflowItem.UserId = workItem.Item.UserId;
                        }
                        else
                        {
                            workflowItem.UserId = session.AuthenticatedUser.Id;
                        }

                        ItemState oldState = new ItemState(workItem.Item.Application.WorkflowState);
                        WorkflowResult result = this.workflowService.Trigger(workflowItem, workItem.Item.Transition, oldState);

                        /*
                        if (workItem.Item.Transition.Trigger == TriggerEvent.EmailLink)
                        {
                            this.MarkWorkflowActionProcessed();
                        }
                        */

                        if (result == null || result.ExitState.Name == oldState.Name)
                        {
                            continue;
                        }

                        this.formServiceGateway.SubmitApplication(session, workItem.Item.Application, result.ExitState.Name, result.ExitAssignee, result.ExitAssigneeType);
                        this.workflowService.LogStateChange(workflowItem, oldState, result.ExitState);
                    }
                }

                /*
                // When paginating...
                work = this.FindWork(session, stateList.FormId, state);
                while (work.Count > 0)
                {

                    // Get more work if available
                    work = this.FindWork(session, stateList.FormId, state);
                }
                */
            }
        }
        /// <summary>
        /// Creates a new application.
        /// </summary>
        /// <param name="session">An authenticated or unauthenticated session that contains the appropriate form id in the token.</param>
        /// <param name="formId">The form id.</param>
        /// <param name="saveApplication">If set to <see langword="true"/>, save the newly created application.</param>
        /// <returns>
        /// The created application.
        /// </returns>
        public Application CreateApplication(SecureSession session, string formId, bool saveApplication = true)
        {
            string responseString = this.AddTokenAndInvoke(session.Token, new Func<string, bool, int?, string>(this.client.CreateApplication), formId, saveApplication, null);

            var template = new
            {
                Success = true,
                application = new Application()
            };

            var returnObj = JsonConvert.DeserializeAnonymousType(responseString, template);
            return returnObj.application;
        }
        public AccessLevel GetApplicationAccess(SecureSession session, Application application, RoleList roleList, int versionNumber)
        {
            string resourceString;
            string userId = session.AuthenticatedUser == null ? string.Empty : session.AuthenticatedUser.Id;
            string formName = string.Format("Test_Data.ApplicationPermissions.FORM-{0}-USER-{1}.json", application.FormId.PadLeft(2, '0'), userId);
            if (AssemblyResourceReader.TryReadAsString(formName, out resourceString))
            {
                var applicationEntitlements = JsonConvert.DeserializeObject<ApplicationEntitlementList>(resourceString);
                applicationEntitlements = new ApplicationEntitlementList(applicationEntitlements.Where(e => e.ProductId == application.FormId && e.ProductVersion == application.FormVersion && e.StateName == application.WorkflowState && roleList.Contains(e.RoleId)));
                return applicationEntitlements.Max(e => e.AccessLevel);
            }

            return AccessLevel.NoAccess;
        }
        public IEnumerable<Application> SearchApplications(SecureSession session, string formId, ApplicationSearchFilter filter, Pagination pagination = null)
        {
            int applicationId = ((MockSecureSession)session).ApplicationId;
            string jsonString = AssemblyResourceReader.ReadAsString(applicationId != 0 ?
                string.Format("Test_Data.Applications.APPLICATION-{0}.json", applicationId) : "Test_Data.Applications.APPLICATION-1.json");
            List<Application> apps = JsonConvert.DeserializeObject<List<Application>>(jsonString);

            if (filter.ApplicationStates != null && filter.ApplicationStates.Count > 0)
            {
                return apps.Where(a => filter.ApplicationStates.Contains(a.WorkflowState)).ToList();
            }

            return apps;
        }
        /// <summary>
        /// Gets the application with an id matching <paramref name="applicationId"/>.
        /// </summary>
        /// <param name="session">An authenticated or unauthenticated session that contains the appropriate form id in the token.</param>
        /// <param name="applicationId">The id of the application to get.</param>
        /// <param name="version">Which version of the application to get. Defaults to <see langword="null"/>.</param>
        /// <returns>The application with an id matching <paramref name="applicationId"/>.</returns>
        public Application GetApplication(SecureSession session, string applicationId, int? version = null)
        {
            string responseString = this.AddTokenAndInvoke(session.Token, new Func<string, int?, string>(this.client.GetApplication), applicationId, version);
            JObject obj = JObject.Parse(responseString);
            JToken applicationToken = obj.SelectToken("application");

            if (applicationToken == null)
            {
                throw new KeyNotFoundException(string.Format(ExceptionMessages.UnknownApplication, applicationId));
            }

            string application = applicationToken.ToString();

            Application returnObj = JsonConvert.DeserializeObject<Application>(application);
            return returnObj;
        }
        public List<ControlAccess> GetControlsAccess(
            SecureSession session,
            Application application,
            ControlList controlList,
            RoleList roleList,
            int versionNumber,
            AccessLevel? defaultAccessLevel = null)
        {
            string resourceString;
            if (AssemblyResourceReader.TryReadAsString(string.Format("Test_Data.ControlPermissions.FORM-{0}-USER-{1}.json", application.FormId.PadLeft(2, '0'), session.AuthenticatedUser.Id), out resourceString))
            {
                var entitlements = JsonConvert.DeserializeObject<ControlEntitlementList>(resourceString);
                entitlements.Merge();
                return new List<ControlAccess>(entitlements.Select(e => new ControlAccess(e.ControlId, e.AccessLevel)));
            }

            return new List<ControlAccess>();
        }
 public Application CreateApplication(SecureSession session, string formId, bool saveApplication = true)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Validates the user is entitled to access the application.
        /// </summary>
        /// <param name="sessionData">The <see cref="SessionData"/> containing the application id.</param>
        /// <param name="applicationId">The application id.</param>
        /// <param name="controlName">The name of the attachment control.</param>
        /// <param name="minimumControlAccess">The minimum control access to check for.</param>
        /// <returns><see langword="true"/> if the user can access the application.</returns>
        /// <exception cref="SecurityException">The user is not authorized to access the application/control.</exception>
        private bool CanAccessControl(SessionData sessionData, string applicationId, string controlName, AccessLevel minimumControlAccess)
        {
            if (string.IsNullOrEmpty(applicationId))
            {
                throw new NullReferenceException();
            }

            User user = this.DataAccess.GetUserById(sessionData.UserId);
            if (user != null && user.IsAdministrator())
            {
                return true;
            }

            SecureSession secureSession = new SecureSession(sessionData.DeserializationSource, sessionData.SessionId, user);

            RetrieveApplicationResponse response = this.applicationManager.GetApplicationSecure(sessionData, applicationId);
            ControlList controlList = new ControlList() { response.Product.FormDefinition.Pages.AllControls.FindRecursive(c => c.Name == controlName) };
            ControlAccess controlsAccess = this.entitlementProvider.GetControlsAccess(secureSession, response.Application, controlList, this.DataAccess.GetRoleList(), response.Product.Version).First();

            // Will throw exception if there is an invalid access request.
            if (controlsAccess.AccessLevel < minimumControlAccess)
            {
                throw new SecurityException();
            }

            return true;
        }
 public List<MetadataControlAccess> GetMetadataControlsAccess(
     SecureSession session,
     Application application,
     MetadataControlList metadataControlsList,
     RoleList roleList,
     int versionNumber,
     AccessLevel? defaultAccessLevel = null)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Gets a list of forms the user is authorised for and in what states.
        /// </summary>
        /// <param name="session">Contains session and user information used to determine access rights.</param>
        /// <param name="roleList">The list of roles.</param>
        /// <returns>A list of forms the user is authorised for and in what states, serialized as JSON.</returns>
        /// <remarks>
        /// A user is deemed to be authorised for a form if they have <see cref="AccessLevel.Read"/> access or greater
        /// to the form in at least one state.
        /// </remarks>
        public virtual UserFormAccessList GetAuthorisedForms(SecureSession session, RoleList roleList)
        {
            session = session ?? new SecureSession();

            var organisationIds = session.AuthenticatedUser == null ? new string[0] : session.AuthenticatedUser.Organisations.Select(o => o.Key).ToArray();

            Dictionary<string, string> roles = this.DetermineRolesForUser(session, roleList);

            var applicationEntitlements = this.securityService.GetApplicationEntitlements(organisationIds, null).GroupBy(e => new { e.ProductId, e.ProductVersion });

            if (this.IsAdministrator(session))
            {
                UserFormAccessList returnList = new UserFormAccessList();

                foreach (var entitlement in applicationEntitlements)
                {
                   List<string> allStates = entitlement.Select(e => e.StateName).Distinct().ToList();
                   returnList.Add(new UserFormAccess(entitlement.Key.ProductId, allStates));
                }

                return returnList;
            }

            UserFormAccessList formAccessList = new UserFormAccessList();

            string originatorRoleId = roleList.FirstOrDefault(r => r.RoleName == SecurityConstants.OriginatorRoleName && r.SystemDefined).Id;
            string assigneeRoleId = roleList.FirstOrDefault(r => r.RoleName == SecurityConstants.AssigneeRoleName && r.SystemDefined).Id;

            foreach (var entitlements in applicationEntitlements)
            {
                List<string> explicitStates = entitlements.Where(e => roles.ContainsKey(e.RoleId) && e.AccessLevel > AccessLevel.NoAccess)
                    .Select(e => e.StateName).ToList();

                List<string> ownedStates = new List<string>();
                List<string> originatorStates = new List<string>();

                if (session.AuthenticatedUser != null)
                {
                    ownedStates = entitlements.Where(e => e.RoleId == assigneeRoleId && e.AccessLevel > AccessLevel.NoAccess).Select(e => e.StateName).ToList();
                    originatorStates = entitlements.Where(e => e.RoleId == originatorRoleId && e.AccessLevel > AccessLevel.NoAccess).Select(e => e.StateName).ToList();
                }

                if (explicitStates.Count > 0 || ownedStates.Count > 0 || originatorStates.Count > 0)
                {
                    Dictionary<string, List<string>> implicitStates = new Dictionary<string, List<string>>
                    {
                        { SecurityConstants.AssigneeRoleName, ownedStates },
                        { SecurityConstants.OriginatorRoleName, originatorStates }
                    };

                    formAccessList.Add(new UserFormAccess(entitlements.Key.ProductId, explicitStates, implicitStates));
                }
            }

            return formAccessList;
        }
 public ProductList<ProductSearchResult> GetProductList(SecureSession session)
 {
     IEnumerable<string> workflowJson = AssemblyResourceReader.ReadAllAsString(key => key.StartsWith("Test_Data.Products"));
     string jsonArray = string.Format("[{0}]", string.Join(",", workflowJson));
     return JsonConvert.DeserializeObject<ProductList<ProductSearchResult>>(jsonArray);
 }
 /// <summary>
 /// Gets the page entitlements that the user has.
 /// </summary>
 /// <param name="session">The session.</param>
 /// <param name="application">The application the user is trying to access.</param>
 /// <param name="pageList">The page list.</param>
 /// <param name="roleList">The list of roles.</param>
 /// <param name="versionNumber">The version number.</param>
 /// <param name="defaultAccessLevel">The default access level to use when there is no entitlement for a page. If not set it will default to the application base access level.</param>
 /// <returns>
 /// The page entitlements that the user has.
 /// </returns>
 public virtual List<PageAccess> GetPagesAccess(SecureSession session, Application application, PageList pageList, RoleList roleList, int versionNumber, AccessLevel? defaultAccessLevel = null)
 {
     return this.GetPagesAccess(session, application, pageList.Select(p => p.PageId), roleList, versionNumber, defaultAccessLevel);
 }
 /// <summary>
 /// Returns the string that should be used to identify the user.
 /// </summary>
 /// <param name="session">The user session.</param>
 /// <returns>The string that should be used to identify the user.</returns>
 /// <remarks>
 /// If the user session contains an authenticated user, the user id
 /// is returned, otherwise the unique session token is returned.
 /// </remarks>
 private string GetSessionUserId(SecureSession session)
 {
     return session.AuthenticatedUser == null ? session.SessionId : session.AuthenticatedUser.Id;
 }
        /// <summary>
        /// Gets the product with an id matching <paramref name="formId"/>.
        /// </summary>
        /// <param name="session">An authenticated or unauthenticated session that contains the appropriate organisation id in the token.</param>
        /// <param name="formId">The form id to get.</param>
        /// <param name="versionNumber">The version number to retrieve. If <see langword="null"/> the most recent version is returned.</param>
        /// <param name="applicationId">The application id.</param>
        /// <param name="validateApplicationId">A flag indicating if the applicaiton Id needs to be validated.</param>
        /// <returns>The product with an id matching <paramref name="formId"/>.</returns>
        public ProductDefinition GetProduct(SecureSession session, string formId, int? versionNumber, string applicationId = null, bool? validateApplicationId = false)
        {
            string responseString = this.AddTokenAndInvoke(session.Token, new Func<string, int?, int?, string, bool?, string>(this.client.GetProduct), formId, null, versionNumber, applicationId, validateApplicationId);
            JObject obj = JObject.Parse(responseString);

            string success = obj.SelectToken("Success").ToString();
            if (success == "False")
            {
                string message = obj.SelectToken("Message").ToString();
                throw new FormServiceException(message);
            }

            string productStr = obj.SelectToken("metadata").ToString();
            ProductDefinition product = JsonConvert.DeserializeObject<ProductDefinition>(productStr);
            return product;
        }
        /// <summary>
        /// Submits the application.
        /// </summary>
        /// <param name="session">An authenticated or unauthenticated session that contains the appropriate form id in the token.</param>
        /// <param name="application">The application to submit.</param>
        /// <param name="workflowState">The requested workflow state to move to.</param>
        /// <param name="assignee">The workflow assignee after moving to <paramref name="workflowState"/>.</param>
        /// <param name="assigneeType">The workflow assignee type.</param>
        /// <param name="submitPageId">The submit page id.</param>
        /// <returns>The submitted application.</returns>
        public Application SubmitApplication(SecureSession session, Application application, string workflowState, string assignee = null, ComparisonType? assigneeType = null, int? submitPageId = null)
        {
            string formId = application.FormId;
            string applicationId = application.ApplicationId;
            string applicationDataJson = JsonConvert.SerializeObject(application.ApplicationData);

            var metadata = new
            {
                requestedState = workflowState,
                assignee,
                assigneeType
            };

            string metadataJson = JsonConvert.SerializeObject(metadata);
            string responseString = this.AddTokenAndInvoke(session.Token, new Func<string, string, string, string, int?, string>(this.client.SubmitApplication), formId, applicationId, applicationDataJson, metadataJson, submitPageId);

            var template = new
            {
                success = true,
                valid = true,
                errors = new Dictionary<string, List<string>>(),
                application = new Application()
            };

            var responseObj = JsonConvert.DeserializeAnonymousType(responseString, template);

            if (!responseObj.valid)
            {
                throw new SubmitValidationException(responseObj.errors);
            }

            return responseObj.application;
        }
        /// <summary>
        /// Returns <see langword="true"/> if default application access should be overridden,
        /// for example if the user is an Administrator or a Service account, otherwise returns
        /// <see langword="false"/>.
        /// </summary>
        /// <param name="session">The user session.</param>
        /// <returns>
        /// <see langword="true"/> if default application access should be overridden,
        /// for example if the user is an Administrator or a Service account, otherwise returns
        /// <see langword="false"/>.
        /// </returns>
        private bool IsAdministrator(SecureSession session)
        {
            if (session == null || session.AuthenticatedUser == null)
            {
                return false;
            }

            return session.AuthenticatedUser.IsAdministrator();
        }
        /// <summary>
        /// Retrieve a list of applications based on the search criteria.
        /// </summary>
        /// <param name="session">An authenticated or unauthenticated session that contains the appropriate form id in the token.</param>
        /// <param name="formId">The form id.</param>
        /// <param name="filter">The search filter, serialised as JSON.</param>
        /// <param name="pagination">The paging information, serialised as JSON.</param>
        /// <returns>A list of applications based on the search criteria.</returns>
        public IEnumerable<Application> SearchApplications(SecureSession session, string formId, ApplicationSearchFilter filter, Pagination pagination = null)
        {
            string filterJson = JsonConvert.SerializeObject(filter);
            string paginationJson = pagination == null ? null : JsonConvert.SerializeObject(pagination);
            string responseString = this.AddTokenAndInvoke(session.Token, new Func<string, string, string, string>(this.client.FindApplications), formId, filterJson, paginationJson);

            var template = new
            {
                success = true,
                applications = new Application[0],
                pagination = new Pagination()
            };

            var responseObj = JsonConvert.DeserializeAnonymousType(responseString, template);
            return responseObj.applications;
        }
        /// <summary>
        /// Saves the application.
        /// </summary>
        /// <param name="session">An authenticated or unauthenticated session that contains the appropriate form id in the token.</param>
        /// <param name="application">The application to save.</param>
        /// <returns>The saved application.</returns>
        public Application SaveApplication(SecureSession session, Application application)
        {
            string formId = application.FormId;
            string applicationId = application.ApplicationId;
            string applicationDataJson = JsonConvert.SerializeObject(application.ApplicationData);

            string responseString = this.AddTokenAndInvoke(session.Token, new Func<string, string, string, bool, bool, string>(this.client.SaveApplication), formId, applicationId, applicationDataJson, false, false);

            var template = new
            {
                success = true,
                application = new Application()
            };

            var returnObj = JsonConvert.DeserializeAnonymousType(responseString, template);
            return returnObj.application;
        }
        /// <summary>
        /// Gets the list of forms.
        /// </summary>
        /// <param name="session">An authenticated or unauthenticated session that contains the appropriate organisation id in the token.</param>
        /// <returns>The list of forms.</returns>
        public ProductList<ProductSearchResult> GetProductList(SecureSession session)
        {
            string responseString = this.AddTokenAndInvoke(session.Token, new Func<string>(this.client.GetProductList));

            var template = new
            {
                response = new
                {
                    Success = true,
                    Products = new ProductList<ProductSearchResult>()
                }
            };

            var responseObj = JsonConvert.DeserializeAnonymousType(responseString, template);
            return responseObj.response.Products;
        }
 public Application GetApplication(SecureSession session, string applicationId, int? version = null)
 {
     throw new NotImplementedException();
 }
 public List<PageAccess> GetPagesAccess(
     SecureSession session,
     Application application,
     IEnumerable<int> pageIds,
     RoleList roleList,
     int versionNumber,
     AccessLevel? defaultAccessLevel = null)
 {
     throw new NotImplementedException();
 }
 public ProductDefinition GetProduct(SecureSession session, string formId, int? versionNumber, string applicationId = null, bool? validateApplicatiobnId = false)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Determines the applicable roles for <paramref name="session"/>.
        /// </summary>
        /// <param name="session">Contains session and user information used to determine access rights.</param>
        /// <param name="roleList">The list of roles.</param>
        /// <param name="application">The application, if relevant Defaults to <see langword="null"/>.</param>
        /// <returns>The applicable roles for <paramref name="session"/>.</returns>
        private Dictionary<string, string> DetermineRolesForUser(SecureSession session, RoleList roleList, Application application = null)
        {
            session = session ?? new SecureSession();
            application = application ?? new Application();
            Role publicRole = roleList.FirstOrDefault(r => r.SystemDefined && r.RoleName == SecurityConstants.PublicRoleName);
            Dictionary<string, string> roleDict = publicRole == null ? new Dictionary<string, string>() : new Dictionary<string, string> { { publicRole.Id, publicRole.RoleName } };

            string compareTo = this.GetSessionUserId(session);
            if (application.IsCreatedBy(compareTo))
            {
                Role originatorRole = roleList.FirstOrDefault(r => r.SystemDefined && r.RoleName == SecurityConstants.OriginatorRoleName);
                if (originatorRole != null)
                {
                    roleDict.Add(originatorRole.Id, originatorRole.RoleName);
                }
            }

            if (session.AuthenticatedUser == null)
            {
                return roleDict;
            }

            if (session.AuthenticatedUser.IsAdministrator())
            {
                foreach (var role in roleList)
                {
                    if (roleDict.ContainsKey(role.Id))
                    {
                        continue;
                    }

                    roleDict.Add(role.Id, role.RoleName);
                }

                return roleDict;
            }

            foreach (var userRole in session.AuthenticatedUser.Roles)
            {
                if (roleList.Exists(role => role.Id == userRole.Key && role.Enabled))
                {
                    roleDict.Add(userRole.Key, userRole.Value);
                }
            }

            if (!string.IsNullOrEmpty(application.AssignedTo) && session.AuthenticatedUser.Id == application.AssignedTo)
            {
                Role assigneeRole = roleList.FirstOrDefault(r => r.SystemDefined && r.RoleName == SecurityConstants.AssigneeRoleName);
                if (assigneeRole != null)
                {
                    roleDict.Add(assigneeRole.Id, assigneeRole.RoleName);
                }
            }

            return roleDict;
        }
 public Application SaveApplication(SecureSession session, Application application)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Gets the page access level for each page in <paramref name="pageIds"/>.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="application">The application the user is trying to access.</param>
        /// <param name="pageIds">The page IDs list.</param>
        /// <param name="roleList">The list of roles.</param>
        /// <param name="versionNumber">The version number.</param>
        /// <param name="defaultAccessLevel">The default access level to use when there is no entitlement for a page. If not set it will default to the application base access level.</param>
        /// <returns>The page entitlements that the user has.</returns>
        public List<PageAccess> GetPagesAccess(SecureSession session, Application application, IEnumerable<int> pageIds, RoleList roleList, int versionNumber, AccessLevel? defaultAccessLevel = null)
        {
            var userRoles = this.DetermineRolesForUser(session, roleList, application);
            var pageEntitlements = this.securityService.GetPageEntitlements(application.FormId, versionNumber, application.WorkflowState, userRoles.Keys);
            pageEntitlements.Merge();

            if (session.AuthenticatedUser.IsAdministrator())
            {
                return pageIds.Select(pageId => new PageAccess(pageId, AccessLevel.Read)).ToList();
            }

            if (!defaultAccessLevel.HasValue)
            {
                defaultAccessLevel = this.GetApplicationAccess(session, application, roleList, versionNumber);
            }

            return pageIds.Select(
                pageId =>
                {
                    var entitlement = pageEntitlements.FirstOrDefault(e => e.PageId == pageId);
                    if (entitlement == null)
                    {
                        return new PageAccess(pageId, defaultAccessLevel.Value);
                    }

                    return new PageAccess(pageId, entitlement.AccessLevel);
                }).ToList();
        }
 public Application SubmitApplication(SecureSession session, Application application, string workflowState, string assignee = null, ComparisonType? assigneeType = null, int? submitPageId = null)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Returns <see langword="true"/> if the user / session has the correct organisation
        /// entitlements to view <paramref name="application"/>, otherwise returns
        /// <see langword="false"/>.
        /// </summary>
        /// <param name="session">The user session.</param>
        /// <param name="application">The application.</param>
        /// <returns>
        /// <see langword="true"/> if the user / session has the correct organisation
        /// entitlements to view <paramref name="application"/>, otherwise <see langword="false"/>.
        /// </returns>
        private bool IsOrganisationEntitled(SecureSession session, Application application)
        {
            if (session == null || session.AuthenticatedUser == null)
            {
                // Have to assume public users are entitled to all orgs.
                return true;
            }

            if (session.AuthenticatedUser != null && session.AuthenticatedUser.AccountType == AccountType.Service)
            {
                return true;
            }

            // Ignore org entitlements for originator and assignee.
            string compareTo = this.GetSessionUserId(session);
            if (application.IsCreatedBy(compareTo) || application.IsAssignedTo(compareTo))
            {
                return true;
            }

            return !string.IsNullOrEmpty(application.OrganisationId) && session.AuthenticatedUser.GetAllOrganisations().ContainsKey(application.OrganisationId);
        }