Esempio n. 1
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. 2
0
 public static async Task<IndexViewModel> ToViewModel(this ApplicationUser user, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
 {
     var result = new IndexViewModel
     {
         HasPassword = await userManager.HasPasswordAsync(user),
         EmailAddress = user.Email,
         IsEmailAddressConfirmed = user.EmailConfirmed,
         IsPhoneNumberConfirmed = user.PhoneNumberConfirmed,
         PhoneNumber = await userManager.GetPhoneNumberAsync(user),
         TwoFactor = await userManager.GetTwoFactorEnabledAsync(user),
         Logins = await userManager.GetLoginsAsync(user),
         BrowserRemembered = await signInManager.IsTwoFactorClientRememberedAsync(user),
         AssociatedSkills = user.AssociatedSkills,
         TimeZoneId = user.TimeZoneId,
         Name = user.Name,
         ProposedNewEmailAddress = user.PendingNewEmail
     };
     return result;
 }
 public static async Task<IndexViewModel> ToViewModel(this ApplicationUser user, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
 {
     var profileCompletenessWarnings = user.ValidateProfileCompleteness();
     var result = new IndexViewModel
     {
         HasPassword = await userManager.HasPasswordAsync(user),
         EmailAddress = user.Email,
         IsEmailAddressConfirmed = user.EmailConfirmed,
         IsPhoneNumberConfirmed = user.PhoneNumberConfirmed,
         PhoneNumber = await userManager.GetPhoneNumberAsync(user),
         TwoFactor = await userManager.GetTwoFactorEnabledAsync(user),
         Logins = await userManager.GetLoginsAsync(user),
         BrowserRemembered = await signInManager.IsTwoFactorClientRememberedAsync(user),
         AssociatedSkills = user.AssociatedSkills,
         TimeZoneId = user.TimeZoneId,
         FirstName = user.FirstName,
         LastName = user.LastName,
         ProposedNewEmailAddress = user.PendingNewEmail,
         IsProfileComplete = user.IsProfileComplete(),
         ProfileCompletenessWarnings = profileCompletenessWarnings.Select(p => p.ErrorMessage)
     };
     return result;
 }
        private async Task <ExternalLoginsState> GetExternalLoginsState()
        {
            var user = await GetCurrentUserAsync();

            var userLogins = await _userManager.GetLoginsAsync(user);

            var schemes = await _signInManager.GetExternalAuthenticationSchemesAsync();

            foreach (var userLogin in userLogins.Where(userLogin => string.IsNullOrEmpty(userLogin.ProviderDisplayName)))
            {
                userLogin.ProviderDisplayName =
                    schemes
                    .SingleOrDefault(x => x.Name.Equals(userLogin.LoginProvider))?
                    .DisplayName;
                if (string.IsNullOrEmpty(userLogin.ProviderDisplayName))
                {
                    userLogin.ProviderDisplayName = userLogin.LoginProvider;
                }
            }
            var otherLogins = schemes.Where(auth => userLogins.All(ul => auth.Name != ul.LoginProvider)).ToList();

            return(new ExternalLoginsState
            {
                CurrentLogins = userLogins.Select(x => new ExternalLoginsState.ExternalLogin
                {
                    ProviderKey = x.ProviderKey,
                    LoginProvider = x.LoginProvider,
                    LoginProviderDisplayName = x.ProviderDisplayName
                }).ToList(),
                OtherLogins = otherLogins.Select(x => new ExternalLoginState.ExternalLoginProvider
                {
                    DisplayName = x.DisplayName,
                    Scheme = x.Name
                }).ToList()
            });
        }
Esempio n. 5
0
        private async Task <ProfileVM> GetProfileVM(UserWithClaims?user, ChangeProfileModel?model = null, string?errorMessage = null, string?successMessage = null)
        {
            if (user == null)
            {
                throw new DomainException("Cannot find user.");
            }

            var taskForProviders = signInManager.GetExternalProvidersAsync();
            var taskForPassword  = userManager.HasPasswordAsync(user.Identity);
            var taskForLogins    = userManager.GetLoginsAsync(user.Identity);

            await Task.WhenAll(taskForProviders, taskForPassword, taskForLogins);

            var result = new ProfileVM
            {
                Id                = user.Id,
                ClientSecret      = user.ClientSecret() !,
                Email             = user.Email,
                ErrorMessage      = errorMessage,
                ExternalLogins    = taskForLogins.Result,
                ExternalProviders = taskForProviders.Result,
                DisplayName       = user.DisplayName() !,
                IsHidden          = user.IsHidden(),
                HasPassword       = taskForPassword.Result,
                HasPasswordAuth   = identityOptions.AllowPasswordAuth,
                SuccessMessage    = successMessage
            };

            if (model != null)
            {
                SimpleMapper.Map(model, result);
            }

            return(result);
        }
    }
Esempio n. 6
0
        public async Task <ActionResult> DeleteUser(string userid)
        {
            if (AdmUsrRole == "Admin")
            {
                return(RedirectToAction("Index", "Admin", new
                {
                    Message =
                        ManageMessageId.HighRankedUser
                }));
            }
            userid = context.Users.Where(x => x.UserName == AdmUsrName).Select(x =>
                                                                               x.Id).FirstOrDefault();
            var user = await UserManager.FindByIdAsync(userid);

            var userClaims = await UserManager.GetClaimsAsync(user.Id);

            var userRoles = await UserManager.GetRolesAsync(user.Id);

            var userLogins = await UserManager.GetLoginsAsync(user.Id);

            foreach (var claim in userClaims)
            {
                await UserManager.RemoveClaimAsync(user.Id, claim);
            }
            string[] roles = new string[userRoles.Count];
            userRoles.CopyTo(roles, 0);
            await UserManager.RemoveFromRolesAsync(user.Id, roles);

            foreach (var log in userLogins)
            {
                await UserManager.RemoveLoginAsync(user.Id, new UserLoginInfo(log.LoginProvider, log.ProviderKey));
            }
            await UserManager.DeleteAsync(user);

            return(RedirectToAction("Index", "Admin", new { Message = ManageMessageId.UserDeleted }));
        }
Esempio n. 7
0
        public async Task <ActionResult> IncompleteSellerIndex()
        {
            var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            var model = new UserIndexViewModel
            {
                HasPassword       = HasPassword(),
                PhoneNumber       = await UserManager.GetPhoneNumberAsync(user.Id),
                TwoFactor         = await UserManager.GetTwoFactorEnabledAsync(user.Id),
                Logins            = await UserManager.GetLoginsAsync(user.Id),
                BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(user.Id),
                Mobile            = await UserManager.GetPhoneNumberAsync(user.Id),
                AddressLine1      = user.AddressLine1,
                AddressLine2      = user.AddressLine2,
                AddressLine3      = user.AddressLine3,
                FirstName         = user.FirstName,
                LastName          = user.LastName,
                Country           = user.Country,
                Email             = user.Email,
                ImagePath         = user.ImagePath
            };

            return(View(model));
        }
Esempio n. 8
0
        //
        // GET: /Manage/Index
        public async Task <ActionResult> Index(ManageMessageId?message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Ваш пароль изменен."
                : message == ManageMessageId.SetPasswordSuccess ? "Пароль задан."
                : message == ManageMessageId.SetTwoFactorSuccess ? "Настроен поставщик двухфакторной проверки подлинности."
                : message == ManageMessageId.Error ? "Произошла ошибка."
                : message == ManageMessageId.AddPhoneSuccess ? "Ваш номер телефона добавлен."
                : message == ManageMessageId.RemovePhoneSuccess ? "Ваш номер телефона удален."
                : "";

            var userId = User.Identity.GetUserId();
            var user   = await UserManager.FindByIdAsync(userId);

            var roleId = user.Roles.FirstOrDefault().RoleId;
            var image  = string.Empty;

            if (user.Image != null)
            {
                image = "data:image/png;base64," + Convert.ToBase64String(user.Image, 0, user.Image.Length);
            }

            var model = new IndexViewModel
            {
                HasPassword = HasPassword(),
                Logins      = await UserManager.GetLoginsAsync(userId),
                FName       = user.FName,
                Name        = user.Name,
                SurName     = user.SurName,
                RolesName   = RoleManager.Roles.FirstOrDefault(r => r.Id == roleId).Name,
                Image       = image,
                Email       = user.Email
            };

            return(View(model));
        }
Esempio n. 9
0
        public async Task <IActionResult> ExternalLogins()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound(_localizer["UserNotFound", _userManager.GetUserId(User)]));
            }

            var model = new ExternalLoginsViewModel
            {
                CurrentLogins = await _userManager.GetLoginsAsync(user)
            };

            model.OtherLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync())
                                .Where(auth => model.CurrentLogins.All(ul => auth.Name != ul.LoginProvider))
                                .ToList();

            model.ShowRemoveButton = await _userManager.HasPasswordAsync(user) || model.CurrentLogins.Count > 1;

            model.StatusMessage = StatusMessage;

            return(View(model));
        }
