示例#1
0
 public void GetUserTest()
 {
     IMembershipContext membershipContext = null; // TODO: Initialize to an appropriate value
     IMembershipService target = new MembershipService(membershipContext); // TODO: Initialize to an appropriate value
     int userID = 0; // TODO: Initialize to an appropriate value
     bool NoTracking = false; // TODO: Initialize to an appropriate value
     User expected = null; // TODO: Initialize to an appropriate value
     User actual;
     actual = target.GetUser(userID, NoTracking);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
示例#2
0
        // created
        // updated
        // manager -> general manager
        private void SendEmail_ConsolidateUpdated(Consolidate consolidate)
        {
            List <ConsolidateStatusRecord> statusRecords = IndentRepository.GetConsolidateStatusRecords(consolidate.ID).ToList();

            string subject = statusRecords.Count() == 1
                                 ? "New consolidate (id :" + consolidate.ID + ")"
                                 : "Consolidate updated (id: " + consolidate.ID + ")";

            //IEnumerable<User> users = MembershipService.GetUsersInRole("General Manager");
            IEnumerable <User> users = MembershipService.GetAllUserOfEmailTemplate("Consolidate", "Initial");

            foreach (User u in users.Where(g => !string.IsNullOrWhiteSpace(g.Email)))
            {
                var viewBag = new { User = u, StatusRecords = statusRecords };
                var message = new RazorMailMessage("Consolidate/Initial", consolidate, viewBag).Render();
                SendEmail(u.Email, subject, message);
            }
        }
示例#3
0
        /// <summary>
        /// 更新用户资料
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            MembershipUserCollection users = MembershipService.FindUserByName(edtUser.UserName);

            if (users.Count > 0)
            {
                try {
                    MembershipUser user = users[edtUser.UserName]; // 获取指定用户
                    user.Email = edtEmail.Text;
                    MembershipService.UpdateUser(user);
                }
                catch (Exception ex) {
                    XtraMessageBox.Show("更新用户 \"" + edtUser.UserName + "\" 的资料时失败," + ex.Message);
                    btnOK.DialogResult = DialogResult.None;
                }
                btnOK.DialogResult = DialogResult.OK;
            }
        }
示例#4
0
 public int Validates()
 {
     if (_account.OwnerId.HasValue)
     {
         _owner = MembershipService.GetUserById(_account.OwnerId.Value) as AccountUser;
     }
     _operatorUser = MembershipService.GetUserById(OperatorUserId);
     if (_operatorUser == null || !(_operatorUser is AdminUser))
     {
         return(ResponseCode.InvalidateUser);
     }
     _dealWay = DealWayService.GetById(this.HowToDeal);
     if (_dealWay == null || _dealWay.State != DealWayStates.Normal)
     {
         return(ResponseCode.InvalidateDealWay);
     }
     return(ResponseCode.Success);
 }
示例#5
0
        /// <summary>
        ///     Gets a member by slug
        /// </summary>
        /// <param name="slug"></param>
        /// <returns></returns>
        public virtual ActionResult GetByName(string slug)
        {
            var member = MembershipService.GetUserBySlug(slug);

            var usersRole = LoggedOnReadOnlyUser == null
                ? RoleService.GetRole(Constants.GuestRoleName, true)
                : LoggedOnReadOnlyUser.Roles.FirstOrDefault();

            var loggedonId  = LoggedOnReadOnlyUser?.Id ?? Guid.Empty;
            var permissions = RoleService.GetPermissions(null, usersRole);

            return(View(new ViewMemberViewModel
            {
                User = member,
                LoggedOnUserId = loggedonId,
                Permissions = permissions
            }));
        }
示例#6
0
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return(RedirectToAction("ChangePasswordSuccess"));
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return(View(model));
        }
