diff --git a/src/Exceptionless.Web/Api/Handlers/AuthHandler.cs b/src/Exceptionless.Web/Api/Handlers/AuthHandler.cs index 46c050f18b..086b5d2884 100644 --- a/src/Exceptionless.Web/Api/Handlers/AuthHandler.cs +++ b/src/Exceptionless.Web/Api/Handlers/AuthHandler.cs @@ -534,7 +534,7 @@ private async Task> ExternalLoginAsync(ExternalAuthInfo auth User? user; try { - user = await FromExternalLoginAsync(userInfo, httpContext); + user = await FromExternalLoginAsync(userInfo, authInfo.InviteToken, httpContext); } catch (ApplicationException ex) { @@ -554,7 +554,7 @@ private async Task> ExternalLoginAsync(ExternalAuthInfo auth return new TokenResult { Token = await GetOrCreateAuthenticationTokenAsync(user) }; } - private async Task FromExternalLoginAsync(UserInfo userInfo, HttpContext httpContext) + private async Task FromExternalLoginAsync(UserInfo userInfo, string? inviteToken, HttpContext httpContext) { ArgumentException.ThrowIfNullOrWhiteSpace(userInfo.Id); ArgumentException.ThrowIfNullOrWhiteSpace(userInfo.ProviderName); @@ -563,7 +563,7 @@ private async Task FromExternalLoginAsync(UserInfo userInfo, HttpContext h var existingUser = await userRepository.GetUserByOAuthProviderAsync(userInfo.ProviderName, userInfo.Id); using var _ = logger.BeginScope(new ExceptionlessState().Tag("External Login").Property("User Info", userInfo).Property("ExistingUser", existingUser).SetHttpContext(httpContext)); - if (httpContext.User.IsUserAuthType()) + if (String.IsNullOrWhiteSpace(inviteToken) && httpContext.User.IsUserAuthType()) { var currentUser = httpContext.Request.GetUser(); if (existingUser is not null) @@ -599,7 +599,7 @@ private async Task FromExternalLoginAsync(UserInfo userInfo, HttpContext h var user = !String.IsNullOrEmpty(userInfo.Email) ? await userRepository.GetByEmailAddressAsync(userInfo.Email) : null; if (user is null) { - if (!authOptions.EnableAccountCreation) + if (!await IsAccountCreationEnabledAsync(inviteToken)) throw new ApplicationException("Account Creation is currently disabled."); user = new User { FullName = userInfo.GetFullName()!, EmailAddress = userInfo.Email }; diff --git a/src/Exceptionless.Web/ClientApp/e2e/fixtures/api-client.ts b/src/Exceptionless.Web/ClientApp/e2e/fixtures/api-client.ts index 909b6f700d..8b3f0f6eaf 100644 --- a/src/Exceptionless.Web/ClientApp/e2e/fixtures/api-client.ts +++ b/src/Exceptionless.Web/ClientApp/e2e/fixtures/api-client.ts @@ -191,6 +191,14 @@ export class E2EApiClient { return toToken(await readJson(response)); } + async inviteOrganizationUser(token: string, organizationId: string, email: string): Promise { + const response = await this.request.post(this.url(`organizations/${organizationId}/users/${encodeURIComponent(email)}`), { + headers: this.authHeaders(token) + }); + + await expectStatus(response, [200], 'invite organization user'); + } + async login(email = this.environment.email, password = this.environment.password): Promise { const token = await this.loginIfExists(email, password); if (!token) { diff --git a/src/Exceptionless.Web/ClientApp/e2e/tests/invitation-acceptance.e2e.ts b/src/Exceptionless.Web/ClientApp/e2e/tests/invitation-acceptance.e2e.ts index d6a92a7393..ebf46ecc9e 100644 --- a/src/Exceptionless.Web/ClientApp/e2e/tests/invitation-acceptance.e2e.ts +++ b/src/Exceptionless.Web/ClientApp/e2e/tests/invitation-acceptance.e2e.ts @@ -31,6 +31,7 @@ test('invited user can accept an organization invitation @signup', async ({ brow try { await invitedPage.goto(`/next/signup?token=${encodeURIComponent(inviteToken)}`); + await expect(invitedPage.getByRole('link', { name: 'Log In' })).toHaveAttribute('href', `/next/login?token=${encodeURIComponent(inviteToken)}`); await invitedPage.getByLabel('Name', { exact: true }).fill(`Invited User ${e2eScenario.run}`); await invitedPage.getByLabel('Email', { exact: true }).fill(invitedEmail); await waitForEmailValidation(invitedPage); @@ -81,3 +82,72 @@ test('invited user can accept an organization invitation @signup', async ({ brow throwIfCleanupFailed(cleanupErrors); } }); + +test('existing invited user can accept an organization invitation when logging in @signup', async ({ browser, e2eApi, e2eScenario }) => { + const invitedEmail = `existing-invited-${e2eScenario.run}@exceptionless.test`.toLowerCase(); + let invitedUserToken: string | undefined; + + try { + await test.step('create an invitation for a new address', async () => { + await e2eApi.inviteOrganizationUser(e2eScenario.userToken, e2eScenario.organizationId, invitedEmail); + }); + + const inviteToken = await e2eApi.pollForMailToken(invitedEmail, 'signup'); + const existingUserToken = await e2eApi.signup(`Existing Invited User ${e2eScenario.run}`, invitedEmail, E2E_TEST_PASSWORD); + invitedUserToken = existingUserToken; + const invitedContext = await browser.newContext({ baseURL: e2eApi.environment.appUrl, ignoreHTTPSErrors: true }); + await invitedContext.addInitScript((token) => window.localStorage.setItem('satellizer_token', token), existingUserToken); + const invitedPage = await invitedContext.newPage(); + + try { + const logoutResponse = invitedPage.waitForResponse((response) => { + const url = new URL(response.url()); + return response.request().method() === 'GET' && url.pathname.endsWith('/api/v2/auth/logout'); + }); + + await invitedPage.goto(`/next/login?token=${encodeURIComponent(inviteToken)}`); + expect((await logoutResponse).ok()).toBe(true); + await expect(invitedPage.getByRole('link', { name: 'Start a free trial' })).toHaveAttribute( + 'href', + `/next/signup?token=${encodeURIComponent(inviteToken)}` + ); + await invitedPage.getByLabel('Email', { exact: true }).fill(invitedEmail); + await invitedPage.getByPlaceholder('Enter password').fill(E2E_TEST_PASSWORD); + + const loginResponse = invitedPage.waitForResponse((response) => { + const url = new URL(response.url()); + return response.request().method() === 'POST' && url.pathname.endsWith('/api/v2/auth/login'); + }); + + await invitedPage.getByRole('button', { exact: true, name: 'Login' }).click(); + const response = await loginResponse; + const requestBody = response.request().postDataJSON() as { invite_token?: string }; + expect(requestBody.invite_token).toBe(inviteToken); + expect(response.ok()).toBe(true); + + invitedUserToken = await getUserToken(invitedPage); + await e2eApi.waitForOrganizationListed(invitedUserToken, e2eScenario.organizationId, 60_000); + await expect(invitedPage.getByRole('button').filter({ hasText: e2eScenario.organizationName }).filter({ visible: true }).first()).toBeVisible(); + } finally { + await invitedContext.close(); + } + } finally { + const cleanupErrors: Error[] = []; + + if (invitedUserToken) { + const token = invitedUserToken; + + await runCleanupStep(cleanupErrors, 'remove existing invited user from organization', async () => { + await e2eApi.deleteOrganizationUser(e2eScenario.userToken, e2eScenario.organizationId, invitedEmail); + await e2eApi.waitForOrganizationNotListed(token, e2eScenario.organizationId); + }); + + await runCleanupStep(cleanupErrors, 'delete existing invited user', async () => { + await e2eApi.deleteCurrentUser(token); + await e2eApi.waitForCurrentUserDeleted(token); + }); + } + + throwIfCleanupFailed(cleanupErrors); + } +}); diff --git a/src/Exceptionless.Web/ClientApp/src/lib/features/auth/api.svelte.ts b/src/Exceptionless.Web/ClientApp/src/lib/features/auth/api.svelte.ts index df85859917..7571b6b417 100644 --- a/src/Exceptionless.Web/ClientApp/src/lib/features/auth/api.svelte.ts +++ b/src/Exceptionless.Web/ClientApp/src/lib/features/auth/api.svelte.ts @@ -80,9 +80,10 @@ export async function isEmailAddressTaken(email: string) { return response.status === 201; } -export async function login(email: string, password: string) { +export async function login(email: string, password: string, inviteToken?: null | string) { const data: Login = { email, + invite_token: inviteToken, password }; const client = useFetchClient(); diff --git a/src/Exceptionless.Web/ClientApp/src/lib/features/auth/index.svelte.ts b/src/Exceptionless.Web/ClientApp/src/lib/features/auth/index.svelte.ts index c66f714cd1..66a3b1ea45 100644 --- a/src/Exceptionless.Web/ClientApp/src/lib/features/auth/index.svelte.ts +++ b/src/Exceptionless.Web/ClientApp/src/lib/features/auth/index.svelte.ts @@ -27,6 +27,7 @@ export { accessToken } from './state.svelte'; export { validateEmailAvailability } from './validators'; export interface OAuthLoginOptions extends OAuthPopupOptions { + inviteToken?: null | string; redirectUrl?: string; } @@ -56,7 +57,7 @@ export const enableOAuthLogin = facebookClientId || gitHubClientId || googleClie // OAuth login functions (interactive popup-based, not pure API calls) -export async function facebookLogin(redirectUrl?: string) { +export async function facebookLogin(redirectUrl?: string, inviteToken?: null | string) { if (!facebookClientId) { throw new Error('Facebook client id not set'); } @@ -64,13 +65,14 @@ export async function facebookLogin(redirectUrl?: string) { await oauthLogin({ authUrl: 'https://www.facebook.com/v2.5/dialog/oauth', clientId: facebookClientId, + inviteToken, provider: 'facebook', redirectUrl, scope: 'email' }); } -export async function githubLogin(redirectUrl?: string) { +export async function githubLogin(redirectUrl?: string, inviteToken?: null | string) { if (!gitHubClientId) { throw new Error('GitHub client id not set'); } @@ -78,6 +80,7 @@ export async function githubLogin(redirectUrl?: string) { await oauthLogin({ authUrl: 'https://github.com/login/oauth/authorize', clientId: gitHubClientId, + inviteToken, popupOptions: { height: 618, width: 1020 @@ -88,7 +91,7 @@ export async function githubLogin(redirectUrl?: string) { }); } -export async function googleLogin(redirectUrl?: string) { +export async function googleLogin(redirectUrl?: string, inviteToken?: null | string) { if (!googleClientId) { throw new Error('Google client id not set'); } @@ -103,6 +106,7 @@ export async function googleLogin(redirectUrl?: string) { service: 'lso', state: encodeURIComponent(Math.random().toString(36).substring(2)) }, + inviteToken, provider: 'google', redirectUrl, scope: 'openid profile email' @@ -118,7 +122,7 @@ export async function gotoLogin() { }); } -export async function liveLogin(redirectUrl?: string) { +export async function liveLogin(redirectUrl?: string, inviteToken?: null | string) { if (!microsoftClientId) { throw new Error('Live client id not set'); } @@ -129,6 +133,7 @@ export async function liveLogin(redirectUrl?: string) { extraParams: { display: 'popup' }, + inviteToken, provider: 'live', redirectUrl, scope: 'wl.emails' @@ -166,6 +171,7 @@ async function oauthLogin(options: OAuthLoginOptions) { const response = await client.postJSON(`auth/${options.provider}`, { clientId: options.clientId, code: data.code, + inviteToken: options.inviteToken, redirectUri: window.location.origin, state: data.state }); diff --git a/src/Exceptionless.Web/ClientApp/src/routes/(auth)/login/+page.svelte b/src/Exceptionless.Web/ClientApp/src/routes/(auth)/login/+page.svelte index 7e86b96997..555609f873 100644 --- a/src/Exceptionless.Web/ClientApp/src/routes/(auth)/login/+page.svelte +++ b/src/Exceptionless.Web/ClientApp/src/routes/(auth)/login/+page.svelte @@ -17,6 +17,7 @@ import { Spinner } from '$comp/ui/spinner'; import { login } from '$features/auth/api.svelte'; import { + accessToken, enableAccountCreation, enableOAuthLogin, facebookClientId, @@ -26,26 +27,41 @@ googleClientId, googleLogin, liveLogin, + logout, microsoftClientId } from '$features/auth/index.svelte'; import { type LoginFormData, LoginSchema } from '$features/auth/schemas'; import { getSafeRedirectUrl } from '$features/shared/url'; import { ariaInvalid, getFormErrorMessages, mapFieldErrors, problemDetailsToFormErrors } from '$shared/validation'; import { createForm } from '@tanstack/svelte-form'; + import { onMount } from 'svelte'; const defaultRedirect = resolve('/'); const redirectUrl = getSafeRedirectUrl(page.url.searchParams.get('redirect'), defaultRedirect); + const inviteToken = page.url.searchParams.get('token'); + const canSignup = enableAccountCreation || !!inviteToken; + const signupUrl = inviteToken ? `${resolve('/(auth)/signup')}?token=${encodeURIComponent(inviteToken)}` : resolve('/(auth)/signup'); + + onMount(async () => { + if (accessToken.current) { + try { + await logout(); + } catch { + // The login flow can continue when an existing session cannot be ended. + } + } + }); const form = createForm(() => ({ defaultValues: { email: '', - invite_token: page.url.searchParams.get('token'), + invite_token: inviteToken, password: '' } as LoginFormData, validators: { onSubmit: LoginSchema, onSubmitAsync: async ({ value }) => { - const response = await login(value.email, value.password); + const response = await login(value.email, value.password, value.invite_token); if (response.ok) { await goto(redirectUrl); return null; @@ -62,7 +78,7 @@ } -
+
@@ -137,7 +153,7 @@ state.isSubmitting}> {#snippet children(isSubmitting)} -
+
- {#if enableAccountCreation} - + {#if canSignup} + {/if}
{/snippet} @@ -161,38 +177,38 @@
{#if microsoftClientId} - {/if} {#if googleClientId} - {/if} {#if facebookClientId} - {/if} {#if gitHubClientId} - {/if}
{/if} - {#if enableAccountCreation} + {#if canSignup}

Not a member? - Start a free trial + Start a free trial

{/if}
- {#if enableAccountCreation} + {#if canSignup}

By signing up, you agree to our Privacy Policy and diff --git a/src/Exceptionless.Web/ClientApp/src/routes/(auth)/signup/+page.svelte b/src/Exceptionless.Web/ClientApp/src/routes/(auth)/signup/+page.svelte index 21bfc71be2..29c7c28133 100644 --- a/src/Exceptionless.Web/ClientApp/src/routes/(auth)/signup/+page.svelte +++ b/src/Exceptionless.Web/ClientApp/src/routes/(auth)/signup/+page.svelte @@ -17,6 +17,7 @@ import { Spinner } from '$comp/ui/spinner'; import { signup } from '$features/auth/api.svelte'; import { + accessToken, enableOAuthLogin, facebookClientId, facebookLogin, @@ -25,16 +26,28 @@ googleClientId, googleLogin, liveLogin, + logout, microsoftClientId } from '$features/auth/index.svelte'; import { type SignupFormData, SignupSchema } from '$features/auth/schemas'; import { validateEmailAvailability } from '$features/auth/validators'; import { ariaInvalid, getFormErrorMessages, mapFieldErrors, problemDetailsToFormErrors } from '$shared/validation'; import { createForm } from '@tanstack/svelte-form'; + import { onMount } from 'svelte'; const inviteToken = page.url.searchParams.get('token'); const redirectUrl = inviteToken ? resolve('/(app)/project/add') : resolve('/(app)/organization/add'); + onMount(async () => { + if (accessToken.current) { + try { + await logout(); + } catch { + // The signup flow can continue when an existing session cannot be ended. + } + } + }); + const form = createForm(() => ({ defaultValues: { email: '', @@ -57,7 +70,7 @@ })); - + Signup for a FREE account in seconds @@ -68,22 +81,22 @@

Sign up with

{#if microsoftClientId} - {/if} {#if googleClientId} - {/if} {#if facebookClientId} - {/if} {#if gitHubClientId} - {/if} @@ -199,7 +212,7 @@

Already have an account? - Log In + Log In

diff --git a/tests/Exceptionless.Tests/Api/Endpoints/AuthEndpointTests.cs b/tests/Exceptionless.Tests/Api/Endpoints/AuthEndpointTests.cs index d2ef684616..1cc6d7a85f 100644 --- a/tests/Exceptionless.Tests/Api/Endpoints/AuthEndpointTests.cs +++ b/tests/Exceptionless.Tests/Api/Endpoints/AuthEndpointTests.cs @@ -560,6 +560,156 @@ public async Task LiveAsync_WithConfiguredProvider_ReturnsToken() await AssertExternalLoginAsync(result, "windowslive", code); } + [Fact] + public async Task GitHubAsync_WithoutInviteAndAuthenticatedSession_LinksCurrentUser() + { + // Arrange + const string code = "github-linked-user"; + var currentUser = await _userRepository.GetByEmailAddressAsync(SampleDataService.TEST_ORG_USER_EMAIL); + Assert.NotNull(currentUser); + + // Act + var result = await SendRequestAsAsync(request => request + .Post() + .AsTestOrganizationUser() + .AppendPaths("auth", "github") + .Content(new ExternalAuthInfo + { + ClientId = "client-id", + Code = code, + RedirectUri = "http://localhost/callback" + }) + .StatusCodeShouldBeOk() + ); + + // Assert + Assert.NotNull(result); + var token = await _tokenRepository.GetByIdAsync(result.Token); + Assert.NotNull(token); + Assert.Equal(currentUser.Id, token.UserId); + + currentUser = await _userRepository.GetByIdAsync(currentUser.Id); + Assert.NotNull(currentUser); + Assert.Contains(currentUser.OAuthAccounts, account => account.Provider == "github" && account.ProviderUserId == code); + } + + [Fact] + public async Task GitHubAsync_WithValidInviteAndAccountCreationDisabled_CreatesInvitedUser() + { + // Arrange + _authOptions.EnableAccountCreation = false; + const string code = "github-invited-user"; + string email = TestOAuthProviderClient.GetEmailAddress(code); + var organization = (await _organizationRepository.GetAllAsync()).Documents.First(); + var invite = new Invite + { + Token = StringExtensions.GetNewToken(), + EmailAddress = email, + DateAdded = DateTime.UtcNow + }; + organization.Invites.Add(invite); + await _organizationRepository.SaveAsync(organization, options => options.ImmediateConsistency()); + + // Act + var result = await SendExternalLoginAsync("github", code, invite.Token); + + // Assert + await AssertExternalLoginAsync(result, "github", code); + var user = await _userRepository.GetByEmailAddressAsync(email); + Assert.NotNull(user); + Assert.Contains(organization.Id, user.OrganizationIds); + var updatedOrganization = await _organizationRepository.GetByIdAsync(organization.Id); + Assert.NotNull(updatedOrganization); + Assert.DoesNotContain(updatedOrganization.Invites, candidate => candidate.Token == invite.Token); + } + + [Fact] + public async Task GitHubAsync_WithValidInviteAndAuthenticatedSession_AuthenticatesInvitedUser() + { + // Arrange + const string code = "github-existing-invited-user"; + string invitedEmail = TestOAuthProviderClient.GetEmailAddress(code); + var initialLogin = await SendExternalLoginAsync("github", code); + Assert.NotNull(initialLogin); + + var invitedUser = await _userRepository.GetByEmailAddressAsync(invitedEmail); + Assert.NotNull(invitedUser); + var currentUser = await _userRepository.GetByEmailAddressAsync(SampleDataService.TEST_ORG_USER_EMAIL); + Assert.NotNull(currentUser); + string[] currentOrganizationIds = currentUser.OrganizationIds.ToArray(); + + var organization = (await _organizationRepository.GetAllAsync()).Documents.First(); + var invite = new Invite + { + Token = StringExtensions.GetNewToken(), + EmailAddress = invitedEmail, + DateAdded = DateTime.UtcNow + }; + organization.Invites.Add(invite); + await _organizationRepository.SaveAsync(organization, options => options.ImmediateConsistency()); + + // Act + var result = await SendRequestAsAsync(request => request + .Post() + .AsTestOrganizationUser() + .AppendPaths("auth", "github") + .Content(new ExternalAuthInfo + { + ClientId = "client-id", + Code = code, + InviteToken = invite.Token, + RedirectUri = "http://localhost/callback" + }) + .StatusCodeShouldBeOk() + ); + + // Assert + Assert.NotNull(result); + var token = await _tokenRepository.GetByIdAsync(result.Token); + Assert.NotNull(token); + Assert.Equal(invitedUser.Id, token.UserId); + + invitedUser = await _userRepository.GetByIdAsync(invitedUser.Id); + Assert.NotNull(invitedUser); + Assert.Contains(invitedUser.OAuthAccounts, account => account.Provider == "github" && account.ProviderUserId == code); + Assert.Contains(organization.Id, invitedUser.OrganizationIds); + + currentUser = await _userRepository.GetByIdAsync(currentUser.Id); + Assert.NotNull(currentUser); + Assert.DoesNotContain(currentUser.OAuthAccounts, account => account.Provider == "github" && account.ProviderUserId == code); + Assert.Equal(currentOrganizationIds, currentUser.OrganizationIds); + + var updatedOrganization = await _organizationRepository.GetByIdAsync(organization.Id); + Assert.NotNull(updatedOrganization); + Assert.DoesNotContain(updatedOrganization.Invites, candidate => candidate.Token == invite.Token); + } + + [Fact] + public async Task GitHubAsync_WithInvalidInviteAndAccountCreationDisabled_IsForbidden() + { + // Arrange + _authOptions.EnableAccountCreation = false; + const string code = "github-invited-user"; + string email = TestOAuthProviderClient.GetEmailAddress(code); + + // Act + await SendRequestAsync(r => r + .Post() + .AppendPaths("auth", "github") + .Content(new ExternalAuthInfo + { + ClientId = "client-id", + Code = code, + InviteToken = StringExtensions.GetNewToken(), + RedirectUri = "http://localhost/callback" + }) + .StatusCodeShouldBeForbidden() + ); + + // Assert + Assert.Null(await _userRepository.GetByEmailAddressAsync(email)); + } + [Fact] public async Task LoginValidAsync() { @@ -1418,7 +1568,7 @@ private async Task AssertExternalLoginAsync(TokenResult? result, string provider Assert.Equal(user.EmailAddress, account.Username); } - private Task SendExternalLoginAsync(string providerPath, string code) + private Task SendExternalLoginAsync(string providerPath, string code, string? inviteToken = null) { return SendRequestAsAsync(r => r .Post() @@ -1427,6 +1577,7 @@ private async Task AssertExternalLoginAsync(TokenResult? result, string provider { ClientId = "client-id", Code = code, + InviteToken = inviteToken, RedirectUri = "http://localhost/callback" }) .StatusCodeShouldBeOk()