Esempio n. 1
0
        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));
        }
Esempio n. 2
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            var appUser = new MyApplicationUser {
                UserName = model.Email, Email = model.Email
            };
            var result = await MyUserManager.CreateAsync(appUser, model.Password);

            /*UsersModel user = new UsersModel();
             * //user.Id = Guid.NewGuid().ToString();
             * user.UserName = model.Username;
             * user.Password = model.Password;
             * user.Email = model.Email;
             * user.EmailConfirmed = false;
             * user.PhoneNumberConfirmed = false;
             * user.TwoFactorEnabled = false;
             * user.LockoutEnabled = false;
             * user.AccessFailedCount = 0;
             *
             * CommonBLL bll = new CommonBLL();
             *
             * object result = bll.Add(user, true);*/

            if (result.Succeeded)
            {
                await MySignInManager.SignInAsync(appUser, isPersistent : false, rememberBrowser : false);

                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                return(View(model));
            }
        }
Esempio n. 3
0
        public async Task <IActionResult> OnPostConfirmationAsync(string email, 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, email, CancellationToken.None);

                await _emailStore.SetEmailAsync(user, 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);
                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
                return(Content(result.ToString()));
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(null);
        }
        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));
                }
            }
        }