public async Task Add_Should_Add_New_Login_Just_After_UserManager_CreateAsync_Get_Called()
        {
            const string userName = "******";
            const string loginProvider = "Twitter";
            const string providerKey = "12345678";

            using (IDocumentStore store = CreateEmbeddableStore())
            {
                using (IAsyncDocumentSession ses = store.OpenAsyncSession())
                {
                    ses.Advanced.UseOptimisticConcurrency = true;
                    RavenUserStore<RavenUser> userStore = new RavenUserStore<RavenUser>(ses);
                    UserManager<RavenUser> userManager = new UserManager<RavenUser>(userStore);

                    RavenUser user = new RavenUser(userName);
                    UserLoginInfo loginToAdd = new UserLoginInfo(loginProvider, providerKey);
                    await userManager.CreateAsync(user);
                    await userManager.AddLoginAsync(user.Id, loginToAdd);
                    await ses.SaveChangesAsync();
                }

                using (IAsyncDocumentSession ses = store.OpenAsyncSession())
                {
                    ses.Advanced.UseOptimisticConcurrency = true;
                    IUserLoginStore<RavenUser, string> userLoginStore = new RavenUserStore<RavenUser>(ses);
                    RavenUser user = await ses.LoadAsync<RavenUser>(RavenUser.GenerateKey(userName));
                    RavenUserLogin foundLogin = await ses.LoadAsync<RavenUserLogin>(RavenUserLogin.GenerateKey(loginProvider, providerKey));

                    // Assert
                    Assert.Equal(1, user.Logins.Count());
                    Assert.NotNull(foundLogin);
                }
            }
        }
Esempio n. 2
45
 public async Task AddDuplicateLoginFailsTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var mgr = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
     var user = new IdentityUser("dupeLogintest");
     UnitTestHelper.IsSuccess(await mgr.CreateAsync(user));
     var userLogin1 = new UserLoginInfo("provider1", "p1-1");
     UnitTestHelper.IsSuccess(await mgr.AddLoginAsync(user.Id, userLogin1));
     UnitTestHelper.IsFailure(await mgr.AddLoginAsync(user.Id, userLogin1));
 }
Esempio n. 3
0
 public async Task AddLoginNullLoginFailsTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
     var user = new IdentityUser("Hao");
     UnitTestHelper.IsSuccess(await manager.CreateAsync(user));
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => manager.AddLoginAsync(user.Id, null)),
         "login");
 }
Esempio n. 4
0
 public async Task LinkUnlinkDeletesTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var mgr = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
     var user = new IdentityUser("linkunlinktest");
     UnitTestHelper.IsSuccess(await mgr.CreateAsync(user));
     var userLogin1 = new UserLoginInfo("provider1", "p1-1");
     var userLogin2 = new UserLoginInfo("provider2", "p2-1");
     Assert.Equal(0, (await mgr.GetLoginsAsync(user.Id)).Count);
     UnitTestHelper.IsSuccess(await mgr.AddLoginAsync(user.Id, userLogin1));
     Assert.Equal(1, user.Logins.Count(l => l.ProviderKey == "p1-1"));
     Assert.Equal(1, (await mgr.GetLoginsAsync(user.Id)).Count);
     UnitTestHelper.IsSuccess(await mgr.AddLoginAsync(user.Id, userLogin2));
     Assert.Equal(1, user.Logins.Count(l => l.ProviderKey == "p2-1"));
     Assert.Equal(2, (await mgr.GetLoginsAsync(user.Id)).Count);
     UnitTestHelper.IsSuccess(await mgr.RemoveLoginAsync(user.Id, userLogin1));
     Assert.Equal(0, user.Logins.Count(l => l.ProviderKey == "p1-1"));
     Assert.Equal(1, user.Logins.Count(l => l.ProviderKey == "p2-1"));
     Assert.Equal(1, (await mgr.GetLoginsAsync(user.Id)).Count());
     UnitTestHelper.IsSuccess(await mgr.RemoveLoginAsync(user.Id, userLogin2));
     Assert.Equal(0, (await mgr.GetLoginsAsync(user.Id)).Count);
     Assert.Equal(0, db.Set<IdentityUserLogin>().Count());
 }
Esempio n. 5
0
		/// <summary>
		/// Invoked after the LTI request has been authenticated so the application can sign in the application user.
		/// </summary>
		/// <param name="context">Contains information about the login session as well as the LTI request.</param>
		/// <param name="claims">Optional set of claims to add to the identity.</param>
		/// <returns>A <see cref="Task"/> representing the completed operation.</returns>
		public static async Task OnAuthenticated(LtiAuthenticatedContext context, IEnumerable<Claim> claims = null)
		{
			// Find existing pairing between LTI user and application user
			var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new LtiDb()));
			var loginProvider = string.Join(":", new[] { context.Options.AuthenticationType, context.LtiRequest.ConsumerKey });
			var providerKey = context.LtiRequest.UserId;
			var login = new UserLoginInfo(loginProvider, providerKey);
			var user = await userManager.FindAsync(login);
			if (user == null)
			{
				var usernameContext = new LtiGenerateUserNameContext(context.OwinContext, context.LtiRequest);
				await context.Options.Provider.GenerateUserName(usernameContext);
				if (string.IsNullOrEmpty(usernameContext.UserName))
				{
					return;
				}
				user = await userManager.FindByNameAsync(usernameContext.UserName);
				if (user == null)
				{
					user = new ApplicationUser { UserName = usernameContext.UserName };
					var result = await userManager.CreateAsync(user);
					if (!result.Succeeded)
					{
						return;
					}
				}
				// Save the pairing between LTI user and application user
				await userManager.AddLoginAsync(user.Id, login);
			}

			// Create the application identity, add the LTI request as a claim, and sign in
			var identity = await userManager.CreateIdentityAsync(user, context.Options.SignInAsAuthenticationType);
			identity.AddClaim(new Claim(context.Options.ClaimType, JsonConvert.SerializeObject(context.LtiRequest, Formatting.None,
					new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }), ClaimValueTypes.String, context.Options.AuthenticationType));
			if (claims != null)
			{
				foreach (var claim in claims)
				{
					identity.AddClaim(claim);
				}
			}
			context.OwinContext.Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);

			// Redirect to original URL so the new identity takes affect
			context.RedirectUrl = context.LtiRequest.Url.ToString();
		}
 private static async System.Threading.Tasks.Task CreateUserIfNotExist(UserManager<ApplicationUser> userManager, string email, string password, string role, string loginProvider = null, string providerKey = null)
 {
     var user = await userManager.FindByEmailAsync(email);
     if (user == null)
     {
         user = new ApplicationUser { UserName = email, Email = email };
         var result = await userManager.CreateAsync(user, password);
         if (!result.Succeeded)
         {
             throw new ApplicationException(string.Join("\n", result.Errors.Select(a => a.Description).ToArray()));
         }
         await userManager.AddToRoleAsync(user, role);
         if (loginProvider != null && providerKey != null)
         {
             await userManager.AddLoginAsync(user, new UserLoginInfo(loginProvider, providerKey, ""));
         }
     }
 }
Esempio n. 7
0
 private static async Task<ApplicationUser> CreateUserIfNotExist(UserManager<ApplicationUser> userManager, ApplicationUser user, string password, string role, string loginProvider = null, string providerKey = null)
 {
     //Debugger.Launch();
     user.EmailConfirmed = true;
     user.Email = user.Email ?? user.UserName;
     if (await userManager.FindByEmailAsync(user.Email) == null)
     {
         var result = await userManager.CreateAsync(user, password);
         if (!result.Succeeded)
         {
             throw new ApplicationException(string.Join("\n", result.Errors.Select(a => a.Description).ToArray()));
         }
         await userManager.AddToRoleAsync(user, role);
         if (loginProvider != null && providerKey != null)
         {
             await userManager.AddLoginAsync(user, new UserLoginInfo(loginProvider, providerKey, ""));
         }
     }
     return user;
 }
