public async Task <ActionResult> FetchPermissions(string roleId, string roleName)
        {
            var model = GetPageData();
            var ownerPermissionsresponse = await _bosIAClient.GetOwnerPermissionsSetsAsFlatAsync <PermissionsModule>(Guid.Parse(roleId));

            List <Module>                allModules          = new List <Module>();
            List <Operation>             allOperations       = new List <Operation>();
            List <IPermissionsOperation> permittedOperations = new List <IPermissionsOperation>();
            List <IPermissionsSet>       permittedModules    = new List <IPermissionsSet>();

            if (ownerPermissionsresponse.IsSuccessStatusCode)
            {
                permittedModules    = ownerPermissionsresponse.Permissions.Modules;
                permittedOperations = ownerPermissionsresponse.Permissions.Operations;
            }

            var modulesResponse = await _bosIAClient.GetModulesAsync <Module>(true, true);

            if (modulesResponse.IsSuccessStatusCode)
            {
                allModules = modulesResponse.Modules;
            }

            var operationsResponse = await _bosIAClient.GetOperationsAsync <Operation>(true, true);

            if (operationsResponse.IsSuccessStatusCode)
            {
                allOperations = operationsResponse.Operations;
            }

            foreach (PermissionsSet module in permittedModules)
            {
                var moduleObj = allModules.FirstOrDefault(x => x.Id == module.ModuleId);

                if (moduleObj != null)
                {
                    moduleObj.IsPermitted = true;
                    if (moduleObj.Operations.Count > 0)
                    {
                        foreach (Operation operation in moduleObj.Operations)
                        {
                            var operationObj = permittedOperations.FirstOrDefault(x => x.OperationId == operation.Id);
                            if (operationObj != null)
                            {
                                operation.IsPermitted = true;
                            }
                        }
                    }
                }
            }

            model.ModuleOperations = allModules;
            model.OwnerId          = roleId;
            model.RoleName         = roleName;
            return(View("Index", model));
        }
