private async Task <List <PermissionsSet> > GetUserPermissionsSets(Guid ownerId)
        {
            List <PermissionsSet> allPermSets = new List <PermissionsSet>();
            var rolePerms = await _iaClient.GetOwnerPermissionsSetsAsync <PermissionsSet>(ownerId);

            allPermSets.AddRange(rolePerms.Permissions);
            return(allPermSets);
        }
Exemplo n.º 2
0
        private async Task <List <PermissionsSet> > GetUserPermissionsSets()
        {
            List <PermissionsSet> allPermSets = new List <PermissionsSet>();

            foreach (var claim in User.Claims.Where(c => c.Type == ClaimTypes.Role))
            {
                var rolePerms = await _iaClient.GetOwnerPermissionsSetsAsync <PermissionsSet>(new Guid(claim.Properties["roleId"]));

                allPermSets.AddRange(rolePerms.Permissions);
            }
            return(allPermSets);
        }
Exemplo n.º 3
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)
        {
            try
            {
                /* Checking if the Cookie Concent has been accepted.
                 * If it is not, before logging-in, we ask the user to accept the terms.
                 * The reason for this is that, we are storing pieces of information in sessions through out the application
                 * In order to be confromant with the GDPR Laws, it is required that we get the constent from the user
                 */
                if (HttpContext != null && !HttpContext.Request.Cookies.ContainsKey(".AspNet.Consent"))
                {
                    ModelState.AddModelError("CustomError", "Before proceeding, please 'Accept' our Cookies' terms.");
                    return(View("Index", new AuthModel()));
                }
                else if (authObj != null)                                                                     //Checking if the authObj is null.
                {
                    var result = await _bosAuthClient.SignInAsync(authObj.Username.Trim(), authObj.Password); //Making the call to the BOS Auth API to verify the user's login credentials

                    if (result.IsVerified)
                    {
                        /* ------- LOGIC ------
                         * First, check for non-null credentials sent as input paramters
                         * Make an API call to BOS Auth to verify the credentials
                         * On successful validation, get the user's roles, based on his Id
                         * After that, make another API to get the user's permissions-set. This API returns all the modules and operations that the user is permitted
                         * Finally, navigating him to the Dashboard
                         */
                        var userRoles = await _bosAuthClient.GetUserByIdWithRolesAsync <User>(result.UserId.Value); //On successful authentication, fetching the user's role

                        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 Claims Identity. Saving all the information in the Claims object
                        var claims = new List <Claim> {
                            new Claim("CreatedOn", DateTime.UtcNow.ToString()),
                            new Claim("Email", user.Email),
                            new Claim("Initials", user.FirstName[0].ToString() + user.LastName[0].ToString()),
                            new Claim("Name", user.FirstName + " " + user.LastName),
                            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
                        });


                        var enabledBOSapis = _configuration.GetSection("BOS:EnabledAPIs").Get <List <string> >();
                        if (enabledBOSapis != null)
                        {
                            if (enabledBOSapis.Contains("IA"))
                            {
                                //Getting the permissions
                                var permissionSet = await _bosIAClient.GetOwnerPermissionsSetsAsync <Permissions>(result.UserId.Value); //Making BOS API call to fetch the user's permission

                                if (permissionSet.IsSuccessStatusCode)
                                {
                                    //Set Permissions in Sessions
                                    if (permissionSet.Permissions.Components != null && permissionSet.Permissions.Components.Count > 0)
                                    {
                                        HttpContext.Session.SetObject("ModuleOperations", permissionSet.Permissions.Components.FirstOrDefault().ChildComponents); //On success, saving it in the Session Object
                                    }
                                }
                            }
                            else
                            {
                                //Set Permissions in Sessions
                                HttpContext.Session.SetObject("ModuleOperations", SetModules()); //On success, saving it in the Session Object
                            }
                        }

                        return(RedirectToAction("Index", "Dashboard")); //Finally, redirecting the user to the Dashboard page
                    }
                    else
                    {
                        ModelState.AddModelError("CustomError", "Username or password is incorrect"); //Returning back to the Login page with an error message
                        return(View("Index", new AuthModel()));
                    }
                }
                else
                {
                    ModelState.AddModelError("CustomError", "Username or password is incorrect");
                    return(View("Index", new AuthModel()));
                }
            }
            catch (ArgumentNullException ex)
            {
                Logger.LogException("Auth", "AuthenticateUser", ex);

                dynamic model = new ExpandoObject();
                model.Message    = ex.Message;
                model.StackTrace = ex.StackTrace;
                return(View("ErrorPage", model));
            }
            catch (Exception ex)
            {
                Logger.LogException("Auth", "AuthenticateUser", ex);

                dynamic model = new ExpandoObject();
                model.Message    = ex.Message;
                model.StackTrace = ex.StackTrace;
                return(View("ErrorPage", model));
            }
        }
