public async Task <IActionResult> FinishAuth(GatewayUser user, FinishAuthInfo model, bool forceGrant, bool trusted) { var authorized = await HasAuthorizedApp(user, model.AppId); if (!authorized && trusted) { // Unauthorized. But viewing a trusted app. Just auto auth him. await GrantTargetApp(user, model.AppId); authorized = true; } if (authorized && forceGrant != true) { // Dont need to auth, and the user don't force to auth. var pack = await GeneratePack(user, model.AppId); var url = new AiurUrl(GetRegexRedirectUri(model.RedirectUri), new AuthResultAddressModel { Code = pack.Code, State = model.State }); return(new RedirectResult(url.ToString())); } else { // Need to do the auth logic. var url = new AiurUrl(string.Empty, "OAuth", nameof(OAuthController.AuthorizeConfirm), new FinishAuthInfo { AppId = model.AppId, RedirectUri = model.RedirectUri, State = model.State }); return(new RedirectResult(url.ToString())); } }
public async Task <IActionResult> SetLang(SetLangViewModel model) { if (!ModelState.IsValid) { return(View(model)); } try { _ApplyCultureCookie(model.Culture); } catch (CultureNotFoundException) { return(this.Protocol(new AiurProtocol { Message = "Not a language.", Code = ErrorType.InvalidInput })); } var user = await GetCurrentUserAsync(); if (user != null) { user.PreferedLanguage = model.Culture; await _userManager.UpdateAsync(user); } var toGo = new AiurUrl(model.Host, "/switch-language", new { model.Culture, ReturnUrl = model.Path }); return(Redirect(toGo.ToString())); }
public async Task <string> Post(AiurUrl url, AiurUrl postDataStr, bool forceHttp = false, bool autoRetry = true) { if (forceHttp && !url.IsLocalhost()) { url.Address = _regex.Replace(url.Address, "http://"); } var request = new HttpRequestMessage(HttpMethod.Post, url.ToString()) { Content = new FormUrlEncodedContent(postDataStr.Params) }; request.Headers.Add("X-Forwarded-Proto", "https"); request.Headers.Add("accept", "application/json"); using var response = autoRetry ? await SendWithRetry(request) : await _client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); if (content.IsValidJson()) { return(content); } else { if (response.IsSuccessStatusCode) { throw new InvalidOperationException($"The {nameof(APIProxyService)} can only handle JSON content while the remote server returned unexpected content: {content.OTake(100)}."); } else { throw new WebException($"The remote server returned unexpected content: {content.OTake(100)}. code: {response.StatusCode} - {response.ReasonPhrase}."); } } }
public async Task <string> Get(AiurUrl url, bool internalRequest) { if (internalRequest) { url.Address = _regex.Replace(url.Address, "http://"); } var request = new HttpRequestMessage(HttpMethod.Get, url.ToString()) { Content = new FormUrlEncodedContent(new Dictionary <string, string>()) }; request.Headers.Add("x-request-origin", Values.ProjectName); request.Headers.Add("accept", "application/json"); var response = await _client.SendAsync(request); if (response.IsSuccessStatusCode) { return(await response.Content.ReadAsStringAsync()); } else { throw new WebException(response.ReasonPhrase); } }
public override void OnException(ExceptionContext context) { base.OnException(context); switch (context.Exception.GetType().Name) { case nameof(NotAiurSignedInException): { var exp = context.Exception as NotAiurSignedInException; var r = context.HttpContext.Request; string ServerPosition = $"{r.Scheme}://{r.Host}"; string url = UrlConverter.UrlWithAuth(ServerPosition, exp.SignInRedirectPath); context.ExceptionHandled = true; context.HttpContext.Response.Redirect(url.ToString()); } break; case nameof(AiurUnexceptedResponse): { var exp = context.Exception as AiurUnexceptedResponse; var arg = new AiurProtocal { code = exp.Response.code, message = exp.Response.message }; var url = new AiurUrl(string.Empty, "api", "exception", arg); context.ExceptionHandled = true; context.HttpContext.Response.Redirect(url.ToString()); } break; case nameof(ModelStateNotValidException): { var exp = context.Exception as ModelStateNotValidException; var arg = new AiurProtocal { code = ErrorType.InvalidInput, message = "Input not valid!" }; var url = new AiurUrl(string.Empty, "api", "exception", arg); context.ExceptionHandled = true; context.HttpContext.Response.Redirect(url.ToString()); } break; default: { var exp = context.Exception as Exception; var arg = new AiurProtocal { code = ErrorType.UnknownError, message = exp.Message }; var url = new AiurUrl(string.Empty, "api", "exception", arg); context.ExceptionHandled = true; context.HttpContext.Response.Redirect(url.ToString()); } break; } }
public async Task <string> Post(AiurUrl url, AiurUrl postDataStr, bool forceHttp = false) { if (forceHttp && !url.IsLocalhost()) { url.Address = _regex.Replace(url.Address, "http://"); } var request = new HttpRequestMessage(HttpMethod.Post, url.ToString()) { Content = new FormUrlEncodedContent(postDataStr.Params) }; request.Headers.Add("X-Forwarded-Proto", "https"); request.Headers.Add("accept", "application/json"); using var response = await _client.SendAsync(request); if (response.IsSuccessStatusCode) { return(await response.Content.ReadAsStringAsync()); } else { throw new WebException($"The remote server returned unexpected status code: {response.StatusCode} - {response.ReasonPhrase}."); } }
public async Task <string> Get(AiurUrl Url, string Coding = "utf-8") { var request = WebRequest.CreateHttp(Url.ToString()); if (CC.Count == 0) { request.CookieContainer = new CookieContainer(); CC = request.CookieContainer; } else { request.CookieContainer = CC; } request.Method = "GET"; request.ContentType = "text/html;charset=" + Coding; var response = await request.GetResponseAsync(); var myResponseStream = response.GetResponseStream(); var myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding(Coding)); string retString = await myStreamReader.ReadToEndAsync(); myStreamReader.Dispose(); myResponseStream.Close(); return(retString); }
public async Task <IActionResult> InitIconUpload() { var accessToken = await _appsContainer.AccessToken(); var siteName = _configuration["UserIconsSiteName"]; var path = DateTime.UtcNow.ToString("yyyy-MM-dd"); var token = await _tokenService.GetTokenAsync( accessToken, siteName, new[] { "Upload" }, path, TimeSpan.FromMinutes(10)); var address = new AiurUrl(_probeLocator.Endpoint, $"/Files/UploadFile/{siteName}/{path}", new UploadFileAddressModel { Token = token, RecursiveCreate = true }); return(Json(new AiurValue <string>(address.ToString()) { Code = ErrorType.Success, Message = "Token is given. You can not upload your file to that address. And your will get your response as 'FilePath'." })); }
public async Task <string> Post(AiurUrl Url, AiurUrl postDataStr, string Decode = "utf-8") { var request = WebRequest.CreateHttp(Url.ToString()); if (CC.Count == 0) { request.CookieContainer = new CookieContainer(); CC = request.CookieContainer; } else { request.CookieContainer = CC; } request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; var myRequestStream = await request.GetRequestStreamAsync(); var myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("GB2312")); await myStreamWriter.WriteAsync(postDataStr.ToString().Trim('?')); myStreamWriter.Dispose(); var response = await request.GetResponseAsync(); var myResponseStream = response.GetResponseStream(); var myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding(Decode)); string retString = await myStreamReader.ReadToEndAsync(); myStreamReader.Dispose(); myResponseStream.Close(); return(retString); }
public async Task <string> Get(AiurUrl url, bool internalRequest) { if (internalRequest) { url.Address = _regex.Replace(url.Address, "http://"); } var request = new HttpRequestMessage(HttpMethod.Get, url.ToString()) { Content = new FormUrlEncodedContent(new Dictionary <string, string>()) }; request.Headers.Add("X-Forwarded-Proto", "https"); request.Headers.Add("accept", "application/json"); var response = await _client.SendAsync(request); if (response.IsSuccessStatusCode) { return(await response.Content.ReadAsStringAsync()); } else { throw new WebException($"The remote server returned unexpected status code: {response.StatusCode} - {response.ReasonPhrase}."); } }
public async Task <string> Get(AiurUrl Url) { var request = WebRequest.CreateHttp(Url.ToString()); request.CookieContainer = CC; request.Method = "GET"; request.ContentType = "text/html;charset=utf-8"; return(await HTTPMethods.ReadFromResponseAsync(request)); }
public string GetSignInRedirectLink(AiurUrl state) { return(new AiurUrl("https://github.com", "/login/oauth/authorize", new GitHubAuthAddressModel { ClientId = _clientId, RedirectUri = new AiurUrl(_serviceLocation.Gateway, $"/third-party/sign-in/{GetName()}", new { }).ToString(), State = state.ToString() }).ToString()); }
public string GetSignInRedirectLink(AiurUrl state) { return(new AiurUrl("https://www.facebook.com", "/v5.0/dialog/oauth", new FaceBookAuthAddressModel { ClientId = _clientId, RedirectUri = new AiurUrl(_serviceLocation.Endpoint, $"/third-party/sign-in/{GetName()}", new { }).ToString(), State = state.ToString(), ResponseType = "code" }).ToString()); }
public async Task <string> Post(AiurUrl Url, AiurUrl postDataStr) { var request = WebRequest.CreateHttp(Url.ToString()); request.CookieContainer = CC; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; await HTTPMethods.SendRequestAsync(request, postDataStr.ToString().TrimStart('?')); return(await HTTPMethods.ReadFromResponseAsync(request)); }
public static IActionResult SignOutRootServer(this Controller controller, string apiServerAddress, AiurUrl viewingUrl) { var request = controller.HttpContext.Request; string serverPosition = $"{request.Scheme}://{request.Host}{viewingUrl}"; var toRedirect = new AiurUrl(apiServerAddress, "OAuth", "UserSignout", new UserSignoutAddressModel { ToRedirect = serverPosition }); return(controller.Redirect(toRedirect.ToString())); }
public string GetSignInRedirectLink(AiurUrl state) { return(new AiurUrl("https://login.microsoftonline.com", $"/{_tenant}/oauth2/v2.0/authorize", new MicrosoftAuthAddressModel { ClientId = _clientId, RedirectUri = new AiurUrl(_serviceLocation.Endpoint, $"/third-party/sign-in/{GetName()}", new { }).ToString(), ResponseType = "code", Scope = "user.read", State = state.ToString() }).ToString()); }
public string GetSignInRedirectLink(AiurUrl state) { return(new AiurUrl("https://accounts.google.com", "/o/oauth2/v2/auth", new GoogleAuthAddressModel { ClientId = _clientId, RedirectUri = new AiurUrl(_serviceLocation.Endpoint, $"/third-party/sign-in/{GetName()}", new { }).ToString(), State = state.ToString(), Scope = "profile", ResponseType = "code" }).ToString()); }
public async Task <string> Get(AiurUrl url, bool internalRequest = false) { HttpWebRequest request = null; if (internalRequest) { url.Address = url.Address.Replace("https://", "http://"); request = WebRequest.CreateHttp(url.ToString()); request.Headers.Add("x-forwarded-for", "localhost"); } else { request = WebRequest.CreateHttp(url.ToString()); } _logger.LogInformation($"Creating HTTP GET request to: {request.RequestUri.ToString()}"); request.CookieContainer = _cc; request.Method = "GET"; request.ContentType = "text/html;charset=utf-8"; return(await HTTPMethods.ReadFromResponseAsync(request)); }
public async Task <string> PostFile(AiurUrl Url, string filepath, string Decode = "utf-8") { var file = new FileInfo(filepath); var fileStream = new FileStream(filepath, mode: FileMode.Open); var request = new HttpClient(); var form = new MultipartFormDataContent(); form.Add(new StreamContent(fileStream), "file", file.FullName); var response = await request.PostAsync(Url.ToString(), form); return(await response.Content.ReadAsStringAsync()); }
public void TestBasic() { var url = new AiurUrl("https://www.bing.com", "Home", "Search", new { Question = "MyQuestion", Count = 10, Email = "*****@*****.**" }); var result = url.ToString(); Assert.AreEqual("https://www.bing.com/Home/Search?question=MyQuestion&count=10&email=aaa%40bbb.com", result); }
public async Task <string> Post(AiurUrl url, AiurUrl postDataStr, bool internalRequest = false) { HttpWebRequest request = null; if (internalRequest) { url.Address = url.Address.Replace("https://", "http://"); request = WebRequest.CreateHttp(url.ToString()); request.Headers.Add("x-forwarded-for", "localhost"); } else { request = WebRequest.CreateHttp(url.ToString()); } _logger.LogInformation($"Creating HTTP Post request to: {request.RequestUri.ToString()}"); request.CookieContainer = _cc; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; await HTTPMethods.SendRequestAsync(request, postDataStr.ToString().TrimStart('?')); return(await HTTPMethods.ReadFromResponseAsync(request)); }
private AiurUrl GenerateAuthUrl(AiurUrl destination, string state, bool?justTry, bool register) { var action = register ? "register" : "authorize"; var url = new AiurUrl(_serviceLocation.Gateway, "oauth", action, new AuthorizeAddressModel { AppId = _appsContainer._currentAppId, RedirectUri = destination.ToString(), State = state, TryAutho = justTry }); return(url); }
public async Task <IActionResult> InitFileAccess(InitFileAccessAddressModel model) { var conversation = await _dbContext .Conversations .Include(nameof(GroupConversation.Users)) .SingleOrDefaultAsync(t => t.Id == model.ConversationId); if (conversation == null) { return(this.Protocol(ErrorType.NotFound, $"Could not find the target conversation with id: {model.ConversationId}!")); } var user = await GetKahlaUser(); if (!conversation.HasUser(user.Id)) { return(this.Protocol(ErrorType.Unauthorized, $"You are not authorized to upload file to conversation: {conversation.Id}!")); } var accessToken = await _appsContainer.AccessToken(); var siteName = _configuration["UserFilesSiteName"]; var path = $"conversation-{conversation.Id}"; var permissions = new List <string>(); if (model.Upload) { permissions.Add("Upload"); } if (model.Download) { permissions.Add("Download"); } var token = await _tokenService.GetTokenAsync( accessToken, siteName, permissions.ToArray(), path, TimeSpan.FromMinutes(60)); var address = new AiurUrl(_probeLocator.Endpoint, $"/Files/UploadFile/{siteName}/{path}/{DateTime.UtcNow:yyyy-MM-dd}", new UploadFileAddressModel { Token = token, RecursiveCreate = true }); return(Json(new InitFileAccessViewModel(token) { UploadAddress = address.ToString(), Code = ErrorType.Success, Message = "Token is given. You can access probe API with the token now. Permissions: " + string.Join(",", permissions) })); }
public void TestComplicated() { var url = new AiurUrl("https://www.bing.com", "Home", "Search", new TestAddressModel { Question = "MyQuestion", Count = 10, Email = "*****@*****.**", MyNull = null, CreateTime = DateTime.Parse("2020-01-01 14:15:16") }); var result = url.ToString(); Assert.AreEqual("https://www.bing.com/Home/Search?question=MyQuestion&count=10&emailaddress=aaa%40bbb.com&createtime=2020-01-01T14%3A15%3A16.0000000", result); }
private AiurUrl GenerateAuthUrl(AiurUrl destination, string state, bool?justTry, bool register) { var action = register ? "register" : "authorize"; var url = new AiurUrl(_serviceLocation.API, "oauth", action, new AuthorizeAddressModel { appid = Extends.CurrentAppId, redirect_uri = destination.ToString(), response_type = "code", scope = "snsapi_base", state = state, tryAutho = justTry }); return(url); }
public async Task <string> Post(AiurUrl url, AiurUrl postDataStr) { var request = new HttpRequestMessage(HttpMethod.Post, url.ToString()) { Content = new FormUrlEncodedContent(postDataStr.Params) }; using var response = await _client.SendAsync(request); if (response.IsSuccessStatusCode) { return(await response.Content.ReadAsStringAsync()); } else { throw new WebException($"The remote server returned unexpected status code: {response.StatusCode} - {response.ReasonPhrase}."); } }
public async Task <string> Get(AiurUrl url) { var request = new HttpRequestMessage(HttpMethod.Get, url.ToString()) { Content = new FormUrlEncodedContent(new Dictionary <string, string>()) }; using var response = await _client.SendAsync(request); if (response.IsSuccessStatusCode) { return(await response.Content.ReadAsStringAsync()); } else { throw new WebException($"The remote server returned unexpected status code: {response.StatusCode} - {response.ReasonPhrase}. Url: {url}"); } }
public async Task <string> Track(AiurUrl url) { var request = new HttpRequestMessage(HttpMethod.Get, url.ToString()) { Content = new FormUrlEncodedContent(new Dictionary <string, string>()) }; request.Headers.Add("accept", "application/json"); var response = await _client.SendAsync(request); if (response.StatusCode == HttpStatusCode.Redirect) { return(response.Headers.Location.OriginalString); } else { throw new WebException(response.ReasonPhrase); } }
public async Task <string> PostFile(AiurUrl url, Stream fileStream, string fileName) { var request = new HttpClient { Timeout = TimeSpan.FromSeconds(3600) }; var form = new MultipartFormDataContent(); string responseString = null; using (var bufferedStream = new BufferedStream(fileStream)) { form.Add(new StreamContent(bufferedStream), "file", fileName); var response = await request.PostAsync(url.ToString(), form); responseString = await response.Content.ReadAsStringAsync(); fileStream.Close(); } fileStream.Dispose(); return(responseString); }
public async Task <string> Get(AiurUrl url) { var request = new HttpRequestMessage(HttpMethod.Get, url.ToString()) { Content = new FormUrlEncodedContent(new Dictionary <string, string>()) }; request.Headers.Add("accept", "application/json"); var response = await _client.SendAsync(request); if (response.IsSuccessStatusCode) { Save(_cookieContainer); return(await response.Content.ReadAsStringAsync()); } else { throw new WebException($"The remote server returned unexpcted status code: {response.StatusCode} - {response.ReasonPhrase}."); } }