') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); feat(clerk-js,shared,types): Remove invalid email addresses from input for Organization Invitation by chanioxaris · Pull Request #1869 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/yellow-pumpkins-buy.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
---
'@clerk/clerk-js': patch
'@clerk/shared': patch
'@clerk/types': patch
---

In invite members screen of the <OrganizationProfile /> component, consume any invalid email addresses as they are returned in the API error and remove them from the input automatically.
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import { isClerkAPIResponseError } from '@clerk/shared';
import type { MembershipRole, OrganizationResource } from '@clerk/types';
import type { ClerkAPIError, MembershipRole, OrganizationResource } from '@clerk/types';
import React from 'react';

import { Flex, Text } from '../../customizables';
Expand DownExpand Up@@ -89,24 +89,29 @@ export const InviteMembersForm = (props: InviteMembersFormProps) => {
.inviteMembers({ emailAddresses: emailAddressField.value.split(','), role: roleField.value as MembershipRole })
.then(onSuccess)
.catch(err => {
if (isClerkAPIResponseError(err)) {
removeInvalidEmails(err.errors[0]);
}

if (isClerkAPIResponseError(err) && err.errors?.[0]?.code === 'duplicate_record') {
const unlocalizedEmailsList = err.errors[0].meta?.emailAddresses || [];

// Create a localized list of email addresses
const localizedList = createListFormat(unlocalizedEmailsList, locale);
setLocalizedEmails(localizedList);

// Remove any invalid email address
const invalids = new Set(unlocalizedEmailsList);
const emails = emailAddressField.value.split(',');
emailAddressField.setValue(emails.filter(e => !invalids.has(e)).join(','));
} else {
setLocalizedEmails(null);
handleError(err, [], card.setError);
}
});
};

const removeInvalidEmails = (err: ClerkAPIError) => {
const invalidEmails = new Set([...(err.meta?.emailAddresses ?? []), ...(err.meta?.identifiers ?? [])]);
const emails = emailAddressField.value.split(',');
emailAddressField.setValue(emails.filter(e => !invalidEmails.has(e)).join(','));
};

return (
<>
{localizedEmails && (
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -133,6 +133,65 @@ describe('InviteMembersPage', () => {
).toBeInTheDocument(),
);
});

it('removes duplicate emails from input after error', async () => {
const { wrapper, fixtures } = await createFixtures(f => {
f.withOrganizations();
f.withUser({
email_addresses: ['test@clerk.dev'],
organization_memberships: [{ name: 'Org1', role: 'admin' }],
});
});

fixtures.clerk.organization?.inviteMembers.mockRejectedValueOnce(
new ClerkAPIResponseError('Error', {
data: [
{
code: 'duplicate_record',
long_message:
'There are already pending invitations for the following email addresses: invalid@clerk.dev',
message: 'duplicate invitation',
meta: { email_addresses: ['invalid@clerk.dev'] },
},
],
status: 400,
}),
);
const { getByRole, userEvent, getByTestId } = render(<InviteMembersPage />, { wrapper });
await userEvent.type(getByTestId('tag-input'), 'invalid@clerk.dev');
await userEvent.click(getByRole('button', { name: 'Send invitations' }));

expect(getByTestId('tag-input')).not.toHaveValue();
});

it('removes blocked/not allowed emails from input after error', async () => {
const { wrapper, fixtures } = await createFixtures(f => {
f.withOrganizations();
f.withUser({
email_addresses: ['test@clerk.dev'],
organization_memberships: [{ name: 'Org1', role: 'admin' }],
});
});

fixtures.clerk.organization?.inviteMembers.mockRejectedValueOnce(
new ClerkAPIResponseError('Error', {
data: [
{
code: 'not_allowed_access',
long_message: 'blocked@clerk.dev is not allowed to access this application.',
message: 'Access not allowed.',
meta: { identifiers: ['blocked@clerk.dev'] },
},
],
status: 403,
}),
);
const { getByRole, userEvent, getByTestId } = render(<InviteMembersPage />, { wrapper });
await userEvent.type(getByTestId('tag-input'), 'blocked@clerk.dev');
await userEvent.click(getByRole('button', { name: 'Send invitations' }));

expect(getByTestId('tag-input')).not.toHaveValue();
});
});

describe('Navigation', () => {
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/errors/Error.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ export function parseError(error: ClerkAPIErrorJSON): ClerkAPIError {
paramName: error?.meta?.param_name,
sessionId: error?.meta?.session_id,
emailAddresses: error?.meta?.email_addresses,
identifiers: error?.meta?.identifiers,
zxcvbn: error?.meta?.zxcvbn,
},
};
Expand Down
1 change: 1 addition & 0 deletions packages/types/src/api.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ export interface ClerkAPIError {
paramName?: string;
sessionId?: string;
emailAddresses?: string[];
identifiers?: string[];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@chanioxaris Did we introduced that to FAPI ? I don't think we support any other identifier than emails, so is this even useful ?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Allowlist & Blocklist are working for every identifier type (email_address, phone_number, web3_wallet). So in such an api error we can't limit them to only email addresses or reuse the existing meta parameter emailAddresses

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@chanioxaris Shall we update the copy here ? (Happy to do it as part of another PR)
image

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the case of Organization Invitations, only email addresses can be provided. Although the API error is used in general for the Allowlist/Blocklist feature

zxcvbn?: {
suggestions: {
code: string;
Expand Down
1 change: 1 addition & 0 deletions packages/types/src/json.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -267,6 +267,7 @@ export interface ClerkAPIErrorJSON {
param_name?: string;
session_id?: string;
email_addresses?: string[];
identifiers?: string[];
zxcvbn?: {
suggestions: {
code: string;
Expand Down