private async Task <DeliverableResponse> CreateUser(string[] args)
        {
            if (args.Length != 5)
            {
                await Out.WriteLineAsync("Please provide 5 arguments, name, username, email, password and groups. For more information see `help`");

                return(DeliverableResponse.Continue);
            }

            var name       = args[0];
            var username   = args[1];
            var email      = args[2];
            var password   = args[3];
            var groupNames = args[4];

            var identity = BackOfficeIdentityUser.CreateNew(username, email, GlobalSettings.DefaultUILanguage);

            identity.Name = name;

            var result = await userManager.CreateAsync(identity);

            if (!result.Succeeded)
            {
                await Out.WriteLineAsync("Error saving the user:"******"\t{error}");
                }

                return(DeliverableResponse.FinishedWithError);
            }

            result = await userManager.AddPasswordAsync(identity.Id, password);

            if (!result.Succeeded)
            {
                await Out.WriteLineAsync("Error saving the user password:"******"\t{error}");
                }

                return(DeliverableResponse.FinishedWithError);
            }

            var user   = userService.GetByEmail(email);
            var groups = userService.GetUserGroupsByAlias(groupNames.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));

            foreach (var group in groups)
            {
                var rg = new ReadOnlyUserGroup(group.Id, group.Name, group.Icon, group.StartContentId, group.StartMediaId, group.Alias, group.AllowedSections, group.Permissions);
                user.AddGroup(rg);
            }
            user.IsApproved = true;
            userService.Save(user);

            return(DeliverableResponse.Continue);
        }
示例#2
0
        public async Task Can_Persist_Is_Approved()
        {
            var userStore = GetUserStore();
            var user      = new BackOfficeIdentityUser(GlobalSettings, 1, new List <IReadOnlyUserGroup>())
            {
                Name     = "Test",
                Email    = "*****@*****.**",
                UserName = "******"
            };
            IdentityResult createResult = await userStore.CreateAsync(user);

            Assert.IsTrue(createResult.Succeeded);
            Assert.IsFalse(user.IsApproved);

            // update
            user.IsApproved = true;
            var saveResult = await userStore.UpdateAsync(user);

            Assert.IsTrue(saveResult.Succeeded);
            Assert.IsTrue(user.IsApproved);

            // get get
            user = await userStore.FindByIdAsync(user.Id);

            Assert.IsTrue(user.IsApproved);
        }
