Exemple #1
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.
                {
                    if (_bosAuthClient == null)
                    {
                        return(RedirectToAction("Index"));
                    }

                    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 != null && result.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        return(RedirectToAction("SignOut", "Auth"));
                    }
                    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

                        if (userRoles != null && userRoles.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                        {
                            return(RedirectToAction("SignOut", "Auth"));
                        }
                        if (userRoles != null && userRoles.User != null && userRoles.User.Roles != null)
                        {
                            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", (!string.IsNullOrEmpty(user.FirstName) ?  user.FirstName[0].ToString() : "")
                                          + (!string.IsNullOrEmpty(user.LastName) ?  user.LastName[0].ToString() : "").ToUpper()),
                                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(140),
                                IsPersistent = false,
                                AllowRefresh = false
                            });

                            var status = await SetModulePermissions(result.UserId.Value);

                            if (status != "")
                            {
                                await SignOut();
                            }

                            return(RedirectToAction("Index", "Dashboard")); //Finally, redirecting the user to the Dashboard page
                        }
                        else
                        {
                            ModelState.AddModelError("CustomError", "User Details Fetch Error");
                            return(View("Index", new AuthModel()));
                        }
                    }
                    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());
                    return(RedirectToAction("Index"));
                }
            }
            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));
            }
        }