Esempio n. 10
0
        public async Task <IActionResult> Index(ManageMessageId?message = null)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
                : message == ManageMessageId.Error ? "An error has occurred."
                : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
                : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
                : "";

            var user = await GetCurrentUserAsync();

            var model = new IndexViewModel
            {
                HasPassword       = await UserManager.HasPasswordAsync(user),
                PhoneNumber       = await UserManager.GetPhoneNumberAsync(user),
                TwoFactor         = await UserManager.GetTwoFactorEnabledAsync(user),
                Logins            = await UserManager.GetLoginsAsync(user),
                BrowserRemembered = await SignInManager.IsTwoFactorClientRememberedAsync(user)
            };

            return(View(model));
        }
Esempio n. 11
0
        public static async Task <IndexViewModel> ToViewModel(this ApplicationUser user, UserManager <ApplicationUser> userManager, SignInManager <ApplicationUser> signInManager)
        {
            var profileCompletenessWarnings = user.ValidateProfileCompleteness();
            var result = new IndexViewModel
            {
                HasPassword             = await userManager.HasPasswordAsync(user),
                EmailAddress            = user.Email,
                IsEmailAddressConfirmed = user.EmailConfirmed,
                IsPhoneNumberConfirmed  = user.PhoneNumberConfirmed,
                PhoneNumber             = await userManager.GetPhoneNumberAsync(user),
                TwoFactor                   = await userManager.GetTwoFactorEnabledAsync(user),
                Logins                      = await userManager.GetLoginsAsync(user),
                BrowserRemembered           = await signInManager.IsTwoFactorClientRememberedAsync(user),
                AssociatedSkills            = user.AssociatedSkills,
                TimeZoneId                  = user.TimeZoneId,
                FirstName                   = user.FirstName,
                LastName                    = user.LastName,
                ProposedNewEmailAddress     = user.PendingNewEmail,
                IsProfileComplete           = user.IsProfileComplete(),
                ProfileCompletenessWarnings = profileCompletenessWarnings.Select(p => p.ErrorMessage)
            };

            return(result);
        }
Esempio n. 12
0
        //
        // GET: /Manage/ManageLogins
        public async Task <ActionResult> ManageLogins(ManageMessageId?message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.RemoveLoginSuccess
          ? "The external login was removed."
          : message == ManageMessageId.Error
            ? "An error has occurred."
            : "";
            var user = await UserManager.FindByIdAsync(CurrentUserId);

            if (user == null)
            {
                return(View("Error"));
            }
            var userLogins = await UserManager.GetLoginsAsync(CurrentUserId);

            var otherLogins =
                AuthenticationManager.GetExternalAuthenticationTypes()
                .Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider))
                .ToList();

            ViewBag.ShowRemoveButton = user.HasPassword || userLogins.Count > 1;
            return(View(new ManageLoginsViewModel
            {
                CurrentLogins = userLogins.Select(ul => new UserLoginInfoViewModel()
                {
                    LoginProvider = ul.LoginProvider,
                    ProviderKey = ul.ProviderKey
                }).ToList(),
                OtherLogins = otherLogins.Select(ol => new AuthenticationDescriptionViewModel()
                {
                    AuthenticationType = ol.AuthenticationType,
                    Caption = ol.Caption
                }).ToList(),
            }));
        }
Esempio n. 13
0
        public async Task <IActionResult> ExternalLogins()
        {
            ViewData["AlleCategorien"] = _categorieRepository.GetAll().ToList();

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var model = new ExternalLoginsViewModel {
                CurrentLogins = await _userManager.GetLoginsAsync(user)
            };

            model.OtherLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync())
                                .Where(auth => model.CurrentLogins.All(ul => auth.Name != ul.LoginProvider))
                                .ToList();
            model.ShowRemoveButton = await _userManager.HasPasswordAsync(user) || model.CurrentLogins.Count > 1;

            model.StatusMessage = StatusMessage;

            return(View(model));
        }
