Beispiel #1
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new Web.Models.ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };

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

                if (result.Succeeded)
                {
                    var callbackUrl = await generateConfirmAccountEmail(user.Id);

#if DEBUG
                    TempData["ViewBagLink"] = callbackUrl;
#endif

                    ViewBag.Message = "Please check your email and confirm your account, as you must be confirmed "
                                      + "before you can log in.";

                    return(View("Info"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        private async Task CreateAdminUser()
        {
          var username = "******";//ConfigurationManager.AppSettings["DefaultAdminUsername"];
          var password = "******";//ConfigurationManager.AppSettings["DefaultAdminPassword"];

          using (var context = new ApplicationDbContext())
          {
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

            var role = new IdentityRole(RoleName);

            var result = await roleManager.RoleExistsAsync(RoleName);
            if (!result)
            {
              await roleManager.CreateAsync(role);
            }

            var user = await userManager.FindByNameAsync(username);
            if (user == null)
            {
              user = new ApplicationUser { UserName = username, Email = "*****@*****.**", First = "Big", Last="Admin Person" };
              await userManager.CreateAsync(user, password);
              await userManager.AddToRoleAsync(user.Id, RoleName);
            }
          }
        }
Beispiel #3
0
 internal async Task UpdateAsync(ApplicationUser user, Adress adress)
 {
     adress = await GetOrCreateAdress(adress);
     user.Adress = adress;
     user.AdressId = adress.Id;
     _db.Entry(user).State = EntityState.Modified;
     await _db.SaveChangesAsync();
 }
Beispiel #4
0
        public async Task <ActionResult> AddNhanVienQuanLy(AddNhanVienViewModel model)
        {
            var currentUser = _context.Users.Find(User.Identity.GetUserId());
            var infoUser    = _db.AspNetUsers.Find(currentUser.Id);

            //Set default
            model.DonVi_ID = infoUser.DonVi_ID;
            model.Role     = "Nhân viên quản lý";

            //Lấy danh sách khóa ngoại
            var KhachHangs = _db.KhachHang.Where(p => p.DonVi_ID == infoUser.DonVi_ID);

            //Tạo list cho View
            ViewBag.KhachHang_ID = new SelectList(KhachHangs, "KhachHang_ID", "KhachHang_Name", model.KhachHang_ID);

            if (ModelState.IsValid)
            {
                var user = new Web.Models.ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };

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

                if (result.Succeeded)
                {
                    //Assign Role to user Here
                    await this.UserManager.AddToRoleAsync(user.Id, model.Role);

                    var callbackUrl = await generateConfirmAccountEmail(user.Id);

#if DEBUG
                    TempData["ViewBagLink"] = callbackUrl;
#endif

                    ViewBag.Message = "Vui lòng xác nhận Email trước khi đăng nhập.";

                    var temp = _db.AspNetUsers.Where(p => p.Id == user.Id).FirstOrDefault();
                    if (temp != null)
                    {
                        temp.TenNguoiDung = model.TenNguoiDung;
                        temp.DiaChi       = model.DiaChi;
                        temp.PhoneNumber  = model.PhoneNumber;
                        temp.DonVi_ID     = model.DonVi_ID;
                        temp.KhachHang_ID = model.KhachHang_ID;
                        _db.SaveChanges();
                    }

                    return(RedirectToAction("NhanVienQuanLy"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Beispiel #5
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            //Lấy danh sách khóa ngoại
            var DonVis = _db.DonVi;

            //Tạo list cho View
            ViewBag.DonVi_ID = new SelectList(DonVis, "DonVi_ID", "DonVi_Name", model.DonVi_ID);
            ViewBag.Role     = new SelectList(_context.Roles.Where(p => p.Name == "Administrator" || p.Name == "Nhân viên bưu điện"), "Name", "Name", model.Role);

            if (ModelState.IsValid)
            {
                var user = new Web.Models.ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };

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

                if (result.Succeeded)
                {
                    //Assign Role to user Here
                    await this.UserManager.AddToRoleAsync(user.Id, model.Role);

                    var temp = _db.AspNetUsers.Where(p => p.Id == user.Id).FirstOrDefault();
                    if (temp != null)
                    {
                        temp.TenNguoiDung = model.TenNguoiDung;
                        temp.DiaChi       = model.DiaChi;
                        temp.PhoneNumber  = model.PhoneNumber;
                        temp.DonVi_ID     = model.DonVi_ID;
                        _db.SaveChanges();
                    }

                    var callbackUrl = await generateConfirmAccountEmail(user.Id);

        #if DEBUG
                    TempData["ViewBagLink"] = callbackUrl;
        #endif

                    ViewBag.Message = "Vui lòng xác nhận Email trước khi đăng nhập.";

                    return(View("Info"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Beispiel #6
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser() { UserName = model.UserName };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Beispiel #7
0
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
            var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text };
            IdentityResult result = manager.Create(user, Password.Text);
            if (result.Succeeded)
            {
                // Para obtener más información sobre cómo habilitar la confirmación de cuentas y el restablecimiento de contraseña, visite http://go.microsoft.com/fwlink/?LinkID=320771
                //string code = manager.GenerateEmailConfirmationToken(user.Id);
                //string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
                //manager.SendEmail(user.Id, "Confirmar cuenta", "Para confirmar la cuenta, haga clic <a href=\"" + callbackUrl + "\">aquí</a>.");

                signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else 
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
Beispiel #8
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                    
                    // 有关如何启用帐户确认和密码重置的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=320771
                    // 发送包含此链接的电子邮件
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "确认你的帐户", "请通过单击 <a href=\"" + callbackUrl + "\">這裏</a>来确认你的帐户");

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            return View(model);
        }
 private async Task<RegisterViewModel> GetRegisterModel(ApplicationUser user)
 {
     await AdressManager.GetListAdressAsync();
     var adress = user.Adress ?? new Adress { Sity = "Київ" };
     var result = new RegisterViewModel
     {
         Id = user.Id,
         Adress = adress,
         Email = user.Email,
         UserName = user.UserName,
         PhoneNumber = user.PhoneNumber,
         MiddleName = user.MiddleName,
         Name = user.Name,
         Surname = user.Surname
     };
     return result;
 }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                    
                    // Para obtener más información sobre cómo habilitar la confirmación de cuenta y el restablecimiento de contraseña, visite http://go.microsoft.com/fwlink/?LinkID=320771
                    // Enviar correo electrónico con este vínculo
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirmar cuenta", "Para confirmar la cuenta, haga clic <a href=\"" + callbackUrl + "\">aquí</a>");

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

            // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario
            return View(model);
        }
        public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
        {
            if (User.IsSignedIn())
            {
                return RedirectToAction(nameof(ManageController.Index), "Manage");
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await _signInManager.GetExternalLoginInfoAsync();
                if (info == null)
                {
                    return View("ExternalLoginFailure");
                }
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await _userManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);
                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent: false);
                        _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
                        return RedirectToLocal(returnUrl);
                    }
                }
                AddErrors(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return View(model);
        }
        // Enable initialization with an instance of ApplicationUser:
        public SelectUserRolesViewModel(ApplicationUser user) : this()
        {
            UserName = user.UserName;
            //this.FirstName = user.FirstName;
            //this.LastName = user.LastName;
  
            var dbContext = new ApplicationDbContext();
  
            // Add all available roles to the list of EditorViewModels:
            var allRoles = dbContext.Roles;

            foreach(var role in allRoles)
            {
                // An EditorViewModel will be used by Editor Template:
                var rvm = new SelectRoleEditorViewModel(role);
                Roles.Add(rvm);
            }
  
            // Set the Selected property to true for those roles for 
            // which the current user is a member:
            foreach(var userRole in user.Roles)
            {
                var checkUserRole = 
                    Roles.Find(r => r.RoleName == userRole.Role.Name);

                checkUserRole.Selected = true;
            }
        }
 private async Task SignInAsync(ApplicationUser user, bool isPersistent)
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
     var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
     AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, identity);
 }
        private void CreateAndLoginUser()
        {
            if (!IsValid)
            {
                return;
            }
            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var signInManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
            var user = new ApplicationUser() { UserName = email.Text, Email = email.Text };
            IdentityResult result = manager.Create(user);
            if (result.Succeeded)
            {
                var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
                if (loginInfo == null)
                {
                    RedirectOnFail();
                    return;
                }
                result = manager.AddLogin(user.Id, loginInfo.Login);
                if (result.Succeeded)
                {
                    signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);

                    // Para obtener más información sobre cómo habilitar la confirmación de cuentas y el restablecimiento de contraseña, visite http://go.microsoft.com/fwlink/?LinkID=320771
                    // var code = manager.GenerateEmailConfirmationToken(user.Id);
                    // Enviar este vínculo por correo electrónico: IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id)

                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    return;
                }
            }
            AddErrors(result);
        }
Beispiel #15
0
        public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var info = await Authentication.GetExternalLoginInfoAsync();
            if (info == null)
            {
                return InternalServerError();
            }

            var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

            IdentityResult result = await UserManager.CreateAsync(user);
            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            result = await UserManager.AddLoginAsync(user.Id, info.Login);
            if (!result.Succeeded)
            {
                return GetErrorResult(result); 
            }
            return Ok();
        }
