sharp-chat/SharpChat/Flashii/FlashiiAuth.cs

82 lines
2.7 KiB
C#
Raw Normal View History

2022-08-30 15:00:58 +00:00
using Hamakaze;
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
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();
public byte[] GetJSON()
=> JsonSerializer.SerializeToUtf8Bytes(this);
}
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; }
public static void Attempt(FlashiiAuthRequest authRequest, Action<FlashiiAuth> onComplete, Action<Exception> onError) {
if(authRequest == null)
throw new ArgumentNullException(nameof(authRequest));
#if DEBUG
if(authRequest.UserId >= 10000) {
onComplete(new FlashiiAuth {
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,
});
return;
}
#endif
HttpRequestMessage hrm = new HttpRequestMessage(@"POST", FlashiiUrls.AUTH);
hrm.AddHeader(@"X-SharpChat-Signature", authRequest.Hash);
hrm.SetBody(authRequest.GetJSON());
HttpClient.Send(hrm, (t, r) => {
try {
onComplete(JsonSerializer.Deserialize<FlashiiAuth>(r.GetBodyBytes()));
} catch(Exception ex) {
onError(ex);
}
}, (t, e) => onError(e));
}
}
}