Esempio n. 14
0
        public async Task <LoginResultDTO> Login(LoginDTO loginDTO)
        {
            var user = _userManager.Users.SingleOrDefault(u => u.Email == loginDTO.Email);

            if (!await _userManager.IsEmailConfirmedAsync(user) && !_userManager.GetLoginsAsync(user).Result.Any())
            {
                throw new ApplicationException(DictionaryResources.EmailNotConfirmed);
            }

            var result = await _signInManager.PasswordSignInAsync(loginDTO.Email, loginDTO.Password, false, false);

            if (!result.Succeeded)
            {
                throw new ApplicationException(DictionaryResources.InvalidLoginAttempt);
            }

            var loginResult = new LoginResultDTO
            {
                Token = GenerateJwtToken(user),
                Id    = user.Id
            };

            return(loginResult);
        }
Esempio n. 15
0
        // GET: /Manage/Index
        public async Task <ActionResult> Index(ManageMessageId?message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                                : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
                                : message == ManageMessageId.Error ? "An error has occurred."
                                : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
                                : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
                                : "";

            var userId = User.Identity.GetUserId <Int64>();
            var model  = new IndexViewModel
            {
                HasPassword = HasPassword(),
                PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
                TwoFactor   = await UserManager.GetTwoFactorEnabledAsync(userId),
                Logins      = await UserManager.GetLoginsAsync(userId),
                // TODO:
                BrowserRemembered = false                 // await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId)
            };

            return(View(model));
        }
Esempio n. 16
0
        public async Task <IActionResult> ManageLogins(ManageMessageId?message = null)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
                : message == ManageMessageId.AddLoginSuccess ? "The external login was added."
                : message == ManageMessageId.Error ? "An error has occurred."
                : "";
            var user = await GetCurrentUserAsync();

            if (user == null)
            {
                return(View("Error"));
            }
            var userLogins = await UserManager.GetLoginsAsync(user);

            var otherLogins = SignInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();

            ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1;
            return(View(new ManageLoginsViewModel
            {
                CurrentLogins = userLogins,
                OtherLogins = otherLogins
            }));
        }
        private async Task <SignInResult> LinkUser(MemberIdentityUser autoLinkUser, ExternalLoginInfo loginInfo)
        {
            var existingLogins = await UserManager.GetLoginsAsync(autoLinkUser);

            var exists = existingLogins.FirstOrDefault(x => x.LoginProvider == loginInfo.LoginProvider && x.ProviderKey == loginInfo.ProviderKey);

            // if it already exists (perhaps it was added in the AutoLink callbak) then we just continue
            if (exists != null)
            {
                //sign in
                return(await SignInOrTwoFactorAsync(autoLinkUser, isPersistent : false, loginInfo.LoginProvider));
            }

            var linkResult = await UserManager.AddLoginAsync(autoLinkUser, loginInfo);

            if (linkResult.Succeeded)
            {
                //we're good! sign in
                return(await SignInOrTwoFactorAsync(autoLinkUser, isPersistent : false, loginInfo.LoginProvider));
            }

            //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)
            {
                var errors = linkResult.Errors.Select(x => x.Description).ToList();
                return(AutoLinkSignInResult.FailedLinkingUser(errors));
            }
            else
            {
                //DOH! ... this isn't good, combine all errors to be shown
                var errors = linkResult.Errors.Concat(deleteResult.Errors).Select(x => x.Description).ToList();
                return(AutoLinkSignInResult.FailedLinkingUser(errors));
            }
        }
Esempio n. 18
0
 public async Task <IList <UserLoginInfo> > GetLoginsAsync(dynamic user)
 {
     return(await UserManager.GetLoginsAsync(user));
 }
Esempio n. 19
0
        private async Task RefreshTokens(ClaimsPrincipal claimUser, ApplicationUser user, UserManager <ApplicationUser> userManager,
                                         SignInManager <ApplicationUser> signInManager, IConfiguration configuration)
        {
            var userLogins = await userManager.GetLoginsAsync(user);

            var login        = userLogins.First();
            var refreshToken = await userManager.GetAuthenticationTokenAsync(user,
                                                                             BluebeamAuthenticationDefaults.AuthenticationScheme, "refresh_token");

            AuthModel authData = null;

            using (var client = new HttpClient())
            {
                var uri     = new Uri("https://authserver.bluebeam.com/auth/token");
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("grant_type", "refresh_token"),
                    new KeyValuePair <string, string>("refresh_token", refreshToken),
                    new KeyValuePair <string, string>("client_id", configuration["ClientID"]),
                    new KeyValuePair <string, string>("client_secret", configuration["ClientSecret"])
                });
                var response = await client.PostAsync(uri, content);

                string tokenResponse = await response.Content.ReadAsStringAsync();

                System.Console.WriteLine(tokenResponse);
                authData = JsonConvert.DeserializeObject <AuthModel>(tokenResponse);
                System.Console.WriteLine(authData.ToString());

                /*var nameIdentifier =
                 *  _user.FindFirstValue("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier");*/
                System.Console.WriteLine("Access Token: " + authData.AccessToken);
                System.Console.WriteLine("Refresh Token: " + authData.RefreshToken);
                System.Console.WriteLine("Provider: " + login.LoginProvider);
                System.Console.WriteLine("ProviderKey: " + login.ProviderKey);
                //System.Console.WriteLine("Name Identifier: " + nameIdentifier);

                var externalLoginInfo =
                    new ExternalLoginInfo(claimUser, login.LoginProvider, login.ProviderKey, claimUser.Identity.Name)
                {
                    AuthenticationTokens = new List <AuthenticationToken>()
                    {
                        new AuthenticationToken()
                        {
                            Name  = "access_token",
                            Value = authData.AccessToken
                        },
                        new AuthenticationToken()
                        {
                            Name  = "refresh_token",
                            Value = authData.RefreshToken
                        },
                        new AuthenticationToken()
                        {
                            Name  = "token_type",
                            Value = authData.TokenType
                        },
                        new AuthenticationToken()
                        {
                            Name  = "expires_at",
                            Value = authData.Expires
                        }
                    }
                };

                var result = await signInManager.UpdateExternalAuthenticationTokensAsync(externalLoginInfo);

                if (!result.Succeeded)
                {
                    System.Console.WriteLine(result.Errors.ToString());
                }
            }
        }
