diff --git a/ChaosBot/WebServer/App/DiscordController.cs b/ChaosBot/WebServer/App/DiscordController.cs new file mode 100644 index 0000000..3bff07d --- /dev/null +++ b/ChaosBot/WebServer/App/DiscordController.cs @@ -0,0 +1,58 @@ +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Newtonsoft.Json; +using NLog; + +namespace ChaosBot.WebServer.App +{ + [ApiController] + [Route("/discord")] + public class DiscordController : Controller + { + private static readonly HttpClient client = new HttpClient(); + private static readonly ILogger Logger = Program.Logger; + + [HttpGet] + public async Task Index(string code = null) + { + string redirectUri = $"{Request.Scheme}://{Request.Host}/discord"; + string clientId = Program.AppSettingsHandler.GetValue("Discord:ClientId"); + string clientSecret = Program.AppSettingsHandler.GetValue("Discord:ClientSecret"); + + if (code == null) + return Redirect($"https://discord.com/api/oauth2/authorize?client_id={clientId}&redirect_uri={redirectUri}&response_type=code&scope=identify%20guilds"); + + Dictionary values = new Dictionary + { + { "client_id", clientId }, + { "client_secret", clientSecret }, + { "grant_type", "authorization_code" }, + { "code", code }, + { "redirect_uri", redirectUri }, + { "scope", "identify guild" } + }; + + FormUrlEncodedContent content = new FormUrlEncodedContent(values); + HttpResponseMessage response = await client.PostAsync("https://discord.com/api/oauth2/token", content); + string responseString = await response.Content.ReadAsStringAsync(); + DiscordOauthResponse responseObject = JsonConvert.DeserializeObject(responseString); + + return LocalRedirect($"/#/?access_token={responseObject.access_token}"); + } + } + + internal class DiscordOauthResponse + { + public string error = null; + public string error_description = null; + + public string access_token = null; + public int expires_in = 0; + public string refresh_token = null; + public string scope = null; + public string token_type = null; + } +} \ No newline at end of file