Beispiel #1
0
            public async Task <Result> Handle(Command request, CancellationToken ct)
            {
                request.ReturnUrl ??= "/";

                var user = new User();

                await _userStore.SetUserNameAsync(user, request.Email, ct);

                await _emailStore.SetEmailAsync(user, request.Email, ct);

                var result = await _userManager.CreateAsync(user, request.Password);

                if (result.Succeeded)
                {
                    await _mailer.SendLaterAsync(new AccountRegisteredMail(user));

                    await _userSession.LoginAsync(request.Email, request.Password);
                }
                else
                {
                    throw new DomainException(result.Errors.Select(x => x.Description).Join(". "));
                }

                return(new Result
                {
                    RedirectTo = request.ReturnUrl,
                    IdentityResult = result
                });
            }
Beispiel #2
0
            public async Task <Result> Handle(Command request, CancellationToken ct)
            {
                request.ReturnUrl ??= "/";

                var user = new User
                {
                    Name = request.Name
                };

                await _userStore.SetUserNameAsync(user, request.Email, ct);

                await _emailStore.SetEmailAsync(user, request.Email, ct);

                var result = await _userManager.CreateAsync(user, request.Password);

                if (result.Succeeded)
                {
                    await _mailer.SendLaterAsync(new AccountRegisteredMail(user));

                    // TODO: configurable LoginAfterRegister?
                    // await _userSession.LoginAsync(request.Email, request.Password);
                }
                else
                {
                    throw result.Errors.ToDomainException();
                }

                return(new Result
                {
                    IdentityResult = result
                });
            }
Beispiel #3
0
    public async Task <IActionResult> OnPostAsync(string returnUrl = null)
    {
        returnUrl ??= Url.Content("~/");
        ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync())
                         .ToList();
        if (ModelState.IsValid)
        {
            var user = CreateUser();

            await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);

            await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);

            var result = await _userManager.CreateAsync(user, Input.Password);

            // Add the email claim and value for this user.
            await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Email, Input.Email));

            // Remaining code removed for brevity.
            #endregion

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

                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, 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> Index(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = new User();
            await _userStore.SetUserNameAsync(user, model.UserName, CancellationToken.None);

            await _userEmailStore.SetEmailAsync(user, model.Email, CancellationToken.None);

            var result = await _userManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                var userId = await _userManager.GetUserIdAsync(user);

                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));

                var callbackUrl = Url.Action("Index", "ConfirmEmail", new
                {
                    area = "",
                    userId, code
                }, Request.Scheme);

                await _emailSender.SendEmailAsync(new MailAddress(user.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 = user.Email }));
                }

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

                if (string.IsNullOrEmpty(model.ReturnUrl))
                {
                    return(Redirect("/"));
                }
                return(LocalRedirect(model.ReturnUrl));
            }

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

            return(View(model));
        }
Beispiel #5
0
        public async Task <IdentityResult> RegisterAsync(
            TUser user,
            string login,
            string password      = "",
            CancellationToken ct = default)
        {
            await _userStore.SetUserNameAsync(user, login, ct);

            await _emailStore.SetEmailAsync(user, login, ct);

            if (string.IsNullOrEmpty(password))
            {
                return(await _userManager.CreateAsync(user));
            }

            return(await _userManager.CreateAsync(user, password));
        }
        public override 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(Redirect($"~/Identity/Account/Login?returnUrl={returnUrl}"));
            }

            if (ModelState.IsValid)
            {
                var user = CreateUser();

                await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);

                await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);

                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("User created an account using {Name} provider.", info.LoginProvider);
                        returnUrl = returnUrl.StartsWith(Url.Content("~/")) ? returnUrl : Url.Content("~/" + returnUrl.Substring(1));
                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
Beispiel #7
0
        public virtual async Task <AuthResult> SetEmailAsync(TUser user, string email)
        {
            ThrowIfDisposed();
            IUserEmailStore <TUser> emailStore = GetEmailStore();

            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            await emailStore.SetEmailAsync(user, email, CancellationToken);

            await emailStore.SetEmailConfirmedAsync(user, false, CancellationToken);

            await UpdateSecurityStampInternal(user);

            return(await UpdateUserAsync(user));
        }