Esempio n. 20
0
        public async Task <IActionResult> DeleteConfirmed(string id)
        {
            if (ModelState.IsValid)
            {
                if (id == null)
                {
                    return(NotFound());
                }
                var user = await _userManager.FindByIdAsync(id);

                var logins = await _userManager.GetLoginsAsync(user);

                var rolesForUser = await _userManager.GetRolesAsync(user);

                var userPosts = _context.Post.Where(p => p.Owner == user).ToList();
                userPosts.ForEach(p => _context.Post.Remove(p));

                var userComments = _context.Comments.Where(c => c.Owner == user).ToList();
                userComments.ForEach(c => _context.Comments.Remove(c));

                using (var transaction = _context.Database.BeginTransaction())
                {
                    IdentityResult result = IdentityResult.Success;
                    foreach (var login in logins)
                    {
                        result = await _userManager.RemoveLoginAsync(user, login.LoginProvider, login.ProviderKey);

                        if (result != IdentityResult.Success)
                        {
                            break;
                        }
                    }
                    if (result == IdentityResult.Success)
                    {
                        foreach (var item in rolesForUser)
                        {
                            result = await _userManager.RemoveFromRoleAsync(user, item);

                            if (result != IdentityResult.Success)
                            {
                                break;
                            }
                        }
                    }
                    if (result == IdentityResult.Success)
                    {
                        result = await _userManager.DeleteAsync(user);

                        if (result == IdentityResult.Success)
                        {
                            transaction.Commit();
                        }
                    }
                }

                return(RedirectToAction("Index"));
            }
            else
            {
                return(View());
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Method to perform login of the external customer
        /// </summary>
        /// <param name="returnUrl"></param>
        /// <param name="remoteError"></param>
        /// <returns></returns>
        public async Task <DefaultServiceResponse> ExternalLoginCallBack(string returnUrl = null, string remoteError = null)
        {
            var loginCallBackResult = new DefaultServiceResponse {
                ActionName = "Index", ControllerName = "HomePage", ResponseData = null, StatusCode = StatusCodesEnum.Ok, ValidationErrors = new List <string>()
            };

            if (remoteError == null)
            {
                var accountDetailsFromProvider = await SignInManager.GetExternalLoginInfoAsync();

                #region Check, that data is provided

                if (accountDetailsFromProvider != null)
                {
                    // Search for the customer in our db

                    var accountData = await UserManager.FindByEmailAsync(accountDetailsFromProvider.Principal.FindFirstValue(ClaimTypes.Email));

                    #region New account for our DB

                    if (accountData == null) // new account
                    {
                        var serviceUser = new ServiceUser
                        {
                            Email    = accountDetailsFromProvider.Principal.FindFirstValue(ClaimTypes.Email),
                            UserName = accountDetailsFromProvider.Principal.FindFirstValue(ClaimTypes.GivenName)
                        };

                        var userResponse = await UserManager.CreateAsync(serviceUser);

                        #region Customer created without any error --> send him email to verify email and add password ( or not )

                        if (userResponse.Succeeded)
                        {
                            if (CheckIfWeHaveRole("User"))
                            {
                                await UserManager.AddToRoleAsync(serviceUser, "User");
                            }
                            else
                            {
                                await RoleManager.CreateAsync(new IdentityRole { Id = new Guid().ToString(), Name = "User", NormalizedName = "USER" });

                                await UserManager.AddToRoleAsync(serviceUser, "User");
                            }

                            var claims = CustomerContext.UserClaims.Select(x => x).ToList();

                            var newClaimId = claims.Count > 0 ? claims.Last().Id + 1 : 1;

                            CustomerContext.UserClaims.Add(new IdentityUserClaim <string> {
                                Id = newClaimId, ClaimType = "UploadPhoto", ClaimValue = "true", UserId = serviceUser.Id
                            });

                            await CustomerContext.SaveChangesAsync();

                            await UserManager.AddLoginAsync(serviceUser, accountDetailsFromProvider); // Creates point in AspNetUserLogins

                            var token = await UserManager.GenerateEmailConfirmationTokenAsync(serviceUser);

                            var emailUrlConfirmation = UrlHelper.Action("ConfirmEmail", "Account", new { Token = token, UserId = serviceUser.Id }, Context.HttpContext.Request.Scheme);

                            await SendEmailService.SendEmail(new ServiceEmail
                            {
                                FromEmail     = "*****@*****.**",
                                FromName      = "Yevhen",
                                ToEmail       = serviceUser.Email,
                                ToName        = serviceUser.UserName,
                                EmailSubject  = "Thank you for register!!!",
                                EmailHtmlText = $"<strong>Hello, {serviceUser.UserName}! Thank you for registering, please confirm your email using this link : {emailUrlConfirmation}</strong>",
                                EmailText     = $"Hello there! Thank you for registering, please confirm your email using this link : {emailUrlConfirmation}",
                            });

                            loginCallBackResult.ActionName = "ConfirmPartnerRegister";

                            loginCallBackResult.ControllerName = "Registration";

                            loginCallBackResult.ResponseData = serviceUser.UserName;

                            loginCallBackResult.StatusCode = StatusCodesEnum.RedirectNeeded;

                            return(loginCallBackResult);
                        }

                        #endregion

                        else
                        {
                            loginCallBackResult.ValidationErrors.Add(DefaultResponseMessages.ExternalLoginFailed);

                            loginCallBackResult.StatusCode = StatusCodesEnum.BadDataProvided;

                            return(loginCallBackResult);
                        }
                    }

                    #endregion

                    else
                    {
                        #region Customer already has account on our db, but email is not confirmed

                        if (!accountData.EmailConfirmed)
                        {
                            var loginsData = await UserManager.GetLoginsAsync(accountData);

                            if (loginsData == null)
                            {
                                await UserManager.AddLoginAsync(accountData, accountDetailsFromProvider);
                            }
                            var token = await UserManager.GenerateEmailConfirmationTokenAsync(accountData);

                            var emailUrlConfirmation = UrlHelper.Action("ConfirmEmail", "Account", new { Token = token, UserId = accountData.Id }, Context.HttpContext.Request.Scheme);

                            await SendEmailService.SendEmail(new ServiceEmail
                            {
                                FromEmail     = "*****@*****.**",
                                FromName      = "Yevhen",
                                ToEmail       = accountData.Email,
                                ToName        = accountData.UserName,
                                EmailSubject  = "Thank you for register!!!",
                                EmailHtmlText = $"<strong>Hello, {accountData.UserName}! Thank you for registering, please confirm your email using this link : {emailUrlConfirmation}</strong>",
                                EmailText     = $"Hello there! Thank you for registering, please confirm your email using this link : {emailUrlConfirmation}",
                            });

                            loginCallBackResult.StatusCode = StatusCodesEnum.RedirectNeeded;

                            loginCallBackResult.ResponseData = accountData.UserName;

                            loginCallBackResult.ActionName = "ConfirmPartnerRegister";

                            loginCallBackResult.ControllerName = "Registration";

                            return(loginCallBackResult);
                        }

                        #endregion

                        #region Email is confirmed but we need to check, that customer has row in ASPNETUSERLOGINS

                        else
                        {
                            var loginReponse = await SignInManager.ExternalLoginSignInAsync(accountDetailsFromProvider.LoginProvider, accountDetailsFromProvider.ProviderKey, false);

                            if (loginReponse.Succeeded)
                            {
                                loginCallBackResult.StatusCode = StatusCodesEnum.Ok;
                            }
                            else
                            {
                                await UserManager.AddLoginAsync(accountData, accountDetailsFromProvider);

                                await SignInManager.SignInAsync(accountData, false);
                            }

                            loginCallBackResult.ActionName = "Index";

                            loginCallBackResult.ControllerName = "HomePage";

                            return(loginCallBackResult);
                        }

                        #endregion
                    }
                }

                #endregion

                #region No data provided from external provider

                else
                {
                    loginCallBackResult.ValidationErrors.Add(DefaultResponseMessages.ExternalLoginFailed);

                    loginCallBackResult.StatusCode = StatusCodesEnum.BadDataProvided;

                    return(loginCallBackResult);
                }

                #endregion
            }

            #region Error from external provider

            else
            {
                loginCallBackResult.ValidationErrors.Add(DefaultResponseMessages.ExternalLoginFailed);

                loginCallBackResult.StatusCode = StatusCodesEnum.RedirectNeeded;

                loginCallBackResult.ActionName = "Login";

                loginCallBackResult.ControllerName = "Account";

                return(loginCallBackResult);
            }

            #endregion
        }
Esempio n. 22
0
 public Task <IList <UserLoginInfo> > GetLoginsAsync(T user)
 {
     return(u.GetLoginsAsync(user));
 }
Esempio n. 23
0
        public Task <IList <UserLoginInfo> > GetLoginsAsync(IUser user)
        {
            Guard.NotNull(user, nameof(user));

            return(userManager.GetLoginsAsync((IdentityUser)user.Identity));
        }
Esempio n. 24
0
        public async Task <IActionResult> Delete([FromRoute] string id)
        {
            if (ModelState.IsValid)
            {
                if (id == null)
                {
                    return(BadRequest(new { invalid = "User is not found" }));
                }

                var user = await _userManager.FindByIdAsync(id);

                var rolesForUser = await _userManager.GetRolesAsync(user);

                var logins = await _userManager.GetLoginsAsync(user);

                string path = user.AvatarUrl;


                using (var transaction = _context.Database.BeginTransaction())
                {
                    IdentityResult result = IdentityResult.Success;

                    foreach (var login in logins)
                    {
                        result = await _userManager.RemoveLoginAsync(user, login.LoginProvider, login.ProviderKey);

                        if (result != IdentityResult.Success)
                        {
                            break;
                        }
                    }

                    if (result == IdentityResult.Success)
                    {
                        foreach (var item in rolesForUser)
                        {
                            result = await _userManager.RemoveFromRoleAsync(user, item);

                            if (result != IdentityResult.Success)
                            {
                                break;
                            }
                        }
                    }

                    if (result == IdentityResult.Success)
                    {
                        result = await _userManager.DeleteAsync(user);

                        //only commit if user and all his logins/roles have been deleted
                        if (result == IdentityResult.Success)
                        {
                            transaction.Commit();
                            _fileService.DeleteImage(path);
                        }
                    }
                }

                return(Ok(user.Id));
            }

            return(Ok());
        }
Esempio n. 25
0
        public async Task <IActionResult> Update(ProfileModel profile)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    AppUser user = await userManager.FindByNameAsync(User.Identity.Name);

                    bool isSameEmail = user.Email.Equals(profile.Email, StringComparison.OrdinalIgnoreCase);
                    user.FirstName   = profile.FirstName;
                    user.LastName    = profile.LastName;
                    user.Address     = profile.Address;
                    user.Email       = profile.Email;
                    user.BirthDate   = profile.BirthDate;
                    user.Gender      = profile.Gender;
                    user.PhoneNumber = profile.Tel;
                    string avatar;
                    if (profile.Photo != null && !string.IsNullOrWhiteSpace(profile.Photo.FileName)) // if photo is change then copy
                    {
                        string filePath = user.UserName + "." + profile.Photo.FileName.Substring(profile.Photo.FileName.LastIndexOf(".") + 1);
                        avatar = await blobService.UploadFile("avatars", filePath, profile.Photo);
                    }
                    else // if not, preserve old one
                    {
                        avatar = user.Avatar;
                    }
                    if (avatar != null)
                    {
                        user.Avatar = avatar;
                        IdentityResult result = null;
                        if (!isSameEmail) // remove external login when email changed
                        {
                            IEnumerable <UserLoginInfo> loginInfos = await userManager.GetLoginsAsync(user);

                            foreach (UserLoginInfo info in loginInfos)
                            {
                                result = await userManager.RemoveLoginAsync(user, info.LoginProvider, info.ProviderKey);
                            }
                        }
                        if (result == null || result.Succeeded)
                        {
                            result = await userManager.UpdateAsync(user);

                            if (result.Succeeded)
                            {
                                return(RedirectToAction(nameof(Index)));
                            }
                        }
                        AddErrorFromResult(result);
                    }
                    else
                    {
                        ModelState.AddModelError("", "Can't upload avatar");
                    }
                }
                return(RedirectToAction(nameof(Edit)));
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                throw;
            }
        }
