コード例 #1
0
ファイル: UserAppAuthManager.cs プロジェクト: cc1993abc/Nexus
        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()));
            }
        }
コード例 #2
0
        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()));
        }
コード例 #3
0
        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}.");
                }
            }
        }
コード例 #4
0
        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);
            }
        }
コード例 #5
0
        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;
            }
        }
コード例 #6
0
        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}.");
            }
        }
コード例 #7
0
        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);
        }
コード例 #8
0
        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'."
            }));
        }
コード例 #9
0
        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);
        }
コード例 #10
0
        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}.");
            }
        }
コード例 #11
0
        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));
        }
コード例 #12
0
ファイル: GitHubService.cs プロジェクト: Xiangrui2019/Pylon
 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());
 }
コード例 #13
0
 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());
 }
コード例 #14
0
        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));
        }
コード例 #15
0
        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()));
        }
コード例 #16
0
 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());
 }
コード例 #17
0
 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());
 }
コード例 #18
0
ファイル: HTTPService.cs プロジェクト: gitter-badger/WebApp-4
        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));
        }
コード例 #19
0
        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());
        }
コード例 #20
0
        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);
        }
コード例 #21
0
ファイル: HTTPService.cs プロジェクト: gitter-badger/WebApp-4
        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));
        }
コード例 #22
0
ファイル: UrlConverter.cs プロジェクト: wangyaoDgit/Nexus
        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);
        }
コード例 #23
0
        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)
            }));
        }
コード例 #24
0
        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);
        }
コード例 #25
0
        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);
        }
コード例 #26
0
ファイル: HttpService.cs プロジェクト: ox208/Infrastructures
        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}.");
            }
        }
コード例 #27
0
        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}");
            }
        }
コード例 #28
0
ファイル: SingletonHTTP.cs プロジェクト: Tangtang1997/Kahla
        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);
            }
        }
コード例 #29
0
ファイル: HTTPService.cs プロジェクト: BenyT/Pylon
        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);
        }
コード例 #30
0
        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}.");
            }
        }