示例#3
0
        public async Task <IActionResult> ExternalLinkLoginCallback()
        {
            BackOfficeIdentityUser user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                // ... this should really not happen
                TempData[ViewDataExtensions.TokenExternalSignInError] = new[] { "Local user does not exist" };
                return(RedirectToLocal(Url.Action(nameof(Default), this.GetControllerName())));
            }

            ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user));

            if (info == null)
            {
                //Add error and redirect for it to be displayed
                TempData[ViewDataExtensions.TokenExternalSignInError] = new[] { "An error occurred, could not get external login info" };
                return(RedirectToLocal(Url.Action(nameof(Default), this.GetControllerName())));
            }

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

            if (addLoginResult.Succeeded)
            {
                // Update any authentication tokens if succeeded
                await _signInManager.UpdateExternalAuthenticationTokensAsync(info);

                return(RedirectToLocal(Url.Action(nameof(Default), this.GetControllerName())));
            }

            //Add errors and redirect for it to be displayed
            TempData[ViewDataExtensions.TokenExternalSignInError] = addLoginResult.Errors;
            return(RedirectToLocal(Url.Action(nameof(Default), this.GetControllerName())));
        }
        public async Task <BackOfficeUserPasswordCheckerResult> CheckPasswordAsync(BackOfficeIdentityUser user, string password)
        {
            var hash = passwordHasher.HashPassword(password);
            var passwordIsCorrect = user.PasswordHash.Equals(hash, StringComparison.InvariantCulture);

            if (!passwordIsCorrect)
            {
                return(BackOfficeUserPasswordCheckerResult.InvalidCredentials);
            }

            if (LatchesShouldBeChecked)
            {
                var latches = latchOperationSvc.GetLatches(LatchOperationType.Login);
                if (!latches.Any())
                {
                    return(BackOfficeUserPasswordCheckerResult.ValidCredentials);
                }

                var latchesToApply = GetLatchesApplyingToUser(latches, user.Id);
                var loginIsLocked  = AnyLatchIsClosed(latchesToApply);
                if (loginIsLocked)
                {
                    return(BackOfficeUserPasswordCheckerResult.InvalidCredentials);
                }
            }

            return(BackOfficeUserPasswordCheckerResult.ValidCredentials);
        }
    /// <inheritdoc />
    protected override async Task <IdentityUserLogin <string> > FindUserLoginAsync(string userId, string loginProvider, string providerKey, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();
        ThrowIfDisposed();

        BackOfficeIdentityUser user = await FindUserAsync(userId, cancellationToken);

        if (user is null || user.Id is null)
        {
            return(null !);
        }

        IList <UserLoginInfo> logins = await GetLoginsAsync(user, cancellationToken);

        UserLoginInfo?found =
            logins.FirstOrDefault(x => x.ProviderKey == providerKey && x.LoginProvider == loginProvider);

        if (found == null)
        {
            return(null !);
        }

        return(new IdentityUserLogin <string>
        {
            LoginProvider = found.LoginProvider,
            ProviderKey = found.ProviderKey,
            ProviderDisplayName = found.ProviderDisplayName, // TODO: We don't store this value so it will be null
            UserId = user.Id,
        });
    }
        public async Task <IHttpActionResult> CreateUser()
        {
            var owinContext = TryGetOwinContext().Result;
            var userManager = owinContext.GetBackOfficeUserManager();

            var email = "*****@*****.**";
            var user  = BackOfficeIdentityUser.CreateNew(email, email, "en-US");

            user.Name = "Paulo Samson";

            await userManager.CreateAsync(user);

            var password = userManager.GeneratePassword();
            await userManager.AddPasswordAsync(user.Id, password);

            //Save group
            var u = Services.UserService.GetByUsername(email);

            u.IsApproved = true;
            var group = Services.UserService.GetUserGroupByAlias("admin") as IReadOnlyUserGroup;

            u.AddGroup(group);
            Services.UserService.Save(u);

            return(Ok(password));
        }
    /// <inheritdoc />
    public override async Task SetPasswordHashAsync(BackOfficeIdentityUser user, string passwordHash, CancellationToken cancellationToken = default)
    {
        await base.SetPasswordHashAsync(user, passwordHash, cancellationToken);

        // Clear this so that it's reset at the repository level
        user.PasswordConfig = null;
    }
示例#8
0
        /// <summary>
        /// Create a new user account.
        /// </summary>
        /// <param name="user">Back office user account</param>
        /// <param name="userGroups">Groups to assign to user</param>
        /// <param name="culture">Culture for user</param>
        /// <param name="email">Email address for user account</param>
        /// <param name="name">Name for user account</param>
        /// <returns></returns>
        protected async virtual Task <IdentityResult> NewCreateUser(BackOfficeIdentityUser user, string[] userGroups, string culture, string email = null, string name = null)
        {
            // Mandate that parameters must be specified.
            //Mandate.ParameterNotNull<BackOfficeIdentityUser>(user, "user");
            //Mandate.ParameterNotNullOrEmpty<string>(userGroups, "userGroups");
            //Mandate.ParameterNotNull<string>(culture, "culture");

            // Assign name to user if not already specified. Use name if specified, otherwise use email address.
            user.Name = user.Name ?? name ?? user.UserName;

            // Assign email to user if not already specified.
            user.Email = user.Email ?? email;
            if (String.IsNullOrWhiteSpace(user.Email))
            {
                throw new ArgumentNullException("email");
            }

            // Assign user to specified groups.
            var groups = Services.UserService.GetUserGroupsByAlias(userGroups);

            foreach (var userGroup in groups)
            {
                user.AddRole(userGroup.Alias);
            }

            // Create user account.
            var userCreationResults = await UserManager.CreateAsync(user);

            return(userCreationResults);
        }
    public void DefineMaps(IUmbracoMapper mapper)
    {
        mapper.Define <IUser, BackOfficeIdentityUser>(
            (source, context) =>
        {
            var target = new BackOfficeIdentityUser(_globalSettings, source.Id, source.Groups);
            target.DisableChangeTracking();
            return(target);
        },
            (source, target, context) =>
        {
            Map(source, target);
            target.ResetDirtyProperties(true);
            target.EnableChangeTracking();
        });

        mapper.Define <IMember, MemberIdentityUser>(
            (source, context) =>
        {
            var target = new MemberIdentityUser(source.Id);
            target.DisableChangeTracking();
            return(target);
        },
            (source, target, context) =>
        {
            Map(source, target);
            target.ResetDirtyProperties(true);
            target.EnableChangeTracking();
        });
    }
            /// <summary>
            /// This will update the current request IPrincipal to be correct and re-create the auth ticket
            /// </summary>
            private async Task ReSync(IUser user, ActionExecutingContext actionContext)
            {
                BackOfficeIdentityUser backOfficeIdentityUser = _umbracoMapper.Map <BackOfficeIdentityUser>(user);
                await _backOfficeSignInManager.SignInAsync(backOfficeIdentityUser, isPersistent : true);

                // flag that we've made changes
                _requestCache.Set(nameof(CheckIfUserTicketDataIsStaleFilter), true);
            }