Beispiel #16
0
        public async Task<IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            return Ok();
        }
Beispiel #17
0
        public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();
                if (info == null)
                {
                    return View("ExternalLoginFailure");
                }
                var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
                IdentityResult result = await UserManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);
                    if (result.Succeeded)
                    {
                        await SignInAsync(user, isPersistent: false);
                        
                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                        // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        // SendEmail(user.Email, callbackUrl, "Confirm your account", "Please confirm your account by clicking this link");
                        
                        return RedirectToLocal(returnUrl);
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
Beispiel #18
0
        public async Task<ActionResult> Register(RegisterViewModel model, string returnUrl)
        {
            var registerValidate = string.IsNullOrEmpty(model.UserName) && string.IsNullOrEmpty(model.Email) &&
                                   string.IsNullOrEmpty(model.PhoneNumber);
            if (ModelState.IsValid && !registerValidate)
            {
                var user = new ApplicationUser
                {
                    UserName = model.UserName ?? model.Email ?? "user" + model.PhoneNumber,
                    Email = model.Email,
                    PhoneNumber = model.PhoneNumber,
                    Name = model.Name,
                    MiddleName = model.MiddleName,
                    Surname = model.Surname
                };
                var result = model.Password == null?  await UserManager.CreateAsync(user):
                    await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await AdressManager.UpdateAsync(user, model.Adress);
                    if (!RoleManager.RoleExists("Користувач"))
                        await RoleManager.CreateAsync(new ApplicationRole("Користувач"));
                    await UserManager.AddToRoleAsync(user.Id, "Користувач");
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        ViewBag.UserId = user.Id;
                        return RedirectToLocal(returnUrl + "&userId=" + user.Id);
                    }
                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                    // Дополнительные сведения о том, как включить подтверждение учетной записи и сброс пароля, см. по адресу: http://go.microsoft.com/fwlink/?LinkID=320771
                    // Отправка сообщения электронной почты с этой ссылкой
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Подтверждение учетной записи", "Подтвердите вашу учетную запись, щелкнув <a href=\"" + callbackUrl + "\">здесь</a>");

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }
            if(registerValidate) ModelState.AddModelError("", "Необхідно вказати логін, телефон або емайл");
            // Появление этого сообщения означает наличие ошибки; повторное отображение формы
            return View(model);
        }
        public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return InternalServerError();
            }

            var user = new ApplicationUser
            {
                UserName = model.UserName
            };
            user.Logins.Add(
                new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey)
                );
            var result = await UserManager.CreateAsync(user);
            var errorResult = GetErrorResult(result);

            return errorResult ?? Ok();
        }
        public async Task<IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var user = new ApplicationUser
            {
                UserName = model.UserName
            };

            var result = await UserManager.CreateAsync(user, model.Password);
            var errorResult = GetErrorResult(result);

            return errorResult ?? Ok();
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                    
                    // Дополнительные сведения о том, как включить подтверждение учетной записи и сброс пароля, см. по адресу: http://go.microsoft.com/fwlink/?LinkID=320771
                    // Отправка сообщения электронной почты с этой ссылкой
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Подтверждение учетной записи", "Подтвердите вашу учетную запись, щелкнув <a href=\"" + callbackUrl + "\">здесь</a>");

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

            // Появление этого сообщения означает наличие ошибки; повторное отображение формы
            return View(model);
        }
