/********************************************************************************************************/ /********************************PRIVATE*HELPER*METHODS**************************************************/ /********************************************************************************************************/ // create form for http request using the given spotify token parameters private static List <KeyValuePair <string, string> > InitializeAccessForm(SpotifyTokenParams spotifyTokenParams) { var postData = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("grant_type", "authorization_code"), new KeyValuePair <string, string>("code", spotifyTokenParams.Code), new KeyValuePair <string, string>("redirect_uri", spotifyTokenParams.RedirectUri), new KeyValuePair <string, string>("client_id", Constants.CLIENT_ID), new KeyValuePair <string, string>("client_secret", Constants.CLIENT_SECRET) }; return(postData); }
public async Task <IActionResult> SpotifyToken([FromBody] SpotifyTokenParams spotifyTokenParams) { using (var client = new HttpClient()) { var postData = InitializeAccessForm(spotifyTokenParams); using (var content = new FormUrlEncodedContent(postData)) { client.BaseAddress = new Uri(Constants.BASE_ADDRESS_ACCOUNTS); content.Headers.Clear(); content.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); HttpResponseMessage response = await client.PostAsync("api/token", content); // if we received a token from the spotify accounts service, convert that into our Dto model if (response.IsSuccessStatusCode) { var responseString = await response.Content.ReadAsStringAsync(); var spotifyConnectionData = Newtonsoft.Json.JsonConvert.DeserializeObject <SpotifyConnectionDataDto>(responseString); if (spotifyConnectionData == null) { throw new Exception("Bad initial request for access token"); } var jsonResponse = await _userRepository.GetUserInfo(spotifyConnectionData); if (jsonResponse == null) { throw new Exception("Failure to retrieve user info from spotify api"); } // if the user is not in our database, create a new user for the app, otherwise, // return the existing user var existingUser = _userRepository.UserExists((string)jsonResponse["id"]); if (existingUser == null) { var newUser = (await _userRepository.AddNewUser(spotifyConnectionData)) .Match( some: nu => nu, none: () => null ); if (newUser != null) { var innerUserDto = new UserDto { SpotifyId = newUser.SpotifyId }; return(Ok(Json(JObject.Parse(JsonConvert.SerializeObject(innerUserDto))))); } return(BadRequest()); } // if the user scope has changed if (existingUser.Scope != spotifyTokenParams.Scope) { existingUser = _userRepository.UpdateUserWithNewScope(existingUser, spotifyConnectionData, spotifyTokenParams.Scope); } var userDto = new UserDto { SpotifyId = existingUser.SpotifyId }; return(Ok(Json(JObject.Parse(JsonConvert.SerializeObject(userDto))))); } return(BadRequest()); } } }