Beispiel #8
0
        private async Task <IdentityResult> InitUserAsync(IdentityUser user, ExternalLoginInfo externalInfo)
        {
            var email = externalInfo.Principal.Identity.Name;
            await _userStore.SetUserNameAsync(user, email, CancellationToken.None);

            await _emailStore.SetEmailAsync(user, email, CancellationToken.None);

            var result = await _userManager.CreateAsync(user);

            var role = externalInfo.GetUserRole();

            if (role != null)
            {
                await _userManager.AddToRoleAsync(user, role);
            }

            return(result);
        }
Beispiel #9
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                //  This part requires code modification.
                //  The account requested for sign up is stored in the cache server, and you must finally approve the subscription through e-mail authentication.
                var user = CreateUser();

                await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);

                await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);

                var result = await _userManager.CreateAsync(user, Input.Password);

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

                    var userId = await _userManager.GetUserIdAsync(user);

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { 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>.");

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

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

            return(Page());
        }
        public async Task <IActionResult> Register(RegisterModel model)
        {
            model.ReturnUrl = model.ReturnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = CreateUser();

                await _userStore.SetUserNameAsync(user, model.Input.Email, CancellationToken.None);

                await _emailStore.SetEmailAsync(user, model.Input.Email, CancellationToken.None);

                var result = await _userManager.CreateAsync(user, model.Input.Password);

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

                    var userId = await _userManager.GetUserIdAsync(user);

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = userId, code = code },
                        protocol: Request.Scheme);

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

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

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

            // If we got this far, something failed, redisplay form
            return(View());
        }
Beispiel #11
0
        public virtual async Task <AuthResult> ChangeEmailAsync(TUser user, string newEmail, string token)
        {
            ThrowIfDisposed();
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

//            if (false)
//                return AuthResult.Failed(ErrorDescriber.InvalidToken());

            IUserEmailStore <TUser> emailStore = GetEmailStore();
            await emailStore.SetEmailAsync(user, newEmail, CancellationToken);

            await emailStore.SetEmailConfirmedAsync(user, true, CancellationToken);

            await UpdateSecurityStampInternal(user);

            return(await UpdateUserAsync(user));
        }
Beispiel #12
0
        public async Task <ActionResult> Create(InputModel newUser)
        {
            User user = Activator.CreateInstance <User>();

            await userStore.SetUserNameAsync(user, newUser.Username, CancellationToken.None);

            IUserEmailStore <User> emailStore = userStore as IUserEmailStore <User>;
            await emailStore.SetEmailAsync(user, newUser.Email, CancellationToken.None);

            AuthResult result = await userManager.CreateAsync(user, newUser.Password);

            if (result.Succeeded)
            {
                logger.LogInformation(LoggerEventIds.UserCreated, "New user created!");
                return(RedirectToAction("Index", "User"));
            }

            ViewData["Error"] = result.ToString();
            return(View());
        }
Beispiel #13
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            ReturnUrl = returnUrl;
            if (ModelState.IsValid)
            {
                User user = Activator.CreateInstance <User>();

                await UserStore.SetUserNameAsync(user, Input.Username, CancellationToken.None);

                IUserEmailStore <User> emailStore = UserStore as IUserEmailStore <User>;
                await emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);

                AuthResult result = await UserManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    Logger.LogInformation(LoggerEventIds.UserCreated, "New user created!");

                    if (UserManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        // DEV ONLY
                        await emailStore.SetEmailConfirmedAsync(user, true, CancellationToken.None);

                        await SignInManager.SignInAsync(user, false);

                        if (returnUrl == null)
                        {
                            return(LocalRedirect("~/"));
                        }
                        else
                        {
                            return(LocalRedirect(returnUrl));
                        }
                    }
                }
            }
            return(Page());
        }
        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 = CreateUser();

                await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);

                await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);

                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 props = new AuthenticationProperties();
                        props.StoreTokens(info.AuthenticationTokens);
                        props.IsPersistent = true;

                        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());
        }
