Пример #1
0
 // Konstruktor uzupełniający model o dane użytkownika. Jest on uzupełnieniem
 // konstruktora tworzącego kompletny obiekt, dlatego niektóre pola będą NULL.
 public CharacterChartDbModel(
     ApplicationUser user
     ) : this()
 {
     if (user != null) CreatorUserID = user.Id;
     else CreatorUserID = null;
 }
Пример #2
0
        public ActionResult SaveCollage(string userID, string stringedJSON, int collageID)
        {
            ApplicationDbContext Context = new ApplicationDbContext();
            ApplicationUser User = new ApplicationUser();
            foreach (var i in Context.Users)
            {
                if (i.UserName == userID)
                    User = i;
            }
            Collages newCollage = new Collages();
            newCollage.userID = User.Id;
            newCollage.collageInfo = stringedJSON;
            if (collageID == 0)
            {
                Context.Collages.Add(newCollage);
                Context.Entry(newCollage).State = System.Data.Entity.EntityState.Added;
            }
            else
            {
                Context.Collages.Find(collageID).collageInfo = stringedJSON;

            }
            Context.SaveChanges();

            return RedirectToAction("Index");
        }
Пример #3
0
 // Konstruktor przypisujący ID przekazanego w parametrach użytkownika do modelu gracza.
 // Wywoływany jest domyślny konstruktor.
 public CharacterDbModel(
     ApplicationUser user
     ) : this()
 {
     if (user != null) UserID = user.Id;
     else UserID = null;
 }
Пример #4
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>.");

                var myMessage = new SendGrid.SendGridMessage();
                myMessage.AddTo(Email.Text);
                myMessage.From = new MailAddress("*****@*****.**", "ToDoTaskList");
                myMessage.Subject = "Welcome to ToDoTaskList!";
                myMessage.Text = "ToDoTaskList is an iterative tasklist that helps you seize the day.";

                var transportWeb = new SendGrid.Web("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");
                transportWeb.DeliverAsync(myMessage);
                signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
 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);
 }
Пример #6
0
 // Konstruktor tworzący obiekt zawierający dane niezbędne do zapisu w bazie.
 // Tworzony jest plik XML zawierający dane wprowadzone podczas tworzenia karty.
 public CharacterChartDbModel(
     CharacterChart chart,
     ApplicationUser user = null
     ) : this(user)
 {
     ChartID = chart.ChartID;
     Name    = chart.Name;
     GenerateXml(chart);
 }
Пример #7
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();
     }
 }
Пример #8
0
        // Konstruktor tworzący kompletny obiekt zawierający wszystkie dane dotyczące gracza. Tworzony
        // jest nowy plik XML (lub nadpisywany istniejący) zawierający informacje o graczu.
        //
        // todo: Pliki są tworzone również dla anonimowych użytkowników (niezalogowanych), można
        //       by zrobić mechanizm, który będzie usuwał stare pliki, żeby nie zajmowały miejsca na
        //       serwerze. Dostęp do pliku z poziomu niezalogowanego użytkownika jest obecnie niemożliwy.
        public CharacterDbModel(
            Character character,
            ApplicationUser user = null
            ) : this(user)
        {
            // Tworzenie pliku XML (nadpisuje istniejące pliki)
            XmlModels.Character characterXml = new XmlModels.Character(character);

            // Aktualizacja danych w modelu
            CharacterName    = character.Name;
            ChartID          = character.ChartID;
            CharacterID      = character.CharacterID;
            AvatarImgSrc     = character.AvatarImg;
            CharacterDataSrc = DefaultConstants.Application.DefaultXmlLocalization(
                                    CharacterID.ToString(),
                                    DefaultConstants.Application.DefaultCharacterXmlFolder
                                    );
        }
Пример #9
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);
        }
Пример #10
0
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            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>.");

                IdentityHelper.SignIn(manager, user, isPersistent: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
Пример #11
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);
                }
            }

            // 如果執行到這裡,發生某項失敗,則重新顯示表單
            return View(model);
        }
