protected void CreateUser_Click(object sender, EventArgs e)
        {
            string userName = UserName.Text;

            var manager = new AuthenticationIdentityManager(new IdentityStore(new AcademyDbContext()));
            ApplicationUser u = new ApplicationUser(userName)
            {
                UserName = userName,
                FirstName = this.TextBoxFirstName.Text,
                LastName = this.TextBoxLastName.Text,
                Email = this.TextBoxEmail.Text,
                JoinDate = DateTime.Now,

            };
            var context = new AcademyDbContext();

            string fileName = string.Empty;

            var fileUpload = this.FileUploadAvatar;
            if (fileUpload.HasFile)
            {
                if (fileUpload.PostedFile.ContentLength < 102400 &&
                (fileUpload.PostedFile.ContentType == PngImageFormat ||
                fileUpload.PostedFile.ContentType == JpegImageFormat ||
                fileUpload.PostedFile.ContentType == GifImageFormat))
                {
                    fileName = userName.Replace("<", string.Empty).Replace(">", string.Empty) + GetAvatarExtension(FileUploadAvatar.PostedFile.FileName);
                    fileUpload.SaveAs(Server.MapPath(MainPath) + fileName);
                    u.AvatarPath = MainPath + fileName;
                }
                else
                {
                    ErrorSuccessNotifier.ShowAfterRedirect = true;
                    ErrorSuccessNotifier.AddErrorMessage("The uploaded avatar exceeds 100KB or is in a wrong format.");
                    Response.Redirect(Request.RawUrl, false);
                    return;
                }
            }
            else
            {
                u.AvatarPath = DefaultImagePath;
            }

            IdentityResult result = manager.Users.CreateLocalUser(u, Password.Text);
            if (result.Success)
            {
                manager.Authentication.SignIn(Context.GetOwinContext().Authentication, u.Id, isPersistent: false);
                ErrorSuccessNotifier.ShowAfterRedirect = true;
                ErrorSuccessNotifier.AddSuccessMessage("Registration completed successfully.");
                OpenAuthProviders.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else
            {
                ErrorSuccessNotifier.AddErrorMessage(result.Errors.FirstOrDefault());
            }
        }
        public void GridViewUsers_UpdateItem(string id)
        {
            var context = new AcademyDbContext();

            Forum.Models.ApplicationUser item = context.Users.Find(id);

            if (item == null)
            {
                ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
                return;
            }

            var editIndex = this.GridViewUsers.EditIndex;

            bool isLecturer = (this.GridViewUsers.Rows[editIndex].FindControl("CheckBoxIsLecturer") as CheckBox).Checked;

            if (isLecturer)
            {
                var lecturerRole = context.Roles.First(r => r.Name == "Lecturer");
                item.Roles.Clear();
                item.Roles.Add(new UserRole()
                {
                    Role = lecturerRole
                });
            }
            else
            {
                item.Roles.Clear();
            }

            TryUpdateModel(item);

            if (ModelState.IsValid)
            {
                context.SaveChanges();
                ErrorSuccessNotifier.AddSuccessMessage("User edited successfully.");
            }
            else
            {
                ErrorSuccessNotifier.AddErrorMessage("There was an error editing the user. Please try again.");
            }
        }
Esempio n. 3
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid || !Request.IsAjaxRequest()) return View(model);
            var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                if (Request.Url == null) return RedirectToAction("Index", "Home");
                var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code }, Request.Url.Scheme);
                await SendAsync(model.Email, "Confirm your account", "Please confirm your email by clicking on this link " + callbackUrl + "");
                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);

            return PartialView(model);
        }
Esempio n. 4
0
 private async Task SignInAsync(ApplicationUser user, bool isPersistent)
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
     AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
 }
Esempio n. 5
0
        public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Manage");
            }

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

            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
Esempio n. 6
0
	    public async Task<ActionResult> Register(RegisterViewModel model)
	    {


		    if (ModelState.IsValid)
		    {
			    var user = new ApplicationUser
			    {
				    UserName = model.UserName,
				    Email = model.Email,
				    EmailConfirmed = false
			    };
			    IdentityResult 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=320771
				    // Send an email with this link
					//string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
				    string code = Guid.NewGuid().ToString();
				    EmailConfirmationTokens[code] = user.UserName;
				    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
				    SendEmail(new EmailFormModel
				    {
					    FromEmail = "*****@*****.**",
					    FromName = "Deniaa forum",
					    Message = string.Format("Confirme authorization: {0}", callbackUrl)
				    }, user.Email);
				    //await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

				    //await SignInAsync(user, isPersistent: false);

					return View("~/Views/Account/ConfirmeEmailPls.cshtml");

			    }
			    AddErrors(result);
			}

			// If we got this far, something failed, redisplay form
			return View(model);
	    }
        private void SetRoles(ApplicationUser user, ICollection<string> roles)
        {
            var userRoles = db.UserRoles.All().Where(x => x.UserId == user.Id).ToList();
            while (userRoles.Count > 0)
            {
                db.UserRoles.Delete(userRoles.First());
                userRoles.RemoveAt(0);
            }

            foreach (var role in roles)
            {
                user.Roles.Add(new UserRole { RoleId = db.Roles.All().First(x => x.Name == role).Id, UserId = user.Id });
            }
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                // Create a local login before signing in the user
                var user = new ApplicationUser
                {
                    UserName = model.UserName,
                    PhotoUrl = @"../../img/Avatars/default-avatar.jpg"
                };
                var result = await IdentityManager.Users.CreateLocalUserAsync(user, model.Password);
                if (result.Success)
                {
                    await IdentityManager.Authentication.SignInAsync(AuthenticationManager, user.Id, 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> 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.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);
        }
 private void CreateAndLoginUser()
 {
     if (!IsValid)
     {
         return;
     }
     var user = new ApplicationUser(userName.Text);
     IAuthenticationManager manager = new AuthenticationIdentityManager(new IdentityStore(new AcademyDbContext())).Authentication;
     IdentityResult result = manager.CreateAndSignInExternalUser(Context.GetOwinContext().Authentication, user);
     if (result.Success)
     {
         OpenAuthProviders.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
     }
     else
     {
         AddErrors(result);
         return;
     }
 }