Beispiel #2
0
        /// <summary>
        /// Author: BOS Framework, Inc
        /// Description: Triggers when the Login button is clicked
        /// </summary>
        /// <param name="authObj"></param>
        /// <returns></returns>
        public async Task <ActionResult> AuthenticateUser(AuthModel authObj)
        {
            if (authObj != null)
            {
                var result = await _bosAuthClient.SignInAsync(authObj.Username, authObj.Password);

                if (result.IsVerified)
                {
                    var userRoles = await _bosAuthClient.GetUserByIdWithRolesAsync <User>(result.UserId.Value);

                    var user  = userRoles.User;
                    var roles = user.Roles;

                    // Convert Roles Array into a comma separated string containing roles
                    string rolesString = string.Empty;
                    if (roles != null && roles.Count > 0)
                    {
                        foreach (UserRole userRole in roles)
                        {
                            RoleUser role = userRole.Role;
                            rolesString = (!string.IsNullOrEmpty(rolesString)) ? (rolesString + "," + role.Name) : (role.Name);
                        }
                    }

                    //Create Claim Identity.
                    var claims = new List <Claim> {
                        new Claim("CreatedOn", DateTime.UtcNow.ToString()),
                        new Claim("Email", user.Email),
                        new Claim("Role", rolesString),
                        new Claim("UserId", user.Id.ToString()),
                        new Claim("Username", user.Username.ToString()),
                        new Claim("IsAuthenticated", "True")
                    };
                    var             userIdentity = new ClaimsIdentity(claims, "Auth");
                    ClaimsPrincipal principal    = new ClaimsPrincipal(userIdentity);

                    //Sign In created claims Identity Principal with cookie Authentication scheme
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties
                    {
                        ExpiresUtc   = DateTime.UtcNow.AddMinutes(3000),
                        IsPersistent = false,
                        AllowRefresh = false
                    });

                    //Getting the permissions
                    //var permissionSet = await _bosIAClient.GetOwnersPermissionsAsync<PermissionsList>(result.UserId.Value.ToString());
                    var permissionSet = await _bosIAClient.GetOwnerPermissionsSetsAsFlatAsync <PermissionsModule>(result.UserId.Value);

                    if (permissionSet.IsSuccessStatusCode)
                    {
                        //Set Permissions in Sessions
                        HttpContext.Session.SetObject("Modules", permissionSet.Permissions.Modules);
                        HttpContext.Session.SetObject("Operations", permissionSet.Permissions.Operations);
                    }

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("CustomError", "Username or password is incorrect");
                    return(View("Index", new AuthModel()));
                }
            }
            else
            {
                return(View("Index", new AuthModel()));
            }
        }
        /// <summary>
        /// Author: BOS Framework, Inc
        /// Description: Returns the view that displays all the modules and operations that are associated with the given role, together with the complete list of modules and operations
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="roleName"></param>
        /// <returns></returns>
        public async Task <ActionResult> FetchPermissions(string roleId, string roleName)
        {
            try
            {
                var model = GetPageData(); //This mehod returns all the data that is required for loading the page
                if (model == null)
                {
                    model = new ExpandoObject(); //If the model object is null, we create a new dynamic object
                }

                /* ------------- LOGIC -------------
                 * Get the roleId and verify if it is non-null or non-empty
                 * Make a call to the BOS API to get the list of all the Modules and Operations that the role is permitted
                 * Get the absolute list of all the modules and permissions in the application
                 * Loop through the permitted modules and operations and set the 'IsPermitted' property to true. Based on this property the View is displayed
                 */
                if (!string.IsNullOrWhiteSpace(roleId))                                                                                           //Checking for non-null roleId. This is the for which the permissions are set
                {
                    var ownerPermissionsresponse = await _bosIAClient.GetOwnerPermissionsSetsAsFlatAsync <PermissionsModule>(Guid.Parse(roleId)); //Making a BOS API call to get the permitted list of modules and operations. GetOwnerPermissionsSetsAsFlatAsync endpoint is called becasue it is easier to iterate through a non-nested list

                    if (ownerPermissionsresponse != null && ownerPermissionsresponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        return(RedirectToAction("SignOut", "Auth"));//Token Expired
                    }
                    //Declaring a few vairables that will help to get to the required output - i.e. a single list of all modules and operations (which is nested) but has a differentiating attribute of 'IsPermitted'
                    List <Module>                allModules          = new List <Module>();
                    List <Operation>             allOperations       = new List <Operation>();
                    List <IPermissionsOperation> permittedOperations = new List <IPermissionsOperation>();
                    List <IPermissionsSet>       permittedModules    = new List <IPermissionsSet>();

                    if (ownerPermissionsresponse != null && ownerPermissionsresponse.IsSuccessStatusCode)
                    {
                        permittedModules    = ownerPermissionsresponse.Permissions.Components; //Assiging the BOS API response of flat-listed modules to the variable
                        permittedOperations = ownerPermissionsresponse.Permissions.Operations; //Assiging the BOS API response of flat-listed operations to the variable
                    }

                    var modulesResponse = await _bosIAClient.GetModulesAsync <Module>(true, true); //Making another BOS API call to get the complete list of Modules in the application

                    if (modulesResponse != null && modulesResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        return(RedirectToAction("SignOut", "Auth"));//Token Expired
                    }
                    if (modulesResponse != null && modulesResponse.IsSuccessStatusCode)
                    {
                        allModules = modulesResponse.Modules; //Assiging the BOS API response of complete list of nested modules to the variable
                    }

                    var operationsResponse = await _bosIAClient.GetOperationsAsync <Operation>(true, true); // Making another BOS API call to get the complete list of Operations in the application

                    if (operationsResponse != null && operationsResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        return(RedirectToAction("SignOut", "Auth"));//Token Expired
                    }
                    if (operationsResponse != null && operationsResponse.IsSuccessStatusCode)
                    {
                        allOperations = operationsResponse.Operations;  //Assiging the BOS API response of complete list of nested operations to the variable
                    }

                    //Iterating through the permitted list of modules and finding it in the other complete list of modules to set the 'IsPermitted' property to True
                    foreach (PermissionsSet module in permittedModules)
                    {
                        var moduleObj = allModules.Where(x => x.Id == module.ComponentId).FirstOrDefault(); //However, this works only at level-0, in the nested list, so we have a few custom methods that help us iterate through the N-Level down nested list

                        if (moduleObj != null)
                        {
                            moduleObj.IsPermitted = true; //If the permitted moduleId is found in the list of all the Modules, we set its "IsPermitted" property to True

                            //We repeat the process for Operations
                            if (moduleObj.Operations.Count > 0)
                            {
                                foreach (Operation operation in moduleObj.Operations)
                                {
                                    var operationObj = permittedOperations.FirstOrDefault(x => x.OperationId == operation.Id);
                                    if (operationObj != null)
                                    {
                                        operation.IsPermitted = true; //If the permitted OperationId is found in the list of all the Operations, we set its "IsPermitted" property to True
                                    }
                                    else
                                    {
                                        if (operation.ChildOperations != null && operation.ChildOperations.Count > 0)
                                        {
                                            var operationsList = operation.ChildOperations;
                                            SetPermittedSubOperations(operation.Id, ref operationsList, ref permittedOperations);
                                        }
                                    }
                                    if (operation.ChildOperations != null && operation.ChildOperations.Count > 0)
                                    {
                                        var operationsList = operation.ChildOperations;
                                        SetPermittedSubOperations(operation.Id, ref operationsList, ref permittedOperations);
                                    }
                                }
                            }
                        }
                        else
                        {
                            //If it is not found, then we go to the next level of the nested list
                            SetPermittedSubModules(module.ComponentId, ref allModules, ref permittedOperations);
                        }
                    }
                    List <Module> myModuleList = allModules[0].ChildComponents.ConvertAll(o => (Module)o);
                    model.ModuleOperations = myModuleList;  //Finally, assigning the updated "allModules" nested-list to the model
                    model.OwnerId          = roleId;
                    model.RoleName         = roleName;
                    return(View("Index", model)); //Returing to the View with the sufficient data to render the page
                }
                else
                {
                    ModelState.AddModelError("CustomError", "The selected role does not have a verified Id. Please try again.");
                    return(View("Index", model));
                }
            }
            catch (Exception ex)
            {
                Logger.LogException("Permissions", "FetchPermissions", ex);

                dynamic model = new ExpandoObject();
                model.Message    = ex.Message;
                model.StackTrace = ex.StackTrace;
                return(View("ErrorPage", model));
            }
        }