Esempio n. 26
0
        public async Task <string> ExternalSignIn(HttpContext httpContext)
        {
            try
            {
                // read external identity from the temporary cookie
                var result = await httpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);

                if (result?.Succeeded != true)
                {
                    return($"~/externalauth/error/{ErrorEnum.ExternalAuthError}");
                }

                // retrieve claims of the external user
                var externalUser = result.Principal;
                if (externalUser == null)
                {
                    return($"~/externalauth/error/{ErrorEnum.ExternalAuthError}");
                }

                // retrieve claims of the external user
                var claims = externalUser.Claims.ToList();

                // try to determine the unique id of the external user - the most common claim type for that are the sub claim and the NameIdentifier
                // depending on the external provider, some other claim type might be used
                var userIdClaim = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject);
                if (userIdClaim == null)
                {
                    userIdClaim = claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
                }
                if (userIdClaim == null)
                {
                    return($"~/externalauth/error/{ErrorEnum.ExternalUnknownUserId}");
                }

                var externalUserId   = userIdClaim.Value;
                var externalProvider = userIdClaim.Issuer;

                //Quick check to sign in
                var externalSignInResult = await _signInManager.ExternalLoginSignInAsync(externalProvider, externalUserId, true);

                if (externalSignInResult.Succeeded)
                {
                    //// delete temporary cookie used during external authentication
                    await httpContext.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);

                    return("~/externalauth/success");
                }

                //If external login/signin failed
                var userNameClaim  = claims.FirstOrDefault(x => x.Type == ClaimTypes.Name);
                var userEmailClaim = claims.FirstOrDefault(x => x.Type == ClaimTypes.Email);

                //get the user by Email (we are forcing it to be unique)
                var user = await _userManager.FindByEmailAsync(userEmailClaim.Value);

                if (user != null)
                {
                    //check if the login for this provider exists
                    var userLogins = await _userManager.GetLoginsAsync(user);

                    if (userLogins.Any(ul => ul.LoginProvider == externalProvider && ul.ProviderKey == externalUserId))
                    {
                        //something went wrong, it should get logged in

                        // If lock out activated and the max. amounts of attempts is reached.
                        if (externalSignInResult.IsLockedOut)
                        {
                            _logger.LogInformation("User Locked out: {0}", user.UserName);
                            return($"~/externalauth/error/{ErrorEnum.UserLockedOut}");
                        }

                        // If your email is not confirmed but you require it in the settings for login.
                        if (externalSignInResult.IsNotAllowed)
                        {
                            _logger.LogInformation("User not allowed to log in: {0}", user.UserName);
                            return($"~/externalauth/error/{ErrorEnum.UserIsNotAllowed}");
                        }

                        return($"~/externalauth/error/{ErrorEnum.Unknown}");
                    }
                }
                else // create new user first
                {
                    var requireConfirmEmail = Convert.ToBoolean(_configuration["SpotToSpotMuzik:RequireConfirmedEmail"] ?? "false");
                    try
                    {
                        user = await _accountManager.RegisterNewUserAsync(userNameClaim.Value, userEmailClaim.Value, null, requireConfirmEmail);
                    }
                    catch (DomainException ex)
                    {
                        _logger.LogError("External login Failed: {0}, {1}", ex.Description, ex.Message);
                        return($"~/externalauth/error/{ErrorEnum.UserCreationFailed}/{ex.Description}");
                    }
                    catch (Exception ex)
                    {
                        _logger.LogInformation("External login Failed: " + ex.Message);
                        return($"~/externalauth/error/{ErrorEnum.UserCreationFailed}");
                    }

                    if (requireConfirmEmail)
                    {
                        //ToDo: suggestion - after confirm, the sign in might fail, user needs to relogin using the external provider
                        //Consider removing this constrain and auto-confirm the email - it has been confirmed by the 3rd party auth provider already
                        return($"~/externalauth/confirm");
                    }
                }


                //All if fine, this user (email) did not try to log in before using this external provider
                //Add external login info
                var addExternalLoginResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(externalProvider, externalUserId, userNameClaim.Value));

                if (addExternalLoginResult.Succeeded == false)
                {
                    return($"~/externalauth/error/{ErrorEnum.CannotAddExternalLogin}");
                }

                //Try to sign in again
                externalSignInResult = await _signInManager.ExternalLoginSignInAsync(externalProvider, externalUserId, true);

                if (externalSignInResult.Succeeded)
                {
                    //// delete temporary cookie used during external authentication
                    await httpContext.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);

                    return("~/externalauth/success");
                }
                else
                {
                    //Something went terrible wrong, user exists, external login info added
                    // If lock out activated and the max. amounts of attempts is reached.
                    if (externalSignInResult.IsLockedOut)
                    {
                        _logger.LogInformation("User Locked out: {0}", user.UserName);
                        return($"~/externalauth/error/{ErrorEnum.UserLockedOut}");
                    }

                    // If your email is not confirmed but you require it in the settings for login.
                    if (externalSignInResult.IsNotAllowed)
                    {
                        _logger.LogInformation("User not allowed to log in: {0}", user.UserName);
                        return($"~/externalauth/error/{ErrorEnum.UserIsNotAllowed}");
                    }

                    return($"~/externalauth/error/{ErrorEnum.Unknown}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogInformation("External login Failed: " + ex.Message);
                return($"~/externalauth/error/{ErrorEnum.Unknown}");
            }
        }
        public virtual async Task <IList <ApplicationUserLoginInfo> > GetLoginsAsync(int userId)
        {
            var list = await _userManager.GetLoginsAsync(userId).ConfigureAwait(false);

            return(list.ToApplicationUserLoginInfoList());
        }