示例#11
0
        /// <summary>
        /// Returns whether two factor authentication is enabled for the user
        /// </summary>
        /// <param name="user"/>
        /// <returns/>
        public override Task <bool> GetTwoFactorEnabledAsync(BackOfficeIdentityUser user)
        {
            var database = ApplicationContext.Current.DatabaseContext.Database;
            var result   = database.Fetch <Models.TwoFactor>("WHERE [userId] = @userId AND [confirmed] = 1", new { userId = user.Id });

            //if there's records for this user then we need to show the two factor screen
            return(Task.FromResult(result.Any()));
        }
        public void Customize(IFixture fixture)
        {
            fixture.Customize <BackOfficeIdentityUser>(
                u => u.FromFactory <string, string, string>(
                    (a, b, c) => BackOfficeIdentityUser.CreateNew(new GlobalSettings(), a, b, c)));

            fixture
            .Customize(new ConstructorCustomization(typeof(UsersController), new GreedyConstructorQuery()))
            .Customize(new ConstructorCustomization(typeof(InstallController), new GreedyConstructorQuery()))
            .Customize(new ConstructorCustomization(typeof(PreviewController), new GreedyConstructorQuery()))
            .Customize(new ConstructorCustomization(typeof(MemberController), new GreedyConstructorQuery()))
            .Customize(new ConstructorCustomization(typeof(BackOfficeController), new GreedyConstructorQuery()))
            .Customize(new ConstructorCustomization(typeof(BackOfficeUserManager), new GreedyConstructorQuery()))
            .Customize(new ConstructorCustomization(typeof(MemberManager), new GreedyConstructorQuery()))
            .Customize(new ConstructorCustomization(typeof(DatabaseSchemaCreatorFactory), new GreedyConstructorQuery()));

            // When requesting an IUserStore ensure we actually uses a IUserLockoutStore
            fixture.Customize <IUserStore <BackOfficeIdentityUser> >(cc => cc.FromFactory(Mock.Of <IUserLockoutStore <BackOfficeIdentityUser> >));

            fixture.Customize <ConfigConnectionString>(
                u => u.FromFactory <string, string, string>(
                    (a, b, c) => new ConfigConnectionString(a, b, c)));

            fixture.Customize <IUmbracoVersion>(
                u => u.FromFactory(
                    () => new UmbracoVersion()));

            fixture.Customize <HostingSettings>(x =>
                                                x.With(settings => settings.ApplicationVirtualPath, string.Empty));

            fixture.Customize <BackOfficeAreaRoutes>(u => u.FromFactory(
                                                         () => new BackOfficeAreaRoutes(
                                                             Options.Create(new GlobalSettings()),
                                                             Mock.Of <IHostingEnvironment>(x => x.ToAbsolute(It.IsAny <string>()) == "/umbraco" && x.ApplicationVirtualPath == string.Empty),
                                                             Mock.Of <IRuntimeState>(x => x.Level == RuntimeLevel.Run),
                                                             new UmbracoApiControllerTypeCollection(Enumerable.Empty <Type>))));

            fixture.Customize <PreviewRoutes>(u => u.FromFactory(
                                                  () => new PreviewRoutes(
                                                      Options.Create(new GlobalSettings()),
                                                      Mock.Of <IHostingEnvironment>(x => x.ToAbsolute(It.IsAny <string>()) == "/umbraco" && x.ApplicationVirtualPath == string.Empty),
                                                      Mock.Of <IRuntimeState>(x => x.Level == RuntimeLevel.Run))));

            var configConnectionString = new ConfigConnectionString(
                "ss",
                "Data Source=(localdb)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Umbraco.mdf;Integrated Security=True");

            fixture.Customize <ConfigConnectionString>(x => x.FromFactory(() => configConnectionString));

            var httpContextAccessor = new HttpContextAccessor {
                HttpContext = new DefaultHttpContext()
            };

            fixture.Customize <HttpContext>(x => x.FromFactory(() => httpContextAccessor.HttpContext));
            fixture.Customize <IHttpContextAccessor>(x => x.FromFactory(() => httpContextAccessor));

            fixture.Customize <WebRoutingSettings>(x => x.With(settings => settings.UmbracoApplicationUrl, "http://localhost:5000"));
        }
        /// <summary>
        /// Returns whether two factor authentication is enabled for the user
        /// </summary>
        /// <param name="user"/>
        /// <returns/>
        /// <remarks>
        /// This Demo does not persist any data, so this method for this Demo always returns true.
        /// If you want to have 2FA configured per user, you will need to store that information somewhere.
        /// See the notes above in the SetTwoFactorEnabledAsync method.
        /// </remarks>
        public override Task <bool> GetTwoFactorEnabledAsync(BackOfficeIdentityUser user)
        {
            return(Task.FromResult(true));

            //If you persisted this data somewhere then you could either look it up now, or you could
            //explicitly implement all IUserStore "Find*" methods, call their base implementation and then lookup
            //your persisted value and assign to the TwoFactorEnabled property of the resulting BackOfficeIdentityUser user.
            //return Task.FromResult(user.TwoFactorEnabled);
        }
