Пример #1
0
        /// <summary>
        /// Зарегестрировать нового пользователя
        /// </summary>
        /// <param name="userName">Имя пользователя</param>
        /// <param name="password">Пароль</param>
        /// <param name="throwIfExist">Выдать исключение, если пользователь с таким именем существует. Ничего не делать, если false</param>
        /// <returns></returns>
        public Guid Register(string userName, string password, bool throwIfExist = true)
        {
            Membership membership;

            using (_unitOfWorkFactory.Create())
            {
                membership = _membershipRepository.GetWithUser().FirstOrDefault(m => m.User.Name == userName);
                if (membership != null)
                {
                    if (throwIfExist)
                    {
                        throw new System.Web.Security.MembershipCreateUserException("Пользователь с таким именем уже существует.");
                    }
                    return(membership.User.Id);
                }
            }
            User user = new User()
            {
                Name = userName
            };

            membership = new Membership()
            {
                User     = user,
                Password = PasswordEncryptor.Encrypt(password)
            };
            using (IUnitOfWork unitOfWork = _unitOfWorkFactory.Create())
            {
                _userRepository.Create(user);
                _membershipRepository.Create(membership);
                unitOfWork.Commit();
            }
            return(user.Id);
        }
        /// <summary>
        /// Вход в систему
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="persistCookie"></param>
        /// <returns></returns>
        public bool Login(string userName, string password, bool persistCookie)
        {
            Membership membership;

            using (_unitOfWorkFactory.Create())
            {
                membership = _membershipRepository.GetWithUser().FirstOrDefault(m => m.User.Name == userName);
            }
            if (membership != null && PasswordEncryptor.Validate(password, membership.Password))
            {
                _cookieUserData = new CookieUserData
                {
                    UserId   = membership.User.Id,
                    UserName = membership.User.Name
                };
                CookieDataProvider.Login(membership.User.Name, _cookieUserData, persistCookie);
                return(true);
            }
            return(false);
        }