예제 #1
0
        public ActionResult Activation(AccountActivationViewModel model)
        {
            if (!Request.IsAuthenticated)
            {
                return(RedirectToAction("signin", "account", null));
            }

            if (ModelState.IsValid)
            {
                if (model.CodeId == Guid.Empty || string.IsNullOrWhiteSpace(model.Code))
                {
                    var phone = UserService.NormalizePhoneNumber(model.Phone);

                    var encryptedPhoneNumber = CryptographyService.EncryptPhone(phone);
                    var usersWithSamePhone   = DataService.PerThread.BaseUserSet.OfType <User>().Count(u => u.EncryptedPhoneNumber == encryptedPhoneNumber && (u.Id != model.Id));
                    if (usersWithSamePhone != 0)
                    {
                        throw new ValidationException("Пользователь с таким номером телефона уже активирован");
                    }

                    var user = DataService.PerThread.BaseUserSet.OfType <User>().SingleOrDefault(u => u.Id == UserContext.Current.Id);
                    if (user == null)
                    {
                        throw new BusinessLogicException("Неверный идентификатор пользователя!");
                    }

                    user.PhoneNumber = phone;
                    user.SubscriptionSettings.SubscriptionEmail = model.SubscribtionMail;

                    UserService.NormalizePhoneNumber(user);

                    ModelState.Clear();

                    model.CodeId   = user.Id;
                    model.ShowCode = true;

                    var code = AccountService.GenerateSecretCode(user.Id);
                    var sms  = "Ваш секретный код для верификации на Демократии2: " + code;

                    if (UserContext.Current.SentSmsCount >= 5)
                    {
                        throw new BusinessLogicException("Лимит ваших смс исчерпан. Обратитесь в техподдержку");
                    }

                    SmsService.SendSms(user.PhoneNumber, sms);
                    UserContext.Current.SentSmsCount++;
                }
                else
                {
                    if (!AccountService.VerifySecretCode(model.CodeId, model.Code))
                    {
                        throw new ValidationException("Введен неверный код!");
                    }

                    if (UserContext.Current.Id != model.Id)
                    {
                        throw new BusinessLogicException("Возникла ошибка. Ключ пользователя начала и завершения активации аккаунта не совпадают.");
                    }

                    var user = DataService.PerThread.BaseUserSet.OfType <User>().SingleOrDefault(x => x.Id == UserContext.Current.Id);
                    if (user == null)
                    {
                        throw new BusinessLogicException("Возникла ошибка. Система не знает такого пользователя.");
                    }

                    user.IsOutdated      = false;
                    user.IsPhoneVerified = true;

                    UserContext.Abandon();

                    return(RedirectToAction("profile", "user", null));
                }
            }

            return(View(model));
        }
예제 #2
0
        public ActionResult SignUp(AccountSignUpViewModel model, bool?isdialog)
        {
            if (ModelState.IsValid)
            {
                var phone = UserService.NormalizePhoneNumber(model.PhoneNumber);

                var encryptedPhoneNumber = CryptographyService.EncryptPhone(phone);
                var usersWithSamePhone   = DataService.PerThread.BaseUserSet.OfType <User>().Count(u => u.EncryptedPhoneNumber == encryptedPhoneNumber);
                if (usersWithSamePhone != 0)
                {
                    throw new ValidationException("Пользователь с таким номером телефона уже зарегистрирован");
                }

                var encryptedEmail     = CryptographyService.EncryptEmail(model.Email);
                var usersWithSameEmail = DataService.PerThread.BaseUserSet.OfType <User>().Count(u => u.EncryptedEmail == encryptedEmail);
                if (usersWithSameEmail != 0)
                {
                    throw new ValidationException("Пользователь с такой электропочтой уже зарегистрирован");
                }

                var user = (User)AccountService.SignUp(model.Email, model.Email, model.Password, false);
                user.FirstName       = model.Name;
                user.SurName         = model.SurName;
                user.Patronymic      = model.Patronymic;
                user.PhoneNumber     = phone;
                user.Sex             = ValueAnalizer.GetGenderFromString(model.Gender);
                user.IsPhoneVerified = false;
                user.IsEmailVerified = false;
                user.IsOutdated      = true;

                UserService.NormalizePhoneNumber(user);

                if (model.ConnectSocial && HttpContext.Session["social_type"] != null && HttpContext.Session["social_id"] != null && HttpContext.Session["social_link"] != null)
                {
                    var socialType = (SocialType)HttpContext.Session["social_type"];
                    var socialLink = HttpContext.Session["social_link"].ToString();
                    var socialKey  = HttpContext.Session["social_id"].ToString();

                    var usersWithSameSocial = DataService.PerThread.SocialAccountSet.Count(u => u.SocialId == socialKey && u.SocialType == (byte)socialType);
                    if (usersWithSameSocial != 0)
                    {
                        throw new ValidationException("Пользователь с таким аккаунтом " + model.SocialType.ToString() + " уже зарегистрирован");
                    }

                    AccountService.ConnectSocialAccount(user, socialType, socialLink, socialKey);
                    HttpContext.Session.Remove("social_id");
                    HttpContext.Session.Remove("social_type");
                    HttpContext.Session.Remove("social_link");
                }

                DataService.PerThread.SaveChanges();

                //var code = AccountService.GenerateSecretCode(user.Id);
                //var sms = "Ваш секретный код для верификации на Демократии2: " + code;
                //SmsService.SendMessage("+7" + telephone, sms);

                //var smtp = new SmtpClient();
                //var link = ConstHelper.AppUrl + Url.Action("codeVerification", new { id = user.Id });
                //var message = new MailMessage
                //{
                //    Subject = "Ввод кода подтверждения на Демократии2",
                //    Body = "<p>Если вы еще не ввели код подтверждения, пришедший вам по смс, перейдите по ссылке: <a href='" + link + "'>" + link + "</a>.</p>" +
                //        "<p>Если вам не пришло смс, напишите на <a href='mailto:[email protected]'>[email protected]</a></p>",
                //    IsBodyHtml = true
                //};

                //message.To.Add(user.Email);

                //smtp.Send(message);
                //smtp.Dispose();

                AccountService.SendEmailVerification(user.Id);
                AccountService.TrySignIn(model.Email, model.Password, true, HttpContext.Request.UserHostAddress);

                MonitoringService.AsynchLogUserRegistration(user.Id, HttpContext.Request.UserHostAddress);

                if (string.IsNullOrWhiteSpace(model.ReturnUrl))
                {
                    return(RedirectToAction("index", "user"));
                }

                return(Redirect(model.ReturnUrl));
            }

            if (isdialog.HasValue)
            {
                if (isdialog.Value)
                {
                    return(View("SignUp", "_LightLayout", model));
                }
            }

            return(View(model));
        }