public async Task <IActionResult> Registr(RegistrModel regist)
        {
            if (!ModelState.IsValid)
            {
                return(View(nameof(Registr)));
            }
            AppUser appUser = await userManager.FindByEmailAsync(regist.Email);

            if (appUser != null)
            {
                ModelState.AddModelError("", "Bu email var");
                return(View());
            }
            else
            {
                if (ModelState.IsValid)
                {
                    var user         = mapper.Map <AppUser>(regist);
                    var registrasiya = await userManager.CreateAsync(user, regist.Password);

                    if (registrasiya.Succeeded)
                    {
                        return(View(nameof(Login)));
                    }
                }
            }

            return(View());
        }
예제 #2
0
        public Task <IActionResult> Registration([FromBody] RegistrModel model)
        {
            // Checking user existence
            User user = _dbContext.users.Where(u => u.Phone == model.Phone).FirstOrDefault();

            if (user == null)
            {
                return(BadRequest(new { Messages = new[] { "Incorrect phone or card number." } }));
            }

            // Verify PAN
            Card card = _dbContext.cards.Where(c => c.PAN == model.PAN).FirstOrDefault();

            if (!CheckCardNumber(model.PAN) || card == null || card.UserId != user.Id)
            {
                return(BadRequest(new { Messages = new[] { "Incorrect phone or card number." } }));
            }

            // Check if SMS was sent recently to this user
            SmsSession smsSession = _dbContext.smsSessions.Where(s => s.UserId == user.Id)
                                    .OrderByDescending(s => s.Id)
                                    .Include(s => s.User)
                                    .Take(1)
                                    .FirstOrDefault();

            if (smsSession != null)
            {
                if (Math.Abs((smsSession.CreatedAt - DateTime.UtcNow).Minutes) < 1)
                {
                    return(BadRequest(new { Messages = new[] { "SMS code has already been sent to you. To send a new one, wait a minute from the moment of sending the past." } }));
                }
            }

            // Generate OTP
            long   hotpCounter = _dbContext.GetHotpCounter();
            string hotpCode    = hotp.ComputeHOTP(1 /*hotpCounter*/);

            //Send SMS
            //HttpStatusCode sendingResult = await _smsSender.SendSmsAsync(model.Phone, hotpCode);
            //if (sendingResult != HttpStatusCode.OK)
            //    return StatusCode(500, new { Message = "Error sending SMS code." });

            // Save SmsSession
            smsSession = new SmsSession()
            {
                UserId = user.Id, CodeHotpCounter = 1 /*hotpCounter*/, CreatedAt = DateTime.UtcNow
            };
            _dbContext.smsSessions.Add(smsSession);
            //await _dbContext.SaveChangesAsync();

            return(Created("", new
            {
                Message = "An SMS with a verification code has been sent to your number.",
                SessionToken = IssueToken(TypeToken.Session, user.Id)
            }));
        }
예제 #3
0
        public async Task <IActionResult> Registr(RegistrModel model)
        {
            if (ModelState.IsValid)
            {
                User user = new User {
                    Email = model.Email, UserName = model.Name, Year = new DateTime(model.Year, 1, 1), StatusComentId = 1
                };

                if (model.Avatar != null && (model.Avatar.ContentType == "image/png" || model.Avatar.ContentType == "image/jpeg"))
                {
                    byte[] imageData = null;
                    using (var binaryReader = new BinaryReader(model.Avatar.OpenReadStream()))
                    {
                        imageData = binaryReader.ReadBytes((int)model.Avatar.Length);
                    }
                    user.Photo = imageData;
                }

                var result = await _userManager.CreateAsync(user, model.Password);

                await _userManager.AddToRoleAsync(user, "user");

                if (result.Succeeded)
                {
                    await SendCode(user, _userManager, model.Email);

                    await _signInManager.SignInAsync(user, true);

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return(View(model));
        }
예제 #4
0
        public async Task <ActionResult> Register(RegistrModel model)
        {
            //Проверяет правильность заполнения формы
            if (ModelState.IsValid)
            {
                //Создает модель пользователя
                AppUser user = new AppUser {
                    Email = model.Email, UserName = model.Login, Name = model.Name, Surname = model.Surname, DateOfRegistration = DateTime.Today.Date, Gender = model.Gender, Online = false
                };
                user.Photo = model.File == null ? AppUser.DefaultPhoto :user.Id.GetHashCode() + ".jpg";
                //Добавляет пользователя в бд
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                //Проверяет был ли пользователь добавлен в бд
                if (result.Succeeded)
                {
                    //Создает токен подтверждения Email
                    var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    // Создаем ссылку для подтверждения
                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code },
                                                 protocol: Request.Url.Scheme);
                    try
                    {
                        // Отправка письма
                        await UserManager.SendEmailAsync(user.Id, "Подтверждение электронной почты",
                                                         "Для завершения регистрации перейдите по ссылке: <a href=\""
                                                         + callbackUrl + "\">завершить регистрацию</a>");
                    }
                    //Возникает,если указанного Email не существует
                    catch (SmtpException e)
                    {
                        ModelState.AddModelError("", e.Message);
                        await UserManager.DeleteAsync(user);

                        return(View(model));
                    }
                    //Проверяет загрузил ли пользователь фото
                    if (model.File != null)
                    {
                        //Добаляет фото пользователя в проект
                        LoadPhoto(model.File, user.Id);
                    }

                    //Удаляет пользователя,если он не подтвердил свою учетную записть в течении 10 минут
                    ThreadPool.QueueUserWorkItem(delegate
                    {
                        Cleaner.DeleteNoConfirmedUser(user.Id);
                    });

                    ViewBag.Message = "На указанный электронный адрес отправлены дальнейшие инструкции по завершению регистрации";
                    return(View("Confirm"));
                }
                else
                {
                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
            }
            return(View(model));
        }