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 <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(this.Protocol(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 <IActionResult> SetLang(string culture, string host, string path) { try { _ApplyCultureCookie(culture); var user = await GetCurrentUserAsync(); if (user != null) { user.PreferedLanguage = culture; await _userManager.UpdateAsync(user); } string toGo = new AiurUrl(host, "Api", "SetSonLang", new { Culture = culture, ReturnUrl = path }).ToString(); return(Redirect(toGo)); } catch (CultureNotFoundException) { return(Json(new AiurProtocal { Message = "Not a language.", Code = ErrorType.InvalidInput })); } }
public async Task <string> Get(AiurUrl url, bool internalRequest) { if (internalRequest) { url.Address = Regex.Replace(url.Address, "^https://", "http://", RegexOptions.Compiled); } var request = new HttpRequestMessage(HttpMethod.Get, url.Address) { Content = new FormUrlEncodedContent(url.Params) }; 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); } }
private async Task <string> GetAccessToken(string clientId, string clientSecret, string code, bool isBinding) { var apiAddress = "https://graph.facebook.com/v5.0/oauth/access_token?"; var url = new AiurUrl(apiAddress, new { }); var action = isBinding ? "bind-account" : "sign-in"; var form = new AiurUrl(string.Empty, new FaceBookAccessTokenAddressModel { ClientId = clientId, ClientSecret = clientSecret, Code = code, RedirectUri = new AiurUrl(_serviceLocation.Endpoint, $"/third-party/{action}/{GetName()}", new { }).ToString() }); try { var json = await _http.Post(url, form); var response = JsonConvert.DeserializeObject <AccessTokenResponse>(json); if (string.IsNullOrWhiteSpace(response.AccessToken)) { throw new AiurAPIModelException(ErrorType.Unauthorized, "Invalid facebook credential"); } return(response.AccessToken); } catch (WebException) { throw new AiurAPIModelException(ErrorType.Unauthorized, "Invalid facebook credential"); } }
public async Task <AiurProtocol> UpdateRecordInfoAsync( string accessToken, string oldRecordName, string newRecordName, RecordType newType, string newUrl, string[] tags, bool enabled) { var url = new AiurUrl(_serviceLocation.Endpoint, "Records", "UpdateRecordInfo", new { }); var form = new AiurUrl(string.Empty, new UpdateRecordInfoAddressModel { AccessToken = accessToken, OldRecordName = oldRecordName, NewRecordName = newRecordName, NewType = newType, NewUrl = newUrl, Enabled = enabled, Tags = string.Join(',', tags.Select(t => t.Trim())) }); var result = await _http.Post(url, form, true); var jResult = JsonConvert.DeserializeObject <AiurProtocol>(result); if (jResult.Code != ErrorType.Success) { throw new AiurUnexpectedResponse(jResult); } return(jResult); }
private async Task <IActionResult> FinishAuth(IAuthorizeViewModel model, bool forceGrant = false) { var user = await GetUserFromEmail(model.Email); if (await user.HasAuthorizedApp(_dbContext, model.AppId) && forceGrant == false) { var pack = await user.GeneratePack(_dbContext, model.AppId); var url = new AiurUrl(model.GetRegexRedirectUrl(), new AuthResultAddressModel { Code = pack.Code, State = model.State }); return(Redirect(url)); } else { return(RedirectToAction(nameof(AuthorizeConfirm), new AuthorizeConfirmAddressModel { AppId = model.AppId, State = model.State, ToRedirect = model.ToRedirect, Scope = model.Scope, ResponseType = model.ResponseType })); } }
public async Task <string> Post(AiurUrl url, AiurUrl postDataStr, bool internalRequest) { if (internalRequest) { url.Address = Regex.Replace(url.Address, "^https://", "http://", RegexOptions.Compiled); } var request = new HttpRequestMessage(HttpMethod.Post, url.Address) { Content = new FormUrlEncodedContent(postDataStr.Params) }; 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 { var content = await response.Content.ReadAsStringAsync(); throw new WebException($"The remote server returned unexpcted 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); }
private async Task <string> GetAccessToken(string clientId, string clientSecret, string code, bool isBinding) { var apiAddress = "https://oauth2.googleapis.com/token"; var url = new AiurUrl(apiAddress, new { }); var action = isBinding ? "bind-account" : "sign-in"; var form = new AiurUrl(string.Empty, new GoogleAccessTokenAddressModel { ClientId = clientId, ClientSecret = clientSecret, Code = code, RedirectUri = new AiurUrl(_serviceLocation.Gateway, $"/third-party/{action}/{GetName()}", new { }).ToString(), GrantType = "authorization_code" }); try { var json = await _http.Post(url, form, false); var response = JsonConvert.DeserializeObject <AccessTokenResponse>(json); if (string.IsNullOrWhiteSpace(response.AccessToken)) { throw new AiurAPIModelException(ErrorType.Unauthorized, "Invalid google crenditial"); } return(response.AccessToken); } catch (WebException) { throw new AiurAPIModelException(ErrorType.Unauthorized, "Invalid google crenditial"); } }
public async Task <IActionResult> SetLang(SetlangViewModel model) { if (!ModelState.IsValid) { return(View(model)); } try { _ApplyCultureCookie(model.Culture); } catch (CultureNotFoundException) { return(Json(new AiurProtocol { Message = "Not a language.", Code = ErrorType.InvalidInput })); } var user = await GetCurrentUserAsync(); if (user != null) { user.PreferedLanguage = model.Culture; await _userManager.UpdateAsync(user); } string toGo = new AiurUrl(model.Host, "Api", "SetSonLang", new { model.Culture, ReturnUrl = model.Path }).ToString(); return(Redirect(toGo)); }
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); }
private async Task <string> GetAccessToken(string clientId, string clientSecret, string code, bool isBinding) { var apiAddress = "https://login.microsoftonline.com" + $"/{_tenant}/oauth2/v2.0/token"; var url = new AiurUrl(apiAddress, new { }); var action = isBinding ? "bind-account" : "sign-in"; var form = new AiurUrl(string.Empty, new MicrosoftAccessTokenAddressModel { ClientId = clientId, ClientSecret = clientSecret, Code = code, Scope = "user.read", RedirectUri = new AiurUrl(_serviceLocation.Endpoint, $"/third-party/{action}/{GetName()}", new { }).ToString(), GrantType = "authorization_code" }); try { var json = await _http.Post(url, form); var response = JsonConvert.DeserializeObject <AccessTokenResponse>(json); if (string.IsNullOrWhiteSpace(response.AccessToken)) { throw new AiurAPIModelException(ErrorType.Unauthorized, "Invalid Microsoft crenditial"); } return(response.AccessToken); } catch (WebException) { throw new AiurAPIModelException(ErrorType.Unauthorized, "Invalid Microsoft crenditial"); } }
public async Task <IActionResult> ForgotPasswordViaEmail(ForgotPasswordViaEmailViewModel model) { var mail = await _dbContext.UserEmails.SingleOrDefaultAsync(t => t.EmailAddress == model.Email.ToLower()); if (mail == null) { return(NotFound()); } var user = await _dbContext .Users .Include(t => t.Emails) .SingleOrDefaultAsync(t => t.Id == mail.OwnerId); var code = await _userManager.GeneratePasswordResetTokenAsync(user); var callbackUrl = new AiurUrl(_serviceLocation.API, "User", nameof(ResetPassword), new { Code = code, UserId = user.Id }); await _emailSender.SendEmail(model.Email, "Reset Password", $"Please reset your password by clicking <a href='{callbackUrl}'>here</a>"); return(RedirectToAction(nameof(ForgotPasswordSent))); }
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; } }
/// <summary> /// /// </summary> /// <param name="accessToken"></param> /// <param name="siteName"></param> /// <param name="permissions">Upload, Download</param> /// <param name="underPath"></param> /// <param name="lifespan"></param> /// <returns></returns> public async Task <string> GetTokenAsync( string accessToken, string siteName, string[] permissions, string underPath, TimeSpan lifespan) { var url = new AiurUrl(_serviceLocation.Endpoint, "Token", "GetToken", new { }); var form = new AiurUrl(string.Empty, new GetTokenAddressModel { AccessToken = accessToken, SiteName = siteName, Permissions = string.Join(",", permissions), UnderPath = underPath, LifespanSeconds = (long)lifespan.TotalSeconds }); var result = await _http.Post(url, form, true); var jResult = JsonConvert.DeserializeObject <AiurValue <string> >(result); if (jResult.Code != ErrorType.Success) { throw new AiurUnexpectedResponse(jResult); } return(jResult.Value); }
public async Task <(string appVersion, string cliVersion)> CheckKahla() { var url = new AiurUrl(_configuration["KahlaMasterPackageJson"], new { }); var response = await _http.Get(url, false); var result = JsonConvert.DeserializeObject <NodePackageJson>(response); var urlcli = new AiurUrl(_configuration["CLIMasterPackageJson"], new { }); var responsecli = await _http.Get(urlcli, false); var resultcli = JsonConvert.DeserializeObject <NodePackageJson>(responsecli); if (result.Name.ToLower() == "kahla") { return(result.Version, resultcli.Version); } else { throw new AiurUnexceptedResponse(new AiurProtocol() { Code = ErrorType.NotFound, Message = "GitHub Json response is not related with Kahla!" }); } }
public async Task <string> OAuthAsync() { var url = new AiurUrl(_kahlaLocation.ToString(), "Auth", "OAuth", new { }); var result = await _http.Track(url); return(result); }
public async Task <string> PostWithFile(AiurUrl url, Stream fileStream, bool internalRequest) { if (internalRequest) { url.Address = _regex.Replace(url.Address, "http://"); } var request = new HttpRequestMessage(HttpMethod.Post, url.Address) { Content = new MultipartFormDataContent { { new StreamContent(fileStream), "file", "file" } } }; 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 async Task SendConfirmation(string userId, string emailAddress, string token) { var callbackUrl = new AiurUrl(_serviceLocation.Endpoint, "Password", nameof(PasswordController.EmailConfirm), new { userId, code = token }); await _emailSender.SendEmail("Aiursoft Account Service", emailAddress, $"{Values.ProjectName} Account Email Confirmation", $"Please confirm your email by clicking <a href='{callbackUrl}'>here</a>"); }
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> SignIn(int code) { var url = new AiurUrl(_kahlaLocation.ToString(), "Auth", "AuthResult", new AuthResultAddressModel { Code = code }); var result = await _http.Track(url); return(result); }
public Task SendResetPassword(string code, string userId, string targetEmail) { var callbackUrl = new AiurUrl(_serviceLocation.Endpoint, "Password", nameof(PasswordController.ResetPassword), new { Code = code, UserId = userId }); return(_emailSender.SendEmail("Aiursoft Account Service", targetEmail, "Reset Password", $"Please reset your password by clicking <a href='{callbackUrl}'>here</a>")); }
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://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 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 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 async Task <ViewMyChannelsViewModel> ViewMyChannelsAsync(string accessToken) { var url = new AiurUrl(_stargateLocator.Endpoint, "Channel", "ViewMyChannels", new ViewMyChannelsAddressModel { AccessToken = accessToken }); var result = await _http.Get(url, true); var jResult = JsonConvert.DeserializeObject <ViewMyChannelsViewModel>(result); return(jResult); }