public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new Data.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));
        }
Beispiel #2
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new Data.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 https://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> EditUser(string id)
        {
            EditUserViewModel model = new EditUserViewModel();

            model.ApplicationRoles = roleManager.Roles.Select(r => new SelectListItem
            {
                Text  = r.Name,
                Value = r.Id
            }).ToList();

            if (!String.IsNullOrEmpty(id))
            {
                Data.ApplicationUser user = await userManager.FindByIdAsync(id);

                if (user != null)
                {
                    model.Name  = user.Name;
                    model.Email = user.Email;
                    if (userManager.GetRolesAsync(user).Result.Count == 0)
                    {
                        model.ApplicationRoleId = "ee90b219-0dcc-4b37-920b-8170c61842f5";
                    }
                    else
                    {
                        model.ApplicationRoleId = roleManager.Roles.Single(r => r.Name == userManager.GetRolesAsync(user).Result.Single()).Id;
                    };
                }
            }
            return(PartialView("_EditUser", model));
        }
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
        {
            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 Data.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 <IActionResult> AddUser(UserViewModel model)
        {
            if (ModelState.IsValid)
            {
                Data.ApplicationUser user = new Data.ApplicationUser
                {
                    Name     = model.Name,
                    UserName = model.UserName,
                    Email    = model.Email
                };
                IdentityResult result = await userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    ApplicationRole applicationRole = await roleManager.FindByIdAsync(model.ApplicationRoleId);

                    if (applicationRole != null)
                    {
                        IdentityResult roleResult = await userManager.AddToRoleAsync(user, applicationRole.Name);

                        if (roleResult.Succeeded)
                        {
                            return(RedirectToAction("Index"));
                        }
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine(result.Errors);
                }
            }
            return(View(model));
        }
        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 Data.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(RegistrationViewModel registration)
 {
     try
     {
         if (registration == null)
         {
             return BadRequest("An error occured. Please contact support");
         }
         Data.ApplicationUser appUser = new Data.ApplicationUser
         {
             Email = registration.Email,
             FirstName = registration.FirstName,
             LastName = registration.LastName,
             UserName = registration.Email
         };
         var user = await _userManager.CreateAsync(appUser, registration.Password);
         if (user.Succeeded)
         {
             _userManager.SendRegistrationEmail(registration.Email);
         }
         return Ok(user);
     }
     catch (Exception ex)
     {
         return BadRequest(ex.Message);
     }
 }
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

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

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

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(new ChallengeResult(provider, this));
            }

            Data.ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                                                                                      externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
            else
            {
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
                Authentication.SignIn(identity);
            }

            return(Ok());
        }
Beispiel #9
0
        private async Task LoadAsync(Data.ApplicationUser user)
        {
            var email = await _userManager.GetEmailAsync(user);

            Email = email;

            Input = new InputModel
            {
                NewEmail = email,
            };

            IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);
        }
Beispiel #10
0
        private async Task LoadAsync(Data.ApplicationUser user)
        {
            var userName = await _userManager.GetUserNameAsync(user);

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            Username = userName;

            Input = new InputModel
            {
                PhoneNumber = phoneNumber
            };
        }
        public async Task <IActionResult> DeleteUser(string id)
        {
            string name = string.Empty;

            if (!String.IsNullOrEmpty(id))
            {
                Data.ApplicationUser applicationUser = await userManager.FindByIdAsync(id);

                if (applicationUser != null)
                {
                    name = applicationUser.Name;
                }
            }
            return(PartialView("_DeleteUser", name));
        }
Beispiel #12
0
        public async Task <IActionResult> OnGetAsync(string id)
        {
            if (String.IsNullOrEmpty(id))
            {
                return(NotFound());
            }

            Data.ApplicationUser applicationUser = await userManager.FindByIdAsync(id);

            if (applicationUser == null)
            {
                return(NotFound());
            }
            else if (!applicationUser.Editable)
            {
                return(RedirectToPage("/Account/AccessDenied"));
            }

            Roles = roleManager.Roles.Select(r => new SelectListItem
            {
                Text  = r.Name,
                Value = r.Id
            }).ToList();

            var role = (await userManager.GetRolesAsync(applicationUser)).SingleOrDefault();

            if (!String.IsNullOrEmpty(role))
            {
                RoleID = roleManager.Roles.SingleOrDefault(r => r.Name == role).Id;
            }

            MyUser = new UserEdit
            {
                Id       = applicationUser.Id,
                Name     = applicationUser.Name,
                UserName = applicationUser.UserName,
                Email    = applicationUser.Email,
                Editable = applicationUser.Editable,
                Role     = await roleManager.Roles.Select(r => new Role
                {
                    Id          = r.Id,
                    RoleName    = r.Name,
                    Description = r.Description
                }).SingleOrDefaultAsync(m => m.Id == RoleID)
            };

            return(Page());
        }
