-
Notifications
You must be signed in to change notification settings - Fork 144
Invitation email sending (only in development and only when RESEND_API_KEY is set now) #1513
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
hoshinotsuyoshi
wants to merge
2
commits into
main
Choose a base branch
from
invitation-email-sending
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+534
−122
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
98 changes: 98 additions & 0 deletions
98
frontend/apps/app/features/organizations/actions/sendInvitationEmail.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
import { createClient } from '@/libs/db/server' | ||
import { Resend } from 'resend' | ||
|
||
// Email template component | ||
const InvitationEmail = ({ | ||
organizationName, | ||
invitationLink, | ||
}: { organizationName: string; invitationLink: string }) => { | ||
return ` | ||
<!DOCTYPE html> | ||
<html> | ||
<head> | ||
<meta charset="utf-8"> | ||
<title>Organization Invitation</title> | ||
</head> | ||
<body> | ||
<h1>You've been invited to join ${organizationName}</h1> | ||
<p>You have been invited to join ${organizationName} on Liam.</p> | ||
<p>Click the link below to accept the invitation:</p> | ||
<a href="${invitationLink}">Accept Invitation</a> | ||
<p>If you did not expect this invitation, you can safely ignore this email.</p> | ||
</body> | ||
</html> | ||
` | ||
} | ||
|
||
type SendInvitationEmailParams = { | ||
email: string | ||
organizationId: string | ||
invitationToken: string | ||
} | ||
|
||
export const sendInvitationEmail = async ({ | ||
email, | ||
organizationId, | ||
invitationToken, | ||
}: SendInvitationEmailParams) => { | ||
// TODO: Enable email sending in preview/production | ||
// For now, we don't want to send emails in preview/production | ||
if (process.env.NODE_ENV !== 'development' || !process.env.RESEND_API_KEY) { | ||
return { success: true, error: null } | ||
} | ||
|
||
const supabase = await createClient() | ||
|
||
// Get organization name for the email | ||
const { data: orgData, error: orgError } = await supabase | ||
.from('organizations') | ||
.select('name') | ||
.eq('id', organizationId) | ||
.single() | ||
|
||
if (orgError) { | ||
console.error('Error fetching organization:', orgError) | ||
return { | ||
success: false, | ||
error: 'Failed to fetch organization details.', | ||
} as const | ||
} | ||
|
||
let baseUrl: string | undefined = undefined | ||
switch (process.env.NEXT_PUBLIC_ENV_NAME) { | ||
case 'production': | ||
baseUrl = process.env.NEXT_PUBLIC_BASE_URL // NEXT_PUBLIC_BASE_URL includes "https://" | ||
break | ||
case 'preview': | ||
baseUrl = `https://${process.env.VERCEL_BRANCH_URL}` // VERCEL_BRANCH_URL does not include "https://" | ||
break | ||
default: | ||
baseUrl = 'http://localhost:3001' | ||
break | ||
} | ||
|
||
// Construct invitation link | ||
const invitationLink = `${baseUrl || ''}/app/invitations/tokens/${invitationToken}` | ||
|
||
// Send email | ||
const resend = new Resend(process.env.RESEND_API_KEY) | ||
const { error: emailError } = await resend.emails.send({ | ||
from: process.env.EMAIL_FROM_ADDRESS || '[email protected]', | ||
to: email, | ||
subject: `Invitation to join ${orgData.name} on Liam`, | ||
html: InvitationEmail({ | ||
organizationName: orgData.name, | ||
invitationLink, | ||
}), | ||
}) | ||
|
||
if (emailError) { | ||
console.error('Error sending invitation email:', emailError) | ||
return { | ||
success: false, | ||
error: 'Failed to send invitation email.', | ||
} as const | ||
} | ||
|
||
return { success: true, error: null } as const | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
-- This empty .sql file is required because a migration with this filename was already applied in production. | ||
-- It will no longer be needed if the production database is ever reset. | ||
98 changes: 2 additions & 96 deletions
98
...tend/packages/db/supabase/migrations/20250423123350_refine_invite_organization_member.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,96 +1,2 @@ | ||
-- Function to handle organization member invitations atomically | ||
create or replace function invite_organization_member( | ||
p_email text, | ||
p_organization_id uuid | ||
) returns jsonb as $$ | ||
declare | ||
v_is_member boolean; | ||
v_invite_by_user_id uuid; | ||
v_existing_invite_id uuid; | ||
v_result jsonb; | ||
begin | ||
-- Start transaction | ||
begin | ||
v_invite_by_user_id := auth.uid(); | ||
|
||
-- Check inviter is a valid user | ||
if not exists ( | ||
select 1 | ||
from organization_members om | ||
where om.user_id = v_invite_by_user_id | ||
and om.organization_id = p_organization_id | ||
) then | ||
v_result := jsonb_build_object( | ||
'success', false, | ||
'error', 'inviter user does not exist' | ||
); | ||
return v_result; | ||
end if; | ||
|
||
-- Check if user is already a member | ||
select exists( | ||
select 1 | ||
from organization_members om | ||
join users u on om.user_id = u.id | ||
where om.organization_id = p_organization_id | ||
and lower(u.email) = lower(p_email) | ||
) into v_is_member; | ||
|
||
if v_is_member then | ||
v_result := jsonb_build_object( | ||
'success', false, | ||
'error', 'this user is already a member of the organization' | ||
); | ||
return v_result; | ||
end if; | ||
|
||
-- Check if invitation already exists | ||
select id into v_existing_invite_id | ||
from invitations | ||
where organization_id = p_organization_id | ||
and lower(email) = lower(p_email) | ||
limit 1; | ||
|
||
-- If invitation exists, update it | ||
if v_existing_invite_id is not null then | ||
update invitations | ||
set invited_at = current_timestamp, | ||
expired_at = current_timestamp + interval '7 days', | ||
invite_by_user_id = v_invite_by_user_id, | ||
token = gen_random_uuid() | ||
where id = v_existing_invite_id; | ||
|
||
v_result := jsonb_build_object('success', true, 'error', null); | ||
else | ||
-- Create new invitation | ||
insert into invitations ( | ||
organization_id, | ||
email, | ||
invited_at, | ||
expired_at, | ||
invite_by_user_id | ||
) values ( | ||
p_organization_id, | ||
lower(p_email), | ||
current_timestamp, | ||
current_timestamp + interval '7 days', | ||
v_invite_by_user_id | ||
); | ||
|
||
v_result := jsonb_build_object('success', true, 'error', null); | ||
end if; | ||
|
||
-- Commit transaction | ||
return v_result; | ||
exception when others then | ||
-- Handle any errors | ||
v_result := jsonb_build_object( | ||
'success', false, | ||
'error', sqlerrm | ||
); | ||
return v_result; | ||
end; | ||
end; | ||
$$ language plpgsql; | ||
|
||
revoke all on function invite_organization_member(text, uuid) from anon; | ||
-- This empty .sql file is required because a migration with this filename was already applied in production. | ||
-- It will no longer be needed if the production database is ever reset. |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I see, I want to squash migrations before first release!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I agree with squashing. I think it's fine to squash all the files, not just the empty ones! :)