Esempio n. 8
0
        public async Task <IdentityResult> AddLoginAsync(string userId, UserLoginInfo login)
        {
            var result = await _userManager.AddLoginAsync(userId, login);

            return(result);
        }
Esempio n. 9
0
        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 IdentityUser {
                    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());
        }
Esempio n. 10
0
        private async Task <IdentityResult> AddLoginAsync(UserWithClaims user)
        {
            var externalLogin = await signInManager.GetExternalLoginInfoWithDisplayNameAsync(userManager.GetUserId(User));

            return(await userManager.AddLoginAsync(user.Identity, externalLogin));
        }
Esempio n. 11
0
        public async Task <LoginResult> PerfromExternalLogin()
        {
            var info = await signin_manager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                throw new UnauthorizedAccessException();
            }

            var user = await user_manager.FindByLoginAsync(info.LoginProvider, info.ProviderKey);

            if (user == null)
            {
                string username = info.Principal.FindFirstValue(ClaimTypes.Name);
                string email    = info.Principal.FindFirstValue(ClaimTypes.Email);

                var new_user = new Entities.User
                {
                    UserName   = username,
                    Email      = email,
                    PictureUrl = null
                };
                var id_result = await user_manager.CreateAsync(new_user);

                if (id_result.Succeeded)
                {
                    user = new_user;
                }
                else
                {
                    // User creation failed, probably because the email address is already present in the database
                    if (id_result.Errors.Any(e => e.Code == "DuplicateEmail"))
                    {
                        var existing = await user_manager.FindByEmailAsync(email);

                        var existing_logins = await user_manager.GetLoginsAsync(existing);

                        if (existing_logins.Any())
                        {
                            throw new OtherAccountException(existing_logins);
                        }
                        else
                        {
                            throw new Exception("Could not create account from social profile");
                        }
                    }
                    else
                    {
                        throw new Exception("Could not create account from social profile");
                    }
                }

                await user_manager.AddLoginAsync(user, new UserLoginInfo(info.LoginProvider, info.ProviderKey, info.ProviderDisplayName));
            }

            await signin_manager.SignInAsync(user, true);

            return(new LoginResult
            {
                Status = true,
                Platform = info.LoginProvider,
                User = ToDto(user)
            });
        }
Esempio n. 12
0
        public async Task <ApiResult <string> > ExternalLoginCallback(ExternalLoginRequest request)
        {
            var signInResult = await _signInManager.ExternalLoginSignInAsync(request.LoginProvider,
                                                                             request.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (signInResult.Succeeded)
            {
                var user = await _userManager.FindByEmailAsync(request.Email);

                var role = await _roleManager.FindByIdAsync(user.RoleID.ToString());

                var cart = await _context.Carts.FirstOrDefaultAsync(x => x.UserId == user.Id);

                var userToken = new UserToken
                {
                    CartId    = cart.Id.ToString(),
                    UserId    = user.Id.ToString(),
                    UserName  = user.UserName,
                    Role      = string.Join(";", role.Name),
                    ImagePath = user.ImagePath,
                    Email     = user.Email,
                };
                var token = CreateToken(userToken);
                return(new ApiResultSuccess <string>(token));
            }
            else
            {
                var email = request.Email;
                if (email != null)
                {
                    var user = await _userManager.FindByEmailAsync(email);

                    var roleDefault = await _roleManager.FindByNameAsync("client");

                    if (user == null)
                    {
                        user = new UserApp
                        {
                            FullName  = request.FullName,
                            ImagePath = request.ImagePath,
                            Email     = request.Email,
                            RoleID    = roleDefault.Id,
                            UserName  = request.Email,
                        };
                        var result = await _userManager.CreateAsync(user);

                        if (result.Succeeded)
                        {
                            var cartadd = new Cart
                            {
                                Created_At   = DateTime.Now,
                                UserId       = user.Id,
                                Price        = 0,
                                CartProducts = new List <CartProduct>(),
                            };
                            _context.Carts.Add(cartadd);
                            await _context.SaveChangesAsync();
                        }
                    }
                    var cart = await _context.Carts.FirstOrDefaultAsync(x => x.UserId == user.Id);

                    var info = new UserLoginInfo(request.LoginProvider, request.ProviderKey, request.ProviderDisPlayName);
                    await _userManager.AddLoginAsync(user, info);

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

                    var role      = _roleManager.FindByIdAsync(user.RoleID.ToString());
                    var userToken = new UserToken
                    {
                        CartId    = cart.Id.ToString(),
                        UserId    = user.Id.ToString(),
                        UserName  = user.UserName,
                        Role      = string.Join(";", role.Result.Name),
                        ImagePath = user.ImagePath,
                        Email     = user.Email,
                    };
                    var token = CreateToken(userToken);
                    return(new ApiResultSuccess <string>(token));
                }
                return(new ApiResultErrors <string>($"Email claim not received from:{request.LoginProvider}"));
            }
        }
Esempio n. 13
0
        ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

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

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

                return(View("Login", loginViewModel));
            }

            var info = await signInManager.GetExternalLoginInfoAsync();

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

                return(View("Login", loginViewModel));
            }

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

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

                if (user != null && !user.EmailConfirmed)
                {
                    ModelState.AddModelError(string.Empty, "Email not confirmed yet");
                    return(View("Login", loginViewModel));
                }
            }

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

            if (signInResult.Succeeded)
            {
                return(LocalRedirect(returnUrl));
            }
            else
            {
                if (email != null)
                {
                    if (user == null)
                    {
                        user = new AppUser
                        {
                            UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
                            Email    = info.Principal.FindFirstValue(ClaimTypes.Email)
                        };

                        await userManager.CreateAsync(user);

                        // After a local user account is created, generate and log the
                        // email confirmation link
                        var token = await userManager.GenerateEmailConfirmationTokenAsync(user);

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

                        EmailMessage Msg = new EmailMessage
                        {
                            ToAddresses = new EmailAddress {
                                Name = user.UserName, Address = user.Email
                            },
                            FromAddresses = new EmailAddress {
                                Name = user.UserName, Address = user.Email
                            },
                            Subject = "Confirm your account",
                            Content = $"Please confirm your account by clicking this link: <a href='{confirmationLink}'>link</a>"
                        };
                        await emailService.Send(Msg);
                    }

                    await userManager.AddLoginAsync(user, info);

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

                    return(LocalRedirect(returnUrl));
                }

                ViewBag.ErrorTitle   = $"Email claim not received from: {info.LoginProvider}";
                ViewBag.ErrorMessage = "Please contact support on [email protected]";

                return(View("Error"));
            }
        }