示例#7
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="loggingService"> </param>
        /// <param name="unitOfWorkManager"> </param>
        /// <param name="membershipService"></param>
        /// <param name="localizationService"></param>
        /// <param name="roleService"></param>
        /// <param name="categoryService"></param>
        /// <param name="settingsService"> </param>
        /// <param name="topicService"> </param>
        /// <param name="categoryNotificationService"> </param>
        public CategoryController(ILoggingService loggingService, IUnitOfWorkManager unitOfWorkManager,
                                  IMembershipService membershipService,
                                  ILocalizationService localizationService,
                                  IRoleService roleService,
                                  ICategoryService categoryService,
                                  ISettingsService settingsService, ITopicService topicService, ICategoryNotificationService categoryNotificationService, IPollAnswerService pollAnswerService, ITopicNotificationService topicNotificationService, IVoteService voteService)
            : base(loggingService, unitOfWorkManager, membershipService, localizationService, roleService, settingsService)
        {
            _categoryService             = categoryService;
            _topicService                = topicService;
            _categoryNotificationService = categoryNotificationService;
            _pollAnswerService           = pollAnswerService;
            _topicNotificationService    = topicNotificationService;
            _voteService = voteService;

            LoggedOnUser = UserIsAuthenticated ? MembershipService.GetUser(Username) : null;
            UsersRole    = LoggedOnUser == null?RoleService.GetRole(AppConstants.GuestRoleName) : LoggedOnUser.Roles.FirstOrDefault();
        }
示例#8
0
        public ActionResult Create(TeamModel model)
        {
            if (ModelState.IsValid)
            {
                bool badName;
                var  team = MembershipService.CreateTeam(model.Name, model.Description, Token.UserID, out badName);
                if (team != null)
                {
                    return(RedirectToAction("Detail", "Team", new { team.Name }));
                }
                if (badName)
                {
                    ModelState.AddModelError("Name", SR.Team_AlreadyExists);
                }
            }

            return(View(model));
        }
示例#9
0
        private List <UserDetailModel> GetDetailUsers()
        {
            var users = MembershipService.GetAllUsers();
            var model = new List <UserDetailModel>();

            foreach (var item in users)
            {
                model.Add(new UserDetailModel
                {
                    Username = item.Username,
                    Name     = item.Name,
                    Surname  = item.Surname,
                    Email    = item.Email,
                    Roles    = item.Roles,
                });
            }
            return(model);
        }
示例#10
0
        public IEnumerable <Claim> GetClaimsForUser(string username)
        {
            List <Claim> result = null;

            UserModel user = MembershipService.GetUser(username);

            if (user != null)
            {
                result = new List <Claim>();
                result.Add(new Claim(ClaimTypes.Name, user.DisplayName));
                result.Add(new Claim(ClaimTypes.Upn, user.Name));
                result.Add(new Claim(ClaimTypes.Email, user.Email));
                result.Add(new Claim(ClaimTypes.Role, Definitions.Roles.Member));
                result.AddRange(RoleProvider.GetRolesForUser(user.Name).Select(x => new Claim(ClaimTypes.Role, x)));
            }

            return(result);
        }
示例#11
0
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return(RedirectToAction("ChangePasswordSuccess"));
                }
                else
                {
                    ModelState.AddModelError("", "当前密码不正确或新密码无效。");
                }
            }

            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return(View(model));
        }
示例#12
0
        public ActionResult Index()
        {
            ViewBag.HasSubscription = false;
            ISubscription model = null;
            ICustomer     c     = Chargify.Find <Customer>(MembershipService.GetUser().ProviderUserKey.ToString());

            if (c != null)
            {
                IDictionary <int, ISubscription> sList = Chargify.GetSubscriptionListForCustomer(c.ChargifyID);
                if (sList.Count > 0)
                {
                    ViewBag.HasSubscription = true;
                    model = sList.FirstOrDefault().Value;
                }
            }

            return(View(model));
        }
