using Microsoft.Graph; using SharepointToolbox.Web.Core.Models; using SharepointToolbox.Web.Services; using SharepointToolbox.Web.Services.Session; namespace SharepointToolbox.Web.Infrastructure.Auth; /// /// Builds a Graph client for a profile. Certificate-configured profiles get an app-only /// client (no interactive sign-in); all others use the delegated OAuth2 refresh-token flow /// via ISessionManager. /// public class GraphClientFactory { private readonly ISessionCredentialStore _credentialStore; private readonly ISessionManager _sessionManager; private readonly IAppOnlyContextFactory _appOnly; public GraphClientFactory( ISessionCredentialStore credentialStore, ISessionManager sessionManager, IAppOnlyContextFactory appOnly) { _credentialStore = credentialStore; _sessionManager = sessionManager; _appOnly = appOnly; } public async Task CreateClientAsync(TenantProfile profile) { ArgumentException.ThrowIfNullOrEmpty(profile.TenantId); if (_appOnly.IsConfigured(profile)) return await _appOnly.CreateGraphClientAsync(profile); 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"]); } }