Пример #12
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)
            {
                // Дополнительные сведения о том, как включить подтверждение учетной записи и сброс пароля, см. по адресу: 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, "Подтверждение учетной записи", "Подтвердите вашу учетную запись, щелкнув <a href=\"" + callbackUrl + "\">здесь</a>.");

                signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else 
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
Пример #13
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)
            {
                // 有关如何启用帐户确认和密码重置的详细信息,请访问 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, "确认你的帐户", "请通过单击 <a href=\"" + callbackUrl + "\">此处 </a> 来确认你的帐户。");

                signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
Пример #14
0
 // Konstruktor tworzący kompletny model użykownika do wykorzystania na stronie (jeżeli zadziała).
 //
 // todo: Powyższy konstruktor może zwrócić wartość null w parametrze. Powoduje to NullReferenceException. 
 //       Obecne rozwiązanie nie gwarantuje bezproblemowej obsługi wyjątków.
 /// <summary>Tworzy nowy model użytkownika gotowy do wykorzystania na stronie</summary>
 /// <param name="user">Użytkownik</param>
 public User(
     ApplicationUser user
     )
 {
     try
     {
         Id           = user.Id;
         Email        = user.Email;
         PhoneNumber  = user.PhoneNumber;
         UserName     = user.UserName;
         UserSecureID = user.UserSecureID;
         Status       = user.Status;
         Banned       = user.Banned;
         AvatarSrc    = user.AvatarSrc;
         Friends      = GetFriends(Id);
     }
     catch(NullReferenceException exception)
     {
         throw exception;
     }
 }
        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)
            {
                // アカウントの確認とパスワードの再設定を有効にする方法については、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, "アカウントの確認", "このリンクをクリックすることによってアカウントを確認してください <a href=\"" + callbackUrl + "\">こちら</a>.");

                signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
Пример #16
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 = UserName.Text, Email = Email.Text };
            IdentityResult result = manager.Create(user, Password.Text);

            try
            {
                SqlConnection MyConnection = new SqlConnection("Data Source=cpeake.asuscomm.com;Integrated Security=False;User ID=matthew;Password=matthew;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False; Initial Catalog=WhenIf_Data;");

                string sql = "UPDATE [dbo].[AspNetUsers] SET DEPAULID = @DEPAULID WHERE USERNAME = @USERNAME";
                MyConnection.Open();
                SqlCommand cmd = new SqlCommand(sql, MyConnection);
                cmd.Parameters.Add("@DEPAULID", System.Data.SqlDbType.VarChar);
                cmd.Parameters.Add("@USERNAME", System.Data.SqlDbType.VarChar);
                cmd.Parameters["@DEPAULID"].Value = DepaulId.Text;
                cmd.Parameters["@USERNAME"].Value = UserName.Text;
                cmd.ExecuteNonQuery();

            } catch (Exception exception) {
                ErrorMessage.Text = exception.ToString();
            }

            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();
            }
        }
Пример #17
0
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var user = new ApplicationUser() { UserName = Email.Text,FirstName=FirstName.Text,LastName=LastName.Text, Email = Email.Text,City=City.Text,Street=Street.Text,ZipCode= Int32.Parse(ZipCode.Text),PhoneNumber=PhoneNumber.Text};
            IdentityResult result = manager.Create(user, Password.Text);

            if (result.Succeeded)
            {
                manager.AddToRole(user.Id, "NotConfirmed");

                IdentityHelper.SignIn(manager, user, isPersistent: false);

                // 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);
                manager.SendEmail(user.Id, "Scifiknihovna.cz - potvrzení registrace", "Prosím potvrďte svůj účet kliknutím na http://www.scifiknihovna.cz" + callbackUrl);

                IdentityHelper.RedirectToReturnUrl("~/Account/RegisterSuccess.aspx", Response);
            }
            else
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
        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);
                        return RedirectToLocal(returnUrl);
                    }
                }
                AddErrors(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return View(model);
        }
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            EnsureDatabaseCreated(_applicationDbContext);
            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: 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");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Пример #20
0
        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);
        }
Пример #21
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);
                    
                    // 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);
        }
Пример #22
0
        public async Task<ActionResult> Update(RegisterViewModel model)
        {
            var SavedUser = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            try
            {
                ApplicationUser UpdatedUser = new ApplicationUser();
                UpdatedUser.SecurityStamp = SavedUser.SecurityStamp;
                UpdatedUser.PasswordHash = SavedUser.PasswordHash;
                UpdatedUser.UserName = SavedUser.UserName;
                UpdatedUser.Id = SavedUser.Id;

                ApplicationDbContext db = new ApplicationDbContext();
                db.Entry(UpdatedUser).State = EntityState.Modified;
                await db.SaveChangesAsync();

                //            var result = await UserManager.UpdateAsync(SavedUser);
                return RedirectToAction("Index", "Home");
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                Exception raise = dbEx;
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        string message = string.Format("{0}:{1}",
                            validationErrors.Entry.Entity.ToString(),
                            validationError.ErrorMessage);
                        // raise a new exception nesting
                        // the current instance as InnerException
                        raise = new InvalidOperationException(message, raise);
                    }
                }
                throw raise;
            }
        }
        private async Task SignInAsync(ApplicationUser user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            
            ///Open Question- Hear it create claimIdentity. But we nothing add as such Claims but just User object.
            //public virtual Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType);

            var identity = await UserManager1.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            //var identity = await UserManager1.CreateAsync(user);//, DefaultAuthenticationTypes.ApplicationCookie);

            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
        }
Пример #24
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);
                    
                    // 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);
        }
Пример #25
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            OglasController aleksaoglas = new OglasController();
            
            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);

                    var korisnik = new Korisnik() { IDKorisnik = user.Id, eMail = user.UserName, MailStize = 0 };
                    aleksaoglas.baza.Korisnik.Add(korisnik);
                    aleksaoglas.baza.SaveChanges();

                    return RedirectToAction("Login", "Account");
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Пример #26
0
 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);
 }
Пример #27
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);
        }
        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);
        }
        public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            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 RedirectToLocal(returnUrl);
                }
                AddErrors(result);
            }

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

            if (ModelState.IsValid)
            {
                // 從外部登入提供者處取得使用者資訊
                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);
        }