Beispiel #13
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new Data.ApplicationUser {
                    UserName = Input.Email, Email = Input.Email, FirstName = Input.FirstName, LastName = Input.LastName
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
        public async Task <IActionResult> DeleteUser(string id, IFormCollection form)
        {
            if (!String.IsNullOrEmpty(id))
            {
                Data.ApplicationUser applicationUser = await userManager.FindByIdAsync(id);

                if (applicationUser != null)
                {
                    IdentityResult result = await userManager.DeleteAsync(applicationUser);

                    if (result.Succeeded)
                    {
                        return(RedirectToAction("Index"));
                    }
                }
            }
            return(View());
        }
Beispiel #15
0
        private async Task LoadSharedKeyAndQrCodeUriAsync(Data.ApplicationUser user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            SharedKey = FormatKey(unformattedKey);

            var email = await _userManager.GetEmailAsync(user);

            AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
        }
Beispiel #16
0
        public async Task <ActionResult> UpdateMyProfileDataPost([Bind(Include = "FirstName, LastName, PhoneNumber, Street, City, PostCode, IsCompany, CompanyName, Regon, Nip, Email")]
                                                                 Data.ApplicationUser model)
        {
            if (!ModelState.IsValid)
            {
                return(PartialView("_infoPartial", InvalidModel()));
            }

            var user = await UserManager.FindByEmailAsync(model.Email);

            user.FirstName   = model.FirstName;
            user.LastName    = model.LastName;
            user.City        = model.City;
            user.Street      = model.Street;
            user.PostCode    = model.PostCode;
            user.PhoneNumber = model.PhoneNumber;
            user.IsCompany   = model.IsCompany;
            user.CompanyName = model.CompanyName;
            user.Regon       = model.Regon;
            user.Nip         = model.Nip;

            if (!model.IsCompany)
            {
                user.CompanyName = string.Empty;
                user.Regon       = string.Empty;
                user.Nip         = string.Empty;
            }

            var result = await UserManager.UpdateAsync(user);

            if (!result.Succeeded)
            {
                return(PartialView("_infoPartial", InvalidResult("Edycja profilu nie powiodła się.")));
            }

            var vm = new InfoViewModel
            {
                Message = "Twoje dane zostały zaktualizowane"
            };

            return(PartialView("_infoPartial", vm));
        }
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

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

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

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

            return(Ok());
        }
        public async Task <IActionResult> EditUser(string id, EditUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                Data.ApplicationUser user = await userManager.FindByIdAsync(id);

                if (user != null)
                {
                    user.Name  = model.Name;
                    user.Email = model.Email;
                    string         existingRole   = userManager.GetRolesAsync(user).Result.Single();
                    string         existingRoleId = roleManager.Roles.Single(r => r.Name == existingRole).Id;
                    IdentityResult result         = await userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        if (existingRoleId != model.ApplicationRoleId)
                        {
                            IdentityResult roleResult = await userManager.RemoveFromRoleAsync(user, existingRole);

                            if (roleResult.Succeeded)
                            {
                                ApplicationRole applicationRole = await roleManager.FindByIdAsync(model.ApplicationRoleId);

                                if (applicationRole != null)
                                {
                                    IdentityResult newRoleResult = await userManager.AddToRoleAsync(user, applicationRole.Name);

                                    if (newRoleResult.Succeeded)
                                    {
                                        return(RedirectToAction("Index"));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(PartialView("_EditUser", model));
        }
Beispiel #19
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 Data.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 <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new Data.ApplicationUser {
                    UserName = Input.Email, Email = Input.Email
                };

                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);

                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = userId, code = code },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                          $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        // If account confirmation is required, we need to show the link if we don't have a real email sender
                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email }));
                        }

                        await _signInManager.SignInAsync(user, isPersistent : false, info.LoginProvider);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            ProviderDisplayName = info.ProviderDisplayName;
            ReturnUrl           = returnUrl;
            return(Page());
        }