aboutsummaryrefslogtreecommitdiff
path: root/VNLib.Plugins.Essentials.SocialOauth/Endpoints/DiscordOauth.cs
blob: 6ee76837c6ddfc94faae7d99ba886f26958efcd0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
/*
* 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;

#nullable enable

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()
        {
            //Get id/secret
            Task<string?> secret = plugin.TryGetSecretAsync("discord_client_secret");
            Task<string?> clientId = plugin.TryGetSecretAsync("discord_client_id");

            //Wait sync
            Task.WaitAll(secret, clientId);

            Config = new("discord", config)
            {
                //get gh client secret and id
                ClientID = clientId.Result ?? throw new KeyNotFoundException("Missing Discord client id from config or vault"),
                ClientSecret = secret.Result ?? throw new KeyNotFoundException("Missing the Discord client secret from config or vault"),

                Passwords = plugin.GetPasswords(),
                Users = plugin.GetUserManager(),
            };

            InitPathAndLog(Config.EndpointPath, plugin.Log);
        }

        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)
            };
        }
    }
}