示例#13
0
        public void Time(EntityIdViewModel timeBadgeViewModel)
        {
            try
            {
                var user = MembershipService.GetUser(timeBadgeViewModel.Id);
                var databaseUpdateNeeded = _badgeService.ProcessBadge(BadgeType.Time, user);

                if (databaseUpdateNeeded)
                {
                    Context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Context.RollBack();
                LoggingService.Error(ex);
            }
        }
示例#14
0
 public ActionResult ResetPassword(ResetPasswordModel model)
 {
     if (ModelState.IsValid)
     {
         var user = MembershipService.GetUserModel(model.Username);
         if (user == null)
         {
             TempData["ResetSuccess"] = false;
             Response.AppendToLog("FAILURE");
         }
         else
         {
             MembershipService.UpdateUser(user.Id, null, null, null, null, model.Password);
             TempData["ResetSuccess"] = true;
         }
     }
     return(View(model));
 }
        public ActionResult Edit(UserEditModel model)
        {
            if (User.Identity.Name != model.Name && !User.IsInRole(Definitions.Roles.Administrator))
            {
                return(RedirectToAction("Unauthorized", "Home"));
            }

            if (ModelState.IsValid)
            {
                bool valid = true;

                if (!User.IsInRole(Definitions.Roles.Administrator) && (model.OldPassword == null && model.NewPassword != null))
                {
                    ModelState.AddModelError("OldPassword", Resources.Account_Edit_OldPasswordEmpty);
                    valid = false;
                }

                if (model.OldPassword != null && !MembershipService.ValidateUser(model.Username, model.OldPassword))
                {
                    ModelState.AddModelError("OldPassword", Resources.Account_Edit_OldPasswordIncorrect);
                    valid = false;
                }

                if (User.IsInRole(Definitions.Roles.Administrator) && model.Username == User.Identity.Name && !(model.Roles != null && model.Roles.Contains(Definitions.Roles.Administrator)))
                {
                    ModelState.AddModelError("Roles", Resources.Account_Edit_CannotRemoveYourselfFromAdminRole);
                    valid = false;
                }

                if (valid)
                {
                    MembershipService.UpdateUser(model.Username, model.Name, model.Surname, model.Email, model.NewPassword);
                    Roles.RemoveUserFromRoles(model.Username, Roles.GetAllRoles());
                    if (model.Roles != null)
                    {
                        Roles.AddUserToRoles(model.Username, model.Roles);
                    }
                    ViewBag.UpdateSuccess = true;
                }
            }

            PopulateRoles();
            return(View(model));
        }
示例#16
0
        public ActionResult Edit(MemberEditViewModel userModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var user = MembershipService.GetUser(userModel.Id);

                // Map everything in model except properties hidden on page
                user.Age                       = userModel.Age;
                user.Comment                   = userModel.Comment;
                user.Email                     = userModel.Email;
                user.Facebook                  = userModel.Facebook;
                user.IsApproved                = userModel.IsApproved;
                user.IsLockedOut               = userModel.IsLockedOut;
                user.Location                  = userModel.Location;
                user.PasswordAnswer            = userModel.PasswordAnswer;
                user.PasswordQuestion          = userModel.PasswordQuestion;
                user.Signature                 = userModel.Signature;
                user.Twitter                   = userModel.Twitter;
                user.UserName                  = userModel.UserName;
                user.Website                   = userModel.Website;
                user.DisableEmailNotifications = userModel.DisableEmailNotifications;
                user.DisablePosting            = userModel.DisablePosting;
                user.DisablePrivateMessages    = userModel.DisablePrivateMessages;

                try
                {
                    unitOfWork.Commit();

                    ViewBag.Message = new GenericMessageViewModel
                    {
                        Message     = "User saved",
                        MessageType = GenericMessages.success
                    };
                }
                catch (Exception ex)
                {
                    unitOfWork.Rollback();
                    LoggingService.Error(ex);
                    ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                }

                return(ListUsers(null, null));
            }
        }