Esempio n. 28
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. 29
0
        public async Task <IActionResult> EditUser(UserViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            //Get some info on the user
            var au = await _userManager.Users.Where(u => u.Id == model.Id).FirstOrDefaultAsync();

            // The user should not be null!
            if (au != null)
            {
                var author = await _qpa.ProcessAsync(new GetAuthorByAppUserIdQuery { Id = au.Id });

                if (author != null)
                {
                    au.Author = author;
                }

                // Make the user an author if it's not already, no author fields can be "updated right now"
                if (model.IsAuthor)
                {
                    if (string.IsNullOrEmpty(model.FirstName) || string.IsNullOrEmpty(model.LastName))
                    {
                        ModelState.AddModelError("", "Author requires both first and last name to be set.");
                        return(View(model));
                    }
                    if (au.Author == null)
                    {
                        var aac = new AddAuthorCommand
                        {
                            ApplicatoinUserId = model.Id,
                            FirstName         = model.FirstName,
                            LastName          = model.LastName
                        };

                        var aacResult = await _cp.ProcessAsync(aac);

                        if (aacResult.Succeeded)
                        {
                            _logger.LogInformation("Set user {0} to be author {1} {2}", au.Email, model.FirstName, model.LastName);

                            await _userManager.AddToRoleAsync(au, "Authors");

                            _logger.LogInformation("Added role Authors to user {0}", au.Email);

                            au.Author = aacResult.Command.Author;
                        }
                        else
                        {
                            _logger.LogWarning("Unable to make user {0} author {1} {2}", au.Email, model.FirstName, model.LastName);

                            ModelState.AddModelError("",
                                                     "Error making the user an author, perhaps first and last name are not unique in database");
                            return(View(model));
                        }
                    }
                    else
                    {
                        var uac = new UpdateAuthorCommand
                        {
                            Id           = au.Author.Id,
                            NewFirstName = model.FirstName,
                            NewLastName  = model.LastName
                        };

                        var uacResult = await _cp.ProcessAsync(uac);

                        if (uacResult.Succeeded)
                        {
                            _logger.LogInformation("Updated author {0} {1} to {2} {3}", au.Author.FirstName, au.Author.LastName,
                                                   model.FirstName, model.LastName);
                            // do nothing
                        }
                        else
                        {
                            _logger.LogWarning("Unable to update author {0} {1} to {2} {3}", au.Author.FirstName, au.Author.LastName,
                                               model.FirstName, model.LastName);

                            ModelState.AddModelError("",
                                                     "Error updating the author, perhaps the first and last name are not unique in the database");
                            return(View(model));
                        }
                    }
                }
                // It's not an author
                else
                {
                    if (au.Author != null)
                    {
                        // Remove it from authors if it was and remove the role

                        var sauidnfa = new SetAppUserIdNullForAuthorCommand
                        {
                            Id = au.Id
                        };

                        var sauidnfaResult = await _cp.ProcessAsync(sauidnfa);

                        if (sauidnfaResult.Succeeded)
                        {
                            _logger.LogInformation("Set AppUserId Null for Author {0} {1} with id {3}", au.Author.FirstName,
                                                   au.Author.LastName, au.Author.Id);

                            await _userManager.RemoveFromRoleAsync(au, "Authors");
                        }
                        else
                        {
                            // Error
                            _logger.LogWarning("Unable to set AppUserId {0} to Null for Author {1} ", au.Id, au.Author.Id);

                            ModelState.AddModelError("", "Error removing author from user!");
                            return(View(model));
                        }
                    }
                }
                // Logic goes like this:
                // Validate user with new email and username
                // If it has an external login, just change the stuff and update the user assuming it passes validation
                au.Email    = model.Email;
                au.UserName = model.UserName;

                var validUser = await _userValidator.ValidateAsync(_userManager, au);

                if (!validUser.Succeeded)
                {
                    foreach (var error in validUser.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                        return(View(model));
                    }
                }

                var logins = await _userManager.GetLoginsAsync(au);

                if (logins.Count != 0)
                {
                    var result = await _userManager.UpdateAsync(au);

                    if (au == await _userManager.GetUserAsync(User))
                    {
                        await _signInManager.RefreshSignInAsync(au);
                    }

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("Updated user {0} to new email {1} username {2}", au.Id, model.Email,
                                               model.UserName);

                        return(RedirectToAction("ManageUsers"));
                    }
                    _logger.LogWarning("Unable to update user {0} to new email {1} username {2}", au.Id, model.Email,
                                       model.UserName);

                    // something happened, throw an exception or something
                    // for now just return to the edit page
                }
                else
                {
                    // If the password string isn't empty and they want to change the password
                    if (!string.IsNullOrEmpty(model.Password) && model.ChangePassword)
                    {
                        var validPassword = await _passwordValidator.ValidateAsync(_userManager, au, model.Password);

                        if (validPassword.Succeeded)
                        {
                            au.PasswordHash = _passwordHasher.HashPassword(au, model.Password);
                            var securityStampUpdate = await _userManager.UpdateSecurityStampAsync(au);

                            if (securityStampUpdate.Succeeded)
                            {
                                _logger.LogInformation("Updated security stamp for user {0}", au.Id);

                                var result = await _userManager.UpdateAsync(au);

                                if (result.Succeeded)
                                {
                                    _logger.LogInformation("Updated user and password for user {0}", au.Id);

                                    if (au == await _userManager.GetUserAsync(User))
                                    {
                                        await _signInManager.RefreshSignInAsync(au);
                                    }
                                    return(RedirectToAction("ManageUsers"));
                                }
                                _logger.LogWarning("Unable to update user and password for user {0}", au.Id);

                                foreach (var error in result.Errors)
                                {
                                    ModelState.AddModelError("", error.Description);
                                }
                            }
                            else
                            {
                                _logger.LogWarning("Unexpected error updating security stamp for user {0}", au.Id);

                                foreach (var error in securityStampUpdate.Errors)
                                {
                                    ModelState.AddModelError("", error.Description);
                                }
                            }
                        }
                        else
                        {
                            foreach (var error in validPassword.Errors)
                            {
                                ModelState.AddModelError("", error.Description);
                            }
                        }
                    }
                    // Can't change the password and have no password there!
                    else if (string.IsNullOrEmpty(model.Password) && model.ChangePassword)
                    {
                        ModelState.AddModelError("", "Password can't be empty");
                    }
                    // Just update the user and don't change the password
                    else
                    {
                        var result = await _userManager.UpdateAsync(au);

                        if (result.Succeeded)
                        {
                            _logger.LogInformation("Updated user {0}", au.Id);

                            if (au == await _userManager.GetUserAsync(User))
                            {
                                await _signInManager.RefreshSignInAsync(au);
                            }
                            return(RedirectToAction("ManageUsers"));
                        }
                        _logger.LogWarning("Unable to update user {0}", au.Id);

                        foreach (var error in result.Errors)
                        {
                            ModelState.AddModelError("", error.Description);
                        }
                    }
                }
                // end if au == null
            }
            else
            {
                _logger.LogWarning("Edit user called with non-existant id {0}", model.Id);
            }
            return(View(model));
        }
