Exemplo n.º 1
0
        public static void Seed(this ModelBuilder builder)
        {
            var passHash = new PasswordHasher <App_IdentityUser>();

            var user = new App_IdentityUser()
            {
                Id                 = "suseradm-su01-9283-7465-k01joannes07",
                UserName           = "******",
                NormalizedUserName = "******",
                Email              = "*****@*****.**",
                NormalizedEmail    = "*****@*****.**",
                EmailConfirmed     = true,
                LockoutEnabled     = true
            };

            user.PasswordHash = passHash.HashPassword(user, "$$$uperuser2020");

            builder.Entity <App_IdentityUser>().HasData(user);

            builder.Entity <IdentityUserClaim <string> >().HasData(
                new IdentityUserClaim <string>()
            {
                Id         = 999999999,
                UserId     = "suseradm-su01-9283-7465-k01joannes07",
                ClaimType  = "Role",
                ClaimValue = "admin1"
            });
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Register(CreateAccount_vmodel model)
        {
            if (ModelState.IsValid)
            {
                if (authorizedEmailRepo.GetByEmail(model.Email) == null)
                {
                    ModelState.AddModelError(string.Empty, "Su correo NO esta autorizado para registrarse");
                    return(View(model));
                }

                var user = new App_IdentityUser()
                {
                    UserName = model.Username,
                    Email    = model.Email,
                    Gender   = model.Gender
                };

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

                if (result.Succeeded)
                {
                    var token = await userManager.GenerateEmailConfirmationTokenAsync(user);

                    var    confirmationLink = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, token }, Request.Scheme);
                    string message          = HtmlEmailTemplate.CreateHtmlBody(user.UserName, "Has click para verificar su cuenta de correo electrónico:",
                                                                               confirmationLink, "Verificar Correo Electrónico");

                    mailService.SendEmail(user.Email, "Verificación de correo electrónico", message);

                    logger.Log(LogLevel.Information, $"Se envio el token de confirmacion de email para el usuario {user.UserName}");

                    if (signInManager.IsSignedIn(User))
                    {
                        return(RedirectToAction("ListUsers", "Administration"));
                    }

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

                    if ((await userManager.GetClaimsAsync(user)).Count() > 0)
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                    return(RedirectToAction("WithoutClaims", new { emailConfirmed = user.EmailConfirmed }));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
            return(View(model));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            returnUrl ??= Url.Content("~/");

            SignIn_vmodel model = new SignIn_vmodel()
            {
                ReturnUrl      = returnUrl,
                ExternalLogins = (await signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
            };

            if (remoteError != null)
            {
                ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
                return(View("Login", model));
            }

            var info = await signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ModelState.AddModelError(string.Empty, "Error loading external login information");
                return(View("Login", model));
            }

            var email = info.Principal.FindFirstValue(ClaimTypes.Email);

            if (authorizedEmailRepo.GetByEmail(email) == null)
            {
                ModelState.AddModelError(string.Empty, "Su correo NO esta autorizado para registrarse");
                return(View("Login", model));
            }

            App_IdentityUser user;

            if (email != null)
            {
                user = await userManager.FindByEmailAsync(email);

                if (user != null && !user.EmailConfirmed)
                {
                    ModelState.AddModelError(string.Empty, "Email no confirmado aún");
                    return(View("Login", model));
                }
            }

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

            if (signInResult.Succeeded)
            {
                user = await userManager.FindByEmailAsync(info.Principal.FindFirstValue(ClaimTypes.Email));

                if ((await userManager.GetClaimsAsync(user)).Count() > 0)
                {
                    return(LocalRedirect(returnUrl));
                }
                return(RedirectToAction("WithoutClaims", new { emailConfirmed = user.EmailConfirmed }));
            }
            else
            {
                user = await userManager.FindByEmailAsync(email);

                if (user == null)
                {
                    string username = info.Principal.FindFirstValue(ClaimTypes.Name);
                    if (username.Contains(" "))
                    {
                        username = username.Split(' ')[0].ToLower();
                    }
                    else
                    {
                        username = username.ToLower();
                    }
                    user = new App_IdentityUser()
                    {
                        UserName = username,
                        Email    = info.Principal.FindFirstValue(ClaimTypes.Email)
                    };

                    var result = await userManager.CreateAsync(user);

                    if (!result.Succeeded)
                    {
                        foreach (var error in result.Errors)
                        {
                            ModelState.AddModelError(string.Empty, $"{error.Description}");
                        }
                        return(View("Login", model));
                    }

                    var token = await userManager.GenerateEmailConfirmationTokenAsync(user);

                    var confirmationLink = Url.Action("ConfirmEmail", "Account",
                                                      new { userId = user.Id, token }, Request.Scheme);

                    string message = HtmlEmailTemplate.CreateHtmlBody(user.UserName, "Has click para verificar su cuenta de correo electrónico:",
                                                                      confirmationLink, "Verificar Correo Electrónico");

                    mailService.SendEmail(user.Email, "Verificación de correo electrónico", message);
                }

                await userManager.AddLoginAsync(user, info);

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

                if ((await userManager.GetClaimsAsync(user)).Count() > 0)
                {
                    return(LocalRedirect(returnUrl));
                }
                return(RedirectToAction("WithoutClaims", new { emailConfirmed = user.EmailConfirmed }));
            }
        }