Inheritance: IdentityUser
        public async Task<IActionResult> Create(EmployeeRegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    FIO = model.FIO,
                    UserName = model.Email,
                    Email = model.Email,
                    OpenPassword = model.Password
                };
                var result = await _userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    var roles = new List<string>();
                    roles.Add(RoleNames.Employee);
                    roles.AddRange(model.GetSelectedRoles());
                    
                    var resultRole = await _userManager.AddToRolesAsync(user, roles);

                    return RedirectToAction(nameof(Index));
                }
                AddErrors(result);
            }
            
            return View(model);
        }
Beispiel #2
0
        private async Task<IActionResult> GetUserInfo(ApplicationUser user) {
            try
            {
                if (user == null)
                {
                    return HttpNotFound();
                }

                var role = (await _userManager.GetRolesAsync(user)).FirstOrDefault();

                if (user.MemberInfo == null)
                {
                    var menber = (from member in this._applicationDbContext.Members
                                  where member.MemberID.Equals(user.UserName)
                                  select new
                                  {
                                      ID = member.MemberID,
                                      Name = member.Name ?? "",
                                      Level = GetLevelDisplayName(member.Level),
                                      Role = role ?? "",
                                      RegisterDate = member.RegisterDate.ToString("yyyy'-'MM'-'dd"),
                                      NeedToChangePassword = user.ChangedPassword == false
                                  }).FirstOrDefault();
                    if (menber == null)
                    {
                        return HttpNotFound();
                    }
                    return new JsonResult(menber);
                }
                else
                {
                    return new JsonResult(new
                    {
                        ID = user.MemberInfo.MemberID,
                        Name = user.MemberInfo.Name ?? "",
                        Level = GetLevelDisplayName(user.MemberInfo.Level),
                        Role = role ?? "",
                        RegisterDate = user.MemberInfo.RegisterDate,
                        NeedToChangePassword = user.ChangedPassword == false
                    });
                }
            }
            catch (Exception e) {
                return new JsonResult(new
                {
                    Message = e.Message
                });
            }
        }
Beispiel #3
0
 protected void CreateUser_Click(object sender, EventArgs e)
 {
     var manager = new UserManager();
     var user = new ApplicationUser() { UserName = UserName.Text };
     IdentityResult result = manager.Create(user, Password.Text);
     if (result.Succeeded)
     {
         IdentityHelper.SignIn(manager, user, isPersistent: false);
         IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
     }
     else
     {
         ErrorMessage.Text = result.Errors.FirstOrDefault();
     }
 }
        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);
                }
            }

            // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario
            return View(model);
        }
        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 #6
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)
            {
                // For more information on how to enable account confirmation and password reset please visit 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, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>.");

                signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else 
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
        public async Task<ActionResult> Create(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);

                    // 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", "AccountManager");
                }
                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);
     var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
     AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
 }
        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 void CreateAndLoginUser()
 {
     if (!IsValid)
     {
         return;
     }
     var manager = new UserManager();
     var user = new ApplicationUser() { UserName = userName.Text };
     IdentityResult result = manager.Create(user);
     if (result.Succeeded)
     {
         var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
         if (loginInfo == null)
         {
             Response.Redirect("~/Account/Login");
             return;
         }
         result = manager.AddLogin(user.Id, loginInfo.Login);
         if (result.Succeeded)
         {
             IdentityHelper.SignIn(manager, user, isPersistent: false);
             IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
             return;
         }
     }
     AddErrors(result);
 }
 private async Task SignInAsync(ApplicationUser user, bool isPersistent)
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
     AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
 }
 private async Task StoreFacebookAuthToken(ApplicationUser user)
 {
     var claimsIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
     if (claimsIdentity != null)
     {
         // Retrieve the existing claims for the user and add the FacebookAccessTokenClaim
         var currentClaims = await UserManager.GetClaimsAsync(user.Id);
         var facebookAccessToken = claimsIdentity.FindAll("FacebookAccessToken").First();
         if (currentClaims.Count() <= 0)
         {
             await UserManager.AddClaimAsync(user.Id, facebookAccessToken);
         }
         else
         {
             await UserManager.RemoveClaimAsync(user.Id, currentClaims[0]);
             await UserManager.AddClaimAsync(user.Id, facebookAccessToken);
         }
     }
 }
 public async Task<ActionResult> AddAccount(AccountViewModel model)
 {
     if (ModelState.IsValid)
     {
         var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
         IdentityResult result = await UserManager.CreateAsync(user, model.Password);
         if (result.Succeeded)
         {
             return RedirectToAction("Index");
         }
         else
         {
             AddErrors(result);
         }
     }
     return _Index();
 }
        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();
        }
        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 #16
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser() { UserName = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await UserManager.AddToRoleAsync(user.Id, "canEdit");
                    await SignInAsync(user, isPersistent: false);
                    await _userManager.EmailService.SendWelcomeEmail(user.UserName, user.Email);

                    TempData["flash"] = new FlashSuccessViewModel("Congratulations! Your account has been created.");
                    return RedirectToAction("Index", "Notes");
                }
                    AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Beispiel #17
