All checks were successful
Create and publish a Docker image / Publish image (push) Successful in 3m0s
86 lines
3.1 KiB
C#
86 lines
3.1 KiB
C#
using Microsoft.Playwright;
|
||
using Quartz;
|
||
|
||
namespace SfeduSchedule.Jobs;
|
||
|
||
public class UpdateJwtJob(IConfiguration configuration, ILogger<UpdateJwtJob> logger) : IJob
|
||
{
|
||
public async Task Execute(IJobExecutionContext jobContext)
|
||
{
|
||
logger.LogInformation("Начало выполнения UpdateJwtJob");
|
||
|
||
string? username = configuration["MS_USERNAME"];
|
||
string? password = configuration["MS_PASSWORD"];
|
||
|
||
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
|
||
{
|
||
logger.LogError("Не указаны учетные данные для входа");
|
||
return;
|
||
}
|
||
|
||
using var playwright = await Playwright.CreateAsync();
|
||
await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
|
||
{
|
||
Headless = true
|
||
});
|
||
var context = await browser.NewContextAsync(new BrowserNewContextOptions
|
||
{
|
||
ViewportSize = null
|
||
});
|
||
var page = await context.NewPageAsync();
|
||
|
||
try
|
||
{
|
||
logger.LogInformation("Начало выполнения авторизации Microsoft");
|
||
await MicrosoftLoginHelper.LoginMicrosoftAsync(page, username, password);
|
||
|
||
var sessionStorageJson = await page.EvaluateAsync<string>(@"
|
||
JSON.stringify(sessionStorage)
|
||
");
|
||
|
||
// Извлечение id_token из sessionStorageJson
|
||
string? idToken = null;
|
||
try
|
||
{
|
||
var sessionStorageDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(sessionStorageJson);
|
||
if (sessionStorageDict != null)
|
||
{
|
||
var oidcKey = sessionStorageDict.Keys.FirstOrDefault(k => k.StartsWith("oidc.user:"));
|
||
if (oidcKey != null)
|
||
{
|
||
var oidcValueJson = sessionStorageDict[oidcKey]?.ToString();
|
||
if (!string.IsNullOrEmpty(oidcValueJson))
|
||
{
|
||
using var doc = System.Text.Json.JsonDocument.Parse(oidcValueJson);
|
||
if (doc.RootElement.TryGetProperty("id_token", out var idTokenElement))
|
||
{
|
||
idToken = idTokenElement.GetString();
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
logger.LogError(ex, "Ошибка при извлечении id_token из sessionStorageJson");
|
||
return;
|
||
}
|
||
|
||
configuration["TOKEN"] = idToken;
|
||
|
||
await File.WriteAllTextAsync(GlobalVariables.JwtFilePath, idToken + "\n" + DateTime.Now.ToString("O"));
|
||
|
||
logger.LogInformation("UpdateJwtJob выполнен успешно");
|
||
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
logger.LogError(ex, "Ошибка при выполнении UpdateJwtJob");
|
||
}
|
||
finally
|
||
{
|
||
await context.CloseAsync();
|
||
await browser.CloseAsync();
|
||
}
|
||
}
|
||
} |