Skip to content
Open
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
15 changes: 3 additions & 12 deletions server/routes/account/sso/discourse.get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,19 +55,10 @@ export default defineEventHandler(async (event) => {
}

// Build final payload for discourse
const returnPayload = new URLSearchParams({
nonce: nonce,
external_id: userData.pid.toString(),
email: `${userData.pid}@invalid.com`, // Don't change, used by other systems
username: userData.username,
name: userData.username,
avatar_url: `${config.public.cdnBaseUrl}/mii/${userData.pid}/normal_face.png`,
avatar_force_update: 'true'
});
const encodedReturnPayload = Buffer.from(returnPayload.toString()).toString('base64');
const returnPayload = await createDiscoursePayload(nonce, userData);

const url = new URL(returnSsoUrl);
url.searchParams.append('sso', encodedReturnPayload);
url.searchParams.append('sig', getDicourseSignature(secret, encodedReturnPayload));
url.searchParams.append('sso', returnPayload);
url.searchParams.append('sig', getDicourseSignature(secret, returnPayload));
return sendRedirect(event, url.toString());
});
93 changes: 93 additions & 0 deletions server/utils/discourse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { createHmac } from 'node:crypto';
import type { GetUserDataResponse } from '@pretendonetwork/grpc/api/v2/get_user_data_rpc';

export function getDicourseSignature(secret: string, payload: string) {
return createHmac('sha256', secret).update(payload).digest('hex');
}

export async function createDiscoursePayload(nonce: string, accountData: GetUserDataResponse): Promise<string> {
const groups = config.discourse.groups;

Check failure on line 9 in server/utils/discourse.ts

View workflow job for this annotation

GitHub Actions / Lint

Cannot find name 'config'.
const managedGroups = Object.values(groups).flatMap(category => Object.values(category));

Check failure on line 10 in server/utils/discourse.ts

View workflow job for this annotation

GitHub Actions / Lint

No overload matches this call.
const addGroups = [];

Check failure on line 11 in server/utils/discourse.ts

View workflow job for this annotation

GitHub Actions / Lint

Variable 'addGroups' implicitly has type 'any[]' in some locations where its type cannot be determined.

// * If more than one of the provided groups in add_groups are configured to
// * be automatically set as the primary group, Discourse unfortunately
// * appears to set the user's primary group arbitrarily and
// * non-deterministically. However, it also ignores groups that the user
// * was already in before this sign-in, so the primary group won't change
// * if none of the user's group memberships change.
if (accountData.connections.discord?.id) {

Check failure on line 19 in server/utils/discourse.ts

View workflow job for this annotation

GitHub Actions / Lint

'accountData.connections' is possibly 'undefined'.
for (const role in groups.discord_role) {
if (await discordMemberHasRole(accountData.connections.discord.id, role)) {

Check failure on line 21 in server/utils/discourse.ts

View workflow job for this annotation

GitHub Actions / Lint

'accountData.connections' is possibly 'undefined'.

Check failure on line 21 in server/utils/discourse.ts

View workflow job for this annotation

GitHub Actions / Lint

Cannot find name 'discordMemberHasRole'.
addGroups.push(groups.discord_role[role]);
}
}
}

if (accountData.connections.stripe?.tier_level) {

Check failure on line 27 in server/utils/discourse.ts

View workflow job for this annotation

GitHub Actions / Lint

Property 'tier_level' does not exist on type 'StripeConnection'. Did you mean 'tierLevel'?

Check failure on line 27 in server/utils/discourse.ts

View workflow job for this annotation

GitHub Actions / Lint

'accountData.connections' is possibly 'undefined'.
for (const tier in groups.stripe_tier) {
if (accountData.connections.stripe.tier_level.toString() === tier) {

Check failure on line 29 in server/utils/discourse.ts

View workflow job for this annotation

GitHub Actions / Lint

Property 'tier_level' does not exist on type 'StripeConnection'. Did you mean 'tierLevel'?

Check failure on line 29 in server/utils/discourse.ts

View workflow job for this annotation

GitHub Actions / Lint

'accountData.connections' is possibly 'undefined'.
addGroups.push(groups.stripe_tier[tier]);
}
}
}

for (const level in groups.access_level) {
if (accountData.access_level.toString() === level) {
addGroups.push(groups.access_level[level]);
}
}

const removeGroups = managedGroups.filter(group => !addGroups.includes(group));

// Discourse SSO Payload
// https://meta.discourse.org/t/official-single-sign-on-for-discourse-sso/13045
const payload = new URLSearchParams({
nonce: nonce,
external_id: accountData.pid.toString(),
email: `${accountData.pid}@invalid.com`, // Don't change, used by other systems
username: accountData.username,
name: accountData.mii.name,
avatar_url: `${config.public.cdnBaseUrl}/mii/${accountData.pid}/normal_face.png`,
avatar_force_update: 'true',
add_groups: addGroups.join(','),
remove_groups: removeGroups.join(',')
});

return Buffer.from(payload.toString()).toString('base64');
}

export async function discourseUserExists(pid: number) {
const response = await $fetch.raw(`/users/by-external/${pid}.json`, {
baseURL: config.discourse.api.base_url,
ignoreResponseError: true,
headers: {
'Api-Username': config.discourse.api.username,
'Api-Key': config.discourse.api.key
}
});
if (response.status === 200) {
return true;
} else if (response.status === 404) {
return false;
} else {
throw new Error(`Discourse API error while checking if user ${pid} exists: ${response.status} - ${JSON.stringify(response._data)}`);
}
}

export async function syncDiscourseSso(pnid: GetUserDataResponse) {
const payload = await createDiscoursePayload('', pnid);
const body = new FormData();
body.set('sso', payload);
body.set('sig', getDicourseSignature(secret, payload));

// Documentation: https://meta.discourse.org/t/sync-discourseconnect-user-data-with-the-sync-sso-route/84398
await fetch(`/admin/users/sync_sso`, {
baseUrl: config.discourse.api.base_url,
body,
headers: {
'Api-Username': config.discourse.api.username,
'Api-Key': config.discourse.api.key
}
});
}
8 changes: 8 additions & 0 deletions server/utils/handleStripeWebhook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -308,5 +308,13 @@ export async function handleStripeEvent(event: H3Event, stripe: Stripe, webhook:
body: `${pnid.username}'s ${product.name} tier subscription status has been changed to ${subscription.status}`
});
}

try {
if (await discourseUserExists(pid)) {
await syncDiscourseSso(userData);
}
} catch (error) {
console.error(`Error syncing user Discourse SSO | ${pid} |`, error);
}
}
}
Loading