Exemplo n.º 1
0
        public void OnResultExecuting(ResultExecutingContext filterContext)
        {
            var model       = filterContext.Controller.ViewData.Model;
            var layoutModel = model as BaseViewModel;

            if (layoutModel != null)
            {
                var layout = new LayoutViewModel()
                {
                    SiteName = "WERC"
                };

                layoutModel.Layout = layout;

                var languageDictionary = new Dictionary <string, string>();// PreLoadData.LoadLanguage(Thread.CurrentThread.CurrentCulture.Name);

                layoutModel.CurrentCultureName = Thread.CurrentThread.CurrentCulture.Name;

                layoutModel.LanguageDictionary = languageDictionary;

                layoutModel.activeLanguageList           = new List <VmActiveLanguage>();// new BLLanguage().GetActiveLanguages();
                layoutModel.activeLanguageCommaSepatated = new BLLanguage().GetActiveLanguagesCommaSeparated(layoutModel.activeLanguageList);

                if (layoutModel.MostSetWelcomeMessage == false)
                {
                    if (filterContext.HttpContext.Session["WelcomeMessage"] != null)
                    {
                        layoutModel.WelcomeMessage = filterContext.HttpContext.Session["WelcomeMessage"].ToString();
                    }
                }

                if (layoutModel.MostSetWelcomeMessage)
                {
                    Random random = new Random();

                    int index = random.Next(layoutModel.WelcomeMessageList.Length);
                    filterContext.HttpContext.Session["WelcomeMessage"] = layoutModel.WelcomeMessage = layoutModel.WelcomeMessageList[index];
                }

                if (filterContext.HttpContext.Request.IsAuthenticated)
                {
                    var userManager = System.Web.HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();
                    var user        = userManager.Users.First(u => u.UserName == System.Web.HttpContext.Current.User.Identity.Name);
                    layoutModel.UserEmailConfirmed = user.EmailConfirmed;

                    string userName = filterContext.HttpContext.User.Identity.Name;
                    if (SmUserRolesList.UserRoles == null)
                    {
                        var blUser = new BLUser();
                        SmUserRolesList.UserRoles = blUser.GetAllUserRoles();
                    }
                    var controller = (filterContext.Controller as BaseController);

                    layoutModel.CurrentUserId    = controller.CurrentUserId;
                    layoutModel.CurrentUserRoles = (from roles in SmUserRolesList.UserRoles where roles.UserName == userName select roles.RoleName).AsEnumerable();
                }
            }
        }
Exemplo n.º 2
0
        public static bool CheckRoleAccessRight(string userName, params SystemRoles[] roles)
        {
            var roleList = roles.Select(r => Enum.GetName(r.GetType(), r)).ToList();

            for (int i = 0; i < roleList.Count; i++)
            {
                roleList[i] = roleList[i].Replace("_", " ");
            }

            if (SmUserRolesList.UserRoles == null)
            {
                var blUser = new BLUser();
                SmUserRolesList.UserRoles = blUser.GetAllUserRoles();
            }

            return(SmUserRolesList.UserRoles.Any(r => r.UserName == userName && roleList.Contains(r.RoleName)));
        }
Exemplo n.º 3
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            try
            {
                ViewBag.ReturnUrl = returnUrl;

                if (!ModelState.IsValid)
                {
                    return(View(model));
                }

                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, change to shouldLockout: true

                IEnumerable <string> userRoles = null;
                var UserName = model.UserName;

                ApplicationUser user = context.Users.Where(u => u.UserName.Equals(model.UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

                if (user != null)
                {
                    UserName = user.UserName;

                    var blUser = new BLUser();
                    SmUserRolesList.UserRoles = blUser.GetAllUserRoles();

                    userRoles = (from roles in SmUserRolesList.UserRoles where roles.UserName == UserName select roles.RoleName).AsEnumerable <string>();

                    if (!await UserManager.IsEmailConfirmedAsync(user.Id))
                    {
                        if (!userRoles.Contains(SystemRoles.Advisor.ToString()) && !userRoles.Contains(SystemRoles.Judge.ToString()))
                        {
                            ModelState.AddModelError("", "You need to confirm your email.");
                            return(View(model));
                        }
                    }
                    //if (await UserManager.IsLockedOutAsync(user.Id))
                    //{
                    //    return View("Lockout");
                    //}


                    TempData["UserRoles"] = userRoles;
                }

                var result = await SignInManager.PasswordSignInAsync(UserName, model.Password, model.RememberMe, shouldLockout : true);

                switch (result)
                {
                case SignInStatus.Success:

                    CurrentUserId = user.Id;
                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        if (userRoles.Contains(SystemRoles.Admin.ToString()))
                        {
                            return(RedirectToAction("index", "admin"));
                        }
                        if (userRoles.Contains(SystemRoles.SafetyAdmin.ToString()))
                        {
                            return(RedirectToAction("index", "SafetyAdmin"));
                        }

                        if (userRoles.Contains("Advisor"))
                        {
                            return(RedirectToAction("tl", "Advisor"));
                        }

                        if (userRoles.Contains(SystemRoles.Judge.ToString()))
                        {
                            return(RedirectToAction("index", "judge"));
                        }

                        if (userRoles.Contains(SystemRoles.Student.ToString()))
                        {
                            return(RedirectToAction("index", "home"));
                        }

                        if (userRoles.Contains(SystemRoles.Leader.ToString()))
                        {
                            return(RedirectToAction("index", "home"));
                        }
                        if (userRoles.Contains(SystemRoles.CoAdvisor.ToString()))
                        {
                            return(RedirectToAction("index", "home"));
                        }
                        ViewBag.UserRole = "";
                    }

                    return(RedirectToLocal(returnUrl));


                //return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe, SetWelcomMessage = true });

                case SignInStatus.LockedOut:
                    return(View("Lockout"));

                case SignInStatus.RequiresVerification:
                    return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, model.RememberMe }));

                case SignInStatus.Failure:

                default:
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return(View(model));
                }
            }
            catch (Exception ex)
            {
                return(RedirectToAction("login"));
            }
        }
