Ejemplo n.º 1
0
        /// <summary>
        ///     Creates view model
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static MemberFrontEndEditViewModel PopulateMemberViewModel(this MembershipUser user)
        {
            var viewModel = new MemberFrontEndEditViewModel
            {
                Id        = user.Id,
                FirstName = user.FirstName,
                Surname   = user.Surname,
                Initials  = user.Initials,
                Email     = user.Email,
                Pronouns  = user.Pronouns,
            };

            return(viewModel);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Creates a MembershipUser from the view model
        /// </summary>
        /// <param name="viewModel"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public static MembershipUser ToMembershipUser(this MemberFrontEndEditViewModel viewModel, MembershipUser user)
        {
            user.Id        = viewModel.Id;
            user.FirstName = viewModel.FirstName;
            user.Surname   = viewModel.Surname ?? null;
            var surnameInitial = string.IsNullOrEmpty(user.Surname) ? string.Empty : user.Surname[0].ToString();

            user.Initials = $"{user.FirstName[0]}{surnameInitial}".ToUpper();


            user.HasAgreedToTermsAndConditions = viewModel.HasAgreedToTermsAndConditions;
            user.Pronouns = viewModel.Pronouns;

            return(user);
        }
Ejemplo n.º 3
0
        private static MemberFrontEndEditViewModel PopulateMemberViewModel(MembershipUser user)
        {
            var viewModel = new MemberFrontEndEditViewModel
            {
                Id          = user.Id,
                Email       = user.Email,
                DisplayName = user.DisplayName,
                FirstName   = user.FirstName,
                LastName    = user.LastName,
                City        = user.City,
                State       = user.State,
                Avatar      = user.Avatar
            };

            return(viewModel);
        }
Ejemplo n.º 4
0
        public virtual async Task <ActionResult> EditAsync(Guid id, MemberFrontEndEditViewModel userModel, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (userModel is null)
            {
                throw new ArgumentNullException(nameof(userModel));
            }

            // Only allow if editing own profile, tweak for admins in the future?
            var loggedOnUserId = LoggedOnReadOnlyUser?.Id ?? Guid.Empty;

            if (loggedOnUserId != userModel.Id)
            {
                return(new HttpUnauthorizedResult());
            }

            // Get the user to edit from the database
            var dbUser = MembershipService.GetUser(userModel.Id);

            if (dbUser is null)
            {
                return(HttpNotFound());
            }

            if (ModelState.IsValid)
            {
                // Map across the viewmodel to the user
                var user = userModel.ToMembershipUser(dbUser);

                // Edit the user via the pipelines
                var pipeline = await MembershipService.EditUserAsync(user, User, userModel.ProfileImage, false, cancellationToken);

                if (pipeline.Successful)
                {
                    return(Redirect(user.NiceUrl));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, pipeline.ProcessLog.FirstOrDefault());
                }
            }

            userModel.Initials = dbUser.Initials;
            userModel.Email    = dbUser.Email;
            return(View(userModel));
        }
 /// <summary>
 /// Creates a MembershipUser from the view model
 /// </summary>
 /// <param name="viewModel"></param>
 /// <param name="user"></param>
 /// <returns></returns>
 public static MembershipUser ToMembershipUser(this MemberFrontEndEditViewModel viewModel, MembershipUser user)
 {
     user.Id        = viewModel.Id;
     user.UserName  = viewModel.UserName;
     user.Email     = viewModel.Email;
     user.Signature = viewModel.Signature;
     user.Age       = viewModel.Age;
     user.Location  = viewModel.Location;
     user.Website   = viewModel.Website;
     user.Twitter   = viewModel.Twitter;
     user.Facebook  = viewModel.Facebook;
     if (!string.IsNullOrWhiteSpace(viewModel.Avatar))
     {
         user.Avatar = viewModel.Avatar;
     }
     user.DisableEmailNotifications = viewModel.DisableEmailNotifications;
     return(user);
 }
