// Method that's fired when the event is raised
        private void BeforeLogin(object sender, LoginEventArgs e)
        {
            // Firstly, I'm going to cancel the event (Optional)
            e.Cancel = true;

            // Sender is the MembersController            
            //var membersController = sender as MembersController;

            // Here I would go off to a webservice, API or custom code and check the username and password is correct
            // against the other database. if it is log them in
            //TODO - Go validate e.UserName and e.Password                                    
            
            // If ok check the user exists and log the user in using the details below
            FormsAuthentication.SetAuthCookie(e.UserName, e.RememberMe);

            // Get membership service - you must create the member in MVCForum if they don't exist
            // Or you'll get an error when they have been redirected to the home page and logged in
            // this is pretty simple to do once we have the member service
            var memberService = ServiceFactory.Get<IMembershipService>();
            var user = memberService.GetUser(e.UserName);
            if (user == null)
            {
                // Create new member here
            }
          
            // Commit any changes you have made
            try
            {
                e.UnitOfWork.Commit();
                
                // Redirect to the home page (Or wherever)
                HttpContext.Current.Response.Redirect("~/");
            }
            catch (Exception)
            {
                e.UnitOfWork.Rollback();
            }

        }
        public ActionResult LogOn(LogOnViewModel model)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var username = model.UserName;
                var password = model.Password;

                try
                {
                    if (ModelState.IsValid)
                    {
                        // We have an event here to help with Single Sign Ons
                        // You can do manual lookups to check users based on a webservice and validate a user
                        // Then log them in if they exist or create them and log them in - Have passed in a UnitOfWork
                        // To allow database changes.

                        var e = new LoginEventArgs
                        {
                            UserName = model.UserName,
                            Password = model.Password,
                            RememberMe = model.RememberMe,
                            ReturnUrl = model.ReturnUrl, 
                            UnitOfWork = unitOfWork
                        };
                        EventManager.Instance.FireBeforeLogin(this, e);

                        if (!e.Cancel)
                        {
                            var message = new GenericMessageViewModel();
                            var user = new MembershipUser();
                            if (MembershipService.ValidateUser(username, password, System.Web.Security.Membership.MaxInvalidPasswordAttempts))
                            {
                                // Set last login date
                                user = MembershipService.GetUser(username);
                                if (user.IsApproved && !user.IsLockedOut && !user.IsBanned)
                                {
                                    FormsAuthentication.SetAuthCookie(username, model.RememberMe);
                                    user.LastLoginDate = DateTime.UtcNow;

                                    if (Url.IsLocalUrl(model.ReturnUrl) && model.ReturnUrl.Length > 1 && model.ReturnUrl.StartsWith("/")
                                        && !model.ReturnUrl.StartsWith("//") && !model.ReturnUrl.StartsWith("/\\"))
                                    {
                                        return Redirect(model.ReturnUrl);
                                    }

                                    message.Message = LocalizationService.GetResourceString("Members.NowLoggedIn");
                                    message.MessageType = GenericMessages.success;

                                    EventManager.Instance.FireAfterLogin(this, new LoginEventArgs
                                    {
                                        UserName = model.UserName,
                                        Password = model.Password,
                                        RememberMe = model.RememberMe,
                                        ReturnUrl = model.ReturnUrl,
                                        UnitOfWork = unitOfWork
                                    });

                                    return RedirectToAction("Index", "Home", new { area = string.Empty });
                                }
                                //else if (!user.IsApproved && SettingsService.GetSettings().ManuallyAuthoriseNewMembers)
                                //{

                                //    message.Message = LocalizationService.GetResourceString("Members.NowRegisteredNeedApproval");
                                //    message.MessageType = GenericMessages.success;

                                //}
                                //else if (!user.IsApproved && SettingsService.GetSettings().NewMemberEmailConfirmation == true)
                                //{

                                //    message.Message = LocalizationService.GetResourceString("Members.MemberEmailAuthorisationNeeded");
                                //    message.MessageType = GenericMessages.success;
                                //}
                            }

                            // Only show if we have something to actually show to the user
                            if (!string.IsNullOrEmpty(message.Message))
                            {
                                TempData[AppConstants.MessageViewBagName] = message;
                            }
                            else
                            {
                                // get here Login failed, check the login status
                                var loginStatus = MembershipService.LastLoginStatus;

                                switch (loginStatus)
                                {
                                    case LoginAttemptStatus.UserNotFound:
                                    case LoginAttemptStatus.PasswordIncorrect:
                                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.PasswordIncorrect"));
                                        break;

                                    case LoginAttemptStatus.PasswordAttemptsExceeded:
                                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.PasswordAttemptsExceeded"));
                                        break;

                                    case LoginAttemptStatus.UserLockedOut:
                                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.UserLockedOut"));
                                        break;

                                    case LoginAttemptStatus.Banned:
                                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.NowBanned"));
                                        break;

                                    case LoginAttemptStatus.UserNotApproved:
                                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.UserNotApproved"));
                                        user = MembershipService.GetUser(username);
                                        SendEmailConfirmationEmail(user);
                                        break;

                                    default:
                                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.LogonGeneric"));
                                        break;
                                }
                            }
                        }
                    }
                }

                finally
                {
                    try
                    {
                        unitOfWork.Commit();
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                    }

                }

                return View(model);
            }
        }
Exemple #3
0
        public void FireAfterLogin(object sender, LoginEventArgs eventArgs)
        {
            var handler = AfterLogin;

            if (handler != null)
            {
                handler(this, eventArgs);
            }
        }