Esempio n. 30
0
        public void AddRemoveUserLogin()
        {
            using (UserStore <IdentityUser> store = new UserStore <IdentityUser>())
            {
                using (UserManager <IdentityUser> manager = new UserManager <IdentityUser>(store))
                {
                    var user = GenTestUser();
                    WriteLineObject <IdentityUser>(user);
                    var taskUser = manager.CreateAsync(user, DefaultUserPassword);
                    taskUser.Wait();
                    Assert.IsTrue(taskUser.Result.Succeeded, string.Concat(taskUser.Result.Errors));

                    var loginInfo        = GenGoogleLogin();
                    var userAddLoginTask = manager.AddLoginAsync(user.Id, loginInfo);
                    userAddLoginTask.Wait();
                    Assert.IsTrue(userAddLoginTask.Result.Succeeded, string.Concat(userAddLoginTask.Result.Errors));

                    var loginGetTask = manager.GetLoginsAsync(user.Id);
                    loginGetTask.Wait();
                    Assert.IsTrue(loginGetTask.Result
                                  .Any(log => log.LoginProvider == loginInfo.LoginProvider
                                       & log.ProviderKey == loginInfo.ProviderKey), "LoginInfo not found: GetLoginsAsync");

                    var loginGetTask2 = manager.FindAsync(loginGetTask.Result.First());
                    loginGetTask2.Wait();
                    Assert.IsNotNull(loginGetTask2.Result, "LoginInfo not found: FindAsync");

                    var userRemoveLoginTaskNeg1 = manager.RemoveLoginAsync(user.Id, new UserLoginInfo(string.Empty, loginInfo.ProviderKey));
                    userRemoveLoginTaskNeg1.Wait();

                    var userRemoveLoginTaskNeg2 = manager.RemoveLoginAsync(user.Id, new UserLoginInfo(loginInfo.LoginProvider, string.Empty));
                    userRemoveLoginTaskNeg2.Wait();

                    var userRemoveLoginTask = manager.RemoveLoginAsync(user.Id, loginInfo);
                    userRemoveLoginTask.Wait();
                    Assert.IsTrue(userRemoveLoginTask.Result.Succeeded, string.Concat(userRemoveLoginTask.Result.Errors));
                    var loginGetTask3 = manager.GetLoginsAsync(user.Id);
                    loginGetTask3.Wait();
                    Assert.IsTrue(!loginGetTask3.Result.Any(), "LoginInfo not removed");

                    //Negative cases

                    var loginFindNeg = manager.FindAsync(new UserLoginInfo("asdfasdf", "http://4343443dfaksjfaf"));
                    loginFindNeg.Wait();
                    Assert.IsNull(loginFindNeg.Result, "LoginInfo found: FindAsync");

                    try
                    {
                        var t1 = store.AddLoginAsync(null, loginInfo);
                        t1.Wait();
                    }
                    catch (AggregateException aggex) {
                        aggex.ValidateAggregateException <ArgumentNullException>();
                    }

                    try
                    {
                        var t2 = store.AddLoginAsync(user, null);
                        t2.Wait();
                    }
                    catch (AggregateException aggex)
                    {
                        aggex.ValidateAggregateException <ArgumentNullException>();
                    }
                    try
                    {
                        var t3 = store.RemoveLoginAsync(null, loginInfo);
                        t3.Wait();
                    }
                    catch (ArgumentException) { }

                    try
                    {
                        var t4 = store.RemoveLoginAsync(user, null);
                        t4.Wait();
                    }
                    catch (ArgumentException) { }

                    try
                    {
                        var t5 = store.FindAsync(null);
                        t5.Wait();
                    }
                    catch (AggregateException aggex) {
                        aggex.ValidateAggregateException <ArgumentNullException>();
                    }
                    try
                    {
                        var t6 = store.GetLoginsAsync(null);
                        t6.Wait();
                    }
                    catch (ArgumentException) { }
                }
            }
        }
        public async Task <IActionResult> OnPostAsync()
        {
            User user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }

            _logger.LogInformation("User with ID '{UserId}' asked for their personal data.", _userManager.GetUserId(User));

            // Only include personal data for download
            var personalData = new Dictionary <string, object>();
            IEnumerable <PropertyInfo> personalDataProps = typeof(User).GetProperties().Where(
                prop => Attribute.IsDefined(prop, typeof(PersonalDataAttribute)));

            // Include methods that return personal data
            IEnumerable <MethodInfo> personalDataMethods = typeof(User).GetMethods().Where(x => Attribute.IsDefined(x, typeof(PersonalDataAttribute)));

            foreach (PropertyInfo p in personalDataProps)
            {
                personalData.Add(p.Name, p.GetValue(user));
            }

            foreach (MethodInfo method in personalDataMethods)
            {
                // Assert that the method returns a task and that it returns an IDictionary
                if (!typeof(Task).IsAssignableFrom(method.ReturnType) ||
                    !method.ReturnType.IsGenericType ||
                    !typeof(IDictionary).IsAssignableFrom(method.ReturnType.GetGenericArguments()[0]))
                {
                    throw new InvalidOperationException("Personal data method must have a return type that inherits from Task<System.Collections.IDictionary>");
                }

                // Resolve dependencies of the method
                var dependencies = new List <object>();
                foreach (ParameterInfo param in method.GetParameters())
                {
                    dependencies.Add(_serviceProvider.GetService(param.ParameterType));
                }

                // Get the dictionary and add it to the personal data
                var task = method.Invoke(user, dependencies.ToArray()) as Task;
                await task.ConfigureAwait(false);

                var result = task.GetType().GetProperty(nameof(Task <object> .Result)).GetValue(task) as IDictionary;
                foreach (var key in result.Keys.Cast <object>())
                {
                    personalData.Add(key.ToString(), result[key]);
                }
            }

            if ((await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList().Any())
            {
                IList <UserLoginInfo> logins = await _userManager.GetLoginsAsync(user);

                foreach (UserLoginInfo l in logins)
                {
                    personalData.Add($"{l.LoginProvider} external login provider key", l.ProviderKey);
                }
            }

            Response.Headers.Add("Content-Disposition", "attachment; filename=PersonalData.json");
            return(new FileContentResult(
                       JsonSerializer.SerializeToUtf8Bytes(personalData, new JsonSerializerOptions {
                WriteIndented = true
            }),
                       "application/json"
                       ));
        }
        public async Task <IActionResult> GetLogins()
        {
            var user = await GetCurrentUserAsync();

            return(Ok(await _userManager.GetLoginsAsync(user)));
        }