Esempio n. 14
0
        public async Task <IActionResult> ExternalLoginCallback(string returnurl = null, string remoteError = null)
        {
            if (remoteError != null)
            {
                _logger.LogCritical(remoteError);
                return(RedirectToAction("Login", "Profile"));
            }
            var externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync();

            if (externalLoginInfo == null)
            {
                _logger.LogCritical("Authentication failed for external provider");
                return(RedirectToAction("Login", "Profile"));
            }

            var email = externalLoginInfo.Principal.Claims.FirstOrDefault(claim =>
            {
                return(claim.Type.Contains($"emailaddress"));
            }).Value;

            //add the user to the database
            //I was getting System.InvalidOperationException: User security stamp cannot be null when calling _userManager.AddLoginAsync.
            //After some digging I found that my newly created User-Entities did not have a SecurityStamp.
            //And the asp.net default UserManager expects a SecurityStamp and wants to set it as a Claim in the ClaimsIdentity.
            var newUser = new ApplicationUser <Guid>(email)
            {
                SecurityStamp = Guid.NewGuid().ToString(),
                Email         = email
            };

            var existingUser = await _userManager.FindByEmailAsync(newUser.Email);

            if (existingUser?.Email == null)
            {
                var createUserResult = await _userManager.CreateAsync(newUser);

                if (!createUserResult.Succeeded)
                {
                    _logger.LogCritical($"Not able to create the user.Reason-{createUserResult}");
                    return(RedirectToAction("Login", "Profile"));
                }
            }

            var addLoginResult = await _userManager.AddLoginAsync(
                existingUser?.Email != null?existingUser : newUser,
                new UserLoginInfo(externalLoginInfo.LoginProvider, externalLoginInfo.ProviderKey, externalLoginInfo.ProviderDisplayName));

            if (addLoginResult == null)
            {
                _logger.LogCritical("Not able to add external user to database");
                return(RedirectToAction("Login", "Profile"));
            }
            //sign in the user
            var signInResult = await _signInManager.ExternalLoginSignInAsync(externalLoginInfo.LoginProvider, externalLoginInfo.ProviderKey, true);

            if (signInResult.Succeeded)
            {
                //sign-in the user with Identity.External scheme

                var claims = new List <Claim>()
                {
                    new Claim(ClaimTypes.Name, externalLoginInfo.Principal.Claims.FirstOrDefault().Subject.Name),
                    new Claim(ClaimTypes.Role, "Administrator")
                };

                var claimsIdentity = new ClaimsIdentity(claims, IdentityConstants.ExternalScheme);

                var authProperties = new AuthenticationProperties();

                await HttpContext.SignInAsync(IdentityConstants.ExternalScheme, new ClaimsPrincipal(claimsIdentity), authProperties);

                _logger.LogTrace($"Logged in with Provider :{externalLoginInfo.ProviderDisplayName}");

                return(RedirectToAction("Dashboard", "Library"));
            }

            _logger.LogCritical(signInResult.ToString());
            return(RedirectToAction("Login", "Profile"));
        }
Esempio n. 15
0
 private Task <bool> AddLoginAsync(UserWithClaims user, UserLoginInfo externalLogin)
 {
     return(MakeIdentityOperation(() => userManager.AddLoginAsync(user.Identity, externalLogin)));
 }
Esempio n. 16
0
            public async Task <ApplicationUser> Handle(CreateUser request, CancellationToken cancellationToken)
            {
                var externalUserInfo = request.ExternalUserDto;
                var claims           = externalUserInfo.ExternalClaims;
                // create a list of claims that we want to transfer into our store
                var filtered = new List <Claim>();

                // user's display name
                var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ??
                           claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;

                if (name != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, name));
                }
                else
                {
                    // build the name from first + last (for facebook)
                    var first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ??
                                claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
                    var last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ??
                               claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value;
                    if (first != null && last != null)
                    {
                        name = first + " " + last;
                        filtered.Add(new Claim(JwtClaimTypes.Name, name));
                    }
                    else if (first != null)
                    {
                        filtered.Add(new Claim(JwtClaimTypes.Name, first));
                    }
                    else if (last != null)
                    {
                        filtered.Add(new Claim(JwtClaimTypes.Name, last));
                    }
                }

                // email will get mapped, so we don't add it explicitly
                var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ??
                            claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;


                var pictureUrl = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Picture)?.Value;

                if (pictureUrl != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Picture, pictureUrl));
                }

                var user = new ApplicationUser
                {
                    UserName = name,
                    Email    = email
                };
                var identityResult = await _userManager.CreateAsync(user);

                if (!identityResult.Succeeded)
                {
                    throw new Exception(identityResult.Errors.First().Description);
                }

                if (filtered.Any())
                {
                    identityResult = await _userManager.AddClaimsAsync(user, filtered);

                    if (!identityResult.Succeeded)
                    {
                        throw new Exception(identityResult.Errors.First().Description);
                    }
                }

                // Add this idP login to user
                identityResult =
                    await _userManager.AddLoginAsync(user, new UserLoginInfo(
                                                         externalUserInfo.Provider,
                                                         externalUserInfo.ProviderUserId,
                                                         externalUserInfo.Provider)
                                                     );

                if (!identityResult.Succeeded)
                {
                    throw new Exception(identityResult.Errors.First().Description);
                }

                return(user);
            }
        public async Task <IActionResult> ExternalLoginCallBack(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

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

            if (remoteError != null)
            {
                ModelState.AddModelError(string.Empty, $"Error from External provider : {remoteError}");

                return(View("Login", loginViewModel));
            }

            var info = await signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ModelState.AddModelError(string.Empty, $"Error loading external login information");

                return(View("Login", loginViewModel));
            }

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

            ApplicationUser user = null;

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

                if (user != null && !user.EmailConfirmed)
                {
                    ModelState.AddModelError(string.Empty, "Email is not confrimed yet");
                    return(View("Login", loginViewModel));
                }
            }

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

            if (signInResult.Succeeded)
            {
                return(LocalRedirect(returnUrl));
            }
            else
            {
                if (email != null)
                {
                    if (user == null)
                    {
                        user = new ApplicationUser
                        {
                            UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
                            Email    = info.Principal.FindFirstValue(ClaimTypes.Email)
                        };

                        await userManager.CreateAsync(user);

                        //var token = userManager.CreateSecurityTokenAsync(user);
                        var token = await userManager.GenerateEmailConfirmationTokenAsync(user);

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

                        logger.Log(LogLevel.Warning, confrimationLink);

                        ViewBag.ErrorTitle   = "Regestation successful";
                        ViewBag.ErrorMessage = "before you can Login please confrim " +
                                               "your account by clicking on confrimation link we have emailed you ";
                        return(View("Error"));
                    }

                    await userManager.AddLoginAsync(user, info);

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

                    return(LocalRedirect(returnUrl));
                }
            }
            ViewBag.ErrorTitle   = $"Email claim not received from : {info.LoginProvider}";
            ViewBag.ErrorMessage = $"please contact support on [email protected]";
            return(View("Error"));
        }
Esempio n. 18
0
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
        {
            if (_signInManager.IsSignedIn(User))
            {
                return(RedirectToAction(nameof(ManageController.Index), "Manage"));
            }

            if (ModelState.IsValid)
            {
                var externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync();

                if (externalLoginInfo == null)
                {
                    return(View("ExternalLoginFailure"));
                }

                var user = new ApplicationUser
                {
                    UserName    = model.Email,
                    Email       = model.Email,
                    TimeZoneId  = _generalSettings.Value.DefaultTimeZone,
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    PhoneNumber = model.PhoneNumber
                };

                var result = await _userManager.CreateAsync(user);

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

                    if (result.Succeeded)
                    {
                        var emailConfirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        if (model.EmailIsVerifiedByExternalLoginProvider)
                        {
                            await _userManager.ConfirmEmailAsync(user, emailConfirmationToken);
                        }
                        else
                        {
                            var callbackUrl = Url.Action(new UrlActionContext
                            {
                                Action     = nameof(ConfirmEmail),
                                Controller = "Account",
                                Values     = new { userId = user.Id, token = emailConfirmationToken },
                                Protocol   = HttpContext.Request.Scheme
                            });
                            await _mediator.SendAsync(new SendConfirmAccountEmail { Email = user.Email, CallbackUrl = callbackUrl });
                        }

                        var changePhoneNumberToken = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);

                        await _mediator.SendAsync(new SendAccountSecurityTokenSms { PhoneNumber = model.PhoneNumber, Token = changePhoneNumberToken });

                        await _userManager.AddClaimAsync(user, new Claim(Security.ClaimTypes.ProfileIncomplete, "NewUser"));

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

                        return(_redirectAccountControllerRequests.RedirectToLocal(returnUrl, user));
                    }
                }

                AddErrorsToModelState(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View(model));
        }
