[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]     //Dynamic get
    public async Task <ContentResult> GetAsync([FromQuery] string code)
    {
        uint userId = this.HttpContext.IsAuthenicatedPr3User();

        if (userId <= 0)
        {
            return(this.Content(@"Please login to the client in the browser! Or <a href=""https://pr3hub.com/login"">click here</a> to do so without the Flash client.", "text/html"));
        }

        if (string.IsNullOrWhiteSpace(code))
        {
            PlayerUserData playerUserData = await UserManager.TryGetUserDataByIdAsync(userId);

            return(this.Content($@"Are you sure that you want to link your {playerUserData.Username} account to your Discord account?

<a href=""https://discordapp.com/api/oauth2/authorize?response_type=code&client_id={Program.Config.DiscordClientId}&scope=identify"">Click here to proceed</a>", "text/html"));
        }

        DiscordTokenResponse tokenResponse = await RequestTokenAsync(code);

        if (!string.IsNullOrWhiteSpace(tokenResponse.Error))
        {
            return(this.Content($"Requesting discord token returned the following error: {tokenResponse.ErrorReason}"));
        }

        DiscordUserResponse user = await GetUser(tokenResponse);

        if (user.Code != null)
        {
            return(this.Content($"Requesting discord profile resulted to the following error: {user.Message}"));
        }

        uint linkedToAccount = await UserManager.HasDiscordLinkage(userId, user.Id);

        if (linkedToAccount == 0)
        {
            if (!await UserManager.TryInsertDiscordLinkage(userId, user.Id))
            {
                return(this.Content("Oops, something went wrong!"));
            }

            return(this.Content("All ok! :sunglasses:"));
        }
        else
        {
            if (linkedToAccount == userId)
            {
                return(this.Content("This account has already been linked to Discord account!"));
            }
            else
            {
                return(this.Content("This Discord account has already been linked to different account!"));
            }
        }
Exemple #2
0
        [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] //Dynamic get
        public async Task <ContentResult> GetAsync([FromQuery] string code)
        {
            uint userId = this.HttpContext.IsAuthenicatedPr3User();

            if (userId > 0)
            {
                if (string.IsNullOrWhiteSpace(code))
                {
                    PlayerUserData playerUserData = await UserManager.TryGetUserDataByIdAsync(userId);

                    return(this.Content($@"Are you sure you want to link your {playerUserData.Username} account to your Discord account?

<a href=""https://discordapp.com/api/oauth2/authorize?response_type=code&client_id={Program.Config.DiscordClientId}&scope=identify"">Click here to proceed</a>", "text/html"));
                }
                else
                {
                    DiscordTokenResponse tokenResponse = await RequestTokenAsync();

                    if (!string.IsNullOrWhiteSpace(tokenResponse.Error))
                    {
                        return(this.Content($"Requesting discord token returned the following error: {tokenResponse.ErrorReason}"));
                    }

                    DiscordUserResponse user = await GetUser();

                    if (user.Code != null)
                    {
                        return(this.Content($"Requesting discord profile resulted to the following error: {user.Message}"));
                    }

                    uint linkedToAccount = await UserManager.HasDiscordLinkage(userId, user.Id);

                    if (linkedToAccount == 0)
                    {
                        if (!await UserManager.TryInsertDiscordLinkage(userId, user.Id))
                        {
                            return(this.Content("Oops, something went wrong!"));
                        }

                        return(this.Content("All ok! :sunglasses:"));
                    }
                    else
                    {
                        if (linkedToAccount == userId)
                        {
                            return(this.Content("This account has already been linked to Discord account!"));
                        }
                        else
                        {
                            return(this.Content("This Discord account has already been linked to different account!"));
                        }
                    }

                    async Task <DiscordUserResponse> GetUser()
                    {
                        using (HttpClient httpClient = new())
                        {
                            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenResponse.TokenType, tokenResponse.AccessToken);

                            using (HttpResponseMessage message = await httpClient.GetAsync(LinkDiscordController.DISCORD_API_ME))
                            {
                                return(JsonConvert.DeserializeObject <DiscordUserResponse>(await message.Content.ReadAsStringAsync()));
                            }
                        }
                    }

                    async Task <DiscordTokenResponse> RequestTokenAsync()
                    {
                        IDictionary <string, string> values = new Dictionary <string, string>()
                        {
                            { "client_id", Program.Config.DiscordClientId },
                            { "client_secret", Program.Config.DiscordClientSecret },
                            { "grant_type", "authorization_code" },
                            { "code", code },
                            { "scope", "identify" },
                        };

                        using (HttpClient httpClient = new())
                        {
                            using (FormUrlEncodedContent content = new(values))
                            {
                                using (HttpResponseMessage message = await httpClient.PostAsync(LinkDiscordController.DISCORD_API_TOKEN, content))
                                {
                                    return(JsonConvert.DeserializeObject <DiscordTokenResponse>(await message.Content.ReadAsStringAsync()));
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                return(this.Content("Please login to the client!"));
            }
        }
Exemple #3
0
        public async Task <IActionResult> DiscordCallback(string state, string code)
        {
            if (!states.Contains(state))
            {
                ErrorMessage = "Error in discord Oauth state.";
                return(RedirectToAction("Index", "Manage", new { area = "" }));
            }

            states.Remove(state);

            string redirect = HttpUtility.UrlEncode("https://spookvooper.com/Account/DiscordCallback");

            HttpClient client = new HttpClient();

            var param = new Dictionary <string, string>
            {
                { "client_id", Secrets.DiscordOauthClient },
                { "client_secret_id", Secrets.DiscordOauthSecret },
                { "grant_type", "authorization_code" },
                { "code", code },
                { "redirect_uri", redirect }
            };

            var response = await client.PostAsync("https://discordapp.com/api/oauth2/token", new FormUrlEncodedContent(param));

            string tokenInfo = await response.Content.ReadAsStringAsync();

            Console.WriteLine(tokenInfo);

            DiscordTokenResponse responseToken = JsonConvert.DeserializeObject <DiscordTokenResponse>(tokenInfo);

            if (responseToken == null)
            {
                Console.WriteLine("Discord connect: Error in token");
                ErrorMessage = "Error in token retrieval.";
                return(RedirectToAction("Index", "Manage", new { area = "" }));
            }

            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", responseToken.access_token);

            var userResponse = await client.GetAsync("https://discordapp.com/api/users/@me");

            string userInfoString = await userResponse.Content.ReadAsStringAsync();

            Console.WriteLine(userInfoString);

            DiscordUserResponse userInfo = JsonConvert.DeserializeObject <DiscordUserResponse>(userInfoString);

            if (userInfo == null)
            {
                Console.WriteLine("Discord connect: Error in user info");
                ErrorMessage = "Error in user info retrieval.";
                return(RedirectToAction("Index", "Manage", new { area = "" }));
            }

            User user = await _userManager.GetUserAsync(User);

            user.discord_id = userInfo.id;

            await _userManager.UpdateAsync(user);

            ErrorMessage = "Successfully linked discord.";

            Console.WriteLine("Discord connect: Connected successfully");
            return(RedirectToAction("Index", "Manage", new { area = "" }));
        }