Files
upstream-rocketchat/apps/meteor/client/providers/AuthenticationProvider/AuthenticationProvider.tsx
upstream-mirror 30810eecd7
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 2s
snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
2026-09-16 01:21:02 +05:00

177 lines
6.0 KiB
TypeScript

import type { LoginServiceConfiguration } from '@rocket.chat/core-typings';
import { capitalize } from '@rocket.chat/tools';
import { AuthenticationContext, useSetting } from '@rocket.chat/ui-contexts';
import { Accounts } from 'meteor/accounts-base';
import { Meteor } from 'meteor/meteor';
import type { ContextType, ReactNode } from 'react';
import { useMemo, useSyncExternalStore } from 'react';
import { useLDAPAndCrowdCollisionWarning } from './hooks/useLDAPAndCrowdCollisionWarning';
import { capitalize as capitalizeService } from '../../../lib/utils/stringUtils';
import { loginServices } from '../../lib/loginServices';
import { getDdpSdk } from '../../lib/sdk/ddpSdk';
import { STORAGE_KEYS, getStoredItem, removeStoredItem } from '../../lib/sdk/storage';
export type LoginMethods = keyof typeof Meteor extends infer T ? (T extends `loginWith${string}` ? T : never) : never;
export type AuthenticationProviderProps = {
children: ReactNode;
};
const callLoginMethod = (
options: { loginToken?: string; token?: string; iframe?: boolean },
userCallback: ((err?: any) => void) | undefined,
) => {
Accounts.callLoginMethod({
methodArguments: [options],
userCallback,
});
};
// Bridge Accounts.loggingIn() — Meteor's Tracker-reactive flag — into a
// non-reactive subscribe/getSnapshot pair for useSyncExternalStore. We hook
// `_setLoggingIn` (Meteor's internal flip, also accessed in
// apps/meteor/client/meteor/overrides/killMeteorStream.ts) to fan out
// transitions without entering a Tracker computation.
const loggingInListeners = new Set<() => void>();
let loggingInBridgeInstalled = false;
const installLoggingInBridge = (): void => {
if (loggingInBridgeInstalled) return;
loggingInBridgeInstalled = true;
const wrap = Accounts as unknown as { _setLoggingIn?: (v: boolean) => void };
const original = wrap._setLoggingIn;
if (typeof original !== 'function') return;
wrap._setLoggingIn = function (this: typeof Accounts, v: boolean) {
original.call(this, v);
loggingInListeners.forEach((cb) => cb());
};
};
const subscribeLoggingIn = (cb: () => void): (() => void) => {
installLoggingInBridge();
loggingInListeners.add(cb);
return () => {
loggingInListeners.delete(cb);
};
};
const getLoggingInSnapshot = (): boolean => Accounts.loggingIn();
const AuthenticationProvider = ({ children }: AuthenticationProviderProps) => {
const isLdapEnabled = useSetting('LDAP_Enable', false);
const isCrowdEnabled = useSetting('CROWD_Enable', false);
const loginMethod: LoginMethods = (isLdapEnabled && 'loginWithLDAP') || (isCrowdEnabled && 'loginWithCrowd') || 'loginWithPassword';
useLDAPAndCrowdCollisionWarning();
const isLoggingIn = useSyncExternalStore(subscribeLoggingIn, getLoggingInSnapshot);
const contextValue = useMemo(
(): ContextType<typeof AuthenticationContext> => ({
isLoggingIn,
loginWithToken: (token: string, callback): Promise<void> =>
new Promise((resolve, reject) =>
Meteor.loginWithToken(token, (err) => {
if (err) {
console.error(err);
callback?.(err);
return reject(err);
}
resolve(undefined);
}),
),
loginWithPassword: (user: string | { username: string } | { email: string } | { id: string }, password: string): Promise<void> =>
new Promise((resolve, reject) => {
Meteor[loginMethod](user, password, (error) => {
if (error) {
reject(error);
return;
}
resolve();
});
}),
loginWithService: <T extends LoginServiceConfiguration>(serviceConfig: T): (() => Promise<true>) => {
const loginMethods: Record<string, string | undefined> = {
'meteor-developer': 'MeteorDeveloperAccount',
};
const { service: serviceName } = serviceConfig;
const clientConfig = ('clientConfig' in serviceConfig && serviceConfig.clientConfig) || {};
const loginWithService = `loginWith${loginMethods[serviceName] || capitalize(String(serviceName || ''))}`;
const method: (config: unknown, cb: (error: any) => void) => Promise<true> = (Meteor as any)[loginWithService];
if (!method) {
return () => Promise.reject(new Error('Login method not found'));
}
return () =>
new Promise((resolve, reject) => {
method(clientConfig, (error: any): void => {
if (!error) {
resolve(true);
return;
}
reject(error);
});
});
},
loginWithCustomOauth: (service: string, options: { redirectUrl: string }, callback) => {
const methodName = `loginWith${capitalizeService(service, true)}`;
const method = (Meteor as any)[methodName] as
((options: { redirectUrl: string }, cb?: (response: unknown) => void) => void) | undefined;
if (!method) {
return;
}
method.call(Meteor, options, callback);
},
loginWithIframe: (token: string, callback) =>
new Promise<void>((resolve, reject) => {
callLoginMethod({ iframe: true, token }, (error) => {
if (error) {
console.error(error);
callback?.(error);
return reject(error);
}
resolve();
});
}),
loginWithTokenRoute: (token: string, callback) =>
new Promise<void>((resolve, reject) => {
callLoginMethod({ token }, (error) => {
if (error) {
console.error(error);
callback?.(error);
return reject(error);
}
resolve();
});
}),
getLoginToken: () => getStoredItem(STORAGE_KEYS.LOGIN_TOKEN),
wipeLocalAuth: () => {
removeStoredItem(STORAGE_KEYS.USER_ID);
removeStoredItem(STORAGE_KEYS.LOGIN_TOKEN);
removeStoredItem(STORAGE_KEYS.LOGIN_TOKEN_EXPIRES);
try {
Meteor.connection.setUserId(null);
} catch {
// ignore
}
},
unstoreLoginToken: (callback) => getDdpSdk().account.onLogout(callback),
queryLoginServices: {
getCurrentValue: () => loginServices.getLoginServiceButtons(),
subscribe: (onStoreChange: () => void) => loginServices.on('changed', onStoreChange),
},
}),
[isLoggingIn, loginMethod],
);
return <AuthenticationContext.Provider value={contextValue}>{children}</AuthenticationContext.Provider>;
};
export default AuthenticationProvider;