示例#17
0
        public ActionResult CreateNew(NewClientModel model)
        {
            MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, Membership.GeneratePassword(MembershipService.MinPasswordLength, MembershipService.MinRequiredNonAlphanumericCharacters), model.Email);

            if (createStatus == MembershipCreateStatus.Success)
            {
                //Если пользователь зарегистрировался, то для своего клиента он Админ
                Roles.AddUserToRole(model.UserName, RoleNames.ADMIN);
                //Создаем клиента
                MembershipUser user   = Membership.GetUser(model.UserName);
                ClientModel    client = null;
                try
                {
                    client = ClientRepo.CreateClient(model, model.OrganizationName, user, null, model.Status, model.IsDealler);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
                if (client != null)
                {
                    bool isMailError = false;
                    try
                    {
                        MailGenerator.Mailer.Send(MailGenerator.GetClientInviteMail(user, OTSession.OperationalClient.OrganizationName, Request.RequestContext));
                    }
                    catch (Exception ex)
                    {
                        isMailError = true;
                        Trace.TraceError("Ошибка отправки уведомления об отправке пользователь {0} email {1}, ошибка {2}", user.UserName, user.Email, ex);
                    }
                    return(RedirectToAction("Index", isMailError?new { User = user, Client = client }: null));
                }
                else
                {
                    return(View(model));
                }
            }
            else
            {
                ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
            }
            return(View(model));
        }
示例#18
0
        /// <summary>
        ///     Resends the email confirmation
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public virtual ActionResult ResendEmailConfirmation(string username)
        {
            try
            {
                // Get the user from the username
                var user = MembershipService.GetUser(username);

                if (user != null && !string.IsNullOrWhiteSpace(user.Id.ToString()))
                {
                    // get the site settings
                    var siteSettings = SettingsService.GetSettings();

                    _emailService.SendEmailConfirmationEmail(user, siteSettings.ManuallyAuthoriseNewMembers, true);

                    TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                    {
                        Message     = LocalizationService.GetResourceString("Members.MemberEmailAuthorisationNeeded"),
                        MessageType = GenericMessages.success
                    };
                }
                else
                {
                    // Log this
                    LoggingService.Error(
                        "Unable to ResendEmailConfirmation as either user was null or RegistrationEmailConfirmationKey is missing");

                    // There was a problem
                    TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                    {
                        Message     = LocalizationService.GetResourceString("Members.Errors.LogonGeneric"),
                        MessageType = GenericMessages.danger
                    };
                }

                Context.SaveChanges();
            }
            catch (Exception ex)
            {
                Context.RollBack();
                LoggingService.Error(ex);
            }

            return(RedirectToAction("Index", "Home"));
        }
示例#19
0
        public virtual ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            if (model is null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            User.GetMembershipUser(MembershipService);

            if (ModelState.IsValid)
            {
                User.GetMembershipUser(MembershipService);

                // ChangePassword will throw an exception rather than return false in certain failure scenarios.
                var loggedOnUser = MembershipService.GetUser(LoggedOnReadOnlyUser?.Id);

                var changePasswordSucceeded = MembershipService.ChangePassword(loggedOnUser, model.OldPassword, model.NewPassword);

                try
                {
                    Context.SaveChanges();
                }
                catch (Exception ex)
                {
                    Context.RollBack();
                    LoggingService.Error(ex);
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    // We use temp data because we are doing a redirect
                    TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                    {
                        Message     = LocalizationService.GetResourceString("Members.ChangePassword.Success"),
                        MessageType = GenericMessages.success
                    };
                    return(View());
                }
                ModelState.AddModelError("", LocalizationService.GetResourceString("Members.ChangePassword.Error"));
            }

            return(View(model));
        }