Esempio n. 19
0
        public async Task <IActionResult> SubmitTokenInput(TokenInputViewModel model)
        {
            if (!ModelState.IsValid ||
                String.IsNullOrWhiteSpace(model.Email) ||
                String.IsNullOrWhiteSpace(model.Purpose) ||
                String.IsNullOrWhiteSpace(model.Token))
            {
                return(View(model));
            }

            var email = _userManager.NormalizeKey(model.Email);

            model.Token = model.Token.Replace(" ", "");

            var userWithConfirmedEmail = await _userManager.FindByLoginAsync("Email", email);

            var userCurrentlySignedIn = await _userManager.GetUserAsync(User);

            var userEmpty = new ApplicationUser()
            {
                Id            = email,
                Email         = email,
                SecurityStamp = ""
            };

            var isTokenValid = false;

            if (model.Purpose == "RegisterOrLogin") // Trying to register or login
            {
                await _signInManager.SignOutAsync();

                isTokenValid = await _userManager.VerifyUserTokenAsync(
                    userWithConfirmedEmail  // Case: logging-in
                    ?? userEmpty,           // Case: registering,
                    "Email", model.Purpose, model.Token);
            }
            else // Trying to add email
            {
                if (userCurrentlySignedIn == null) // If the user is not signed in, prompt them to, with the return url leading back here
                {
                    return(RedirectToAction(nameof(Login), new
                    {
                        returnUrl = Request.Path + Request.QueryString
                    }));
                }

                isTokenValid = await _userManager.VerifyUserTokenAsync(
                    userCurrentlySignedIn,
                    "Email", model.Purpose, model.Token);
            }

            if (!isTokenValid)
            {
                _notice.AddErrors(ModelState, "Error validating code, it might have expired. Please try again!");
                return(View(model));
            }

            // Invalidates all tokens for user when trying to login or add login
            // Note: this also invalidates any attempts to add more logins than allowed
            if ((userCurrentlySignedIn ?? userWithConfirmedEmail) != null)
            {
                var updateSecStampResult = await _userManager.UpdateSecurityStampAsync(userCurrentlySignedIn ?? userWithConfirmedEmail);

                if (!updateSecStampResult.Succeeded)
                {
                    _notice.AddErrors(ModelState);
                    return(View(model));
                }
            }

            // Valid {token + email (user) + purpose} supplied

            if (model.Purpose == "RegisterOrLogin") // Trying to register or login
            {
                if (userWithConfirmedEmail == null) // Success trying to register
                {
                    var token = await _userManager.GenerateUserTokenAsync(userEmpty, "Default", "Register");

                    return(View(nameof(Register), new RegisterViewModel
                    {
                        RememberMe = model.RememberMe,
                        Email = email,
                        UserName = email.Split('@')[0]?.ToLower(),
                        Token = token,
                        ReturnUrl = model.ReturnUrl
                    }));
                }
                else // Success trying to login
                {
                    await _events.AddEvent(AuthEventType.Login, JsonConvert.SerializeObject(new
                    {
                        LoginProvider = "Email",
                        ProviderKey   = model.Email
                    }), userWithConfirmedEmail);

                    await _signInManager.SignInAsync(userWithConfirmedEmail, isPersistent : model.RememberMe);
                }
            }
            else // Trying to add email
            {
                var userWithConfirmedEmailToAdd = await _userManager.FindByLoginAsync("Email", email);

                if (userWithConfirmedEmailToAdd == null) // Email to be added never seen before, add email to userCurrentlySignedIn
                {
                    var addLoginResult = await _userManager.AddLoginAsync(userCurrentlySignedIn,
                                                                          new UserLoginInfo("Email", email, "Email"));

                    if (!addLoginResult.Succeeded)
                    {
                        _notice.AddErrors(ModelState, addLoginResult);
                        return(View(model));
                    }

                    userCurrentlySignedIn.Email          = email;
                    userCurrentlySignedIn.EmailConfirmed = true;
                    var updateUserResult = await _userManager.UpdateAsync(userCurrentlySignedIn);

                    if (!updateUserResult.Succeeded)
                    {
                        _notice.AddErrors(ModelState, updateUserResult);
                        return(View(model));
                    }

                    await _events.AddEvent(AuthEventType.AddLogin, JsonConvert.SerializeObject(new
                    {
                        LoginProvider = "Email",
                        ProviderKey   = model.Email
                    }), userCurrentlySignedIn);
                }
                else // Email to be added is in use
                {
                    // Note: this area is unlikely to be reached since security stamp is changed once a login is added
                    if (userWithConfirmedEmailToAdd.Id == userCurrentlySignedIn.Id) // Email is already in user's account
                    {
                        _notice.AddErrors(ModelState, "This email is already in your account.");
                        return(View(model));
                    }
                    else // Email associated with another account (same user since both verified!)
                    {
                        _notice.AddErrors(ModelState, "This email is in another user's account. Try logging in using that email instead.");
                        return(View(model));
                    }
                }
            }

            // Success
            return(RedirectToLocal(model.ReturnUrl));
        }
Esempio n. 20
0
        public virtual async Task <ApplicationIdentityResult> AddLoginAsync(int userId, ApplicationUserLoginInfo login)
        {
            var identityResult = await _userManager.AddLoginAsync(userId, login.ToUserLoginInfo()).ConfigureAwait(false);

            return(identityResult.ToApplicationIdentityResult());
        }
Esempio n. 21
0
        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 ApplicationUser
                {
                    UserName      = Input.Email,
                    Email         = Input.Email,
                    StreetAddress = Input.StreetAddress,
                    City          = Input.City,
                    State         = Input.State,
                    PostalCode    = Input.PostalCode,
                    Name          = Input.Name,
                    PhoneNumber   = Input.PhoneNumber,
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, SD.Role_Customer);

                    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);

                        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>.");

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

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
Esempio n. 22
0
        private async Task <bool> AutoLinkAndSignInExternalAccount(ExternalLoginInfo loginInfo)
        {
            //Here we can check if the provider associated with the request has been configured to allow
            // new users (auto-linked external accounts). This would never be used with public providers such as
            // Google, unless you for some reason wanted anybody to be able to access the backend if they have a Google account
            // .... not likely!

            var authType = OwinContext.Authentication.GetExternalAuthenticationTypes().FirstOrDefault(x => x.AuthenticationType == loginInfo.Login.LoginProvider);

            if (authType == null)
            {
                Logger.Warn <BackOfficeController>("Could not find external authentication provider registered: " + loginInfo.Login.LoginProvider);
                return(false);
            }

            var autoLinkOptions = authType.GetExternalAuthenticationOptions();

            if (autoLinkOptions != null)
            {
                if (autoLinkOptions.ShouldAutoLinkExternalAccount(UmbracoContext, loginInfo))
                {
                    //we are allowing auto-linking/creating of local accounts
                    if (loginInfo.Email.IsNullOrWhiteSpace())
                    {
                        ViewData[TokenExternalSignInError] = new[] { "The requested provider (" + loginInfo.Login.LoginProvider + ") has not provided an email address, the account cannot be linked." };
                    }
                    else
                    {
                        //Now we need to perform the auto-link, so first we need to lookup/create a user with the email address
                        var foundByEmail = Services.UserService.GetByEmail(loginInfo.Email);
                        if (foundByEmail != null)
                        {
                            ViewData[TokenExternalSignInError] = new[] { "A user with this email address already exists locally. You will need to login locally to Umbraco and link this external provider: " + loginInfo.Login.LoginProvider };
                        }
                        else
                        {
                            var defaultUserType = autoLinkOptions.GetDefaultUserType(UmbracoContext, loginInfo);
                            var userType        = Services.UserService.GetUserTypeByAlias(defaultUserType);
                            if (userType == null)
                            {
                                ViewData[TokenExternalSignInError] = new[] { "Could not auto-link this account, the specified User Type does not exist: " + defaultUserType };
                            }
                            else
                            {
                                if (loginInfo.Email.IsNullOrWhiteSpace())
                                {
                                    throw new InvalidOperationException("The Email value cannot be null");
                                }
                                if (loginInfo.ExternalIdentity.Name.IsNullOrWhiteSpace())
                                {
                                    throw new InvalidOperationException("The Name value cannot be null");
                                }

                                var autoLinkUser = new BackOfficeIdentityUser()
                                {
                                    Email           = loginInfo.Email,
                                    Name            = loginInfo.ExternalIdentity.Name,
                                    UserTypeAlias   = userType.Alias,
                                    AllowedSections = autoLinkOptions.GetDefaultAllowedSections(UmbracoContext, loginInfo),
                                    Culture         = autoLinkOptions.GetDefaultCulture(UmbracoContext, loginInfo),
                                    UserName        = loginInfo.Email
                                };

                                //call the callback if one is assigned
                                if (autoLinkOptions.OnAutoLinking != null)
                                {
                                    autoLinkOptions.OnAutoLinking(autoLinkUser, loginInfo);
                                }

                                var userCreationResult = await UserManager.CreateAsync(autoLinkUser);

                                if (userCreationResult.Succeeded == false)
                                {
                                    ViewData[TokenExternalSignInError] = userCreationResult.Errors;
                                }
                                else
                                {
                                    var linkResult = await UserManager.AddLoginAsync(autoLinkUser.Id, loginInfo.Login);

                                    if (linkResult.Succeeded == false)
                                    {
                                        ViewData[TokenExternalSignInError] = linkResult.Errors;

                                        //If this fails, we should really delete the user since it will be in an inconsistent state!
                                        var deleteResult = await UserManager.DeleteAsync(autoLinkUser);

                                        if (deleteResult.Succeeded == false)
                                        {
                                            //DOH! ... this isn't good, combine all errors to be shown
                                            ViewData[TokenExternalSignInError] = linkResult.Errors.Concat(deleteResult.Errors);
                                        }
                                    }
                                    else
                                    {
                                        //sign in
                                        await SignInManager.SignInAsync(autoLinkUser, isPersistent : false, rememberBrowser : false);
                                    }
                                }
                            }
                        }
                    }
                }
                return(true);
            }

            return(false);
        }
Esempio n. 23
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                // If the user aleady has an account with any other provider, log them in.
                if (await LoginIfExternalProviderAlreadyAssignedAsync() && User.Identity.IsAuthenticated)
                {
                    return(RedirectToAction("Index", "Start"));
                }

                // Get the information about the user from the external login provider
                var socialLoginDetails = await UserService.GetExternalLoginInfoAsync();

                if (socialLoginDetails == null)
                {
                    return(View("ExternalLoginFailure"));
                }

                string firstName = null;
                string lastName  = null;
                var    nameClaim = socialLoginDetails.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name");
                if (nameClaim != null)
                {
                    string[] names = nameClaim.Value.Split(' ');
                    firstName = names[0];
                    lastName  = names.Length > 1 ? names[1] : string.Empty;
                }
                string eMail = socialLoginDetails.Email;

                var customerAddress = CustomerAddress.CreateInstance();
                customerAddress.Line1       = viewModel.Address;
                customerAddress.PostalCode  = viewModel.PostalCode;
                customerAddress.City        = viewModel.City;
                customerAddress.CountryName = viewModel.Country;

                var user = new SiteUser
                {
                    UserName           = eMail,
                    Email              = eMail,
                    FirstName          = firstName,
                    LastName           = lastName,
                    RegistrationSource = "Social login",
                    NewsLetter         = viewModel.Newsletter,
                    IsApproved         = true
                };

                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    user.Addresses = new List <CustomerAddress>(new[]
                    {
                        customerAddress
                    });
                    UserService.CreateCustomerContact(user);
                    result = await UserManager.AddLoginAsync(user.Id, socialLoginDetails.Login);

                    if (result.Succeeded)
                    {
                        return(RedirectToLocal(viewModel.ReturnUrl));
                    }
                }

                AddErrors(result.Errors);
            }

            return(View(viewModel));
        }
Esempio n. 24
0
        public async Task <IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var info = await Authentication.GetExternalLoginInfoAsync();

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

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

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

            var existingEmail = await _userRepository.FindByEmailAsync(model.Email);

            if (existingEmail != null)
            {
                //check if login provider is facebook -> connect existing account with facebook account.
                //if (externalLogin.LoginProvider == "Facebook")
                //{
                //    if (!existingEmail.UserLogins.Any(n => n.ProviderKey == "Facebook"))
                //    {
                //        existingEmail.UserLogins.Add(new IdentityUserLogin
                //        {
                //            LoginProvider = externalLogin.LoginProvider,
                //            ProviderKey = externalLogin.ProviderKey
                //        });
                //        _unitOfWork.Commit();
                //        return Ok();
                //    }
                //}
                //else
                //{
                //    //var siteName = ConfigurationManager.AppSettings["SiteName"];
                //    //ModelState.AddModelError("", string.Format(Resources.ErrorResource.ExistsEmail, existingEmail.Email, siteName));
                //    return BadRequest();
                //}
            }

            var existingUser = await _userRepository.FindByNameAsync(model.UserName);

            if (existingUser != null)
            {
                var siteName = ConfigurationManager.AppSettings["SiteName"];
                ModelState.AddModelError("", string.Format(model.UserName + "is registered on" + siteName));
                return(BadRequest(ModelState));
            }

            var user = new ApplicationUser()
            {
                UserName     = model.UserName,
                Email        = model.Email,
                FirstName    = model.FirstName,
                LastName     = model.LastName,
                Gender       = "Male",
                EmployeeCode = "500010"
            };

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

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
                IdentityResult response = await UserManager.AddToRoleAsync(user.Id, model.Role);

                result = await UserManager.AddLoginAsync(user.Id, info.Login);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}",
                                               validationError.PropertyName,
                                               validationError.ErrorMessage);
                    }
                }
            }

            return(Ok());
        }