0
        public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Obtener datos del usuario del proveedor de inicio de sesión externo
                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);
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Type = model.Type };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                    ApplicationDbContext db = new ApplicationDbContext();

                    GeneralUser generalUser = null;
                    if (user.Type == 1)
                        generalUser = new StudentUser() { Email = user.Email };
                    else generalUser = new ProviderUser() { Email = user.Email };

                    ApplicationUser savedUser = db.Users.FirstOrDefault(x => x.Id == user.Id);
                    savedUser.GeneralUser = generalUser;
                    db.Entry(savedUser).State = System.Data.Entity.EntityState.Modified;

                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception e)
                    {

                    }

                    // 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>");
					if (user.Type == 1)
	                    return RedirectToAction("Index", "student");
					else
						return RedirectToAction("Index", "providers");
				}
                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 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);
                    
                    // Pour plus d'informations sur l'activation de la confirmation du compte et la réinitialisation du mot de passe, consultez http://go.microsoft.com/fwlink/?LinkID=320771
                    // Envoyer un message électronique avec ce lien
                    // 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, "Confirmez votre compte", "Confirmez votre compte en cliquant <a href=\"" + callbackUrl + "\">ici</a>");

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

            // Si nous sommes arrivés là, un échec s’est produit. Réafficher le formulaire
            return View(model);
        }
Beispiel #20
0
       // [ValidateAntiForgeryToken]
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            EnsureDatabaseCreated(_applicationDbContext);
            if (ModelState.IsValid)
            {
                Member menberReference = null;
                string refID = model.ReferenceID;
                if (String.IsNullOrWhiteSpace(refID)) {
                    var adminUser = (await _userManager.GetUsersInRoleAsync("Administrator")).FirstOrDefault();
                    if (adminUser != null) {
                        refID = adminUser.UserName;
                    }
                }

                if (String.IsNullOrWhiteSpace(refID) == false) {
                    menberReference = (from m in this._applicationDbContext.Members
                                          where m.MemberID.Equals(refID) 
                                          select m 
                                       ).FirstOrDefault();
                }

                if (menberReference == null) {
                    return ErrorMessage.BadRequestJsonResult("ReferenceID is not exist.");
                }

                var member = new Member {
                    MemberID = model.AccountID,
                    Reference = menberReference,
                    Name = model.Name,
                    IDCard = model.CardID,
                    Address = model.Address,
                    Level = model.Level
                };

                var user = new ApplicationUser
                {
                    Id = model.AccountID,
                    UserName = model.AccountID,
                    MemberInfo = member,
                    PhoneNumber = model.Phone
                };

                this._applicationDbContext.Members.Add(member);

                var result = await _userManager.CreateAsync(user, ApplicationUser.IINT_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: Context.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);
                    //return RedirectToAction(nameof(HomeController.Index), "Home");
                    return new JsonResult("OK");
                }
                AddErrors(result);
            }
            
            return ErrorMessage.BadRequestJsonResult(ModelState.Values.SelectMany(x => x.Errors));
        }
Beispiel #21
0
 private async Task CreateUsers(string id, string name, string role)
 {
     ApplicationUser user = new ApplicationUser
     {
         Id = id,
         UserName = id
     };
     user.MemberInfo = new Member { MemberID = id, Name = name };
     ctx.Members.Add(user.MemberInfo);
     var rulst =  await userManager.CreateAsync(user, ApplicationUser.IINT_PASSWORD);
     await userManager.AddToRoleAsync(user, role);
     //await userManager.AddClaimAsync(user, new Claim("ManageStore", "Allowed"));
 }
        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);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // var code = manager.GenerateEmailConfirmationToken(user.Id);
                    // Send this link via email: IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id)

                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    return;
                }
            }
            AddErrors(result);
        }
        public async Task<ActionResult> Edit(ApplicationUser user)
        {
            if (ModelState.IsValid)
            {
                var item = await UserManager.FindByIdAsync(user.Id);
                item.UserName = user.UserName;
                item.PhoneNumber = user.PhoneNumber;
                item.Email = user.Email;
                var result = await UserManager.UpdateAsync(item);
                if (result.Succeeded)
                {
                    return RedirectToAction("Index", "AccountManager");
                }
                AddErrors(result);
            }
            return View(user);

        }
        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);
        }
        public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "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 };
                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);
        }
        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)
                {
                    #region Userinformation
                    ////Userinformation
                    UserInformationController objController = new UserInformationController();
                    UserInformation objuser = new UserInformation();
                    objuser.AspNetUserId = user.Id;
                    objuser.AspNetRoleID = model.AspNetRoleID;
                    objuser.UserFullName = model.UserFullName;
                    objuser.UPassword = model.Password;
                    objuser.Email = model.Email;
                    objuser.CreateDate = DateTime.Now;
                    objuser.UserTypeID = 2;
                    objController.Save(objuser);
                    #endregion
                   // await SignInAsync(user, isPersistent: false);
                    return RedirectToAction("RegisterSuccess", "Account");
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }