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)
                {
                    return RedirectToAction("Index");
                }                
            }

            // 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.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);
        }
        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);
        }
 private async Task SignInAsync(ApplicationUser user, bool isPersistent)
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
     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.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);
        }
        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);
        }
        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 user = new ApplicationUser
                //{
                //    UserName = model.Email,
                //    Name = model.Name,
                //    Password = model.Password,
                //    Email = model.Email,
                //    LastVisition = curDate,
                //    RegistrationDate = curDate,
                //    UserInfo = "user",
                //    DateOfBlocking = curDate,
                //    BlockForDate = curDate,
                //    IsBlocked = false,
                //    BlockReason = "",
                //    Balance = 0
                //};
                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);
        }
        /// <summary>
        /// Валидация пользователя при входе в систему
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool ValidateUser(ApplicationUser user)
        {
            var currentDate = DateTime.Now;

            bool validated = true;
            if(user.IsBlocked)
            {
                validated = !(currentDate < user.BlockForDate);
            }
            
            return validated;
        }
Exemple #9
0
        public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Manage");
            }
            var info = await AuthenticationManager.GetExternalLoginInfoAsync();
            UserFields UserFields = new UserFields(info.ExternalIdentity);
            if (ModelState.IsValid)
            {
                // Получение сведений о пользователе от внешнего поставщика входа
                
                if (info == null)
                {
                    return View("ExternalLoginFailure");
                }
                                                
                var user = new ApplicationUser { UserName = model.ExternalLogin, Email = model.Email, Surname = UserFields.Surname, Givenname = UserFields.Givenname, Birthday = model.Birthday };

                //Подставим SID в качестве Id при наличии
                if(UserFields.Primarysid != "")
                {
                    user.Id = UserFields.Primarysid;
                }
                // Use your file here
                //if(model.File != null)
                //{
                //    MemoryStream memoryStream = new MemoryStream();
                //    model.File.InputStream.CopyTo(memoryStream);
                //    user.ImageData = memoryStream.ToArray();
                //}
                //if (model.File == null && UserFields.LinkImg != "") 
                //{
                //    //System.Net.WebClient wc = new System.Net.WebClient();
                //    //user.ImageData = wc.DownloadData("./UploadedFiles/ifempty.png");                    
                //}
                
                var result = await UserManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);
                    if (result.Succeeded)
                    {
                        await UserManager.AddToRoleAsync(user.Id, "user");
                        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                        return RedirectToLocal(returnUrl);
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            ViewBag.LoginProvider = info.Login.LoginProvider;
            model.UrlFile = UserFields.LinkImg;
            model.Givenname = UserFields.Givenname;
            return View(model);
        }