Esempio n. 25
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            var redirectUrl = "/#/login/";

            if (remoteError != null)
            {
                return(BadRequest(new { Success = false, Error = "Error from external provider" }));
            }
            var info = await _signInManager.GetExternalLoginInfoAsync();



            if (info == null)
            {
                return(Redirect(redirectUrl));
            }

            // Sign in the user with this external login provider if the user already has a login.
            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                //var email = info.Principal.FindFirstValue(ClaimTypes.Email);
                //var user = await _userManager.FindByEmailAsync(email);
                //DateTime issuedAt = DateTime.Now;
                //await _googleService.SaveToken(user.Id, accessToken, issuedAt);
                _logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);

                redirectUrl = "/#/status";
                return(Redirect(redirectUrl));
            }
            if (result.IsLockedOut)
            {
                return(Redirect(redirectUrl));
            }
            else
            {
                // If the user does not have an account, then ask the user to create an account.
                ViewData["ReturnUrl"]     = returnUrl;
                ViewData["LoginProvider"] = info.LoginProvider;
                var email = info.Principal.FindFirstValue(ClaimTypes.Email);
                var user  = await _userManager.FindByEmailAsync(email);

                if (user == null)
                {
                    return(Redirect(redirectUrl));
                }

                var addProvider = await _userManager.AddLoginAsync(user, info);

                var gettoken        = info.AuthenticationTokens.FirstOrDefault(u => u.Name == "access_token");
                var accessToken     = gettoken.Value;
                var getExpireTime   = info.AuthenticationTokens.FirstOrDefault(u => u.Name == "expires_at");
                var expireTime      = getExpireTime.Value;
                var getRefreshToken = info.AuthenticationTokens.FirstOrDefault(u => u.Name == "refresh_token");
                var refreshToken    = getRefreshToken.Value;

                if (addProvider.Succeeded)
                {
                    DateTime issuedAt = DateTime.Now;
                    await _googleService.SaveToken(user.Id, accessToken, issuedAt, refreshToken);

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

                    _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                    redirectUrl = "/#/status";
                    return(Redirect(redirectUrl));
                }
                return(Redirect(redirectUrl)); //redirect ve trang index
            }
        }
Esempio n. 26
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            LoginViewModel model = new LoginViewModel
            {
                ReturnUrl     = returnUrl,
                ExternalLogin = (await signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
            };

            if (remoteError != null)
            {
                ModelState.AddModelError(string.Empty, $"Error from ecternal login 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);
            ApplicationUser user  = null;

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

                if (user != null && !user.EmailConfirmed)
                {
                    ModelState.AddModelError("", "Email henüz onaylanmadı. Lütfen mailinizi kontrol ediniz.");
                    return(View("Login", model));
                }
            }
            var signInResult = await signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (signInResult.Succeeded)
            {
                return(LocalRedirect(returnUrl));
            }
            else
            {
                if (email != null)
                {
                    if (user == null)
                    {
                        user = new ApplicationUser
                        {
                            UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
                            Email    = info.Principal.FindFirstValue(ClaimTypes.Email)
                        };
                        await userManager.CreateAsync(user);

                        var token            = userManager.GenerateEmailConfirmationTokenAsync(user).Result;
                        var confirmationLink = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, token = token }, Request.Scheme);
                        ViewBag.Title   = "Kayıt başarıyla tamamlandı.";
                        ViewBag.Messaje = "Giriş yapmadan önce lütfen mail adresinizi onaylayınız";
                        ViewBag.Link    = confirmationLink;
                        return(View("_Success"));
                    }
                    await userManager.AddLoginAsync(user, info);

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

                    return(LocalRedirect(returnUrl));
                }
            }
            ViewBag.ErrorTitle = $"E posta talebi alınmadı:{info.LoginProvider}";
            return(View("_Error"));
        }
Esempio n. 27
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl)
        {
            var info = await HttpContext.Authentication.GetAuthenticateInfoAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme);

            var tempUser = info?.Principal;

            if (tempUser == null)
            {
                throw new Exception("External authentication error");
            }

            var claims = tempUser.Claims.ToList();

            var userIdClaim = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject);

            if (userIdClaim == null)
            {
                userIdClaim = claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
            }
            if (userIdClaim == null)
            {
                throw new Exception("Unknown userid");
            }

            claims.Remove(userIdClaim);
            var provider = info.Properties.Items["scheme"];
            var userId   = userIdClaim.Value;

            var user = await _userManager.FindByLoginAsync(provider, userId);

            if (user == null)
            {
                user = new IdentityUser {
                    UserName = Guid.NewGuid().ToString()
                };
                await _userManager.CreateAsync(user);

                await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, userId, provider));
            }

            var additionalClaims = new List <Claim>();

            var sid = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId);

            if (sid != null)
            {
                additionalClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value));
            }

            AuthenticationProperties props = null;
            var id_token = info.Properties.GetTokenValue("id_token");

            if (id_token != null)
            {
                props = new AuthenticationProperties();
                props.StoreTokens(new[] { new AuthenticationToken {
                                              Name = "id_token", Value = id_token
                                          } });
            }

            await _events.RaiseAsync(new UserLoginSuccessEvent(provider, userId, user.Id, user.UserName));

            await HttpContext.Authentication.SignInAsync(user.Id, user.UserName, provider, additionalClaims.ToArray());

            await HttpContext.Authentication.SignOutAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme);

            if (_interaction.IsValidReturnUrl(returnUrl) || Url.IsLocalUrl(returnUrl))
            {
                return(Redirect(returnUrl));
            }

            return(Redirect("~/"));
        }
        public async Task <IActionResult> ExternalLoginCallback()
        {
            //if you use this technique, make sure to include LoginProvider key in the Auth Props Items
            var externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync();

            //if you don't wanna use the technique above, you can use this one
            //var authenticationResult = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme);
            if (externalLoginInfo != null)
            {
                var user = await _userManager.FindByLoginAsync(externalLoginInfo.LoginProvider, externalLoginInfo.ProviderKey);

                if (user != null)
                {
                    var signInResult = await _signInManager.ExternalLoginSignInAsync(externalLoginInfo.LoginProvider, externalLoginInfo.ProviderKey, true);

                    if (signInResult.Succeeded)
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                    else if (signInResult.RequiresTwoFactor)
                    {
                        return(RedirectToAction(nameof(TwoFactorLoginHandler), new { email = user.Email }));
                    }
                    else
                    {
                        return(View("Error", new List <string>
                        {
                            "External login failed. Please try again"
                        }));
                    }
                }
                else
                {
                    string email = externalLoginInfo.Principal?.FindFirstValue("email") ??
                                   externalLoginInfo.Principal?.FindFirstValue(ClaimTypes.Email);
                    if (!string.IsNullOrEmpty(email))
                    {
                        user = await _userManager.FindByEmailAsync(email);

                        if (user != null)
                        {
                            await _userManager.AddLoginAsync(user, externalLoginInfo);

                            var signInResult = await _signInManager.ExternalLoginSignInAsync(externalLoginInfo.LoginProvider, externalLoginInfo.ProviderKey, true);

                            if (signInResult.Succeeded)
                            {
                                return(RedirectToAction("Index", "Home"));
                            }
                            else
                            {
                                return(View("Error", new List <string>
                                {
                                    "External login failed. Please try again"
                                }));
                            }
                        }
                        else
                        {
                            string name = externalLoginInfo.Principal?.FindFirstValue("name") ??
                                          externalLoginInfo.Principal?.FindFirstValue(ClaimTypes.Name) ??
                                          email;
                            AppUser newUser = new AppUser
                            {
                                FullName                  = name,
                                Email                     = email,
                                EmailConfirmed            = true,
                                LockoutEnabled            = false,
                                IsAuthenticatorKeyEnabled = false,
                                UserName                  = email
                            };
                            var createUserResult = await _userManager.CreateAsync(newUser);

                            if (createUserResult.Succeeded)
                            {
                                await _userManager.AddLoginAsync(newUser, externalLoginInfo);

                                var signInResult = await _signInManager.ExternalLoginSignInAsync(externalLoginInfo.LoginProvider, externalLoginInfo.ProviderKey, true);

                                if (signInResult.Succeeded)
                                {
                                    return(RedirectToAction("Index", "Home"));
                                }
                                else
                                {
                                    return(View("Error", new List <string>
                                    {
                                        "External login failed. Please try again"
                                    }));
                                }
                            }
                            else
                            {
                                return(View("Error", createUserResult.Errors.Select(c => c.Description).ToList()));
                            }
                        }
                    }
                    else
                    {
                        return(View("Error", new List <string>
                        {
                            "External login failed. Email claim is empty"
                        }));
                    }
                }
            }
            return(View("Error", new List <string>
            {
                "External login info object is null. External login process is failed"
            }));
        }