Ejemplo n.º 6
0
        public virtual async Task <ActionResult> RemoveProfileImageAsync(Guid userId, CancellationToken cancellationToken = default(CancellationToken))
        {
            MemberFrontEndEditViewModel viewModel = null;

            if (ModelState.IsValid)
            {
                if (Guid.Empty == userId)
                {
                    throw new ArgumentOutOfRangeException(nameof(userId));
                }

                // Only allow if editing own profile, tweak for admins in the future?
                var loggedOnUserId = LoggedOnReadOnlyUser?.Id ?? Guid.Empty;
                if (loggedOnUserId != userId)
                {
                    return(new HttpUnauthorizedResult());
                }

                // Get the user to edit from the database
                var dbUser = MembershipService.GetUser(userId);

                if (dbUser is null)
                {
                    return(HttpNotFound());
                }

                viewModel = dbUser.PopulateMemberViewModel();

                var pipeline = await MembershipService.EditUserAsync(dbUser, User, null, true, cancellationToken);

                if (pipeline.Successful)
                {
                    return(RedirectToAction("Edit", new { id = userId }));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, pipeline.ProcessLog.FirstOrDefault());
                }
            }
            return(View("Edit", viewModel));
        }
        /// <summary>
        ///     Creates view model
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static MemberFrontEndEditViewModel PopulateMemberViewModel(this MembershipUser user)
        {
            var viewModel = new MemberFrontEndEditViewModel
            {
                Id                        = user.Id,
                UserName                  = user.UserName,
                Email                     = user.Email,
                Signature                 = user.Signature,
                Age                       = user.Age,
                Location                  = user.Location,
                Website                   = user.Website,
                Twitter                   = user.Twitter,
                Facebook                  = user.Facebook,
                DisableFileUploads        = user.DisableFileUploads == true,
                Avatar                    = user.Avatar,
                DisableEmailNotifications = user.DisableEmailNotifications == true,
                AmountOfPoints            = user.TotalPoints
            };

            return(viewModel);
        }
Ejemplo n.º 8
0
        public ActionResult Edit(MemberFrontEndEditViewModel userModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var loggedOnUserId = LoggedOnReadOnlyUser?.Id ?? Guid.Empty;
                //var permissions = RoleService.GetPermissions(null, UsersRole);

                // Check is has permissions
                if (loggedOnUserId == userModel.Id) //|| permissions[SiteConstants.Instance.PermissionEditMembers].IsTicked)
                {
                    // Get the user from DB
                    var user = MembershipService.Get(userModel.Id);

                    StatesViewModel statesViewModel = new StatesViewModel()
                    {
                        allStates = SettingsService.ListOfStates().ToList()
                    };
                    userModel._stateViewModel = statesViewModel;

                    if (userModel.DisplayName.Count() < 3)
                    {
                        //Check if user name is taken *****
                        ShowMessage(new GenericMessageViewModel
                        {
                            Message     = "Username must have atleast 3 characters.",
                            MessageType = GenericMessages.danger
                        });
                        return(View(userModel));
                    }


                    // Sort image out first
                    if (userModel.Files != null)
                    {
                        // Before we save anything, check the user already has an upload folder and if not create one
                        var uploadFolderPath = HostingEnvironment.MapPath(string.Concat(SiteConstants.Instance.UploadFolderPath, LoggedOnReadOnlyUser.Id));
                        if (!Directory.Exists(uploadFolderPath))
                        {
                            Directory.CreateDirectory(uploadFolderPath);
                        }

                        // Loop through each file and get the file info and save to the users folder and Db
                        var file = userModel.Files[0];
                        if (file != null)
                        {
                            // If successful then upload the file
                            var uploadResult = AppHelpers.UploadFile(file, uploadFolderPath, true);

                            if (!uploadResult.UploadSuccessful)
                            {
                                TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                {
                                    Message     = uploadResult.ErrorMessage,
                                    MessageType = GenericMessages.danger
                                };
                                return(View(userModel));
                            }

                            // Save avatar to user
                            user.Avatar = uploadResult.UploadedFileName;
                        }
                    }

                    // Set the users Avatar for the confirmation page
                    userModel.Avatar = user.Avatar;

                    // Update other users properties
                    //user.Location = _bannedWordService.SanitiseBannedWords(userModel.City, bannedWords);
                    user.City  = userModel.City;
                    user.State = userModel.State;

                    // User is trying to change username, need to check if a user already exists
                    // with the username they are trying to change to
                    var changedUsername = false;
                    //var sanitisedUsername = _bannedWordService.SanitiseBannedWords(userModel.UserName, bannedWords);

                    if (userModel.DisplayName != user.DisplayName)
                    {
                        if (MembershipService.GetUserByDisplayName(userModel.DisplayName) != null)
                        {
                            unitOfWork.Rollback();
                            ModelState.AddModelError(string.Empty, "Duplicate Display Name");
                            return(View(userModel));
                        }

                        user.DisplayName = userModel.DisplayName;
                        changedUsername  = true;
                    }

                    // User is trying to update their email address, need to
                    // check the email is not already in use
                    //if (userModel.Email != user.Email)
                    //{
                    //    // Add get by email address
                    //    if (MembershipService.GetUserByEmail(userModel.Email) != null)
                    //    {
                    //        unitOfWork.Rollback();
                    //        ModelState.AddModelError(string.Empty, "Duplicate Email.");
                    //        return View(userModel);
                    //    }
                    //    user.Email = userModel.Email;
                    //}


                    try
                    {
                        MembershipService.ProfileUpdated(user);

                        unitOfWork.Commit();

                        ShowMessage(new GenericMessageViewModel
                        {
                            Message     = "Profile updated",
                            MessageType = GenericMessages.success
                        });

                        if (changedUsername)  //This is email (not implimented yet....)
                        {
                            // User has changed their username so need to log them in
                            // as there new username of
                            var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                            if (authCookie != null)
                            {
                                var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                                if (authTicket != null)
                                {
                                    var newFormsIdentity = new FormsIdentity(new FormsAuthenticationTicket(authTicket.Version,
                                                                                                           user.Email,
                                                                                                           authTicket.IssueDate,
                                                                                                           authTicket.Expiration,
                                                                                                           authTicket.IsPersistent,
                                                                                                           authTicket.UserData));
                                    var roles = authTicket.UserData.Split("|".ToCharArray());
                                    var newGenericPrincipal = new GenericPrincipal(newFormsIdentity, roles);
                                    System.Web.HttpContext.Current.User = newGenericPrincipal;
                                }
                            }

                            // sign out current user
                            FormsAuthentication.SignOut();

                            // Abandon the session
                            Session.Abandon();

                            // Sign in new user
                            FormsAuthentication.SetAuthCookie(user.Email, false);
                        }
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        ModelState.AddModelError(string.Empty, "Error updating profile");
                    }
                    return(View(userModel));
                }
                return(ErrorToHomePage("Profile disabled"));
            }
        }