示例#14
0
    /// <inheritdoc />
    public override Task <IdentityResult> UpdateAsync(
        BackOfficeIdentityUser user,
        CancellationToken cancellationToken = default)
    {
        cancellationToken.ThrowIfCancellationRequested();
        ThrowIfDisposed();
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        if (!int.TryParse(user.Id, NumberStyles.Integer, CultureInfo.InvariantCulture, out var asInt))
        {
            throw new InvalidOperationException("The user id must be an integer to work with the Umbraco");
        }

        using (ICoreScope scope = _scopeProvider.CreateCoreScope())
        {
            IUser?found = _userService.GetUserById(asInt);
            if (found != null)
            {
                // we have to remember whether Logins property is dirty, since the UpdateMemberProperties will reset it.
                var isLoginsPropertyDirty = user.IsPropertyDirty(nameof(BackOfficeIdentityUser.Logins));
                var isTokensPropertyDirty = user.IsPropertyDirty(nameof(BackOfficeIdentityUser.LoginTokens));

                if (UpdateMemberProperties(found, user))
                {
                    _userService.Save(found);
                }

                if (isLoginsPropertyDirty)
                {
                    _externalLoginService.Save(
                        found.Key,
                        user.Logins.Select(x => new ExternalLogin(
                                               x.LoginProvider,
                                               x.ProviderKey,
                                               x.UserData)));
                }

                if (isTokensPropertyDirty)
                {
                    _externalLoginService.Save(
                        found.Key,
                        user.LoginTokens.Select(x => new ExternalLoginToken(
                                                    x.LoginProvider,
                                                    x.Name,
                                                    x.Value)));
                }
            }

            scope.Complete();
        }

        return(Task.FromResult(IdentityResult.Success));
    }
示例#15
0
    /// <inheritdoc />
    public override async Task <bool> GetTwoFactorEnabledAsync(
        BackOfficeIdentityUser user,
        CancellationToken cancellationToken = default)
    {
        if (!int.TryParse(user.Id, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intUserId))
        {
            return(await base.GetTwoFactorEnabledAsync(user, cancellationToken));
        }

        return(await _twoFactorLoginService.IsTwoFactorEnabledAsync(user.Key));
    }
示例#16
0
        /// <summary>
        /// Returns whether two factor authentication is enabled for the user
        /// </summary>
        /// <param name="user"/>
        /// <returns/>
        public override Task <bool> GetTwoFactorEnabledAsync(BackOfficeIdentityUser user)
        {
            using (var scope = Current.ScopeProvider.CreateScope(autoComplete: true))
            {
                var result = scope.Database.Fetch <Models.TwoFactor>("WHERE [userId] = @userId AND [confirmed] = 1",
                                                                     new { userId = user.Id });

                //if there's records for this user then we need to show the two factor screen
                return(Task.FromResult(result.Any()));
            }
        }
