77} from "../../common/config.js" ;
88import {
99 BaseError ,
10+ EntraFetchError ,
1011 EntraGroupError ,
1112 EntraInvitationError ,
1213 InternalServerError ,
@@ -19,6 +20,7 @@ import {
1920 EntraInvitationResponse ,
2021} from "../../common/types/iam.js" ;
2122import { FastifyInstance } from "fastify" ;
23+ import { UserProfileDataBase } from "common/types/msGraphApi.js" ;
2224
2325function validateGroupId ( groupId : string ) : boolean {
2426 const groupIdPattern = / ^ [ a - z A - Z 0 - 9 - ] + $ / ; // Adjust the pattern as needed
@@ -351,3 +353,47 @@ export async function listGroupMembers(
351353 } ) ;
352354 }
353355}
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