Esempio n. 29
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            if (remoteError != null)
            {
                ErrorMessage = $"Error from external provider: {remoteError}";
                return(RedirectToAction(nameof(Login)));
            }
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(RedirectToAction(nameof(Login)));
            }
            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                _logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);
                return(RedirectToLocal(returnUrl));
            }
            if (result.IsLockedOut)
            {
                return(RedirectToAction(nameof(Lockout)));
            }
            else
            {
                ViewData["ReturnUrl"]     = returnUrl;
                ViewData["LoginProvider"] = info.LoginProvider;
                var email    = info.Principal.FindFirstValue(ClaimTypes.Email);
                var username = info.Principal.FindFirstValue(ClaimTypes.GivenName);

                string thumbnailUrl   = "https://ssl.gstatic.com/accounts/ui/avatar_2x.png";
                string nameIdentifier = info.Principal.FindFirstValue(ClaimTypes.NameIdentifier);

                if (info.LoginProvider == "Facebook")
                {
                    thumbnailUrl = string.Format("https://graph.facebook.com/{0}/picture?type=large", nameIdentifier);
                }

                ExternalLoginViewModel model = new ExternalLoginViewModel {
                    Email = email, UserName = username, UrlImage = thumbnailUrl
                };

                var user = new User {
                    UserName = model.UserName, Email = model.Email, UrlImage = model.UrlImage
                };
                var resultUser = await _userManager.CreateAsync(user);

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

                    if (resultUser.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(resultUser);


                ViewData["ReturnUrl"] = returnUrl;

                //return View(nameof(ExternalLogin), model);

                return(RedirectToAction("List", "Post"));
            }
        }
Esempio n. 30
0
        private async Task <UserIdentity> AutoProvisionUserAsync(string provider, string providerUserId, IEnumerable <Claim> claims)
        {
            // create a list of claims that we want to transfer into our store
            var filtered = new List <Claim>();

            // user's display name
            var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ??
                       claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;

            if (name != null)
            {
                filtered.Add(new Claim(JwtClaimTypes.Name, name));
            }
            else
            {
                var first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ??
                            claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
                var last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ??
                           claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value;
                if (first != null && last != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last));
                }
                else if (first != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, first));
                }
                else if (last != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, last));
                }
            }

            // email
            var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ??
                        claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;

            if (email != null)
            {
                filtered.Add(new Claim(JwtClaimTypes.Email, email));
            }

            var user = new UserIdentity
            {
                UserName = Guid.NewGuid().ToString(),
            };
            var identityResult = await _userManager.CreateAsync(user);

            if (!identityResult.Succeeded)
            {
                throw new Exception(identityResult.Errors.First().Description);
            }

            if (filtered.Any())
            {
                identityResult = await _userManager.AddClaimsAsync(user, filtered);

                if (!identityResult.Succeeded)
                {
                    throw new Exception(identityResult.Errors.First().Description);
                }
            }

            identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider));

            if (!identityResult.Succeeded)
            {
                throw new Exception(identityResult.Errors.First().Description);
            }

            return(user);
        }
Esempio n. 31
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            if (!Input.Email.EndsWith("@mvla.net"))
            {
                ModelState.AddModelError(string.Empty, "Not a valid MVLA email address!");
                return(Page());
            }

            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)
            {
                StringBuilder sb = new StringBuilder();
                using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
                {
                    byte[] inputBytes = Encoding.ASCII.GetBytes(Input.Email.Trim().ToLower());
                    byte[] hashBytes  = md5.ComputeHash(inputBytes);

                    for (int i = 0; i < hashBytes.Length; i++)
                    {
                        sb.Append(hashBytes[i].ToString("X2"));
                    }
                }

                var user = new ContraUser
                {
                    Name = info.Principal.FindFirstValue(ClaimTypes.Name),

                    Articles       = new List <Article>(),
                    ArticlesLiked  = new List <Article>(),
                    ArticlesViewed = new List <Article>(),
                    CommentsLiked  = new List <Comment>(),

                    ProfilePictureURL = "https://gravatar.com/avatar/" + sb.ToString() + "?d=identicon",
                    UserName          = Input.Email,
                    Email             = Input.Email,
                    DateJoined        = DateTime.Now
                };
                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);

                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

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

                        await _emailSender.SendConfirmEmailAsync(Input.Email, info.Principal.FindFirstValue(ClaimTypes.Name), callbackUrl);

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

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

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            LoginViewModel loginViewModel = new LoginViewModel
            {
                ReturnUrl      = returnUrl,
                ExternalLogins =
                    (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
            };

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

                return(View("Login", loginViewModel));
            }

            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(View("Login", loginViewModel));
            }

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

            if (signResult.Succeeded)
            {
                return(LocalRedirect(returnUrl));
            }

            else if (signResult.IsLockedOut)
            {
                return(RedirectToAction(nameof(RecoverPassword)));
            }

            else
            {
                var email = info.Principal.FindFirstValue(ClaimTypes.Email);
                if (email != null)
                {
                    var user = await _userHelper.GetUserByEmailAsync(email);

                    if (user == null)
                    {
                        user = new User
                        {
                            UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
                            Email    = info.Principal.FindFirstValue(ClaimTypes.Email)
                        };

                        await _userManager.CreateAsync(user);
                    }

                    await _userManager.AddLoginAsync(user, info);

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

                    return(LocalRedirect(returnUrl));
                }

                ViewBag.ErrorTittle = $"Error claim not received from: {info.LoginProvider}";

                return(View("Error"));
            }
        }
Esempio n. 33
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

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

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

                return(View("Login", loginViewModel));
            }

            // Get the login information about the user from the external login provider
            var info = await signInManager.GetExternalLoginInfoAsync();

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

                return(View("Login", loginViewModel));
            }
            // Get the email claim from external login provider (Google, Facebook etc)
            var             email = info.Principal.FindFirstValue(ClaimTypes.Email);
            ApplicationUser user  = null;

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

                // If email is not confirmed, display login view with validation error
                if (user != null && !user.EmailConfirmed)
                {
                    ModelState.AddModelError(string.Empty, "Email not confirmed yet");
                    return(View("Login", loginViewModel));
                }
            }
            // If the user already has a login (i.e if there is a record in AspNetUserLogins
            // table) then sign-in the user with this external login provider
            var signInResult = await signInManager.ExternalLoginSignInAsync(info.LoginProvider,
                                                                            info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (signInResult.Succeeded)
            {
                return(LocalRedirect(returnUrl));
            }
            // If there is no record in AspNetUserLogins table, the user may not have
            // a local account
            else
            {
                // Check the email claim value
                if (email != null)
                {
                    if (user == null)
                    {
                        user = new ApplicationUser
                        {
                            UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
                            Email    = info.Principal.FindFirstValue(ClaimTypes.Email)
                        };

                        await userManager.CreateAsync(user);

                        // After a local user account is created, generate and log the
                        // email confirmation link
                        var token = await userManager.GenerateEmailConfirmationTokenAsync(user);

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

                        logger.Log(LogLevel.Warning, confirmationLink);

                        ViewBag.ErrorTitle   = "Registration successful";
                        ViewBag.ErrorMessage = "Before you can Login, please confirm your " +
                                               "email, by clicking on the confirmation link we have emailed you";
                        return(View("Error"));
                    }

                    //Add a login(i.e insert a row for the user in AspNetUserLogins table)
                    await userManager.AddLoginAsync(user, info);

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

                    return(LocalRedirect(returnUrl));
                }

                // If we cannot find the user email we cannot continue
                ViewBag.ErrorTitle   = $"Email claim not received from: {info.LoginProvider}";
                ViewBag.ErrorMessage = "Please contact support on [email protected]";
                return(View("Error"));
            }
        }