Ejemplo n.º 9
0
        public ActionResult Edit(MemberFrontEndEditViewModel userModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var loggedOnUserId = LoggedOnReadOnlyUser?.Id ?? Guid.Empty;
                var permissions = RoleService.GetPermissions(null, UsersRole);

                // Check is has permissions
                if (UserIsAdmin || loggedOnUserId == userModel.Id || permissions[SiteConstants.Instance.PermissionEditMembers].IsTicked)
                {
                    // Get the user from DB
                    var user = MembershipService.GetUser(userModel.Id);

                    // Before we do anything - Check stop words
                    var stopWords = _bannedWordService.GetAll(true);
                    var bannedWords = _bannedWordService.GetAll().Select(x => x.Word).ToList();

                    // Check the fields for bad words
                    foreach (var stopWord in stopWords)
                    {
                        if ((userModel.Facebook != null && userModel.Facebook.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0) ||
                            (userModel.Location != null && userModel.Location.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0) ||
                            (userModel.Signature != null && userModel.Signature.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0) ||
                            (userModel.Twitter != null && userModel.Twitter.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0) ||
                            (userModel.Website != null && userModel.Website.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0))
                        {

                            ShowMessage(new GenericMessageViewModel
                            {
                                Message = LocalizationService.GetResourceString("StopWord.Error"),
                                MessageType = GenericMessages.danger
                            });

                            // Ahhh found a stop word. Abandon operation captain.
                            return View(userModel);

                        }
                    }

                    // Repopulate any viewmodel data
                    userModel.AmountOfPoints = user.TotalPoints;

                    // Sort image out first
                    if (userModel.Files != null)
                    {
                        // Before we save anything, check the user already has an upload folder and if not create one
                        var uploadFolderPath = HostingEnvironment.MapPath(string.Concat(SiteConstants.Instance.UploadFolderPath, LoggedOnReadOnlyUser.Id));
                        if (!Directory.Exists(uploadFolderPath))
                        {
                            Directory.CreateDirectory(uploadFolderPath);
                        }

                        // Loop through each file and get the file info and save to the users folder and Db
                        var file = userModel.Files[0];
                        if (file != null)
                        {
                            // If successful then upload the file
                            var uploadResult = AppHelpers.UploadFile(file, uploadFolderPath, LocalizationService, true);

                            if (!uploadResult.UploadSuccessful)
                            {
                                TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                {
                                    Message = uploadResult.ErrorMessage,
                                    MessageType = GenericMessages.danger
                                };
                                return View(userModel);
                            }

                            // Save avatar to user
                            user.Avatar = uploadResult.UploadedFileName;
                        }
                    }

                    // Set the users Avatar for the confirmation page
                    userModel.Avatar = user.Avatar;

                    // Update other users properties
                    user.Age = userModel.Age;
                    user.Facebook = _bannedWordService.SanitiseBannedWords(userModel.Facebook, bannedWords);
                    user.Location = _bannedWordService.SanitiseBannedWords(userModel.Location, bannedWords);
                    user.Signature = _bannedWordService.SanitiseBannedWords(StringUtils.ScrubHtml(userModel.Signature, true), bannedWords);
                    user.Twitter = _bannedWordService.SanitiseBannedWords(userModel.Twitter, bannedWords);
                    user.Website = _bannedWordService.SanitiseBannedWords(userModel.Website, bannedWords);
                    user.DisableEmailNotifications = userModel.DisableEmailNotifications;

                    // User is trying to change username, need to check if a user already exists
                    // with the username they are trying to change to
                    var changedUsername = false;
                    var sanitisedUsername = _bannedWordService.SanitiseBannedWords(userModel.UserName, bannedWords);
                    if (sanitisedUsername != user.UserName)
                    {
                        if (MembershipService.GetUser(sanitisedUsername) != null)
                        {
                            unitOfWork.Rollback();
                            ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.DuplicateUserName"));
                            return View(userModel);
                        }

                        user.UserName = sanitisedUsername;
                        changedUsername = true;
                    }

                    // User is trying to update their email address, need to
                    // check the email is not already in use
                    if (userModel.Email != user.Email)
                    {
                        // Add get by email address
                        if (MembershipService.GetUserByEmail(userModel.Email) != null)
                        {
                            unitOfWork.Rollback();
                            ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.DuplicateEmail"));
                            return View(userModel);
                        }
                        user.Email = userModel.Email;
                    }

                    MembershipService.ProfileUpdated(user);

                    ShowMessage(new GenericMessageViewModel
                    {
                        Message = LocalizationService.GetResourceString("Member.ProfileUpdated"),
                        MessageType = GenericMessages.success
                    });

                    try
                    {
                        unitOfWork.Commit();

                        if (changedUsername)
                        {
                            // User has changed their username so need to log them in
                            // as there new username of
                            var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                            if (authCookie != null)
                            {
                                var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                                if (authTicket != null)
                                {
                                    var newFormsIdentity = new FormsIdentity(new FormsAuthenticationTicket(authTicket.Version,
                                                                                                           user.UserName,
                                                                                                           authTicket.IssueDate,
                                                                                                           authTicket.Expiration,
                                                                                                           authTicket.IsPersistent,
                                                                                                           authTicket.UserData));
                                    var roles = authTicket.UserData.Split("|".ToCharArray());
                                    var newGenericPrincipal = new GenericPrincipal(newFormsIdentity, roles);
                                    System.Web.HttpContext.Current.User = newGenericPrincipal;
                                }
                            }

                            // sign out current user
                            FormsAuthentication.SignOut();

                            // Abandon the session
                            Session.Abandon();

                            // Sign in new user
                            FormsAuthentication.SetAuthCookie(user.UserName, false);
                        }
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                    }

                    return View(userModel);
                }

                return ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"));
            }
        }
Ejemplo n.º 10
0
 private static MemberFrontEndEditViewModel PopulateMemberViewModel(MembershipUser user)
 {
     var viewModel = new MemberFrontEndEditViewModel
     {
         Id = user.Id,
         UserName = user.UserName,
         Email = user.Email,
         Signature = user.Signature,
         Age = user.Age,
         Location = user.Location,
         Website = user.Website,
         Twitter = user.Twitter,
         Facebook = user.Facebook,
         DisableFileUploads = user.DisableFileUploads == true,
         Avatar = user.Avatar,
         DisableEmailNotifications = user.DisableEmailNotifications == true,
         AmountOfPoints = user.TotalPoints
     };
     return viewModel;
 }