示例#17
0
    public async Task <ActionResult> CompleteInstall()
    {
        await _runtime.RestartAsync();

        BackOfficeIdentityUser identityUser =
            await _backOfficeUserManager.FindByIdAsync(Constants.Security.SuperUserIdAsString);

        _backOfficeSignInManager.SignInAsync(identityUser, false);

        return(NoContent());
    }
示例#18
0
    /// <inheritdoc />
    protected override async Task <IdentityUserRole <string> > FindUserRoleAsync(string userId, string roleId, CancellationToken cancellationToken)
    {
        BackOfficeIdentityUser user = await FindUserAsync(userId, cancellationToken);

        if (user == null)
        {
            return(null !);
        }

        IdentityUserRole <string>?found = user.Roles.FirstOrDefault(x => x.RoleId.InvariantEquals(roleId));

        return(found !);
    }
                public void Customize(IFixture fixture)
                {
                    fixture.Customize <BackOfficeIdentityUser>(
                        u => u.FromFactory <string, string, string>(
                            (a, b, c) => BackOfficeIdentityUser.CreateNew(new GlobalSettings(), a, b, c)));
                    fixture
                    .Customize(new ConstructorCustomization(typeof(UsersController), new GreedyConstructorQuery()))
                    .Customize(new ConstructorCustomization(typeof(InstallController), new GreedyConstructorQuery()))
                    .Customize(new ConstructorCustomization(typeof(PreviewController), new GreedyConstructorQuery()))
                    .Customize(new ConstructorCustomization(typeof(MemberController), new GreedyConstructorQuery()))
                    .Customize(new ConstructorCustomization(typeof(BackOfficeController), new GreedyConstructorQuery()))
                    .Customize(new ConstructorCustomization(typeof(BackOfficeUserManager), new GreedyConstructorQuery()))
                    .Customize(new ConstructorCustomization(typeof(MemberManager), new GreedyConstructorQuery()));

                    fixture.Customize(new AutoMoqCustomization());

                    // When requesting an IUserStore ensure we actually uses a IUserLockoutStore
                    fixture.Customize <IUserStore <BackOfficeIdentityUser> >(cc => cc.FromFactory(() => Mock.Of <IUserLockoutStore <BackOfficeIdentityUser> >()));

                    fixture.Customize <ConfigConnectionString>(
                        u => u.FromFactory <string, string, string>(
                            (a, b, c) => new ConfigConnectionString(a, b, c)));

                    fixture.Customize <IUmbracoVersion>(
                        u => u.FromFactory(
                            () => new UmbracoVersion()));

                    fixture.Customize <BackOfficeAreaRoutes>(u => u.FromFactory(
                                                                 () => new BackOfficeAreaRoutes(
                                                                     Options.Create(new GlobalSettings()),
                                                                     Mock.Of <IHostingEnvironment>(x => x.ToAbsolute(It.IsAny <string>()) == "/umbraco" && x.ApplicationVirtualPath == string.Empty),
                                                                     Mock.Of <IRuntimeState>(x => x.Level == RuntimeLevel.Run),
                                                                     new UmbracoApiControllerTypeCollection(() => Enumerable.Empty <Type>()))));

                    fixture.Customize <PreviewRoutes>(u => u.FromFactory(
                                                          () => new PreviewRoutes(
                                                              Options.Create(new GlobalSettings()),
                                                              Mock.Of <IHostingEnvironment>(x => x.ToAbsolute(It.IsAny <string>()) == "/umbraco" && x.ApplicationVirtualPath == string.Empty),
                                                              Mock.Of <IRuntimeState>(x => x.Level == RuntimeLevel.Run))));

                    var connectionStrings = new ConnectionStrings();

                    fixture.Customize <ConnectionStrings>(x => x.FromFactory(() => connectionStrings));

                    var httpContextAccessor = new HttpContextAccessor {
                        HttpContext = new DefaultHttpContext()
                    };

                    fixture.Customize <HttpContext>(x => x.FromFactory(() => httpContextAccessor.HttpContext));
                    fixture.Customize <IHttpContextAccessor>(x => x.FromFactory(() => httpContextAccessor));
                }
        /// <summary>
        /// Determines if a username and password are valid using the BackofficeMembershipProvider.
        /// </summary>
        /// <param name="user">User to test.</param>
        /// <param name="password">Password to test.</param>
        /// <returns>Object showing if user credentials are valid or not.</returns>
        public Task <BackOfficeUserPasswordCheckerResult> CheckPasswordAsync(BackOfficeIdentityUser user, string password)
        {
            // Access provider.
            if (Membership.Providers["BackofficeMembershipProvider"] == null)
            {
                throw new InvalidOperationException("Provider 'BackofficeMembershipProvider' is not defined.");
            }
            var adProvider = Membership.Providers["BackofficeMembershipProvider"];

            // Check the user's password.
            var validUser = adProvider.ValidateUser(user.UserName, password) ? Task.FromResult(BackOfficeUserPasswordCheckerResult.ValidCredentials) : Task.FromResult(BackOfficeUserPasswordCheckerResult.InvalidCredentials);

            return(validUser);
        }
