7
7
} from "../../common/config.js" ;
8
8
import {
9
9
BaseError ,
10
+ EntraFetchError ,
10
11
EntraGroupError ,
11
12
EntraInvitationError ,
12
13
InternalServerError ,
@@ -19,6 +20,7 @@ import {
19
20
EntraInvitationResponse ,
20
21
} from "../../common/types/iam.js" ;
21
22
import { FastifyInstance } from "fastify" ;
23
+ import { UserProfileDataBase } from "common/types/msGraphApi.js" ;
22
24
23
25
function validateGroupId ( groupId : string ) : boolean {
24
26
const groupIdPattern = / ^ [ a - z A - Z 0 - 9 - ] + $ / ; // Adjust the pattern as needed
@@ -351,3 +353,47 @@ export async function listGroupMembers(
351
353
} ) ;
352
354
}
353
355
}
356
+
357
+ /**
358
+ * Retrieves the profile of a user from Entra ID.
359
+ * @param token - Entra ID token authorized to perform this action.
360
+ * @param userId - The user ID to fetch the profile for.
361
+ * @throws {EntraUserError } If fetching the user profile fails.
362
+ * @returns {Promise<UserProfileDataBase> } The user's profile information.
363
+ */
364
+ export async function getUserProfile (
365
+ token : string ,
366
+ email : string ,
367
+ ) : Promise < UserProfileDataBase > {
368
+ const userId = await resolveEmailToOid ( token , email ) ;
369
+ try {
370
+ const url = `https://graph.microsoft.com/v1.0/users/${ userId } ?$select=userPrincipalName,givenName,surname,displayName,otherMails,mail` ;
371
+ const response = await fetch ( url , {
372
+ method : "GET" ,
373
+ headers : {
374
+ Authorization : `Bearer ${ token } ` ,
375
+ "Content-Type" : "application/json" ,
376
+ } ,
377
+ } ) ;
378
+
379
+ if ( ! response . ok ) {
380
+ const errorData = ( await response . json ( ) ) as {
381
+ error ?: { message ?: string } ;
382
+ } ;
383
+ throw new EntraFetchError ( {
384
+ message : errorData ?. error ?. message ?? response . statusText ,
385
+ email,
386
+ } ) ;
387
+ }
388
+ return ( await response . json ( ) ) as UserProfileDataBase ;
389
+ } catch ( error ) {
390
+ if ( error instanceof EntraFetchError ) {
391
+ throw error ;
392
+ }
393
+
394
+ throw new EntraFetchError ( {
395
+ message : error instanceof Error ? error . message : String ( error ) ,
396
+ email,
397
+ } ) ;
398
+ }
399
+ }
0 commit comments