sharp-chat/SharpChat/Flashii/FlashiiAuth.cs

86 lines
2.8 KiB
C#
Raw Normal View History

2023-02-06 20:14:50 +00:00
using System;
using System.Net.Http;
2022-08-30 15:00:58 +00:00
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
2022-08-30 15:00:58 +00:00
namespace SharpChat.Flashii {
public class FlashiiAuthRequest {
[JsonPropertyName(@"user_id")]
public long UserId { get; set; }
[JsonPropertyName(@"token")]
public string Token { get; set; }
[JsonPropertyName(@"ip")]
public string IPAddress { get; set; }
[JsonIgnore]
public string Hash
=> string.Join(@"#", UserId, Token, IPAddress).GetSignedHash();
2023-02-07 15:01:56 +00:00
public byte[] GetJSON() {
return JsonSerializer.SerializeToUtf8Bytes(this);
}
2022-08-30 15:00:58 +00:00
}
public class FlashiiAuth {
[JsonPropertyName(@"success")]
public bool Success { get; set; }
[JsonPropertyName(@"reason")]
public string Reason { get; set; } = @"none";
[JsonPropertyName(@"user_id")]
public long UserId { get; set; }
[JsonPropertyName(@"username")]
public string Username { get; set; }
[JsonPropertyName(@"colour_raw")]
public int ColourRaw { get; set; }
[JsonPropertyName(@"hierarchy")]
public int Rank { get; set; }
[JsonPropertyName(@"is_silenced")]
public DateTimeOffset SilencedUntil { get; set; }
[JsonPropertyName(@"perms")]
public ChatUserPermissions Permissions { get; set; }
2023-02-06 20:14:50 +00:00
public static async Task<FlashiiAuth> AttemptAsync(HttpClient httpClient, FlashiiAuthRequest authRequest) {
if(httpClient == null)
throw new ArgumentNullException(nameof(httpClient));
2022-08-30 15:00:58 +00:00
if(authRequest == null)
throw new ArgumentNullException(nameof(authRequest));
#if DEBUG
2023-02-07 15:01:56 +00:00
if(authRequest.UserId >= 10000)
return new FlashiiAuth {
2022-08-30 15:00:58 +00:00
Success = true,
UserId = authRequest.UserId,
Username = @"Misaka-" + (authRequest.UserId - 10000),
ColourRaw = (RNG.Next(0, 255) << 16) | (RNG.Next(0, 255) << 8) | RNG.Next(0, 255),
Rank = 0,
SilencedUntil = DateTimeOffset.MinValue,
Permissions = ChatUserPermissions.SendMessage | ChatUserPermissions.EditOwnMessage | ChatUserPermissions.DeleteOwnMessage,
};
2022-08-30 15:00:58 +00:00
#endif
2023-02-06 20:14:50 +00:00
HttpRequestMessage request = new(HttpMethod.Post, FlashiiUrls.AuthURL) {
Content = new ByteArrayContent(authRequest.GetJSON()),
Headers = {
{ @"X-SharpChat-Signature", authRequest.Hash },
},
};
using HttpResponseMessage response = await httpClient.SendAsync(request);
return JsonSerializer.Deserialize<FlashiiAuth>(
await response.Content.ReadAsByteArrayAsync()
);
2022-08-30 15:00:58 +00:00
}
}
}