diff --git a/backend/src/Designer/Controllers/AnsattPortenController.cs b/backend/src/Designer/Controllers/AnsattPortenController.cs new file mode 100644 index 00000000000..95f7f73dee7 --- /dev/null +++ b/backend/src/Designer/Controllers/AnsattPortenController.cs @@ -0,0 +1,45 @@ +using System.Threading.Tasks; +using Altinn.Studio.Designer.Constants; +using Altinn.Studio.Designer.Models.Dto; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.FeatureManagement.Mvc; + +namespace Altinn.Studio.Designer.Controllers; + +[FeatureGate(StudioFeatureFlags.AnsattPorten)] +[Route("designer/api/[controller]")] +[ApiController] +public class AnsattPortenController : ControllerBase +{ + [Authorize(AnsattPortenConstants.AnsattportenAuthorizationPolicy)] + [HttpGet("login")] + public async Task Login([FromQuery(Name = "redirect_to")] string redirectTo) + { + await Task.CompletedTask; + if (!Url.IsLocalUrl(redirectTo)) + { + return Forbid(); + } + + return LocalRedirect(redirectTo); + } + + [AllowAnonymous] + [HttpGet("auth-status")] + public async Task AuthStatus() + { + await Task.CompletedTask; + var authenticateResult = + await HttpContext.AuthenticateAsync(AnsattPortenConstants.AnsattportenAuthenticationScheme); + + var authStatus = new AuthStatus + { + IsLoggedIn = authenticateResult.Succeeded + }; + + return Ok(authStatus); + } + +} diff --git a/backend/src/Designer/Controllers/AppScopesController.cs b/backend/src/Designer/Controllers/AppScopesController.cs index b17e6fa8421..2fbc5a3be16 100644 --- a/backend/src/Designer/Controllers/AppScopesController.cs +++ b/backend/src/Designer/Controllers/AppScopesController.cs @@ -18,7 +18,6 @@ namespace Altinn.Studio.Designer.Controllers; [ApiController] [FeatureGate(StudioFeatureFlags.AnsattPorten)] [Route("designer/api/{org}/{app:regex(^(?!datamodels$)[[a-z]][[a-z0-9-]]{{1,28}}[[a-z0-9]]$)}/app-scopes")] - public class AppScopesController(IMaskinPortenHttpClient maskinPortenHttpClient, IAppScopesService appScopesService) : ControllerBase { @@ -28,7 +27,7 @@ public async Task GetScopesFromMaskinPorten(string org, string ap { var scopes = await maskinPortenHttpClient.GetAvailableScopes(cancellationToken); - var reponse = new AppScopesResponse() + var response = new AppScopesResponse() { Scopes = scopes.Select(x => new MaskinPortenScopeDto() { @@ -37,10 +36,9 @@ public async Task GetScopesFromMaskinPorten(string org, string ap }).ToHashSet() }; - return Ok(reponse); + return Ok(response); } - [Authorize] [HttpPut] public async Task UpsertAppScopes(string org, string app, [FromBody] AppScopesUpsertRequest appScopesUpsertRequest, @@ -56,7 +54,6 @@ public async Task UpsertAppScopes(string org, string app, [FromBody] AppScopesUp await appScopesService.UpsertScopesAsync(AltinnRepoEditingContext.FromOrgRepoDeveloper(org, app, developer), scopes, cancellationToken); } - [Authorize] [HttpGet] public async Task GetAppScopes(string org, string app, CancellationToken cancellationToken) @@ -74,5 +71,4 @@ public async Task GetAppScopes(string org, string app, Cancellati return Ok(reponse); } - } diff --git a/backend/src/Designer/Infrastructure/AnsattPorten/AnsattPortenExtensions.cs b/backend/src/Designer/Infrastructure/AnsattPorten/AnsattPortenExtensions.cs index 8cfdfcc3881..073da38601c 100644 --- a/backend/src/Designer/Infrastructure/AnsattPorten/AnsattPortenExtensions.cs +++ b/backend/src/Designer/Infrastructure/AnsattPorten/AnsattPortenExtensions.cs @@ -75,8 +75,7 @@ private static IServiceCollection AddAnsattPortenAuthentication(this IServiceCol options.Events.OnRedirectToIdentityProvider = context => { - if (!context.Request.Path.StartsWithSegments("/designer/api") || - !context.Request.Path.Value!.Contains("/maskinporten")) + if (!context.Request.Path.StartsWithSegments("/designer/api/ansattporten/login")) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; context.HandleResponse(); diff --git a/backend/src/Designer/Infrastructure/AuthenticationConfiguration.cs b/backend/src/Designer/Infrastructure/AuthenticationConfiguration.cs index 7c0230e33ce..b85b469c457 100644 --- a/backend/src/Designer/Infrastructure/AuthenticationConfiguration.cs +++ b/backend/src/Designer/Infrastructure/AuthenticationConfiguration.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Threading.Tasks; using Altinn.Studio.Designer.Configuration; +using Altinn.Studio.Designer.Constants; using Altinn.Studio.Designer.Helpers; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; @@ -38,6 +39,7 @@ private static IServiceCollection AddGiteaOidcAuthentication(this IServiceCollec IConfiguration configuration, IWebHostEnvironment env) { var oidcSettings = FetchOidcSettingsFromConfiguration(configuration, env); + bool ansattPortenFeatureFlag = configuration.GetSection($"FeatureManagement:{StudioFeatureFlags.AnsattPorten}").Get(); services .AddAuthentication(options => @@ -49,7 +51,8 @@ private static IServiceCollection AddGiteaOidcAuthentication(this IServiceCollec { options.Cookie.HttpOnly = true; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; - options.Cookie.SameSite = SameSiteMode.Strict; + options.Cookie.SameSite = ansattPortenFeatureFlag ? SameSiteMode.Lax : SameSiteMode.Strict; + options.Cookie.IsEssential = true; options.ExpireTimeSpan = TimeSpan.FromMinutes(oidcSettings.CookieExpiryTimeInMinutes); diff --git a/backend/src/Designer/Models/Dto/AuthStatus.cs b/backend/src/Designer/Models/Dto/AuthStatus.cs new file mode 100644 index 00000000000..3ff49e8f39b --- /dev/null +++ b/backend/src/Designer/Models/Dto/AuthStatus.cs @@ -0,0 +1,6 @@ +namespace Altinn.Studio.Designer.Models.Dto; + +public class AuthStatus +{ + public bool IsLoggedIn { get; set; } +} diff --git a/backend/tests/Designer.Tests/Controllers/AnsattPortenController/AuthStatusTests.cs b/backend/tests/Designer.Tests/Controllers/AnsattPortenController/AuthStatusTests.cs new file mode 100644 index 00000000000..59958508764 --- /dev/null +++ b/backend/tests/Designer.Tests/Controllers/AnsattPortenController/AuthStatusTests.cs @@ -0,0 +1,82 @@ +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using Altinn.Studio.Designer.Models.Dto; +using Designer.Tests.Controllers.AnsattPortenController.Base; +using Designer.Tests.Controllers.ApiTests; +using FluentAssertions; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.Mvc.Testing.Handlers; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace Designer.Tests.Controllers.AnsattPortenController; + +public class AuthStatusTest : AnsattPortenControllerTestsBase, IClassFixture> +{ + private static string VersionPrefix => "/designer/api/ansattporten/auth-status"; + + // Setup unauthenticated http client + protected override HttpClient GetTestClient() + { + string configPath = GetConfigPath(); + IConfiguration configuration = new ConfigurationBuilder() + .AddJsonFile(configPath, false, false) + .AddJsonStream(GenerateJsonOverrideConfig()) + .AddEnvironmentVariables() + .Build(); + + return Factory.WithWebHostBuilder(builder => + { + builder.UseConfiguration(configuration); + builder.ConfigureAppConfiguration((_, conf) => + { + conf.AddJsonFile(configPath); + conf.AddJsonStream(GenerateJsonOverrideConfig()); + }); + builder.ConfigureTestServices(ConfigureTestServices); + builder.ConfigureServices(ConfigureTestServicesForSpecificTest); + }).CreateDefaultClient(new CookieContainerHandler()); + } + + public AuthStatusTest(WebApplicationFactory factory) : base(factory) + { + } + + [Fact] + public async Task AuthStatus_Should_ReturnFalse_IfNotAuthenticated() + { + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, VersionPrefix); + + using var response = await HttpClient.SendAsync(httpRequestMessage); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + AuthStatus authStatus = await response.Content.ReadAsAsync(); + authStatus.IsLoggedIn.Should().BeFalse(); + } + + [Fact] + public async Task AuthStatus_Should_ReturnTrue_IfAuthenticated() + { + // Setup test authentication + ConfigureTestServicesForSpecificTest = services => + { + services.AddAuthentication(defaultScheme: TestAuthConstants.TestAuthenticationScheme) + .AddScheme( + TestAuthConstants.TestAuthenticationScheme, options => { }); + services.AddTransient(); + }; + + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, VersionPrefix); + + using var response = await HttpClient.SendAsync(httpRequestMessage); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + AuthStatus authStatus = await response.Content.ReadAsAsync(); + authStatus.IsLoggedIn.Should().BeTrue(); + } +} diff --git a/backend/tests/Designer.Tests/Controllers/AnsattPortenController/Base/AnsattPortenControllerTestsBase.cs b/backend/tests/Designer.Tests/Controllers/AnsattPortenController/Base/AnsattPortenControllerTestsBase.cs new file mode 100644 index 00000000000..c305064be10 --- /dev/null +++ b/backend/tests/Designer.Tests/Controllers/AnsattPortenController/Base/AnsattPortenControllerTestsBase.cs @@ -0,0 +1,24 @@ +using Altinn.Studio.Designer.Constants; +using Designer.Tests.Controllers.ApiTests; +using Microsoft.AspNetCore.Mvc.Testing; + +namespace Designer.Tests.Controllers.AnsattPortenController.Base; + +public class AnsattPortenControllerTestsBase : DesignerEndpointsTestsBase where TControllerTest : class +{ + public AnsattPortenControllerTestsBase(WebApplicationFactory factory) : base(factory) + { + JsonConfigOverrides.Add( + $$""" + { + "FeatureManagement": { + "{{StudioFeatureFlags.AnsattPorten}}": true + }, + "AnsattPortenLoginSettings": { + "ClientId": "non-empty-for-testing", + "ClientSecret": "non-empty-for-testing" + } + } + """); + } +} diff --git a/backend/tests/Designer.Tests/Controllers/AnsattPortenController/LoginTests.cs b/backend/tests/Designer.Tests/Controllers/AnsattPortenController/LoginTests.cs new file mode 100644 index 00000000000..daa6b2f9339 --- /dev/null +++ b/backend/tests/Designer.Tests/Controllers/AnsattPortenController/LoginTests.cs @@ -0,0 +1,37 @@ +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using Altinn.Studio.Designer.Constants; +using Designer.Tests.Controllers.AnsattPortenController.Base; +using Designer.Tests.Controllers.ApiTests; +using Microsoft.AspNetCore.Mvc.Testing; +using Xunit; + +namespace Designer.Tests.Controllers.AnsattPortenController; + +public class LoginTests : AnsattPortenControllerTestsBase, IClassFixture> +{ + private static string VersionPrefix => "/designer/api/ansattporten/login"; + + public LoginTests(WebApplicationFactory factory) : base(factory) + { + } + + [Theory] + [InlineData("/test", HttpStatusCode.Redirect)] + [InlineData("/", HttpStatusCode.Redirect)] + [InlineData("https://docs.altinn.studio/", HttpStatusCode.Forbidden)] + public async Task LoginShouldReturn_ExpectedCode(string redirectTo, HttpStatusCode expectedStatusCode) + { + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get + , $"{VersionPrefix}?redirect_to={redirectTo}"); + + using var response = await HttpClient.SendAsync(httpRequestMessage); + Assert.Equal(expectedStatusCode, response.StatusCode); + + if (expectedStatusCode == HttpStatusCode.Redirect) + { + Assert.Equal(redirectTo, response.Headers.Location?.ToString()); + } + } +} diff --git a/backend/tests/Designer.Tests/Controllers/ApiTests/ApiTestsBase.cs b/backend/tests/Designer.Tests/Controllers/ApiTests/ApiTestsBase.cs index 109345e8f49..7b03c34ac9e 100644 --- a/backend/tests/Designer.Tests/Controllers/ApiTests/ApiTestsBase.cs +++ b/backend/tests/Designer.Tests/Controllers/ApiTests/ApiTestsBase.cs @@ -44,7 +44,7 @@ protected HttpClient HttpClient /// protected abstract void ConfigureTestServices(IServiceCollection services); - protected Action ConfigureTestForSpecificTest { get; set; } = delegate { }; + protected Action ConfigureTestServicesForSpecificTest { get; set; } = delegate { }; /// /// Location of the assembly of the executing unit test. @@ -97,7 +97,7 @@ protected virtual HttpClient GetTestClient() TestAuthConstants.TestAuthenticationScheme, options => { }); services.AddTransient(); }); - builder.ConfigureServices(ConfigureTestForSpecificTest); + builder.ConfigureServices(ConfigureTestServicesForSpecificTest); }).CreateDefaultClient(new ApiTestsAuthAndCookieDelegatingHandler(), new CookieContainerHandler()); } @@ -152,7 +152,7 @@ private void InitializeJsonConfigOverrides() } - private Stream GenerateJsonOverrideConfig() + protected Stream GenerateJsonOverrideConfig() { var overrideJson = Newtonsoft.Json.Linq.JObject.Parse(JsonConfigOverrides.First()); if (JsonConfigOverrides.Count > 1) diff --git a/backend/tests/Designer.Tests/Controllers/AppScopesController/Base/AppScopesControllerTestsBase.cs b/backend/tests/Designer.Tests/Controllers/AppScopesController/Base/AppScopesControllerTestsBase.cs index 4e6e468ae06..0398fe48dea 100644 --- a/backend/tests/Designer.Tests/Controllers/AppScopesController/Base/AppScopesControllerTestsBase.cs +++ b/backend/tests/Designer.Tests/Controllers/AppScopesController/Base/AppScopesControllerTestsBase.cs @@ -1,3 +1,4 @@ +using Altinn.Studio.Designer.Constants; using Designer.Tests.Controllers.ApiTests; using Designer.Tests.Fixtures; using Microsoft.AspNetCore.Mvc.Testing; @@ -9,16 +10,17 @@ public class AppScopesControllerTestsBase : DbDesignerEndpoints { public AppScopesControllerTestsBase(WebApplicationFactory factory, DesignerDbFixture designerDbFixture) : base(factory, designerDbFixture) { - JsonConfigOverrides.Add($@" - {{ - ""FeatureManagement"": {{ - ""AnsattPorten"": true - }}, - ""AnsattPortenLoginSettings"": {{ - ""ClientId"": ""non-empty-for-testing"", - ""ClientSecret"": ""non-empty-for-testing"" - }} - }} - "); + JsonConfigOverrides.Add( + $$""" + { + "FeatureManagement": { + "{{StudioFeatureFlags.AnsattPorten}}": true + }, + "AnsattPortenLoginSettings": { + "ClientId": "non-empty-for-testing", + "ClientSecret": "non-empty-for-testing" + } + } + """); } } diff --git a/backend/tests/Designer.Tests/Controllers/PreviewController/GetImageTests.cs b/backend/tests/Designer.Tests/Controllers/PreviewController/GetImageTests.cs index afcc096ffcc..e314dfb04bb 100644 --- a/backend/tests/Designer.Tests/Controllers/PreviewController/GetImageTests.cs +++ b/backend/tests/Designer.Tests/Controllers/PreviewController/GetImageTests.cs @@ -84,7 +84,7 @@ public async Task Get_Image_Non_Existing_Image_Return_NotFound() public async Task Call_To_Get_Designer_Iframe_Does_Not_Hit_Image_EndPoint() { Mock factMock = new(); - ConfigureTestForSpecificTest = s => + ConfigureTestServicesForSpecificTest = s => { s.AddTransient(_ => factMock.Object); }; diff --git a/charts/altinn-designer/values.yaml b/charts/altinn-designer/values.yaml index f45614a2836..5e57f21f2f7 100644 --- a/charts/altinn-designer/values.yaml +++ b/charts/altinn-designer/values.yaml @@ -53,7 +53,7 @@ environmentVariables: - name: OidcLoginSettings__CookieExpiryTimeInMinutes value: 59 - name: FeatureManagement__AnsattPorten - value: "false" + value: "true" - name: FeatureManagement__EidLogging value: "true" staging: diff --git a/frontend/app-development/hooks/queries/useIsLoggedInWithAnsattportenQuery.ts b/frontend/app-development/hooks/queries/useIsLoggedInWithAnsattportenQuery.ts index b40dfd28ad7..c35de4a9bf8 100644 --- a/frontend/app-development/hooks/queries/useIsLoggedInWithAnsattportenQuery.ts +++ b/frontend/app-development/hooks/queries/useIsLoggedInWithAnsattportenQuery.ts @@ -4,8 +4,8 @@ import { useServicesContext } from 'app-shared/contexts/ServicesContext'; export const useIsLoggedInWithAnsattportenQuery = () => { const { getIsLoggedInWithAnsattporten } = useServicesContext(); - return useQuery({ + return useQuery<{ isLoggedIn: boolean }>({ queryKey: [QueryKey.IsLoggedInWithAnsattporten], - queryFn: () => getIsLoggedInWithAnsattporten(), + queryFn: getIsLoggedInWithAnsattporten, }); }; diff --git a/frontend/app-development/layout/PageHeader/SubHeader/SettingsModalButton/SettingsModal/components/Tabs/Maskinporten/Maskinporten.test.tsx b/frontend/app-development/layout/PageHeader/SubHeader/SettingsModalButton/SettingsModal/components/Tabs/Maskinporten/Maskinporten.test.tsx index bc975820bfa..c11d8119313 100644 --- a/frontend/app-development/layout/PageHeader/SubHeader/SettingsModalButton/SettingsModal/components/Tabs/Maskinporten/Maskinporten.test.tsx +++ b/frontend/app-development/layout/PageHeader/SubHeader/SettingsModalButton/SettingsModal/components/Tabs/Maskinporten/Maskinporten.test.tsx @@ -7,21 +7,13 @@ import { queriesMock } from 'app-shared/mocks/queriesMock'; import { createQueryClientMock } from 'app-shared/mocks/queryClientMock'; import userEvent from '@testing-library/user-event'; -describe('Maskinporten', () => { - const consoleLogMock = jest.fn(); - const originalConsoleLog = console.log; - beforeEach(() => { - console.log = consoleLogMock; - }); - - afterEach(() => { - console.log = originalConsoleLog; - }); +jest.mock('app-shared/api/paths'); +describe('Maskinporten', () => { it('should check and verify if the user is logged in', async () => { const getIsLoggedInWithAnsattportenMock = jest .fn() - .mockImplementation(() => Promise.resolve(false)); + .mockImplementation(() => Promise.resolve({ isLoggedIn: false })); renderMaskinporten({ queries: { @@ -54,7 +46,7 @@ describe('Maskinporten', () => { it('should display content if logged in', async () => { const getIsLoggedInWithAnsattportenMock = jest .fn() - .mockImplementation(() => Promise.resolve(true)); + .mockImplementation(() => Promise.resolve({ isLoggedIn: true })); renderMaskinporten({ queries: { getIsLoggedInWithAnsattporten: getIsLoggedInWithAnsattportenMock, @@ -70,6 +62,9 @@ describe('Maskinporten', () => { }); it('should invoke "handleLoginWithAnsattPorten" when login button is clicked', async () => { + // jsdom does not support .href navigation, therefore this mock is needed. + const hrefMock = mockWindowLocationHref(); + const user = userEvent.setup(); renderMaskinporten(); await waitForLoggedInStatusCheckIsDone(); @@ -79,16 +74,13 @@ describe('Maskinporten', () => { }); await user.click(loginButton); - - expect(consoleLogMock).toHaveBeenCalledWith( - 'Will be implemented in next iteration when backend is ready', - ); + expect(hrefMock).toHaveBeenCalledTimes(1); }); it('should show an alert with text that no scopes are available for user', async () => { const getIsLoggedInWithAnsattportenMock = jest .fn() - .mockImplementation(() => Promise.resolve(true)); + .mockImplementation(() => Promise.resolve({ isLoggedIn: true })); const mockGetMaskinportenScopes = jest.fn().mockImplementation(() => Promise.resolve([])); @@ -118,3 +110,14 @@ const renderMaskinporten = ({ queries = queriesMock }: RenderMaskinporten = {}) async function waitForLoggedInStatusCheckIsDone() { await waitForElementToBeRemoved(() => screen.queryByTitle(textMock('general.loading'))); } + +function mockWindowLocationHref(): jest.Mock { + const hrefMock = jest.fn(); + delete window.location; + window.location = { href: '' } as Location; + Object.defineProperty(window.location, 'href', { + set: hrefMock, + }); + + return hrefMock; +} diff --git a/frontend/app-development/layout/PageHeader/SubHeader/SettingsModalButton/SettingsModal/components/Tabs/Maskinporten/Maskinporten.tsx b/frontend/app-development/layout/PageHeader/SubHeader/SettingsModalButton/SettingsModal/components/Tabs/Maskinporten/Maskinporten.tsx index bb82c7c9501..634220ea5f1 100644 --- a/frontend/app-development/layout/PageHeader/SubHeader/SettingsModalButton/SettingsModal/components/Tabs/Maskinporten/Maskinporten.tsx +++ b/frontend/app-development/layout/PageHeader/SubHeader/SettingsModalButton/SettingsModal/components/Tabs/Maskinporten/Maskinporten.tsx @@ -2,24 +2,25 @@ import React, { type ReactNode, type ReactElement } from 'react'; import { useTranslation } from 'react-i18next'; import { TabContent } from '../../TabContent'; import { StudioButton, StudioHeading, StudioParagraph, StudioSpinner } from '@studio/components'; -import { useIsLoggedInWithAnsattportenQuery } from 'app-development/hooks/queries/useIsLoggedInWithAnsattportenQuery'; +import { useIsLoggedInWithAnsattportenQuery } from '../../../../../../../../hooks/queries/useIsLoggedInWithAnsattportenQuery'; +import { loginWithAnsattPorten } from 'app-shared/api/paths'; import { ScopeList } from './ScopeList'; export const Maskinporten = (): ReactElement => { - const { data: isLoggedInWithAnsattporten, isPending: isPendingAuthStatus } = + const { data: ansattportenAuthStatus, isPending: isPendingAuthStatus } = useIsLoggedInWithAnsattportenQuery(); const { t } = useTranslation(); const handleLoginWithAnsattporten = (): void => { - console.log('Will be implemented in next iteration when backend is ready'); + window.location.href = loginWithAnsattPorten(window.location.pathname + window.location.search); }; if (isPendingAuthStatus) { return ; } - if (isLoggedInWithAnsattporten) { + if (ansattportenAuthStatus.isLoggedIn) { return ( diff --git a/frontend/packages/shared/src/api/paths.js b/frontend/packages/shared/src/api/paths.js index 545ac846aaf..0e7b416dd78 100644 --- a/frontend/packages/shared/src/api/paths.js +++ b/frontend/packages/shared/src/api/paths.js @@ -4,6 +4,10 @@ import { PREVIEW_MOCK_PARTY_ID, PREVIEW_MOCK_INSTANCE_GUID } from '../constants' // Base path const basePath = '/designer/api'; +// Ansattporten +export const authStatusAnsattporten = () => `${basePath}/ansattporten/auth-status`; +export const loginWithAnsattPorten = (redirectTo) => `${basePath}/ansattporten/login?redirect_to=${redirectTo}`; + // ApplicationMetadata export const appMetadataPath = (org, app) => `${basePath}/${org}/${app}/metadata`; // Get, Put, Post export const appMetadataAttachmentPath = (org, app) => `${basePath}/${org}/${app}/metadata/attachment-component`; // Post, Put, Delete diff --git a/frontend/packages/shared/src/api/queries.ts b/frontend/packages/shared/src/api/queries.ts index 279f9e03379..acb4ddc0547 100644 --- a/frontend/packages/shared/src/api/queries.ts +++ b/frontend/packages/shared/src/api/queries.ts @@ -53,7 +53,9 @@ import { repoDiffPath, getImageFileNamesPath, validateImageFromExternalUrlPath, + authStatusAnsattporten, } from './paths'; + import type { AppReleasesResponse, DataModelMetadataResponse, SearchRepoFilterParams, SearchRepositoryResponse } from 'app-shared/types/api'; import type { DeploymentsResponse } from 'app-shared/types/api/DeploymentsResponse'; import type { BranchStatus } from 'app-shared/types/BranchStatus'; @@ -85,13 +87,10 @@ import type { ExternalImageUrlValidationResponse } from 'app-shared/types/api/Ex import type { MaskinportenScope } from 'app-shared/types/MaskinportenScope'; import type { OptionsLists } from 'app-shared/types/api/OptionsLists'; -export const getIsLoggedInWithAnsattporten = async (): Promise => - // TODO: replace with endpoint when it's ready in the backend. - new Promise((resolve) => { - setTimeout(() => { - return resolve(false); - }, 1000); - }); +export const getIsLoggedInWithAnsattporten = () => + get<{ + isLoggedIn: boolean; + }>(authStatusAnsattporten()); export const getMaskinportenScopes = async (): Promise => // TODO: replace with endpoint when it's ready in the backend. new Promise((resolve) => { @@ -99,7 +98,6 @@ export const getMaskinportenScopes = async (): Promise => return resolve([]); }, 1000); }); - export const getAppMetadataModelIds = (org: string, app: string, onlyUnReferenced: boolean) => get(appMetadataModelIdsPath(org, app, onlyUnReferenced)); export const getAppReleases = (owner: string, app: string) => get(releasesPath(owner, app, 'Descending')); export const getAppVersion = (org: string, app: string) => get(appVersionPath(org, app)); diff --git a/frontend/packages/shared/src/mocks/queriesMock.ts b/frontend/packages/shared/src/mocks/queriesMock.ts index 28fa137c748..8ab1f1b05ac 100644 --- a/frontend/packages/shared/src/mocks/queriesMock.ts +++ b/frontend/packages/shared/src/mocks/queriesMock.ts @@ -170,11 +170,10 @@ export const queriesMock: ServicesContextProps = { getProcessTaskType: jest.fn().mockImplementation(() => Promise.resolve('')), getIsLoggedInWithAnsattporten: jest .fn() - .mockImplementation(() => Promise.resolve(false)), + .mockImplementation(() => Promise.resolve<{ isLoggedIn: false }>({ isLoggedIn: false })), getMaskinportenScopes: jest .fn() .mockImplementation(() => Promise.resolve([])), - // Mutations addAppAttachmentMetadata: jest.fn().mockImplementation(() => Promise.resolve()), addDataTypeToAppMetadata: jest.fn().mockImplementation(() => Promise.resolve()),