Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 0 additions & 27 deletions Calendula.Console/LocalFileService.cs

This file was deleted.

8 changes: 4 additions & 4 deletions Calendula.Console/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
            DO NOT close this window until you see the final logging message.
");

var primaryAccountRefreshToken = configuration["PrimaryAccountRefreshToken"];
var primaryUsername = configuration["PrimaryAccountUsername"];
var primaryAccountSubjectPrefix = configuration["PrimaryAccountSubjectPrefix"];
var secondaryAccountRefreshToken = configuration["SecondaryAccountRefreshToken"];
var secondaryUsername = configuration["SecondaryAccountUsername"];
var secondaryAccountSubjectPrefix = configuration["SecondaryAccountSubjectPrefix"];
var hour24Time = int.Parse(configuration["Hour24Time"]);
var minute24Time = int.Parse(configuration["Minute24Time"]);
Expand Down Expand Up @@ -52,8 +52,8 @@
td.Actions.Add(new ExecAction($"{dir}/Calendula.Console.exe", dir, null));
ts.RootFolder.RegisterTaskDefinition(DailyTaskName, td);

var source = new SecondaryAccToPrimaryAccProfile(secondaryAccountRefreshToken, secondaryAccountSubjectPrefix);
var dest = new PrimaryAccToSecondaryAccProfile(primaryAccountRefreshToken, primaryAccountSubjectPrefix);
var source = new SecondaryAccToPrimaryAccProfile(secondaryUsername, secondaryAccountSubjectPrefix);
var dest = new PrimaryAccToSecondaryAccProfile(primaryUsername, primaryAccountSubjectPrefix);
var service = new CalendulaService(dest, source, logger, clientId, orgConnectionString);
var startTime = DateTime.UtcNow;
var endTime = startTime.AddDays(daysToSync);
Expand Down
14 changes: 0 additions & 14 deletions Calendula.Console/TokenFile.cs

This file was deleted.

72 changes: 51 additions & 21 deletions Calendula/AuthService.cs
Original file line number Diff line number Diff line change
@@ -1,34 +1,64 @@
using System.Text.Json;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Extensions.Msal;
using System.Text.Json;

namespace Calendula
{
public class AuthService
{
private readonly string ClientId = "";
private HttpClient Client { get; set; } = new HttpClient();
public AuthService(string clientId)
private const string TokenCacheFileName = "CalendulaTokenCache";

private IPublicClientApplication ClientApp;
private MsalCacheHelper Cache;

protected AuthService(IPublicClientApplication clientApp, MsalCacheHelper cache)
{
ClientId = clientId;
ClientApp = clientApp;
Cache = cache;
}

public async Task<RefreshTokenResponse> GetToken(string refreshToken)
public static async Task<AuthService> BuildAsync(string clientId)
{
var values = new Dictionary<string, string>()
var storageProperties = new StorageCreationPropertiesBuilder(TokenCacheFileName, MsalCacheHelper.UserRootDirectory)
.Build();

var cache = await MsalCacheHelper.CreateAsync(storageProperties);

var app = PublicClientApplicationBuilder.Create(clientId)
.WithRedirectUri("http://localhost")
.Build();

cache.RegisterCache(app.UserTokenCache);

return new AuthService(app, cache);
}

public async Task<string> GetToken(string username)
{
var accounts = await ClientApp.GetAccountsAsync();
var account = accounts.FirstOrDefault(a => a.Username == username);

var scopes = new[] { "offline_access", "https://graph.microsoft.com/Calendars.ReadWrite" };
AuthenticationResult authResult;

try
{
authResult = await ClientApp.AcquireTokenSilent(scopes, account)
.ExecuteAsync();
}
catch (MsalUiRequiredException)
{
["client_id"] = ClientId,
["grant_type"] = "refresh_token",
["scope"] = "offline_access Calendars.ReadWrite",
["refresh_token"] = refreshToken,
};
var body = new FormUrlEncodedContent(values);

using var response = await Client.PostAsync("https://login.microsoftonline.com/common/oauth2/v2.0/token", body);

var resp = await response.Content.ReadAsStringAsync();
using var stream = await response.Content.ReadAsStreamAsync();
response.EnsureSuccessStatusCode();
var responseBody = await JsonSerializer.DeserializeAsync<RefreshTokenResponse>(stream);
return responseBody;
var tokenBuilder = ClientApp.AcquireTokenInteractive(scopes)
.WithPrompt(Prompt.NoPrompt);

tokenBuilder = account == null
? tokenBuilder.WithLoginHint(username)
: tokenBuilder.WithAccount(account);

authResult = await tokenBuilder.ExecuteAsync();
}

return authResult.AccessToken;
}
}
}
10 changes: 5 additions & 5 deletions Calendula/CalendarSyncService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,16 @@ public CalendulaService(SyncProfile sourceProfile, SyncProfile destProfile, ILog

private async Task InitGraphClientsAsync()
{
var auth = new AuthService(ClientId);
var auth = await AuthService.BuildAsync(ClientId);
if (SourceGraph == null)
{
var response = await auth.GetToken(SourceProfile.RefreshToken);
SourceGraph = new GraphService(response.AccessToken);
var accessToken = await auth.GetToken(SourceProfile.Username);
SourceGraph = new GraphService(accessToken);
}
if (DestinationGraph == null)
{
var response = await auth.GetToken(DestinationProfile.RefreshToken);
DestinationGraph = new GraphService(response.AccessToken);
var accessToken = await auth.GetToken(DestinationProfile.Username);
DestinationGraph = new GraphService(accessToken);
}
}

Expand Down
2 changes: 2 additions & 0 deletions Calendula/Calendula.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

<ItemGroup>
<PackageReference Include="Microsoft.Graph" Version="4.47.0" />
<PackageReference Include="Microsoft.Identity.Client" Version="4.50.0" />
<PackageReference Include="Microsoft.Identity.Client.Extensions.Msal" Version="2.26.0" />
<PackageReference Include="Microsoft.PowerPlatform.Dataverse.Client" Version="1.0.26" />
</ItemGroup>

Expand Down
4 changes: 2 additions & 2 deletions Calendula/PrimaryAccToSecondaryAccProfile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ namespace Calendula
{
public class PrimaryAccToSecondaryAccProfile : SyncProfile
{
public PrimaryAccToSecondaryAccProfile(string refreshToken, string subjectPrefix)
public PrimaryAccToSecondaryAccProfile(string username, string subjectPrefix)
{
RefreshToken = refreshToken;
Username = username;
SubjectPrefix = subjectPrefix;
}

Expand Down
16 changes: 0 additions & 16 deletions Calendula/RefreshTokenResponse.cs

This file was deleted.

4 changes: 2 additions & 2 deletions Calendula/SecondaryAccToPrimaryAccProfile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ namespace Calendula
{
public class SecondaryAccToPrimaryAccProfile : SyncProfile
{
public SecondaryAccToPrimaryAccProfile(string refreshToken, string subjectPrefix)
public SecondaryAccToPrimaryAccProfile(string username, string subjectPrefix)
{
RefreshToken = refreshToken;
Username = username;
SubjectPrefix = subjectPrefix;
}

Expand Down
2 changes: 1 addition & 1 deletion Calendula/SyncProfile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace Calendula
public abstract class SyncProfile
{
public string SubjectPrefix { get; set; }
public string RefreshToken { get; set; }
public string Username { get; set; }
public abstract Event MapEvent(Event calendarEvent);
}
}