Esempio n. 33
0
        public async Task <IActionResult> Index(ManageMessageId?message = null)
        {
            // Optionaly use the region info to get default currency for user

            ViewData["StatusMessage"] =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
                : message == ManageMessageId.Error ? "An error has occurred."
                : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
                : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
                : "";

            var user = await GetCurrentUserAsync();

            if (user == null)
            {
                return(View("Error"));
            }

            // Give the user a default currency if they dont have
            if (string.IsNullOrEmpty(user.Currency))
            {
                var requestCulture = Request.HttpContext.Features.Get <IRequestCultureFeature>();
                var culture        = requestCulture.RequestCulture.Culture;
                user.Currency = _currencyService.GetCurrent().Name;
            }

            var currencies = _currencyService.GetAll();

            var model = new IndexViewModel
            {
                HasPassword       = await _userManager.HasPasswordAsync(user),
                PhoneNumber       = await _userManager.GetPhoneNumberAsync(user),
                TwoFactor         = await _userManager.GetTwoFactorEnabledAsync(user),
                Logins            = await _userManager.GetLoginsAsync(user),
                BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user),
                FullName          = user.FullName,
                Culture           = user.Culture,
                Currency          = user.Currency,
                CurrencyList      = new List <SelectListItem>(currencies.Select(c =>
                                                                                new SelectListItem
                {
                    Text = c.Symbol,
                    Value = c.CultureName
                })),
                CultureList = new List <SelectListItem>
                {
                    new SelectListItem
                    {
                        Value = "en-US",
                        Text  = "English"
                    },
                    new SelectListItem
                    {
                        Value = "zh-CN",
                        Text  = "Chinese"
                    }
                }
            };

            return(View(model));
        }