Gordon Pedersen
5fb95c8305
Unfortunately it does not refresh at first login. Have to figure out how to make it refresh
70 lines
2.5 KiB
C#
70 lines
2.5 KiB
C#
using Microsoft.AspNetCore.Components.Authorization;
|
|
using Neighbourhood.omg.lol.Models;
|
|
using System.Security.Claims;
|
|
|
|
namespace Neighbourhood.omg.lol {
|
|
public class CustomAuthenticationStateProvider : AuthenticationStateProvider {
|
|
public CustomAuthenticationStateProvider() {
|
|
}
|
|
|
|
public async Task Login(string token) {
|
|
await SecureStorage.SetAsync("accounttoken", token);
|
|
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
|
}
|
|
|
|
public async Task Logout() {
|
|
SecureStorage.Remove("accounttoken");
|
|
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
|
}
|
|
|
|
public override async Task<AuthenticationState> GetAuthenticationStateAsync() {
|
|
var identity = new ClaimsIdentity();
|
|
try {
|
|
var token = await SecureStorage.GetAsync("accounttoken");
|
|
if (token != null) {
|
|
var name = await SecureStorage.GetAsync("accountname");
|
|
var email = await SecureStorage.GetAsync("accountemail");
|
|
var addresses = await SecureStorage.GetAsync("accountaddresses");
|
|
|
|
RestService api = new RestService(token);
|
|
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(email)) {
|
|
AccountResponseData? accountInfo = await api.AccountInfo();
|
|
if (accountInfo != null) {
|
|
name = accountInfo.Name;
|
|
email = accountInfo.Email;
|
|
}
|
|
}
|
|
if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(email)) {
|
|
if (string.IsNullOrEmpty(addresses)) {
|
|
AddressResponseList? addressList = await api.Addresses();
|
|
List<string> addressStrings = new List<string>();
|
|
if (addressList != null) foreach (var address in addressList) {
|
|
if (!address.Expiration.Expired && !string.IsNullOrEmpty(address.Address)) {
|
|
addressStrings.Add(address.Address);
|
|
}
|
|
}
|
|
addresses = string.Join(',', addressStrings);
|
|
}
|
|
if(!string.IsNullOrEmpty(addresses)) {
|
|
await SecureStorage.SetAsync("accountname", name);
|
|
await SecureStorage.SetAsync("accountemail", email);
|
|
await SecureStorage.SetAsync("accountaddresses", addresses);
|
|
}
|
|
|
|
var claims = new[] {
|
|
new Claim(ClaimTypes.Name, name),
|
|
new Claim(ClaimTypes.Email, email),
|
|
new Claim("addresses", addresses)
|
|
};
|
|
identity = new ClaimsIdentity(claims, "Server authentication");
|
|
}
|
|
}
|
|
}
|
|
catch (HttpRequestException ex) {
|
|
Console.WriteLine("Request failed:" + ex.ToString());
|
|
}
|
|
|
|
return new AuthenticationState(new ClaimsPrincipal(identity));
|
|
}
|
|
}
|
|
}
|