2022-10-07 04:23:29 +03:00
|
|
|
//
|
|
|
|
// Copyright (c) Microsoft.
|
|
|
|
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
|
|
//
|
|
|
|
|
|
|
|
import { jsonError } from '..';
|
|
|
|
import { IProviders, ReposAppRequest } from '../../interfaces';
|
2024-01-03 22:44:13 +03:00
|
|
|
import { ErrorHelper, getProviders } from '../../lib/transitional';
|
2023-05-11 23:07:14 +03:00
|
|
|
import { IndividualContext } from '../../business/user';
|
2022-10-07 04:23:29 +03:00
|
|
|
|
|
|
|
const cachedCorporateMailRequestKey = '__corporateMail';
|
|
|
|
|
2022-10-08 01:25:28 +03:00
|
|
|
export async function getCorporateMailFromRequest(req: ReposAppRequest): Promise<string> {
|
2022-10-07 04:23:29 +03:00
|
|
|
if (req[cachedCorporateMailRequestKey]) {
|
|
|
|
return req[cachedCorporateMailRequestKey];
|
|
|
|
}
|
2022-10-08 01:25:28 +03:00
|
|
|
const activeContext = (req.individualContext || req.apiContext) as IndividualContext;
|
2022-10-07 04:23:29 +03:00
|
|
|
const providers = getProviders(req);
|
2022-10-08 01:25:28 +03:00
|
|
|
const corporateAlias = await getCorporateMailFromActiveContext(providers, activeContext);
|
2022-10-07 04:23:29 +03:00
|
|
|
req[cachedCorporateMailRequestKey] = corporateAlias;
|
|
|
|
return corporateAlias;
|
|
|
|
}
|
|
|
|
|
2022-10-07 09:59:30 +03:00
|
|
|
export async function getCorporateMailFromActiveContext(
|
|
|
|
providers: IProviders,
|
|
|
|
activeContext: IndividualContext
|
|
|
|
): Promise<string> {
|
2022-10-07 04:23:29 +03:00
|
|
|
if (!activeContext.corporateIdentity || !activeContext.corporateIdentity.id) {
|
|
|
|
throw jsonError('No corporate identity', 401);
|
|
|
|
}
|
|
|
|
let corporateMail = activeContext?.link?.corporateMailAddress;
|
|
|
|
if (!corporateMail) {
|
2023-07-13 07:00:23 +03:00
|
|
|
const mail = await tryGetCorporateMailFromId(providers, activeContext.corporateIdentity.id);
|
|
|
|
if (!mail) {
|
2022-10-07 04:23:29 +03:00
|
|
|
throw jsonError('Invalid corporate identity', 401);
|
|
|
|
}
|
2023-07-13 07:00:23 +03:00
|
|
|
corporateMail = mail;
|
2022-10-07 04:23:29 +03:00
|
|
|
}
|
|
|
|
return corporateMail;
|
|
|
|
}
|
2023-07-13 07:00:23 +03:00
|
|
|
|
|
|
|
export async function tryGetCorporateMailFromId(providers: IProviders, corporateId: string): Promise<string> {
|
|
|
|
const { graphProvider } = providers;
|
|
|
|
try {
|
|
|
|
const info = await graphProvider.getUserById(corporateId);
|
|
|
|
if (info?.mail) {
|
|
|
|
return info.mail;
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
if (!ErrorHelper.IsNotFound(error)) {
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|