Beispiel #4
0
        /// <summary>
        /// Author: BOS Framework, Inc
        /// Description: Returns the view that displays all the modules and operations that are associated with the given role
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="roleName"></param>
        /// <returns></returns>
        public async Task <ActionResult> FetchPermissions(string roleId, string roleName)
        {
            try
            {
                var model = GetPageData();
                if (model == null)
                {
                    model = new ExpandoObject();
                }

                if (!string.IsNullOrWhiteSpace(roleId))
                {
                    var ownerPermissionsresponse = await _bosIAClient.GetOwnerPermissionsSetsAsFlatAsync <PermissionsModule>(Guid.Parse(roleId));

                    List <Module>                allModules          = new List <Module>();
                    List <Operation>             allOperations       = new List <Operation>();
                    List <IPermissionsOperation> permittedOperations = new List <IPermissionsOperation>();
                    List <IPermissionsSet>       permittedModules    = new List <IPermissionsSet>();

                    if (ownerPermissionsresponse != null && ownerPermissionsresponse.IsSuccessStatusCode)
                    {
                        permittedModules    = ownerPermissionsresponse.Permissions.Modules;
                        permittedOperations = ownerPermissionsresponse.Permissions.Operations;
                    }

                    var modulesResponse = await _bosIAClient.GetModulesAsync <Module>(true, true);

                    if (modulesResponse != null && modulesResponse.IsSuccessStatusCode)
                    {
                        allModules = modulesResponse.Modules;
                    }

                    var operationsResponse = await _bosIAClient.GetOperationsAsync <Operation>(true, true);

                    if (operationsResponse != null && operationsResponse.IsSuccessStatusCode)
                    {
                        allOperations = operationsResponse.Operations;
                    }

                    foreach (PermissionsSet module in permittedModules)
                    {
                        var moduleObj = allModules.FirstOrDefault(x => x.Id == module.ModuleId);

                        if (moduleObj != null)
                        {
                            moduleObj.IsPermitted = true;
                            if (moduleObj.Operations.Count > 0)
                            {
                                foreach (Operation operation in moduleObj.Operations)
                                {
                                    var operationObj = permittedOperations.FirstOrDefault(x => x.OperationId == operation.Id);
                                    if (operationObj != null)
                                    {
                                        operation.IsPermitted = true;
                                    }
                                }
                            }
                        }
                    }

                    model.ModuleOperations = allModules;
                    model.OwnerId          = roleId;
                    model.RoleName         = roleName;
                    return(View("Index", model));
                }
                else
                {
                    ModelState.AddModelError("CustomError", "The selected role does not have a verified Id. Please try again.");
                    return(View("Index", model));
                }
            }
            catch (Exception ex)
            {
                Logger.LogException("Permissions", "FetchPermissions", ex);

                dynamic model = new ExpandoObject();
                model.Message    = ex.Message;
                model.StackTrace = ex.StackTrace;
                return(View("ErrorPage", model));
            }
        }