Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | 1x 1x 1x 1x 1x 1x 1x | import axios, {AxiosInstance} from 'axios';
import {bind, BindingScope} from '@loopback/core';
@bind({scope: BindingScope.TRANSIENT})
export class MicrosoftGraphService {
private readonly tenantId = process.env.MS_TENANT_ID ?? '';
private readonly clientId = process.env.MS_CLIENT_ID ?? '';
private readonly clientSecret = process.env.MS_CLIENT_SECRET ?? '';
private readonly graphClient: AxiosInstance;
constructor() {
this.graphClient = axios.create({
baseURL: 'https://graph.microsoft.com/v1.0',
headers: {
'Content-Type': 'application/json',
},
});
}
private async getAccessToken(): Promise<string> {
const params = new URLSearchParams({
client_id: this.clientId,
client_secret: this.clientSecret,
grant_type: 'client_credentials',
scope: 'https://graph.microsoft.com/.default',
});
const {data} = await axios.post(
`https://login.microsoftonline.com/${this.tenantId}/oauth2/v2.0/token`,
params.toString(),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
},
);
return data.access_token;
}
private async getAuthHeaders() {
const accessToken = await this.getAccessToken();
return {
Authorization: `Bearer ${accessToken}`,
};
}
async findUser(email: string) {
const headers = await this.getAuthHeaders();
const {data} = await this.graphClient.get('/users', {
headers,
params: {
$filter: `mail eq '${email}' or userPrincipalName eq '${email}'`,
},
});
return data.value?.[0] ?? null;
}
async inviteUser(email: string, redirectUrl?: string) {
try {
const headers = await this.getAuthHeaders();
const {data} = await this.graphClient.post(
'/invitations',
{
invitedUserEmailAddress: email,
inviteRedirectUrl: redirectUrl ?? 'http://localhost:4200',
sendInvitationMessage: false,
},
{headers},
);
return data;
} catch (err: any) {
console.error('Graph Error:', JSON.stringify(err.response?.data, null, 2));
throw err;
}
}
}
|