Пример #1
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                User user = await db.Users.FirstOrDefaultAsync(u => u.Email == model.Email);

                if (user == null)
                {
                    Role role = new Role();
                    // добавляем пользователя в бд
                    if (User.IsInRole("Admin"))
                    {
                        role = db.Roles.Find(model.RoleId);
                    }
                    else
                    {
                        role = await db.Roles.FirstOrDefaultAsync(r => r.RoleName == "User");
                    }

                    user = new User
                    {
                        FirstName = model.FirstName,
                        LastName  = model.LastName,
                        Email     = model.Email,
                        Password  = PasswordGenerate.HashPassword(model.Password),
                        Role      = role ?? null
                    };
                    db.Users.Add(user);
                    await db.SaveChangesAsync();

                    await Authenticate(user); // аутентификация

                    return(RedirectToAction("Login", "Account"));
                }
                else
                {
                    ModelState.AddModelError("", "Такой пользователь уже существует");
                }
            }


            return(View(model));
        }
Пример #2
0
        public async Task <IActionResult> Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                User user = await db.Users.Include(u => u.Role).
                            FirstOrDefaultAsync(u => u.Email == model.Email &&
                                                u.Password == PasswordGenerate.HashPassword(model.Password));

                if (user != null)
                {
                    await Authenticate(user); // аутентификация

                    return(RedirectToAction("Index", "Home"));
                }
                ModelState.AddModelError("", "Некорректные логин и(или) пароль");
            }

            return(View(model));
        }