11import { HttpRequest } from '@azure/functions' ;
22import { DefaultAzureCredential , getBearerTokenProvider } from '@azure/identity' ;
3+ import { UserDbService } from './user-db-service' ;
34
45const azureOpenAiScope = 'https://cognitiveservices.azure.com/.default' ;
56
@@ -17,18 +18,31 @@ export function getAzureOpenAiTokenProvider() {
1718 return getBearerTokenProvider ( getCredentials ( ) , azureOpenAiScope ) ;
1819}
1920
20- export function getUserId ( request : HttpRequest , body ?: any ) : string | undefined {
21+ export function getAuthenticationUserId ( request : HttpRequest , body ?: any ) : string | undefined {
2122 let userId : string | undefined ;
2223
23- // Get the user ID from Azure easy auth if it's available
24+ // Get the user ID from Azure easy auth
2425 try {
2526 const token = Buffer . from ( request . headers . get ( 'x-ms-client-principal' ) ?? '' , 'base64' ) . toString ( 'ascii' ) ;
2627 const infos = token && JSON . parse ( token ) ;
2728 userId = infos ?. userId ;
2829 } catch { }
2930
30- // Get the user ID from the request as a fallback
31- userId ??= body ?. context ?. userId ?? request . query . get ( 'userId' ) ?? undefined ;
32-
3331 return userId ;
3432}
33+
34+ export async function getInternalUserId ( request : HttpRequest , body ?: any ) : Promise < string | undefined > {
35+ // Get the user ID from Azure easy auth if it's available,
36+ let authUserId = getAuthenticationUserId ( request , body ) ;
37+ if ( authUserId ) {
38+ // Exchange the auth user ID to the internal user ID
39+ const db = await UserDbService . getInstance ( ) ;
40+ let user = await db . getUserById ( authUserId ) ;
41+ if ( user ) {
42+ return user . id ;
43+ }
44+ }
45+
46+ // Get the user ID from the request as a fallback
47+ return body ?. context ?. userId ?? request . query . get ( 'userId' ) ?? undefined ;
48+ }
0 commit comments