Beispiel #15
0
        public override async Task <IDisplayResult> UpdateAsync(User user, UpdateEditorContext context)
        {
            var model = new EditUserViewModel();

            if (!await context.Updater.TryUpdateModelAsync(model, Prefix))
            {
                return(await EditAsync(user, context));
            }

            model.UserName      = model.UserName?.Trim();
            model.Email         = model.Email?.Trim();
            user.EmailConfirmed = model.EmailConfirmed;

            if (string.IsNullOrWhiteSpace(model.UserName))
            {
                context.Updater.ModelState.AddModelError("UserName", T["A user name is required."]);
            }

            if (string.IsNullOrWhiteSpace(model.Email))
            {
                context.Updater.ModelState.AddModelError("Email", T["An email is required."]);
            }

            await _userStore.SetUserNameAsync(user, model.UserName, default(CancellationToken));

            await _userEmailStore.SetEmailAsync(user, model.Email, default(CancellationToken));

            var userWithSameName = await _userStore.FindByNameAsync(_userManager.NormalizeKey(model.UserName), default(CancellationToken));

            if (userWithSameName != null)
            {
                var userWithSameNameId = await _userStore.GetUserIdAsync(userWithSameName, default(CancellationToken));

                if (userWithSameNameId != model.Id)
                {
                    context.Updater.ModelState.AddModelError(string.Empty, T["The user name is already used."]);
                }
            }

            var userWithSameEmail = await _userEmailStore.FindByEmailAsync(_userManager.NormalizeKey(model.Email), default(CancellationToken));

            if (userWithSameEmail != null)
            {
                var userWithSameEmailId = await _userStore.GetUserIdAsync(userWithSameEmail, default(CancellationToken));

                if (userWithSameEmailId != model.Id)
                {
                    context.Updater.ModelState.AddModelError(string.Empty, T["The email is already used."]);
                }
            }

            if (context.Updater.ModelState.IsValid)
            {
                var roleNames = model.Roles.Where(x => x.IsSelected).Select(x => x.Role).ToList();

                if (context.IsNew)
                {
                    // Add new roles
                    foreach (var role in roleNames)
                    {
                        await _userRoleStore.AddToRoleAsync(user, _userManager.NormalizeKey(role), default(CancellationToken));
                    }
                }
                else
                {
                    // Remove roles in two steps to prevent an iteration on a modified collection
                    var rolesToRemove = new List <string>();
                    foreach (var role in await _userRoleStore.GetRolesAsync(user, default(CancellationToken)))
                    {
                        if (!roleNames.Contains(role))
                        {
                            rolesToRemove.Add(role);
                        }
                    }

                    foreach (var role in rolesToRemove)
                    {
                        await _userRoleStore.RemoveFromRoleAsync(user, _userManager.NormalizeKey(role), default(CancellationToken));
                    }

                    // Add new roles
                    foreach (var role in roleNames)
                    {
                        if (!await _userRoleStore.IsInRoleAsync(user, _userManager.NormalizeKey(role), default(CancellationToken)))
                        {
                            await _userRoleStore.AddToRoleAsync(user, _userManager.NormalizeKey(role), default(CancellationToken));
                        }
                    }
                }
            }

            return(await EditAsync(user, context));
        }
        public async Task <IActionResult> SignInCompleteAsync()
        {
            string returnUrl = "/";
            //returnUrl = returnUrl ?? "/";
            var info = await SignInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                // El login no es válido o no se ha completado
                return(BadRequest());
            }

            //var userid = info.Principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
            //var name = info.Principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name);

            //var identityAtDb = await UserManager.FindByLoginAsync(info.LoginProvider, info.ProviderKey);
            //if (identityAtDb == null)
            //{
            //    identityAtDb = await UserManager.FindByEmailAsync(email);
            //    if(identityAtDb == null)
            //    {
            //        identityAtDb = new MyUser();
            //        identityAtDb.Email = email;
            //    }
            //}
            //var userAtIdentity = await UserManager.FindByEmailAsync


            var result = await SignInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                return(Ok());
            }
            if (result.IsLockedOut)
            {
                return(Forbid());
            }
            else
            {
                // La idea es: si el usuario no tiene una cuenta creada y enlazada con el proveedor (hubiera pasado por result.Succeeded)
                // exijimos (si aplica) que se cree una cuenta.
                // Podemos coger los Claims que nos provee el servicio externo.
                var email = info.Principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
                if (string.IsNullOrWhiteSpace(email))
                {
                    return(SignOut());
                }

                var identityUser = new MyUser();
                await UserStore.SetUserNameAsync(identityUser, email, System.Threading.CancellationToken.None);

                await EmailStore.SetEmailAsync(identityUser, email, System.Threading.CancellationToken.None);

                var createResult = await UserManager.CreateAsync(identityUser);

                if (createResult.Succeeded)
                {
                    await SignInManager.SignInAsync(identityUser, isPersistent : false);

                    return(Redirect("/"));
                }
                else
                {
                    foreach (var error in createResult.Errors)
                    {
                        ModelState.AddModelError(error.Code, error.Description);
                    }
                    return(BadRequest(ModelState));
                }
            }
        }