public RedirectResult Authorize() { // Generate a random 16char GUID nonce to validate on the callback var nonce = Guid.NewGuid().ToString().Replace("-", ""); Memory.Set(nonce, nonce, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(Config.PathOfExileApi.NonceExpirySeconds), Size = nonce.Length }); var authUri = UriPath.Combine(Config.PathOfExileApi.Route, "/OAuth/Authorize"); var redirectUri = Url.Action("AuthorizeCallback", "OAuth", null, Request.Scheme); // Build up query params to append to the provided redirect Uri var queryParams = new Dictionary <string, string> { { "client_id", Config.PathOfExileApi.ClientId }, { "response_type", "code" }, { "scope", "profile" }, { "redirect_uri", redirectUri }, { "state", nonce } }; var authQuery = QueryHelpers.AddQueryString(authUri, queryParams); return(Redirect(authQuery)); }
public async Task <RestReturnObj <UserToken> > UserAuthRequest(string apiResources, UserData userData) { HttpContent content = new StringContent(JsonConvert.SerializeObject(userData), Encoding.UTF8, "application/json"); HttpResponseMessage response = await m_Client.PostAsync(UriPath.Combine(m_Uri, apiResources), content); if (!response.IsSuccessStatusCode) { return new RestReturnObj <UserToken> { IsSuccess = false } } ; var str = await response.Content.ReadAsStringAsync(); UserToken token = new UserToken(); if (!String.IsNullOrWhiteSpace(str)) { token = JsonConvert.DeserializeObject <UserToken>(str); } return(new RestReturnObj <UserToken> { IsSuccess = response.IsSuccessStatusCode, Obj = token }); }
public async Task <RestReturnObj <PostedFoodMarkerRetObj> > PostFoodMarker(FoodMarker foodMarker) { HttpContent content = new StringContent(JsonConvert.SerializeObject(foodMarker), Encoding.UTF8, "application/json"); HttpResponseMessage responseMsg = await m_Client.PostAsync(UriPath.Combine(m_Uri, "FullFoodAndGeoData"), content); if (!responseMsg.IsSuccessStatusCode) { return new RestReturnObj <PostedFoodMarkerRetObj>() { IsSuccess = false } } ; var response = await responseMsg.Content.ReadAsStringAsync(); if (String.IsNullOrEmpty(response)) { return(null); } PostedFoodMarkerRetObj ret = JsonConvert.DeserializeObject <PostedFoodMarkerRetObj>(response); return(new RestReturnObj <PostedFoodMarkerRetObj> { IsSuccess = responseMsg.IsSuccessStatusCode, Obj = ret }); }
public async Task <RestReturnObj <IEnumerable <FoodCategories> > > GetAllFoodCategories() { HttpResponseMessage responseMsg = await m_Client.GetAsync(UriPath.Combine(m_Uri, "FoodCategories")); if (!responseMsg.IsSuccessStatusCode) { return new RestReturnObj <IEnumerable <FoodCategories> > { IsSuccess = false } } ; var response = await responseMsg.Content.ReadAsStringAsync(); if (String.IsNullOrEmpty(response)) { return(null); } IEnumerable <FoodCategories> ret = JsonConvert.DeserializeObject <IEnumerable <FoodCategories> >(response); return(new RestReturnObj <IEnumerable <FoodCategories> > { IsSuccess = responseMsg.IsSuccessStatusCode, Obj = ret }); }
public async Task <bool> IsTokenValid() { HttpContent content = new StringContent(""); HttpResponseMessage response = await m_Client.PostAsync(UriPath.Combine(m_Uri, "Ping"), content); return(response.IsSuccessStatusCode); }
private async Task <OAuthTokenEntity> EnsureUserAsync(string access_token) { var token = await DBContext.OAuthTokens.SingleOrDefaultAsync(t => t.Value == access_token && (t.Expiry == null || t.Expiry.Value > DateTime.Now)); // User exists, short circuit out if (!string.IsNullOrEmpty(token?.UserId)) { return(token); } var profileUri = UriPath.Combine(Config.PathOfExileApi.Route, "/profile"); var profileQuery = QueryHelpers.AddQueryString(profileUri, nameof(access_token), access_token); using var client = new HttpClient(); using var response = await client.GetAsync(profileQuery); if (!response.IsSuccessStatusCode) { throw new AuthenticationException(response.ReasonPhrase); } var contentRaw = await response.Content.ReadAsStringAsync(); var profile = JsonConvert.DeserializeObject <ProfileResponse>(contentRaw); if (string.IsNullOrEmpty(profile?.Name)) { throw new AuthenticationException(); } var user = await UserManager.FindByNameAsync(profile.Name); if (user == null) { user = new UserEntity { UserName = profile.Name, Name = profile.Name, Realm = profile.Realm, UUID = profile.UUID }; var result = await UserManager.CreateAsync(user); if (!result.Succeeded) { throw new AuthenticationException(result.Errors.First().Description); } } token = new OAuthTokenEntity { Value = access_token, UserId = user.Id }; return(token); }
public async Task <RedirectResult> AuthorizeCallback(string code, string state) { if (string.IsNullOrEmpty(state) || !Memory.TryGetValue(state, out _)) { // Unrecognized Nonce, go back home return(BackToHome()); } // Delete the nonce now, we are done with it Memory.Remove(state); // Check if we already recognize this code, if not, build it var codeEntity = await DBContext.OAuthCodes.FindAsync(code); if (codeEntity == null) { codeEntity = new OAuthCodeEntity { Value = code }; await DBContext.AddAsync(codeEntity); await DBContext.SaveChangesAsync(); } var token = string.IsNullOrEmpty(codeEntity.UserId) ? null : DBContext .OAuthTokens .FirstOrDefault(t => t.UserId == codeEntity.UserId && (t.Expiry == null || t.Expiry.Value > DateTime.Now) ); // This user already has a valid access token, lets just use that instead if (token != null) { return(BackToHome(token)); } // This is a new, unrecognized user, try and fetch an access token var tokenUri = UriPath.Combine(Config.PathOfExileApi.Route, "/OAuth/Token"); var redirectUri = Url.Action("TokenCallback", "OAuth", null, Request.Scheme); var queryParams = new Dictionary <string, string> { { "client_id", Config.PathOfExileApi.ClientId }, { "client_secret", Config.PathOfExileApi.ClientSecret }, { "code", code }, { "grant_type", "authorization_code" }, { "redirect_uri", redirectUri } }; var tokenQuery = QueryHelpers.AddQueryString(tokenUri, queryParams); return(Redirect(tokenQuery)); }
public async Task <bool> DeleteFoodMarker(int foodMarkerId) { string uri = UriPath.Combine(m_Uri, "FoodMarker"); HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Delete, UriPath.Combine(uri, foodMarkerId.ToString())); HttpResponseMessage response = await m_Client.SendAsync(requestMessage); if (!response.IsSuccessStatusCode) { return(false); } return(true); }
public async Task <RestReturnObj <IEnumerable <FoodMarkerImageMeta> > > PostPhotos(int foodMarkerId, List <byte[]> images) { string uri = UriPath.Combine(m_Uri, "Photos"); HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, UriPath.Combine(uri, foodMarkerId.ToString())); MultipartFormDataContent content = new MultipartFormDataContent(); foreach (var image in images) { ByteArrayContent byteArrayContent = new ByteArrayContent(image); byteArrayContent.Headers.Add("Content-Type", "application/octet-stream"); Guid uniqueId = Guid.NewGuid(); content.Add(byteArrayContent, "file", "image" + uniqueId.ToString() + ".png"); } requestMessage.Content = content; HttpResponseMessage response = await m_Client.SendAsync(requestMessage); if (!response.IsSuccessStatusCode) { return new RestReturnObj <IEnumerable <FoodMarkerImageMeta> > { IsSuccess = false } } ; var resContent = response.Content; var str = await resContent.ReadAsStringAsync(); var ret = JsonConvert.DeserializeObject <IEnumerable <FoodMarkerImageMeta> >(str); foreach (var meta in ret) { meta.ImageUrl = WebUtility.UrlDecode(meta.ImageUrl); } return(new RestReturnObj <IEnumerable <FoodMarkerImageMeta> > { IsSuccess = response.IsSuccessStatusCode, Obj = ret }); }