示例#21
0
    /// <inheritdoc />
    public override Task <IList <UserLoginInfo> > GetLoginsAsync(
        BackOfficeIdentityUser user,
        CancellationToken cancellationToken = default)
    {
        cancellationToken.ThrowIfCancellationRequested();
        ThrowIfDisposed();
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        return(Task.FromResult((IList <UserLoginInfo>)user.Logins
                               .Select(l => new UserLoginInfo(l.LoginProvider, l.ProviderKey, l.LoginProvider)).ToList()));
    }
示例#22
0
        /// <summary>
        /// Called when a new user should be created.
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public override async Task <IdentityResult> CreateAsync(BackOfficeIdentityUser user)
        {
            // autolinked users have this role assigned before they are saved
            var isAutolinked = user.Roles.Any(r => r.RoleId == "autolinked");

            var result = await base.CreateAsync(user);

            if (isAutolinked)
            {
                // do custom stuff when a new user is auto linked
            }

            return(result);
        }
        /// <summary>
        /// Determines if a username and password are valid using the BackofficeMembershipProvider.
        /// </summary>
        /// <param name="user">User to test.</param>
        /// <param name="password">Password to test.</param>
        /// <returns>Object showing if user credentials are valid or not.</returns>
        public Task<BackOfficeUserPasswordCheckerResult> CheckPasswordAsync(BackOfficeIdentityUser user, string password)
        {
            // Access provider.
            if (Membership.Providers["BackofficeMembershipProvider"] == null)
            {
                throw new InvalidOperationException("Provider 'BackofficeMembershipProvider' is not defined.");
            }
            var adProvider = Membership.Providers["BackofficeMembershipProvider"];

            // Check the user's password.
            var validUser = adProvider.ValidateUser(user.UserName, password) ? Task.FromResult(BackOfficeUserPasswordCheckerResult.ValidCredentials) : Task.FromResult(BackOfficeUserPasswordCheckerResult.InvalidCredentials);

            return validUser;
        }
        /// <summary>
        /// Determines if a username and password are valid using the BackofficeMembershipProvider.
        /// </summary>
        /// <param name="user">User to test.</param>
        /// <param name="password">Password to test.</param>
        /// <returns>Object showing if user credentials are valid or not.</returns>
        public async Task <BackOfficeUserPasswordCheckerResult> CheckPasswordAsync(BackOfficeIdentityUser user, string password)
        {
            // Check the password against Active Directory.
            var validPassword = MembershipProvider.ValidateUser(user.UserName, password);

            // Automatically create a user account if needed.
            if (validPassword && !user.HasIdentity && CreateAccounts)
            {
                // Create user.
                var userResult = await CreateUserForLogin(user);
            }

            return(validPassword ? BackOfficeUserPasswordCheckerResult.ValidCredentials : BackOfficeUserPasswordCheckerResult.InvalidCredentials);
        }
示例#25
0
        public async override Task<bool> CheckPasswordAsync(BackOfficeIdentityUser user, string password)
        {
            var groupManager = GroupBasedUserManagerResolver.Current.Manager;

            // First check the user against Active Directory
            bool validLogin = groupManager.CheckPassword(user.UserName, password);

            if (!validLogin)
            {
                // Now check the Umbraco Backoffice user manager
                validLogin = await base.CheckPasswordAsync(user, password);
            }

            return validLogin;
        }
示例#26
0
        public Task <BackOfficeUserPasswordCheckerResult> CheckPasswordAsync(BackOfficeIdentityUser user, string password)
        {
            bool isValid;

            using (var pc = new PrincipalContext(ContextType.Domain, ActiveDirectoryDomain))
            {
                isValid = pc.ValidateCredentials(user.UserName, password);
            }

            var result = isValid
                ? BackOfficeUserPasswordCheckerResult.ValidCredentials
                : BackOfficeUserPasswordCheckerResult.InvalidCredentials;

            return(Task.FromResult(result));
        }