示例#20
0
        public ActionResult AddPOC(BusinessContactViewModel viewModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var loggedOnUserId = LoggedOnReadOnlyUser?.Id ?? Guid.Empty;
                var admin          = MembershipService.Get(loggedOnUserId);
                var settings       = SettingsService.GetSettings();
                var business       = _businessService.Get(viewModel.Id);

                var newContact = new BusinessContact
                {
                    FirstName    = viewModel.FirstName,
                    LastName     = viewModel.LastName,
                    PrimaryPhone = viewModel.PrimaryPhoneNumber,
                    Email        = viewModel.Email,
                    Business     = business
                };

                try
                {
                    _businessService.AddBusinessContact(newContact);
                    _businessService.AdminBusinessContactAdded(newContact, admin);
                    unitOfWork.Commit();
                    TempData[AppConstants.MessageViewBagName] = new AdminGenericMessageViewModel
                    {
                        Message     = "Business Contact Added.",
                        MessageType = GenericMessages.success
                    };
                    return(RedirectToAction("POC", "AdminBusiness", new { id = business.Id }));
                }
                catch (Exception ex)
                {
                    unitOfWork.Rollback();
                    //LoggingService.Error(ex);
                    TempData[AppConstants.MessageViewBagName] = new AdminGenericMessageViewModel
                    {
                        Message     = "Adding a business contact failed.",
                        MessageType = GenericMessages.danger
                    };
                }

                return(RedirectToAction("POC", "AdminBusiness", new { id = business.Id }));
            }
        }
示例#21
0
        public virtual async Task <ActionResult> VoteUpPost(EntityIdViewModel voteUpViewModel)
        {
            if (Request.IsAjaxRequest())
            {
                var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService);

                // Quick check to see if user is locked out, when logged in
                if (loggedOnReadOnlyUser.IsLockedOut | !loggedOnReadOnlyUser.IsApproved)
                {
                    FormsAuthentication.SignOut();
                    throw new Exception(LocalizationService.GetResourceString("Errors.NoAccess"));
                }

                // Get a db user
                var loggedOnUser = MembershipService.GetUser(loggedOnReadOnlyUser.Id);

                // Firstly get the post
                var post = _postService.Get(voteUpViewModel.Id);

                // Now get the current user
                var voter = loggedOnUser;

                // Also get the user that wrote the post
                var postWriter = post.User;

                // Mark the post up or down
                await MarkPostUpOrDown(post, postWriter, voter, PostType.Positive, loggedOnReadOnlyUser);

                try
                {
                    Context.SaveChanges();
                }

                catch (Exception ex)
                {
                    Context.RollBack();
                    LoggingService.Error(ex);
                    throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
                }
            }

            // TODO - need to return something more meaningful
            return(Content(string.Empty));
        }
