using Microsoft.Graph; using SharepointToolbox.Web.Core.Models; using SharepointToolbox.Web.Services; using SharepointToolbox.Web.Services.Session; namespace SharepointToolbox.Web.Infrastructure.Auth; /// Delegated Graph client using OAuth2 refresh-token flow via ISessionManager. public class GraphClientFactory { private readonly ISessionCredentialStore _credentialStore; private readonly ISessionManager _sessionManager; public GraphClientFactory(ISessionCredentialStore credentialStore, ISessionManager sessionManager) { _credentialStore = credentialStore; _sessionManager = sessionManager; } public async Task CreateClientAsync(TenantProfile profile) { ArgumentException.ThrowIfNullOrEmpty(profile.TenantId); var hasTokens = await _credentialStore.HasCredentialsAsync(); if (!hasTokens) throw new InvalidOperationException( "No session tokens found. Please authenticate via Microsoft first."); var credential = new SessionTokenCredential(_sessionManager); return new GraphServiceClient(credential, ["https://graph.microsoft.com/.default"]); } }