diff options
author | vnugent <public@vaughnnugent.com> | 2023-01-12 17:47:40 -0500 |
---|---|---|
committer | vnugent <public@vaughnnugent.com> | 2023-01-12 17:47:40 -0500 |
commit | 551066ed9a255bd47c1c5789ec1998fda64bd5aa (patch) | |
tree | d6caceb0e7caa44478c6611903b4b7e120964c89 /VNLib.Plugins.Essentials.SocialOauth/Endpoints | |
parent | b6481038bc6573af30492e9ce52b36d9f64195f3 (diff) |
Large project reorder and consolidation
Diffstat (limited to 'VNLib.Plugins.Essentials.SocialOauth/Endpoints')
3 files changed, 0 insertions, 572 deletions
diff --git a/VNLib.Plugins.Essentials.SocialOauth/Endpoints/Auth0.cs b/VNLib.Plugins.Essentials.SocialOauth/Endpoints/Auth0.cs deleted file mode 100644 index c7512b7..0000000 --- a/VNLib.Plugins.Essentials.SocialOauth/Endpoints/Auth0.cs +++ /dev/null @@ -1,195 +0,0 @@ -/* -* Copyright (c) 2022 Vaughn Nugent -* -* Library: VNLib -* Package: VNLib.Plugins.Essentials.SocialOauth -* File: Auth0.cs -* -* Auth0.cs is part of VNLib.Plugins.Essentials.SocialOauth which is part of the larger -* VNLib collection of libraries and utilities. -* -* VNLib.Plugins.Essentials.SocialOauth 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. -* -* VNLib.Plugins.Essentials.SocialOauth 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/. -*/ - -using System; -using System.Linq; -using System.Text; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using System.Collections.Generic; - -using RestSharp; - -using VNLib.Net.Rest.Client; -using VNLib.Hashing; -using VNLib.Hashing.IdentityUtility; -using VNLib.Utils.Logging; -using VNLib.Plugins.Essentials.Accounts; -using VNLib.Plugins.Extensions.Loading; -using VNLib.Plugins.Extensions.Loading.Users; - -namespace VNLib.Plugins.Essentials.SocialOauth.Endpoints -{ - - [ConfigurationName("auth0")] - internal sealed class Auth0 : SocialOauthBase - { - - protected override OauthClientConfig Config { get; } - - - private readonly Task<JsonDocument> Auth0VerificationJwk; - - public Auth0(PluginBase plugin, IReadOnlyDictionary<string, JsonElement> config) : base() - { - string keyUrl = config["key_url"].GetString() ?? throw new KeyNotFoundException("Missing Auth0 'key_url' from config"); - - Uri keyUri = new(keyUrl); - - //Get certificate on background thread - Auth0VerificationJwk = Task.Run(() => GetRsaCertificate(keyUri)); - - Config = new("auth0", config) - { - Passwords = plugin.GetPasswords(), - Users = plugin.GetUserManager(), - }; - - InitPathAndLog(Config.EndpointPath, plugin.Log); - - //Load secrets - _ = plugin.DeferTask(async () => - { - //Get id/secret - Task<SecretResult?> secretTask = plugin.TryGetSecretAsync("auth0_client_secret"); - Task<SecretResult?> clientIdTask = plugin.TryGetSecretAsync("auth0_client_id"); - - await Task.WhenAll(secretTask, clientIdTask); - - using SecretResult? secret = await secretTask; - using SecretResult? clientId = await clientIdTask; - - Config.ClientID = clientId?.Result.ToString() ?? throw new KeyNotFoundException("Missing Auth0 client id from config or vault"); - Config.ClientSecret = secret?.Result.ToString() ?? throw new KeyNotFoundException("Missing the Auth0 client secret from config or vault"); - - }, 100); - } - - - private async Task<JsonDocument> GetRsaCertificate(Uri certUri) - { - try - { - Log.Debug("Getting Auth0 signing keys"); - //Get key request - RestRequest keyRequest = new(certUri, Method.Get); - keyRequest.AddHeader("Accept", "application/json"); - - //rent client from pool - using ClientContract client = ClientPool.Lease(); - - RestResponse response = await client.Resource.ExecuteAsync(keyRequest); - - response.ThrowIfError(); - - return JsonDocument.Parse(response.RawBytes); - } - catch (Exception e) - { - Log.Error(e, "Failed to get Auth0 signing keys"); - throw; - } - } - - /* - * Account data may be recovered from the identity token - * and it happens after a call to GetLoginData so - * we do not need to re-verify the token - */ - protected override Task<AccountData?> GetAccountDataAsync(IOAuthAccessState clientAccess, CancellationToken cancellationToken) - { - using JsonWebToken jwt = JsonWebToken.Parse(clientAccess.IdToken); - - //verify signature - - using JsonDocument userData = jwt.GetPayload(); - - if (!userData.RootElement.GetProperty("email_verified").GetBoolean()) - { - return Task.FromResult<AccountData?>(null); - } - - string fullName = userData.RootElement.GetProperty("name").GetString() ?? " "; - - return Task.FromResult<AccountData?>(new AccountData() - { - EmailAddress = userData.RootElement.GetProperty("email").GetString(), - First = fullName.Split(' ')[0], - Last = fullName.Split(' ')[1], - }); - } - - private static string GetUserIdFromPlatform(string userName) - { - /* - * Auth0 uses the format "platoform|{user_id}" for the user id so it should match the - * external platofrm as github and discord endoints also - */ - - return ManagedHash.ComputeHash(userName, HashAlg.SHA1, HashEncodingMode.Hexadecimal); - } - - - private static readonly Task<UserLoginData?> EmptyLoginData = Task.FromResult<UserLoginData?>(null); - - protected override Task<UserLoginData?> GetLoginDataAsync(IOAuthAccessState clientAccess, CancellationToken cancellation) - { - using JsonWebToken jwt = JsonWebToken.Parse(clientAccess.IdToken); - - //Verify the token against the first signing key - if (!jwt.VerifyFromJwk(Auth0VerificationJwk.Result.RootElement.GetProperty("keys").EnumerateArray().First())) - { - return EmptyLoginData; - } - - using JsonDocument userData = jwt.GetPayload(); - - int iat = userData.RootElement.GetProperty("iat").GetInt32(); - int exp = userData.RootElement.GetProperty("exp").GetInt32(); - - string userId = userData.RootElement.GetProperty("sub").GetString() ?? throw new Exception("Missing sub in jwt"); - string audience = userData.RootElement.GetProperty("aud").GetString() ?? throw new Exception("Missing aud in jwt"); - string issuer = userData.RootElement.GetProperty("iss").GetString() ?? throw new Exception("Missing iss in jwt"); - - if(exp < DateTimeOffset.UtcNow.ToUnixTimeSeconds()) - { - //Expired - return EmptyLoginData; - } - - //Verify audience matches client id - if (!Config.ClientID.Equals(audience, StringComparison.Ordinal)) - { - //Invalid audience - return EmptyLoginData; - } - - return Task.FromResult<UserLoginData?>(new UserLoginData() - { - UserId = GetUserIdFromPlatform(userId) - }); - } - } -} diff --git a/VNLib.Plugins.Essentials.SocialOauth/Endpoints/DiscordOauth.cs b/VNLib.Plugins.Essentials.SocialOauth/Endpoints/DiscordOauth.cs deleted file mode 100644 index d8b2394..0000000 --- a/VNLib.Plugins.Essentials.SocialOauth/Endpoints/DiscordOauth.cs +++ /dev/null @@ -1,158 +0,0 @@ -/* -* Copyright (c) 2022 Vaughn Nugent -* -* Library: VNLib -* Package: VNLib.Plugins.Essentials.SocialOauth -* File: DiscordOauth.cs -* -* DiscordOauth.cs is part of VNLib.Plugins.Essentials.SocialOauth which is part of the larger -* VNLib collection of libraries and utilities. -* -* VNLib.Plugins.Essentials.SocialOauth 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. -* -* VNLib.Plugins.Essentials.SocialOauth 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/. -*/ - -using System; -using System.Text; -using System.Threading; -using System.Text.Json; -using System.Threading.Tasks; -using System.Collections.Generic; -using System.Text.Json.Serialization; - -using RestSharp; - -using VNLib.Hashing; -using VNLib.Utils.Logging; -using VNLib.Net.Rest.Client; -using VNLib.Plugins.Essentials.Accounts; -using VNLib.Plugins.Extensions.Loading; -using VNLib.Plugins.Extensions.Loading.Users; - - -namespace VNLib.Plugins.Essentials.SocialOauth.Endpoints -{ - [ConfigurationName("discord")] - internal sealed class DiscordOauth : SocialOauthBase - { - protected override OauthClientConfig Config { get; } - - public DiscordOauth(PluginBase plugin, IReadOnlyDictionary<string, JsonElement> config) : base() - { - Config = new("discord", config) - { - Passwords = plugin.GetPasswords(), - Users = plugin.GetUserManager(), - }; - - InitPathAndLog(Config.EndpointPath, plugin.Log); - - //Load secrets - _ = plugin.DeferTask(async () => - { - //Get id/secret - Task<SecretResult?> clientIdTask = plugin.TryGetSecretAsync("discord_client_id"); - Task<SecretResult?> secretTask = plugin.TryGetSecretAsync("discord_client_secret"); - - await Task.WhenAll(secretTask, clientIdTask); - - using SecretResult? secret = await secretTask; - using SecretResult? clientId = await clientIdTask; - - Config.ClientID = clientId?.Result.ToString() ?? throw new KeyNotFoundException("Missing Discord client id from config or vault"); - Config.ClientSecret = secret?.Result.ToString() ?? throw new KeyNotFoundException("Missing the Discord client secret from config or vault"); - - }, 100); - } - - - private static string GetUserIdFromPlatform(string userName) - { - return ManagedHash.ComputeHash($"discord|{userName}", HashAlg.SHA1, HashEncodingMode.Hexadecimal); - } - - - /* - * Matches the profile endpoint (@me) json object - */ - private sealed class UserProfile - { - [JsonPropertyName("username")] - public string? Username { get; set; } - [JsonPropertyName("id")] - public string? UserID { get; set; } - [JsonPropertyName("url")] - public string? ProfileUrl { get; set; } - [JsonPropertyName("verified")] - public bool Verified { get; set; } - [JsonPropertyName("email")] - public string? EmailAddress { get; set; } - } - - - protected override async Task<AccountData?> GetAccountDataAsync(IOAuthAccessState accessToken, CancellationToken cancellationToken) - { - //Get the user's email address's - RestRequest request = new(Config.UserDataUrl); - //Add authorization token - request.AddHeader("Authorization", $"{accessToken.Type} {accessToken.Token}"); - //Get client from pool - using ClientContract client = ClientPool.Lease(); - //get user's profile data - RestResponse<UserProfile> getProfileResponse = await client.Resource.ExecuteAsync<UserProfile>(request, cancellationToken: cancellationToken); - //Check response - if (!getProfileResponse.IsSuccessful || getProfileResponse.Data == null) - { - Log.Debug("Discord user request responded with code {code}:{data}", getProfileResponse.StatusCode, getProfileResponse.Content); - return null; - } - UserProfile discordProfile = getProfileResponse.Data; - //Make sure the user's account is verified - if (!discordProfile.Verified) - { - return null; - } - return new() - { - EmailAddress = discordProfile.EmailAddress, - First = discordProfile.Username, - }; - } - - protected override async Task<UserLoginData?> GetLoginDataAsync(IOAuthAccessState accessToken, CancellationToken cancellationToken) - { - //Get the user's email address's - RestRequest request = new(Config.UserDataUrl); - //Add authorization token - request.AddHeader("Authorization", $"{accessToken.Type} {accessToken.Token}"); - //Get client from pool - using ClientContract client = ClientPool.Lease(); - //get user's profile data - RestResponse<UserProfile> getProfileResponse = await client.Resource.ExecuteAsync<UserProfile>(request, cancellationToken: cancellationToken); - //Check response - if (!getProfileResponse.IsSuccessful || getProfileResponse.Data?.UserID == null) - { - Log.Debug("Discord user request responded with code {code}:{data}", getProfileResponse.StatusCode, getProfileResponse.Content); - return null; - } - - UserProfile discordProfile = getProfileResponse.Data; - - return new() - { - //Get unique user-id from the discord profile and sha1 hex hash to store in db - UserId = GetUserIdFromPlatform(discordProfile.UserID) - }; - } - } -}
\ No newline at end of file diff --git a/VNLib.Plugins.Essentials.SocialOauth/Endpoints/GitHubOauth.cs b/VNLib.Plugins.Essentials.SocialOauth/Endpoints/GitHubOauth.cs deleted file mode 100644 index 676f2bb..0000000 --- a/VNLib.Plugins.Essentials.SocialOauth/Endpoints/GitHubOauth.cs +++ /dev/null @@ -1,219 +0,0 @@ -/* -* Copyright (c) 2022 Vaughn Nugent -* -* Library: VNLib -* Package: VNLib.Plugins.Essentials.SocialOauth -* File: GitHubOauth.cs -* -* GitHubOauth.cs is part of VNLib.Plugins.Essentials.SocialOauth which is part of the larger -* VNLib collection of libraries and utilities. -* -* VNLib.Plugins.Essentials.SocialOauth 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. -* -* VNLib.Plugins.Essentials.SocialOauth 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/. -*/ - -using System; -using System.Text; -using System.Threading; -using System.Text.Json; -using System.Threading.Tasks; -using System.Collections.Generic; -using System.Text.Json.Serialization; - -using RestSharp; - -using VNLib.Hashing; -using VNLib.Utils.Logging; -using VNLib.Net.Rest.Client; -using VNLib.Plugins.Essentials.Accounts; -using VNLib.Plugins.Extensions.Loading; -using VNLib.Plugins.Extensions.Loading.Users; - -namespace VNLib.Plugins.Essentials.SocialOauth.Endpoints -{ - [ConfigurationName("github")] - internal sealed partial class GitHubOauth : SocialOauthBase - { - private const string GITHUB_V3_ACCEPT = "application/vnd.github.v3+json"; - - private readonly string UserEmailUrl; - - protected override OauthClientConfig Config { get; } - - public GitHubOauth(PluginBase plugin, IReadOnlyDictionary<string, JsonElement> config) : base() - { - - UserEmailUrl = config["user_email_url"].GetString() ?? throw new KeyNotFoundException("Missing required key 'user_email_url' for github configuration"); - - Config = new("github", config) - { - Passwords = plugin.GetPasswords(), - Users = plugin.GetUserManager(), - }; - - InitPathAndLog(Config.EndpointPath, plugin.Log); - - //Load secrets - _ = plugin.DeferTask(async () => - { - //Get id/secret - Task<SecretResult?> clientIdTask = plugin.TryGetSecretAsync("github_client_id"); - Task<SecretResult?> secretTask = plugin.TryGetSecretAsync("github_client_secret"); - - await Task.WhenAll(secretTask, clientIdTask); - - using SecretResult? secret = await secretTask; - using SecretResult? clientId = await clientIdTask; - - Config.ClientID = clientId?.Result.ToString() ?? throw new KeyNotFoundException("Missing Github client id from config or vault"); - Config.ClientSecret = secret?.Result.ToString() ?? throw new KeyNotFoundException("Missing the Github client secret from config or vault"); - - }, 100); - } - - protected override void StaticClientPoolInitializer(RestClient client) - { - client.UseSerializer<RestSharp.Serializers.Json.SystemTextJsonSerializer>(); - //add accept types of normal json and github json - client.AcceptedContentTypes = new string[2] { "application/json", GITHUB_V3_ACCEPT }; - } - - /* - * Matches the json result from the - */ - private sealed class GithubProfile - { - [JsonPropertyName("login")] - public string? Username { get; set; } - [JsonPropertyName("id")] - public int ID { get; set; } - [JsonPropertyName("node_id")] - public string? NodeID { get; set; } - [JsonPropertyName("avatar_url")] - public string? AvatarUrl { get; set; } - [JsonPropertyName("url")] - public string? ProfileUrl { get; set; } - [JsonPropertyName("type")] - public string? Type { get; set; } - [JsonPropertyName("name")] - public string? FullName { get; set; } - [JsonPropertyName("company")] - public string? Company { get; set; } - } - /* - * Matches the required data from the github email endpoint - */ - private sealed class EmailContainer - { - [JsonPropertyName("email")] - public string? Email { get; set; } - [JsonPropertyName("primary")] - public bool Primary { get; set; } - [JsonPropertyName("verified")] - public bool Verified { get; set; } - } - - private static string GetUserIdFromPlatform(int userId) - { - return ManagedHash.ComputeHash($"github|{userId}", HashAlg.SHA1, HashEncodingMode.Hexadecimal); - } - - protected override async Task<UserLoginData?> GetLoginDataAsync(IOAuthAccessState accessToken, CancellationToken cancellationToken) - { - //Get the user's email address's - RestRequest request = new(Config.UserDataUrl, Method.Get); - - //Add authorization token - request.AddHeader("Authorization", $"{accessToken.Type} {accessToken.Token}"); - - //Get new client from pool - using ClientContract client = ClientPool.Lease(); - - //Exec the get for the profile - RestResponse<GithubProfile> profResponse = await client.Resource.ExecuteAsync<GithubProfile>(request, cancellationToken); - - if (!profResponse.IsSuccessful || profResponse.Data == null || profResponse.Data.ID < 100) - { - Log.Debug("Github login data attempt responded with status code {code}", profResponse.StatusCode); - return null; - } - - //Return login data - return new() - { - //User-id is just the SHA 1 - UserId = GetUserIdFromPlatform(profResponse.Data.ID) - }; - } - - protected override async Task<AccountData?> GetAccountDataAsync(IOAuthAccessState accessToken, CancellationToken cancellationToken = default) - { - AccountData? accountData = null; - //Get the user's email address's - RestRequest request = new(UserEmailUrl, Method.Get); - //Add authorization token - request.AddHeader("Authorization", $"{accessToken.Type} {accessToken.Token}"); - - using ClientContract client = ClientPool.Lease(); - - //get user's emails - RestResponse<EmailContainer[]> getEmailResponse = await client.Resource.ExecuteAsync<EmailContainer[]>(request, cancellationToken: cancellationToken); - //Check status - if (getEmailResponse.IsSuccessful && getEmailResponse.Data != null) - { - //Filter emails addresses - foreach (EmailContainer email in getEmailResponse.Data) - { - //Capture the first primary email address and make sure its verified - if (email.Primary && email.Verified) - { - accountData = new() - { - //store email on current profile - EmailAddress = email.Email - }; - goto Continue; - } - } - //No primary email found - return null; - } - else - { - Log.Debug("Github account data request failed but GH responded with status code {code}", getEmailResponse.StatusCode); - return null; - } - Continue: - //We need to get the user's profile in order to create a new account - request = new(Config.UserDataUrl, Method.Get); - //Add authorization token - request.AddHeader("Authorization", $"{accessToken.Type} {accessToken.Token}"); - //Exec the get for the profile - RestResponse<GithubProfile> profResponse = await client.Resource.ExecuteAsync<GithubProfile>(request, cancellationToken); - if (!profResponse.IsSuccessful || profResponse.Data == null) - { - Log.Debug("Github account data request failed but GH responded with status code {code}", profResponse.StatusCode); - return null; - } - - //Get the user's name from gh profile - string[] names = profResponse.Data.FullName!.Split(" ", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - - //setup the user's profile data - accountData.First = names.Length > 0 ? names[0] : string.Empty; - accountData.Last = names.Length > 1 ? names[1] : string.Empty; - return accountData; - } - - } -}
\ No newline at end of file |