Exemplo n.º 4
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            try
            {
                if (ModelState.IsValid)
                {
                    var result = await _authClient.SignInAsync(Input.Username.Trim(), Input.Password.Trim());

                    if (result.IsSuccessStatusCode)
                    {
                        if (result.IsVerified)
                        {
                            _logger.LogInformation("User logged in.");

                            var rolesResponse = await _authClient.GetUserRolesByUserIdAsync <Role>(result.UserId.Value).ConfigureAwait(false);

                            // Setting up claims for all the relevant information.
                            // The following sections set up:
                            // 1. The user claims, such as username and email,
                            // 2. A Role Claim for each role assosciated with the user
                            // 3. For each role, the permissions set for that role is retrieved,
                            //      and then role claims are created with the relevant codes.

                            var claims = new List <Claim>
                            {
                                new Claim(ClaimTypes.NameIdentifier, result.UserId.ToString()),
                                new Claim(ClaimTypes.Email, result.Email),
                                new Claim(ClaimTypes.Name, result.Username)
                            };

                            foreach (Role r in rolesResponse.Roles)
                            {
                                var roleClaim = new Claim(ClaimTypes.Role, r.Name);
                                roleClaim.Properties.Add("roleId", r.Id.ToString());

                                claims.Add(roleClaim);
                            }

                            foreach (var role in rolesResponse.Roles)
                            {
                                var permSets = await _iaClient.GetOwnerPermissionsSetsAsync <PermissionsSet>(role.Id);

                                AddModuleCodeClaims(claims, permSets.Permissions);
                                AddOperationsPermissionsClaims(claims, permSets.Permissions);
                            }

                            var claimsIdentity = new ClaimsIdentity(
                                claims, CookieAuthenticationDefaults.AuthenticationScheme);

                            var authProperties = new AuthenticationProperties
                            {
                                RedirectUri  = returnUrl,
                                IssuedUtc    = DateTime.UtcNow,
                                ExpiresUtc   = Input.RememberMe ? DateTime.UtcNow.AddDays(30) : DateTime.UtcNow.AddMinutes(15),
                                IsPersistent = true
                            };

                            await HttpContext.SignInAsync(
                                CookieAuthenticationDefaults.AuthenticationScheme,
                                new ClaimsPrincipal(claimsIdentity),
                                authProperties);

                            return(LocalRedirect(returnUrl));
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                            return(Page());
                        }
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "Uh oh! Either your email address or password is incorrect. Try again");
                        return(Page());
                    }
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "Sorry something went wrong! Please contact Administrator.");
            }
            return(Page());
        }
Exemplo n.º 5
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)
        {
            try
            {
                if (!HttpContext.Request.Cookies.ContainsKey(".AspNet.Consent"))
                {
                    ModelState.AddModelError("CustomError", "Before proceeding, please 'Accept' our Cookies' terms.");
                    return(View("Index", new AuthModel()));
                }
                if (authObj != null)
                {
                    var result = await _bosAuthClient.SignInAsync(authObj.Username.Trim(), 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("Initials", user.FirstName[0].ToString() + user.LastName[0].ToString()),
                            new Claim("Name", user.FirstName + " " + user.LastName),
                            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.GetOwnerPermissionsSetsAsync <Permissions>(result.UserId.Value);

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

                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        ModelState.AddModelError("CustomError", "Username or password is incorrect");
                        return(View("Index", new AuthModel()));
                    }
                }
                else
                {
                    return(View("Index", new AuthModel()));
                }
            }
            catch (ArgumentNullException ex)
            {
                Logger.LogException("Auth", "AuthenticateUser", ex);

                dynamic model = new ExpandoObject();
                model.Message    = ex.Message;
                model.StackTrace = ex.StackTrace;
                return(View("ErrorPage", model));
            }
            catch (Exception ex)
            {
                Logger.LogException("Auth", "AuthenticateUser", ex);

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