64 lines
1.4 KiB
C#
64 lines
1.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Threading.Tasks;
|
|
using Interlinked.Shared.Model;
|
|
|
|
namespace Interlinked.Core.Services;
|
|
|
|
public class UserManager
|
|
{
|
|
public UserManager(IServiceProvider serv)
|
|
{
|
|
_serv = serv;
|
|
}
|
|
|
|
private readonly IServiceProvider _serv;
|
|
private bool _init = false;
|
|
static SemaphoreSlim sem = new SemaphoreSlim(1, 1);
|
|
|
|
|
|
public async Task InitAsync()
|
|
{
|
|
await sem.WaitAsync();
|
|
if (_init)
|
|
{
|
|
sem.Release();
|
|
return;
|
|
}
|
|
|
|
using var scope = _serv.CreateAsyncScope();
|
|
var resp = await scope.ServiceProvider.GetRequiredService<HttpClient>().GetAsync("/api/auth/userdata");
|
|
if (resp.StatusCode == HttpStatusCode.OK)
|
|
{
|
|
this.User = (await resp.Content.ReadFromJsonAsync<UserModel>())!;
|
|
Console.WriteLine($"User: {User.Id}");
|
|
}
|
|
|
|
_init = true;
|
|
|
|
sem.Release();
|
|
}
|
|
|
|
private UserModel User { get; set; } = default!;
|
|
public async Task<UserModel?> GetUser()
|
|
{
|
|
if (User == null)
|
|
{
|
|
if (!_init)
|
|
{
|
|
await InitAsync();
|
|
}
|
|
}
|
|
|
|
return User;
|
|
}
|
|
|
|
public void SetUser(UserModel u)
|
|
{
|
|
User = u;
|
|
}
|
|
public bool IsAuthorized => User != null;
|
|
}
|