示例#22
0
        public ActionResult Register(RegisterModel model)
        {
            ViewBag.RegionId = new SelectList(market.Regions, "Id", "Name");

            if (ModelState.IsValid)
            {
                UserModel user = new UserModel();
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.Password, model.Email.ToLower());

                if (createStatus == MembershipCreateStatus.Success)
                {
                    user.ActivationId = System.Guid.NewGuid().ToString();
                    MembershipUser RegisteredUser = Membership.GetUser(model.Email.ToLower());
                    RegisteredUser.IsApproved = false;
                    Membership.UpdateUser(RegisteredUser);
                    user.Email     = model.Email.ToLower();
                    user.FirstName = model.FirstName.Substring(0, 1).ToUpper() + model.FirstName.Substring(1);
                    user.LastName  = model.LastName.Substring(0, 1).ToUpper() + model.LastName.Substring(1);
                    user.City      = model.City;
                    user.RegionId  = model.RegionId;
                    user.CountryId = 1;
                    market.Badges.SingleOrDefault(b => b.Name == "Individual").Users.Add(user);
                    market.Users.Add(user);
                    market.SaveChanges();

                    //Use MvcMailer to send welcome email to newly registered user.
                    UserMailer.Welcome(newUser: user).Send();
                    Session["REGISTERED_USER"] = true;
                    log.Info("Account - New user registered (" + model.Email.ToLower() + ")");
                    return(View());
                }
                else
                {
                    log.Error("Account - Error registering new user. " + createStatus.ToString());
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            log.Error("Account - RegisterModel Error.");
            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return(View(model));
        }
    public void OnStateChanged(string state)
    {
        if (!(state == HandledState) || !(rootStateMachine != null))
        {
            return;
        }
        CPDataEntityCollection cPDataEntityCollection = Service.Get <CPDataEntityCollection>();

        if (cPDataEntityCollection == null || cPDataEntityCollection.LocalPlayerHandle.IsNull)
        {
            throw new Exception("Unable to resolve data entity collection");
        }
        if (cPDataEntityCollection.TryGetComponent(cPDataEntityCollection.LocalPlayerHandle, out ProfileData component))
        {
            MembershipService membershipService = Service.Get <MembershipService>();
            string            text;
            if (component.IsFirstTimePlayer && !membershipService.LoginViaMembership && !membershipService.LoginViaRestore)
            {
                QuestService        questService        = Service.Get <QuestService>();
                GameStateController gameStateController = Service.Get <GameStateController>();
                text = ((questService.ActiveQuest == null || !(questService.ActiveQuest.Id == gameStateController.FTUEConfig.FtueQuestId)) ? FirstTimePlayerEvent : ReturnPlayerEvent);
            }
            else
            {
                if (membershipService.LoginViaRestore)
                {
                    SessionManager sessionManager = Service.Get <SessionManager>();
                    if (sessionManager.HasSession)
                    {
                        sessionManager.ReturnToRestorePurchases();
                    }
                    Service.Get <ICPSwrveService>().Funnel(Service.Get <MembershipService>().AccountFunnelName, "21", "check_cpremixprofile", "ReturnToSettings");
                    AccountPopupController componentInParent = GetComponentInParent <AccountPopupController>();
                    componentInParent.OnClosePopup();
                    return;
                }
                text = ReturnPlayerEvent;
            }
            Service.Get <ICPSwrveService>().Funnel(Service.Get <MembershipService>().AccountFunnelName, "21", "check_cpremixprofile", text);
            rootStateMachine.SendEvent(text);
            return;
        }
        throw new MissingReferenceException("No profile data found for local player");
    }
示例#24
0
        public async Task <ActionResult> Edit(MemberEditViewModel userModel)
        {
            var user = MembershipService.GetUser(userModel.Id);

            // Map everything in model except properties hidden on page
            user.Age                       = userModel.Age;
            user.Comment                   = userModel.Comment;
            user.Email                     = userModel.Email;
            user.Facebook                  = userModel.Facebook;
            user.IsApproved                = userModel.IsApproved;
            user.IsLockedOut               = userModel.IsLockedOut;
            user.IsBanned                  = userModel.IsBanned;
            user.Location                  = userModel.Location;
            user.PasswordAnswer            = userModel.PasswordAnswer;
            user.PasswordQuestion          = userModel.PasswordQuestion;
            user.Signature                 = userModel.Signature;
            user.Twitter                   = userModel.Twitter;
            user.UserName                  = userModel.UserName;
            user.Website                   = userModel.Website;
            user.DisableEmailNotifications = userModel.DisableEmailNotifications;
            user.DisablePosting            = userModel.DisablePosting;
            user.DisablePrivateMessages    = userModel.DisablePrivateMessages;
            user.IsTrustedUser             = userModel.IsTrustedUser;

            try
            {
                Context.SaveChanges();

                TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                {
                    Message     = "User saved",
                    MessageType = GenericMessages.success
                };
            }
            catch (Exception ex)
            {
                Context.RollBack();
                LoggingService.Error(ex);
                ModelState.AddModelError(string.Empty,
                                         LocalizationService.GetResourceString("Errors.GenericMessage"));
            }

            return(await ListUsers(null, null));
        }
        public ActionResult Create(Guid?id, Guid?to)
        {
            // Check if private messages are enabled
            if (!SettingsService.GetSettings().EnablePrivateMessages || LoggedOnUser.DisablePrivateMessages == true)
            {
                return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage")));
            }

            // Check flood control
            var lastMessage = _privateMessageService.GetLastSentPrivateMessage(LoggedOnUser.Id);

            if (lastMessage != null && DateUtils.TimeDifferenceInMinutes(DateTime.UtcNow, lastMessage.DateSent) < SettingsService.GetSettings().PrivateMessageFloodControl)
            {
                return(ErrorToInbox(LocalizationService.GetResourceString("PM.SendingToQuickly")));
            }

            // Check outbox size
            var senderCount = _privateMessageService.GetAllSentByUser(LoggedOnUser.Id).Count;

            if (senderCount > SettingsService.GetSettings().MaxPrivateMessagesPerMember)
            {
                return(ErrorToInbox(LocalizationService.GetResourceString("PM.SentItemsOverCapcity")));
            }

            var viewModel = new CreatePrivateMessageViewModel();

            // add the username to the to box if available
            if (to != null)
            {
                var userTo = MembershipService.GetUser((Guid)to);
                viewModel.UserToUsername = userTo.UserName;
            }

            // See if this is a reply or not
            if (id != null)
            {
                var previousMessage = _privateMessageService.Get((Guid)id);
                // Its a reply, get the details
                viewModel.UserToUsername  = previousMessage.UserFrom.UserName;
                viewModel.Subject         = previousMessage.Subject;
                viewModel.PreviousMessage = previousMessage.Message;
            }
            return(View(viewModel));
        }
示例#26
0
        public ActionResult RoleAssignOfUser_EditData(string ParentRowId, Guid UserId, bool?IsInRole)
        {
            bool isInRole = IsInRole.HasValue?IsInRole.Value:true;
            Guid rid      = Guid.Parse(ParentRowId);

            var r = db.aspnet_Roles.Where(w => w.RoleId == rid).FirstOrDefault();

            if (isInRole)
            {
                MembershipUser user = MembershipService.GetUser(UserId);
                RoleService.AddToRole(user, r.RoleName);
            }
            else
            {
                MembershipUser user = MembershipService.GetUser(UserId);
                RoleService.RemoveFromRole(user, r.RoleName);
            }
            return(RedirectToAction("RoleAssign"));
        }
示例#27
0
        public ResultMsg Resume(int id)
        {
            ResultMsg msg = new ResultMsg();

            try
            {
                Account item = AccountService.GetById(id);
                if (item != null && item.State == States.Invalid)
                {
                    item.State = States.Normal;
                    AccountService.Update(item);
                    if (!string.IsNullOrWhiteSpace(HostSite.MessageTemplateOfAccountResume))
                    {
                        var owner = item.OwnerId.HasValue ? MembershipService.GetUserById(item.OwnerId.Value) : null;
                        if (owner != null && owner.IsMobileAvailable)
                        {
                            var accountType = AccountTypeService.GetById(item.AccountTypeId);
                            if (accountType != null && accountType.IsSmsResume)
                            {
                                var msgs = MessageFormator.Format(HostSite.MessageTemplateOfAccountResume, owner);
                                msgs = MessageFormator.Format(msgs, item);
                                SmsHelper.Send(owner.Mobile, msgs);
                            }
                        }
                    }
                    Logger.LogWithSerialNo(LogTypes.AccountResume, SerialNoHelper.Create(), id, item.Name);
                    msg.Code     = 1;
                    msg.CodeText = "启用会员 " + item.Name + " 成功";
                    //AddMessage("resume.success", item.Name);
                }
                else
                {
                    msg.CodeText = "不好意思,没有找到会员";
                }
                return(msg);
            }
            catch (Exception ex)
            {
                msg.CodeText = "不好意思,系统异常";
                Logger.Error("启用会员", ex);
                return(msg);
            }
        }
示例#28
0
        /// <summary>
        /// 删除选定数据资料
        /// </summary>
        public override void Delete()
        {
            if (View.RoleList.Selection.Count > 0)
            {
                string role = View.RoleList.Selection[0].GetDisplayText(0); // 获取选定角色的名称
                if (XtraMessageBox.Show("您是否真的要从系统中删除角色 \"" + role + "\" ?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    string[] users = MembershipService.GetUsersForRole(role);
                    if (users.Length > 0)
                    {
                        MembershipService.RemoveUsersFromRole(users, role); // 移除角色下的所有成员
                    }
                    MembershipService.DeleteRole(role);

                    // 更新视图
                    View.RoleList.DeleteNode(View.RoleList.Selection[0]);
                }
            }
        }
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var status = LoginStatus();

            if (status)
            {
                filterContext.Result = RedirectToAction("Index", "Dashboard", new { area = "Admin" });
            }
            else
            {
                this.BusinessService   = new BusinessService(this.Token);
                this.MembershipService = new MembershipService(this.Token);
                this.CountryService    = new CountryService(this.Token);
                this.TimezoneService   = new TimezoneService(this.Token);

                this.BusinessCategoryService = new BusinessCategoryService(this.Token);
                this.BusinessEmployeeService = new BusinessEmployeeService(this.Token);
            }
        }
示例#30
0
        public ActionResult ChangePassword(ChangePasswordWithOldModel model)
        {
            if (ModelState.IsValid)
            {
                bool isSuccess = MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                if (isSuccess)
                {
                    return(RedirectToAction("ChangePasswordSuccess"));
                }
                else
                {
                    ModelState.AddModelError("", "Текущий пароль не верен или новый пароль некорректен.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return(View(model));
        }
        public void Should_Reject_Users_Without_Membership_On_Current_Tenant()
        {
            var tenant   = DbContext.Tenants.Single(x => x.HostName == SetupConsts.Tenants.Subdomain2.HostName);
            var adminJoe = DbContext.Users.Single(x => x.UserName == SetupConsts.Users.AdminJoe.UserName);
            var johnRoe  = DbContext.Users.Single(x => x.UserName == SetupConsts.Users.JohnRoe.UserName);

            DbContext.UserId   = adminJoe.Id;
            DbContext.TenantId = tenant.Id;

            var session = new Session()
            {
                TenantId = DbContext.TenantId, UserId = DbContext.UserId
            };

            var membershipService = new MembershipService(DbContext, session);

            Assert.True(membershipService.IsMember(adminJoe.Id));
            Assert.True(!membershipService.IsMember(johnRoe.Id)); // not a member of 'subdomain2 / Company 2'
        }
        public void TestSetup()
        {
            this.Setup = new NhibernateTestSetupHelper();
            this._singleProvider = new ProviderMappingGroup("default", new WildcardUriMatch(new Uri("content://")), this.Setup.ReadonlyProviderSetup, this.Setup.ProviderSetup, this.Setup.FakeFrameworkContext);
            this.HiveManager = new HiveManager(this._singleProvider, this._singleProvider.FrameworkContext);

            this.AppContext = new FakeRebelApplicationContext(this.HiveManager, false);

            this._resolverContext = new MockedMapResolverContext(this.HiveManager.FrameworkContext, this.HiveManager, new MockedPropertyEditorFactory(this.AppContext), new MockedParameterEditorFactory());

            //mappers
            var cmsModelMapper = new CmsModelMapper(this._resolverContext);
            var persistenceToRenderModelMapper = new RenderTypesModelMapper(this._resolverContext);
            
            this.Setup.FakeFrameworkContext.SetTypeMappers(new FakeTypeMapperCollection(new AbstractMappingEngine[] { cmsModelMapper, persistenceToRenderModelMapper }));

            var membersMembershipProvider = new MembersMembershipProvider { AppContext = AppContext };
            MembershipService = new MembershipService<Member, MemberProfile>(AppContext.FrameworkContext, HiveManager,
                "security://member-profiles", "security://member-groups", Framework.Security.Model.FixedHiveIds.MemberProfileVirtualRoot,
                membersMembershipProvider, Enumerable.Empty<MembershipProviderElement>());

            PublicAccessService = new PublicAccessService(HiveManager, MembershipService, AppContext.FrameworkContext);
        }
 public void TestFixtureSetUp()
 {
     this.membershipService = new MembershipService(Constants.ApiToken);
 }
 public void TestFixtureSetUp()
 {
     membershipService = new MembershipService(AuthenticationService.Authenticate(TestCredentials.Username, TestCredentials.Password));
 }
		public void TestFixtureSetUp() {
			membershipService = new MembershipService(AuthenticationService.Authenticate(Constants.Username, Constants.Password));
		}