Exemple #10
0
 private void LoadBookmark(ApplicationUser user)
 {
     AD AD = new AD();
     Target response_bookmarks = new Target(ResponseBookmarks);
     foreach (var item in user.Bookmarks)
     {
         string SID = item.SID;
         AD.SearchAll(SID, response_bookmarks);
     }
 }
 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);

                    // 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> 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 ActionResult Create(RegisterViewModel model)
        {
            var user = new ApplicationUser {
                UserName = model.Email, Name = model.Name, Password=model.Password, Email = model.Email,LastVisition=DateTime.Now, RegistrationDate = DateTime.Now, UserInfo="user",
                BlockDate = DateTime.Now, IsBlocked = true,
                BlockReason=""
            };

            var role = db.Roles.First(x => x.Id == model.RoleId);

            UserManager.Create(user, model.Password);
            
            // и добавим его к роли
            UserManager.AddToRole(user.Id, role.Name);

            db.SaveChanges();

            if (model.StudentsGroupId != null)
            {
                var studentsGroup = db.StudentsGroups.First(x => x.Id == model.StudentsGroupId);

                user.StudentGroup = studentsGroup;
                user.StudentGroupId = studentsGroup.Id;

                db.Entry(user).State = EntityState.Modified;
                db.Entry(studentsGroup).State = EntityState.Modified;

                db.SaveChanges();
            }

            var users = db.Users.ToList();
            return View("Index", users);
        }
        void createUser(string name, string email, string password, string role, StudentGroup group = null)
        {
            var user = new ApplicationUser
            {
                UserName = email,
                Name = name,
                Password = password,
                Email = email,
                LastVisition = DateTime.Now,
                RegistrationDate = DateTime.Now,
                UserInfo = "user",
                BlockDate = DateTime.Now,
                IsBlocked = true,
                BlockReason = ""
            };
            
            UserManager.Create(user, password);

            UserManager.AddToRole(user.Id, role);

            if (group!=null)
            {
                var thisUser = db.Users.First(x => x.Id == user.Id);

                // var group = groups[r.Next(groups.Count())%groups.Count()];

                thisUser.StudentGroup = group;
                thisUser.StudentGroupId = group.Id;

                db.Entry(thisUser).State = EntityState.Modified;
                db.Entry( group ).State = EntityState.Modified;

            }
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (!this.CheckCaptcha())
            {
                return RedirectToAction("Register");
            }

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Username.ToHtmlString(), Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                    var mail = new MailMessage("*****@*****.**", user.Email)
                    {
                        Subject = "Confirm your account",
                        Body = "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>",
                        IsBodyHtml = true
                    };
                    _smtpClient.Send(mail);

                    return RedirectToAction("NeedEmailConfirmation");
                }
                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);
                    
                    // アカウント確認とパスワード リセットを有効にする方法の詳細については、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<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();
        }
        protected void TryCreate(ApplicationUser user, MathTask mathTask, HttpPostedFileBase file)
        {
            //получаем время открытия
            DateTime current = DateTime.Now;

            Document doc = null ; ;

            string fileName = current.ToString(user.Id.GetHashCode() + "dd/MM/yyyy H:mm:ss").Replace(":", "_").Replace("/", ".").Replace(" ", "_");
            string path = Server.MapPath("~/Files/RequestFiles/" + fileName);
            string ext = "png";

            // Если приложен код латекса - грузим его как файл(создаем и грузим)
            // Иначе - сохраняем как файл
            if ( !mathTask.LatexCode.IsNullOrWhiteSpace() )
            {
                Bitmap bmp = MathMLFormulaControl.generateBitmapFromLatex(mathTask.LatexCode);

                bmp.Save(path, System.Drawing.Imaging.ImageFormat.Png);
                bmp.Dispose();

                doc = new Document();
                doc.Size = 0;
                doc.Type = "png";
                doc.Url = path + ".png";
            }
            else if (file != null)
            {

                // Получаем расширение
                ext = file.FileName.Substring(file.FileName.LastIndexOf('.'));
                path = path + ext;
                // сохраняем файл по определенному пути на сервере
                file.SaveAs(path);

                doc = new Document();
                doc.Size = file.ContentLength;
                doc.Type = ext;
                doc.Url = path;
            }
            else
            {
                mathTask.Description = DeterminantComplexity.GenerateByLevel(mathTask.MathTaskTypeId - 1, mathTask.Level, true).ToString();
            }

            mathTask.Executors = new List<ApplicationUser>();

            // Если не рассылка - добавляем всю выбранную группу
            if (mathTask.SelectedExecutorId != null)
            {
                var executor = this.Db.Users.First(x => x.Id == mathTask.SelectedExecutorId);
                mathTask.Executors.Add(executor);
            }
            else
            {
                var students = Db.Users.Where(x => x.Id == mathTask.StudentsGroupId.ToString());

                foreach (var student in students)
                {
                    mathTask.Executors.Add(student);
                }
            } // Иначе - добавляем указанного пользователя

            // указываем автора задачи
            mathTask.Author = user;
            mathTask.AuthorId = user.Id;

            // если сформирован файл
            if (doc != null)
            {
                mathTask.Document = doc;
                Db.Documents.Add(doc);
            }
            else
                mathTask.Document = null;

            mathTask.Status = (int)MathTaskStatus.Open;

            //Добавляем задачу с возможно приложенными документами
            Db.MathTasks.Add( mathTask );
            user.MathTasks.Add( mathTask );

            Db.Entry(user).State = EntityState.Modified;

            try
            {
                Db.SaveChanges();
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
        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 ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var curDate = DateTime.Now;
                var user = new ApplicationUser
                {
                    UserName = model.Email,
                    Name = model.Name,
                    Password = model.Password,
                    Email = model.Email,
                    LastVisition = curDate,
                    RegistrationDate = curDate,
                    UserInfo = "user",
                    DateOfBlocking = curDate,
                    BlockForDate = curDate,
                    IsBlocked = false,
                    BlockReason = "",
                    Balance = 0
                };

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

                // Пока что всех делаем администраторами, потом, конечно, это стоит убрать
                if (_db.Users.Any() == false || true) { 
                    UserManager.AddToRole(user.Id, "Administrator");
                }
                else {
                    UserManager.AddToRole(user.Id, "User");
                }

                if (result.Succeeded)
                {
                    SignInManager.SignIn(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);
        }
Exemple #22
0
        public ActionResult Register(RegisterViewModel model, HttpPostedFileBase avatar)
        {
            if (ModelState.IsValid)
            {
                //получаем время открытия
                DateTime current = DateTime.Now;

                var newAvatar = new Document();
                if (avatar!=null)
                {
                    newAvatar.Size = avatar.ContentLength;
                    // Получаем расширение
                    string ext = avatar.FileName.Substring(avatar.FileName.LastIndexOf('.'));
                    newAvatar.Type = ext;
                    // сохраняем файл по определенному пути на сервере
                    string path = current.ToString(this.User.Identity.GetUserId().GetHashCode() + "dd/MM/yyyy H:mm:ss").Replace(":", "_").Replace("/", ".") + ext;
                    avatar.SaveAs(Server.MapPath("~/Files/UserAvatarFiles/" + path));
                    newAvatar.Url = path;
                    db.SaveChanges();
                }

                var user = new ApplicationUser {
                    UserName = model.Email, Name = model.Name, Password=model.Password, Email = model.Email, RegistrationDate = DateTime.Now, UserInfo="user"
                };
               
                var result = UserManager.Create(user, model.Password);
                
                if (result.Succeeded)
                {
                    if(avatar!=null)
                    {
                        var newUser = db.Users.First(x => x.Id == user.Id);
                        newUser.Avatar.Add(newAvatar);
                        db.Entry(newUser).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                    SignInManager.SignIn(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: Article.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Подтверждение учетной записи", "Подтвердите вашу учетную запись, щелкнув <a href=\"" + callbackUrl + "\">здесь</a>");

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

            // Появление этого сообщения означает наличие ошибки; повторное отображение формы
            return View(model);
        }
        public async Task<ActionResult> Create(RegisterViewModel model)
        {
            var curDate = DateTime.Now;
            var user = new ApplicationUser
            {
                UserName = model.Email,
                Name = model.Name,
                Password = model.Password,
                Email = model.Email,
                LastVisition = curDate,
                RegistrationDate = curDate,
                UserInfo = "user",
                BlockForDate = curDate,
                DateOfBlocking = curDate,
                IsBlocked = false,
                BlockReason = "",
                Balance=0
            };

            var role = _db.Roles.First(x => x.Id == model.RoleId);
            // создадим пользователя
            var result = await UserManager.CreateAsync(user, model.Password);
            // и добавим его к роли
            UserManager.AddToRole(user.Id, role.Name);
            
            var users = _db.Users.ToList();
            return View("Index", users);
        }
Exemple #24
0
        public async Task<ActionResult> Create(RegisterViewModel model)
        {
            var user = new ApplicationUser
            {
                UserName = model.Email,
                Name = model.Name,
                Password = model.Password,
                Email = model.Email,
                RegistrationDate = DateTime.Now,
                UserInfo = "user"
            };

            var role = db.Roles.First(x => x.Id == model.RoleId);
            // создадим пользователя
            var result = await UserManager.CreateAsync(user, model.Password);
            // и добавим его к роли
            UserManager.AddToRole(user.Id, role.Name);
            
            var users = db.Users.ToList();
            return View("Index", users);
        }
Exemple #25
0
        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);
        }
        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> 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> 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);
        }