示例#27
0
    /// <summary>
    ///     Overridden to support Umbraco's own data storage requirements
    /// </summary>
    /// <remarks>
    ///     The base class's implementation of this calls into FindTokenAsync, RemoveUserTokenAsync and AddUserTokenAsync, both
    ///     methods will only work with ORMs that are change
    ///     tracking ORMs like EFCore.
    /// </remarks>
    /// <inheritdoc />
    public override Task <string?> GetTokenAsync(BackOfficeIdentityUser user, string loginProvider, string name, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();
        ThrowIfDisposed();

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

        IIdentityUserToken?token = user.LoginTokens.FirstOrDefault(x =>
                                                                   x.LoginProvider.InvariantEquals(loginProvider) && x.Name.InvariantEquals(name));

        return(Task.FromResult(token?.Value));
    }
示例#28
0
        public async override Task <bool> CheckPasswordAsync(BackOfficeIdentityUser user, string password)
        {
            var groupManager = ManagerFactory.GetManager();

            // First check the user against Active Directory
            bool validLogin = groupManager.CheckPassword(user.UserName, password);

            if (!validLogin)
            {
                // Now check the Umbraco Backoffice user manager
                validLogin = await base.CheckPasswordAsync(user, password);
            }

            return(validLogin);
        }
        public void PostUnlockUsers_When_User_Lockout_Update_Fails_Expect_Failure_Response(
            [Frozen] IBackOfficeUserManager backOfficeUserManager,
            UsersController sut,
            BackOfficeIdentityUser user,
            int[] userIds,
            string expectedMessage)
        {
            Mock.Get(backOfficeUserManager)
            .Setup(x => x.FindByIdAsync(It.IsAny <string>()))
            .ReturnsAsync(user);

            var result = sut.PostUnlockUsers(userIds).Result as ObjectResult;

            Assert.AreEqual(StatusCodes.Status400BadRequest, result.StatusCode);
        }
        /// <summary>
        /// Returns whether two factor authentication is enabled for the user
        /// </summary>
        /// <param name="user"/>
        /// <returns/>
        /// <remarks>
        /// This Demo does not persist any data, so this method for this Demo always returns true.
        /// If you want to have 2FA configured per user, you will need to store that information somewhere.
        /// See the notes above in the SetTwoFactorEnabledAsync method.
        /// </remarks>
        public override Task <bool> GetTwoFactorEnabledAsync(BackOfficeIdentityUser user)
        {
            var db      = new FortressDatabase();
            var details = db.GetUserDetails(user.Id);

            if (details != null && details.IsValidated)
            {
                return(Task.FromResult(true));
            }
            return(Task.FromResult(false));

            //If you persisted this data somewhere then you could either look it up now, or you could
            //explicitly implement all IUserStore "Find*" methods, call their base implementation and then lookup
            //your persisted value and assign to the TwoFactorEnabled property of the resulting BackOfficeIdentityUser user.
            //return Task.FromResult(user.TwoFactorEnabled);
        }
    public async Task <Dictionary <string, string> > GetCurrentUserLinkedLogins()
    {
        BackOfficeIdentityUser identityUser = await _backOfficeUserManager.FindByIdAsync(_backofficeSecurityAccessor
                                                                                         .BackOfficeSecurity?.GetUserId().ResultOr(0).ToString(CultureInfo.InvariantCulture));

        // deduplicate in case there are duplicates (there shouldn't be now since we have a unique constraint on the external logins
        // but there didn't used to be)
        var result = new Dictionary <string, string>();

        foreach (IIdentityUserLogin l in identityUser.Logins)
        {
            result[l.LoginProvider] = l.ProviderKey;
        }

        return(result);
    }
示例#32
0
    public TestAuthHandler(
        IOptionsMonitor <AuthenticationSchemeOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock,
        IBackOfficeSignInManager backOfficeSignInManager,
        IUserService userService,
        IUmbracoMapper umbracoMapper)
        : base(options, logger, encoder, clock)
    {
        _backOfficeSignInManager = backOfficeSignInManager;

        var user = userService.GetUserById(Constants.Security.SuperUserId);

        _fakeUser = umbracoMapper.Map <IUser, BackOfficeIdentityUser>(user);
        _fakeUser.SecurityStamp = "Needed";
    }