Wonky.Client/Wonky.Client/Local.Services/RefreshTokenService.cs
2023-06-01 17:28:51 +02:00

51 lines
No EOL
1.8 KiB
C#

// Copyright (C) 2022 FCS Frede's Computer Services.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see [https://www.gnu.org/licenses/agpl-3.0.en.html]
//
using Microsoft.AspNetCore.Components.Authorization;
namespace Wonky.Client.Local.Services;
public class RefreshTokenService
{
private readonly AuthenticationStateProvider _authStateProvider;
private readonly IAuthenticationService _authService;
private ILogger<RefreshTokenService> _logger;
public RefreshTokenService(AuthenticationStateProvider authProvider,
IAuthenticationService authService, ILogger<RefreshTokenService> logger)
{
_authStateProvider = authProvider;
_authService = authService;
_logger = logger;
}
public async Task<string> TryRefreshToken()
{
var authState = await _authStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
var expClaim = user.FindFirst(c => c.Type.Contains("exp"))?.Value;
var expTime = DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(expClaim));
var diff = expTime - DateTime.UtcNow;
return diff.TotalMinutes <= 10
? await _authService.RefreshToken()
: await _authService.AccessToken();
}
}