Exemplo n.º 4
0
        public async Task <ActionResult> ConfirmEmail(string userId, string code, string returnUrl = "")
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            Session.Clear();

            if (userId == null || code == null)
            {
                return(View("Error", new VMHandleErrorInfo("Email Confirmation not valid")));
            }


            var user = await UserManager.Users.FirstOrDefaultAsync(u => u.Id == userId);

            var blUser = new BLUser();

            IEnumerable <string> userRoles = null;

            if (user != null)
            {
                SmUserRolesList.UserRoles = blUser.GetAllUserRoles();
                userRoles = (from roles in SmUserRolesList.UserRoles where roles.UserName == user.UserName select roles.RoleName).AsEnumerable <string>();

                TempData["UserRoles"] = userRoles;

                if (user.EmailConfirmed == true)
                {
                    return(RedirectToAction("login", "account"));
                }
            }

            var result = await UserManager.ConfirmEmailAsync(userId, code);

            if (result.Succeeded)
            {
                if (userRoles.Contains(SystemRoles.Advisor.ToString()) || userRoles.Contains(SystemRoles.Judge.ToString()))
                {
                    user.EmailConfirmed = false;
                    UserManager.Update(user);

                    return(View("ConfirmEmail", new VMConfirmEmail
                    {
                        Message = "Thank you for confirming your WERC Design Contest 2019 account. \n" +
                                  "Your account will be approved and active by the WERC administrator within 24 hours."
                    }));
                }

                await SignInManager.SignInAsync(user, false, true);

                if (returnUrl != "")
                {
                    return(RedirectToLocal(returnUrl));
                }
                else
                {
                    CurrentUserId = user.Id;
                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        return(RedirectToAction("index", "home"));
                    }
                }
                //return View("ConfirmEmail", new VMConfirmEmail());
            }

            if (result.Errors.First().ToLower().Contains("invalid token"))
            {
                code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId, code }, protocol: Request.Url.Scheme);

                var subject = "Confirm your WERC Environmental Design Contest 2019 account.";

                var blPerson = new BLPerson();
                var person   = blPerson.GetPersonByUserId(userId);

                var body = "<h1> 29th WERC Environmental Design Contest 2019" + "</h1>" +  //Body ...
                           "<br/>" +
                           "Dear " + person.FirstName + " " + person.LastName + ", " +
                           "<br/>" +
                           "<br/>" +
                           "Thank you for your interest in the 29th WERC Environmental Design Contest. We have received your request for access to the online platform. Each request requires approval from our system administrator." +
                           "<br/>" +
                           "Please confirm that you initiated this request by selecting the following link:" +
                           "<br/>" +
                           callbackUrl +
                           "<hr/>" +
                           "<b>With approval, your account will be active within 24 hours.</b>" +
                           "<hr/>" +
                           "If you have questions about the WERC Environmental Design Contest online platform, please call 575-646-8171 or email [email protected] ." +
                           "<br/>" +
                           "<br/>" +
                           "<span>User Name: </span>" + user.UserName;

                await UserManager.SendEmailAsync(user.Id,
                                                 subject, // Subject
                                                 body);

                var emailHelper = new EmailHelper
                {
                    Subject    = subject,
                    Body       = body,
                    IsBodyHtml = true,
                    EmailList  = new string[] { specialEmail }
                };

                emailHelper.Send();

                return(View("Error", new
                            VMHandleErrorInfo("Confirmation email link has been expired for security reasons. \n New Confirmation email has sent to your email." +
                                              "\n" + "If you do not receive the confirmation message within a few minutes of signing up, please check your Spam or Bulk or Junk E - Mail folder just in case the confirmation email got delivered there instead of your inbox. If so, select the confirmation message and mark it Not Spam, which should allow future messages to get through.")));
            }

            return(View("Error", new VMHandleErrorInfo(result.Errors.First())));
        }