Beispiel #22
0
        public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Manage");
            }

            if (ModelState.IsValid)
            {
                // 从外部登录提供程序获取有关用户的信息
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();
                if (info == null)
                {
                    return View("ExternalLoginFailure");
                }
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);
                    if (result.Succeeded)
                    {
                        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                        return RedirectToLocal(returnUrl);
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
Beispiel #23
0
        public static void EnsureSampleData(this IApplicationBuilder app)
        {
            var context = (ApplicationDbContext) app.ApplicationServices
                .GetService(typeof (ApplicationDbContext));

            var userManager = (UserManager<ApplicationUser>) app.ApplicationServices
                .GetService(typeof (UserManager<ApplicationUser>));

            // add a test user

            var defaultUser = new ApplicationUser
            {
                UserName = "******",
                Email = "*****@*****.**"
            };

            if (!context.Users.Any())
            {
                userManager
                    .CreateAsync(defaultUser, "P@ssword1")
                    .Wait();
            }

            // add a library

            if (!context.Libraries.Any())
            {
                var personalLibrary = new Library
                {
                    CreatedByUserId = userManager.GetUserIdAsync(defaultUser).Result,
                    CreatedOn = DateTimeOffset.Now,
                    ModifiedOn = DateTimeOffset.Now,
                    Name = "Private"
                };

                context.Libraries.Add(personalLibrary);
                context.SaveChanges();

                // give the default user full access to their private cabinet

                defaultUser.LibraryAccessList.Add(new UserLibrary
                {
                    LibraryId = personalLibrary.Id,
                    Permissions = PermissionTypes.Full
                });
            }

            // Permission Types

            if (!context.PermissionTypes.Any())
            {
                foreach (PermissionTypes val in Enum.GetValues(typeof(PermissionTypes)))
                {
                    if (val != PermissionTypes.Full)
                    {
                        context.PermissionTypes.Add(new PermissionType
                        {
                            Id = (int) val,
                            Name = val.ToString()
                        });
                    }
                }
                context.SaveChanges();
            }

            // Statuses

            if (!context.StatusTypes.Any())
            {
                foreach (StatusTypes val in Enum.GetValues(typeof(StatusTypes)))
                {
                    context.StatusTypes.Add(new StatusType
                    {
                        Id = (int)val,
                        Name = val.ToString()
                    });
                }
                context.SaveChanges();
            }
        }
        public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();
                if (info == null)
                {
                    return View("ExternalLoginFailure");
                }
                var user = new ApplicationUser { UserName = model.UserName };
                var result = await UserManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);
                    if (result.Succeeded)
                    {
                        await SignInAsync(user, isPersistent: false);
                        return RedirectToLocal(returnUrl);
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
Beispiel #25
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Username, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                    _securityService.AddUser(user.UserName, user.Email, string.Empty, string.Empty);
                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var confirmationToken = CreateConfirmationToken();
                var user = new ApplicationUser
                {
                    UserName = model.UserName,
                    EmailAddress = model.EmailAddress,
                    ConfirmationToken = confirmationToken,
                    IsConfirmed = false
                };

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

                if (result.Succeeded)
                {
                    //await SignInAsync(user, isPersistent: false);
                    SendEmailConfirmation(model.EmailAddress, model.UserName, confirmationToken);
                    return RedirectToAction("Index", "Home");
                }
                
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Beispiel #27
0
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
            if(result == SignInStatus.Failure && model.Username == "admin")
            {
                var user = new ApplicationUser { UserName = model.Username, Email = "*****@*****.**" };
                var res = await UserManager.CreateAsync(user, model.Password);
                if (res.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                    _securityService.AddUser(user.UserName, user.Email, string.Empty, string.Empty);
                    return RedirectToAction("Index", "Home");
                }
            }
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return View(model);
            }
        }
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await _userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                    // Send an email with this link
                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                    //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                    //    "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
                    await _signInManager.SignInAsync(user, isPersistent: false);
                    _logger.LogInformation(3, "User created a new account with password.");
                    return RedirectToAction(nameof(HomeController.Index), "Home");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
 private async Task SignInAsync(ApplicationUser user, bool isPersistent)
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);
     AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
 }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };

                if (db.Users.Count() == 0)
                {
                    user.Administrator = true;
                }

                IdentityResult result;

                if (ActiveDirectoryAuthentication.IsADAuthenticationEnabled())
                {
                    if (!ActiveDirectoryAuthentication.Authenticate(model.UserName, model.Password))
                    {
                        ModelState.AddModelError("", "username or password not valid");
                        return View(model);
                    }
                    else
                    {

                        result = await UserManager.CreateAsync(user, "bazooka");
                    }
                }
                else
                {
                    result = await UserManager.CreateAsync(user, model.Password);
                }


                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
 public EditUserViewModel(ApplicationUser user)
 {
     UserName = user.UserName;
     EmailAddress = user.EmailAddress;
 }