Esempio n. 34
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            if (remoteError != null)
            {
                ErrorMessage = $"Error from external provider: {remoteError}";
                return(RedirectToAction(nameof(Login)));
            }
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(RedirectToAction(nameof(Login)));
            }

            // Sign in the user with this external login provider if the user already has a login.
            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                _logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);
                return(RedirectToLocal(returnUrl));
            }
            if (result.IsLockedOut)
            {
                return(RedirectToAction(nameof(Lockout)));
            }
            else
            {
                // If the user does not have an account, then ask the user to create an account.
                ViewData["ReturnUrl"]     = returnUrl;
                ViewData["LoginProvider"] = info.LoginProvider;
                var email     = info.Principal.FindFirstValue(ClaimTypes.Email);
                var firstname = info.Principal.FindFirstValue(ClaimTypes.GivenName);
                var lastname  = info.Principal.FindFirstValue(ClaimTypes.Surname);

                firstname = ConvertToProperNameCase(firstname);
                lastname  = ConvertToProperNameCase(lastname);

                if (!email.Contains("@eastonsd.org") && !email.Contains("@roverkids.org"))
                {
                    return(RedirectToAction(nameof(DomainNotAuthorized)));
                }

                var user = new ApplicationUser {
                    UserName = email, Email = email, FirstName = firstname, LastName = lastname
                };
                var result2 = await _userManager.CreateAsync(user);

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

                    if (result2.Succeeded)
                    {
                        // reset user roles
                        var roles = await _userManager.GetRolesAsync(user);

                        await _userManager.RemoveFromRolesAsync(user, roles);

                        // assign new role
                        await _userManager.AddToRoleAsync(user, "Student");

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

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return(RedirectToLocal(returnUrl));
                    }
                }

                return(View("ExternalLogin", new ExternalLoginViewModel {
                    Email = email
                }));
            }
        }
Esempio n. 35
0
        public async Task <IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
        {
            if (remoteError != null)
            {
                ErrorMessage = _localizer["Error_ErrorFromExternalProvider0", remoteError];
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = _localizer["Error_LoadingExternalLoginInformation"];
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            // Sign in the user with this external login provider if the user already has a login.
            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
                return(OnSignIn(returnUrl));
            }
            if (result.IsLockedOut)
            {
                return(RedirectToPage("./Lockout"));
            }
            else
            {
                // If we don't find a matching login we try to match the email claim to one of the existing users
                string email = info.Principal.FindFirstValue(ClaimTypes.Email);
                if (email == null)
                {
                    ErrorMessage = _localizer["Error_EmailNotProvidedByExternalSignIn"];
                    return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
                }

                var user = await _userManager.FindByEmailAsync(email);

                if (user == null)
                {
                    ErrorMessage = _localizer["Error_AUserWithEmail0CouldNotBeFound", email];
                    return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
                }

                if (!await _userManager.IsEmailConfirmedAsync(user))
                {
                    var emailConfirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var confirmEmailResult = await _userManager.ConfirmEmailAsync(user, emailConfirmationToken);

                    if (!confirmEmailResult.Succeeded)
                    {
                        ErrorMessage = _localizer["Error_ConfirmingYourEmail"];
                        string errors = string.Join(", ", confirmEmailResult.Errors.Select(e => e.Description));
                        _logger.LogError($"Failed to confirm email for user with ID '{user.Id}' and email '{user.Email}', errors: " + errors);

                        return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
                    }
                }

                var addLoginResult = await _userManager.AddLoginAsync(user, info);

                if (!addLoginResult.Succeeded)
                {
                    ErrorMessage = _localizer["Error_AddingLoginForUserWithEmail0", email];
                    return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
                }

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

                if (result.Succeeded)
                {
                    _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
                    return(OnSignIn(returnUrl));
                }
                if (result.IsLockedOut)
                {
                    return(RedirectToPage("./Lockout"));
                }
                else
                {
                    ErrorMessage = _localizer["Error_TryingToSignYouInWithExternalProvider"];
                    _logger.LogError($"Failed to log user with ID '{user.Id}' and email '{user.Email}'");
                    return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
                }
            }
        }
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            if (remoteError != null)
            {
                ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
                return(BadRequest(ModelState));
            }

            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            /*** Return 400 when can't get externalLoginInfo ***/
            if (info == null)
            {
                return(BadRequest("Please Login"));
            }

            // Sign in the user with this external login provider if the user already has a login.
            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false);

            if (result.Succeeded)
            {
                return(Ok("Redirect to homepage after login"));
            }
            else
            {
                var email = info.Principal.FindFirstValue(ClaimTypes.Email);
                var user  = await _userManager.FindByNameAsync(email);

                var login = new IdentityResult();
                if (user != null)
                {
                    /*** Check activation of account ***/
                    if (!await _userManager.IsEmailConfirmedAsync(user))
                    {
                        /*** Do Confirm email ***/
                        var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        var confirmEmail = await _userManager.ConfirmEmailAsync(user, token);

                        /*** Get error result if it can't confirm email ***/
                        if (!confirmEmail.Succeeded)
                        {
                            return(GetErrorResult(confirmEmail));
                        }
                    }
                    /*** Do AddLoginProvider ***/
                    login = await _userManager.AddLoginAsync(user, info);

                    /*** Get error result if it can't add provider ***/
                    if (!login.Succeeded)
                    {
                        return(GetErrorResult(login));
                    }
                    /*** Do SignIn ***/
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    /*** Generate Token ***/
                    var response = await LogicUnitOfWork.AccessTokenService.PublishToken(await PrepareGenerateTokenExternalLogin(email));

                    return(Ok(response));
                }
                else
                {
                    return(Ok("Register"));
                }
            }
        }
Esempio n. 37
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            LoginViewModel loginViewModel = new LoginViewModel
            {
                ReturnUrl      = returnUrl,
                ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
            };

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

                return(View("Login", loginViewModel));
            }

            var info = await _signInManager.GetExternalLoginInfoAsync();

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

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

            var signInResult = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, false, true);

            if (signInResult.Succeeded)
            {
                return(LocalRedirect(returnUrl));
            }
            else
            {
                if (email != null)
                {
                    if (user is null)
                    {
                        user = new ApplicationUser
                        {
                            UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
                            Email    = info.Principal.FindFirstValue(ClaimTypes.Email)
                        };

                        await _userManager.CreateAsync(user);
                    }

                    await _userManager.AddLoginAsync(user, info);

                    await _signInManager.SignInAsync(user, false);

                    return(LocalRedirect(returnUrl));
                }

                ViewBag.ErrorTitle   = $"Email claim not received from: {info.LoginProvider}";
                ViewBag.ErrorMessage = "Plaese contact support.";

                return(View(error));
            }
        }