redirect to the first allowed section if we don't have a location

This commit is contained in:
Mads Rasmussen
2024-05-27 13:40:26 +02:00
parent d0420ec2a1
commit fd70593bde

View File

@@ -7,6 +7,8 @@ import { firstValueFrom } from '@umbraco-cms/backoffice/external/rxjs';
import { UMB_AUTH_CONTEXT } from '@umbraco-cms/backoffice/auth';
import { UmbObjectState } from '@umbraco-cms/backoffice/observable-api';
import { umbLocalizationRegistry } from '@umbraco-cms/backoffice/localization';
import { umbExtensionsRegistry } from '@umbraco-cms/backoffice/extension-registry';
import { UMB_SECTION_PATH_PATTERN } from '@umbraco-cms/backoffice/section';
export class UmbCurrentUserContext extends UmbContextBase<UmbCurrentUserContext> {
#currentUser = new UmbObjectState<UmbCurrentUserModel | undefined>(undefined);
@@ -43,6 +45,7 @@ export class UmbCurrentUserContext extends UmbContextBase<UmbCurrentUserContext>
if (asObservable) {
this.observe(asObservable(), (currentUser) => {
this.#currentUser?.setValue(currentUser);
this.#redirectToFirstAllowedSectionIfNeeded();
});
}
}
@@ -75,6 +78,36 @@ export class UmbCurrentUserContext extends UmbContextBase<UmbCurrentUserContext>
}
});
}
async #redirectToFirstAllowedSectionIfNeeded() {
const url = new URL(window.location.href);
if (url.pathname === '/') {
const sectionManifest = await this.#firstAllowedSection();
if (!sectionManifest) return;
const fallbackSectionPath = UMB_SECTION_PATH_PATTERN.generateLocal({
sectionName: sectionManifest.meta.pathname,
});
history.pushState(null, '', fallbackSectionPath);
}
}
async #firstAllowedSection() {
const currentUser = this.#currentUser.getValue();
if (!currentUser) return;
/* TODO: this solution is not bullet proof as we still rely on the "correct" section to be registered at this point in time so we can get the path.
It probably would have been better if we used the section alias instead as the path.
Then we would have it available at all times and it also ensured a unique path. */
const sections = await this.observe(
umbExtensionsRegistry.byTypeAndAliases('section', currentUser.allowedSections),
() => {},
).asPromise();
return sections[0];
}
}
export default UmbCurrentUserContext;