Esempio n. 1
0
        public async Task <IActionResult> Callback(string code)
        {
            var data = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("code", code),
                new KeyValuePair <string, string>("client_id", await configurationService.GetValue("Authentication:Google:ClientId")),
                new KeyValuePair <string, string>("client_secret", await configurationService.GetValue("Authentication:Google:ClientSecret")),
                new KeyValuePair <string, string>("redirect_uri",
                                                  Url.Action("Callback", "Youtube", null, Request.Scheme, null)),
                new KeyValuePair <string, string>("grant_type", "authorization_code")
            };

            var response = await youtubeService.Post("https://accounts.google.com/o/oauth2/token", data);

            var content = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                return(StatusCode((int)response.StatusCode, content));
            }

            var token = JsonConvert.DeserializeObject <AccessToken>(content);

            var user = await userService.GetUsers().FirstOrDefaultAsync();

            if (user == null)
            {
                user = new User();
                await userService.Create(user);
            }

            await userService.AddToken(user.Id, ApiSource.Youtube, token);

            return(RedirectToAction("Index"));
        }