APIToken CreateAPIToken(APIToken APIToken, NpgsqlConnection connection) { if (string.IsNullOrEmpty(APIToken.Token)) { APIToken.CreateToken(_tokenSize); } string insertOrUpdate = "INSERT INTO APIToken (account, channel, token, description, canread, canwrite, validfrom) " + "VALUES(@account, @channel, @token, @description, @canread, @canwrite, @validfrom) " + "RETURNING *;"; return(connection.Query <APIToken>(insertOrUpdate, new { account = APIToken.Account, channel = APIToken.Channel, token = APIToken.Token, description = APIToken.Description, canread = APIToken.CanRead, canwrite = APIToken.CanWrite, validfrom = DateTime.UtcNow } ).Single()); }
private IEnumerator GetRefreshCodeCoroutine(UnityWebRequest www, Action <int, string> errorEvent, Action <Purchase, int> successEvent) { yield return(www.SendWebRequest()); if (www.isDone && !www.isNetworkError && !www.isHttpError) { string resultJSON = www.downloadHandler.text; APIToken token = JsonUtility.FromJson <APIToken>(resultJSON); string checkURL = "https://pardakht.cafebazaar.ir/devapi/v2/api/validate/" + Application.identifier + "/inapp/" + currentPurchase.productId + "/purchases/" + currentPurchase.orderId + "/?access_token=" + token.access_token; UnityWebRequest www1 = UnityWebRequest.Get(checkURL); StartCoroutine(ValidatePurchaseCoroutine(www1, errorEvent, successEvent)); } else { if (errorEvent != null) { errorEvent.Invoke(ERROR_CONNECTING_VALIDATE_API, "error requesting access code."); errorEvent = null; } } }
/// <summary> /// 令牌验证 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btntoken_Click(object sender, EventArgs e) { //在推送前必须先进行令牌验证 string ServiceKey = this.txtServiceKey.Text; //推送key string SecurityKey = this.txtSecurityKey.Text; //推送安全key if ((System.String.IsNullOrEmpty(ServiceKey) == false) && (System.String.IsNullOrEmpty(SecurityKey) == false)) { Smobiler.Utility.API.PushClient client = new Smobiler.Utility.API.PushClient(ServiceKey, SecurityKey); APIToken token = client.GetToken();//令牌验证 if (token.status == 0) { this.lbltoken.Text = token.token; tokenstr = token.token; } else { this.lbltoken.Text = token.error; } this.lblresult.Text = token.ToString(); } else { if (System.String.IsNullOrEmpty(ServiceKey) == true) { this.lblresult.Text = "请输入ServiceKey!"; } if (System.String.IsNullOrEmpty(SecurityKey) == true) { this.lblresult.Text = "请输入SecurityKey!"; } } }
public async Task <List <PayrollEmployees> > Post([FromBody] JObject jObject) { List <PayrollEmployees> list = new List <PayrollEmployees>(); //APIToken apiToken = new APIToken(); //apiToken.CompanyId = "ABRAAJ"; //apiToken.DivisionId = "DEFAULT"; //apiToken.DepartmentId = "DEFAULT"; PayrollEmployees payrollEmployees = jObject["payrollEmp"].ToObject <PayrollEmployees>(); APIToken apiToken = jObject["apiToken"].ToObject <APIToken>(); try { var empDetails = await _DBContext.PayrollEmployees.Where(x => x.CompanyId == apiToken.CompanyId && x.DivisionId == apiToken.DivisionId && x.DepartmentId == apiToken.DepartmentId && x.EmployeeId == payrollEmployees.EmployeeId && x.EmployeePassword == payrollEmployees.EmployeePassword).ToListAsync(); if (empDetails != null) { list = empDetails; } } catch (Exception dd) { } return(list); }
public async Task <ActionResult <IEnumerable <MessageViewModelGet> > > MarkMessage(string channelid, long sequence, [FromQuery] bool?older, [FromBody] MessageViewModelMark data) { logger.LogInformation($"Flag message {sequence} from {channelid} as {(data.Read ? "read" : "unread")}."); // Retrieve token information from identity APIToken apiToken = await authRepository.GetAPITokenAsync(HttpContext.User.Identity.Name); // Validate that sequence exists if (!messageRepository.SequenceExists(apiToken.Id, sequence)) { logger.LogInformation($"Sequence {sequence} not found for API Token {apiToken.Id}."); return(NotFound(ProblemDetailsFactory.CreateProblemDetails(HttpContext, (int)HttpStatusCode.NotFound, $"Sequence not found."))); } // Mark messages messageRepository.MarkMessages(channelid, apiToken.Id, sequence, older ?? false, data.Read); logger.LogInformation($"Message {sequence} was flagged as {(data.Read ? "read" : "unread")}."); return(Ok()); }
public async Task <IActionResult> Login(LoginViewModel user) { if (ModelState.IsValid) { APIToken token = await _tokenservice.GetIdentityToken(user); if (!token.Success) { ModelState.AddModelError(string.Empty, "Неправильное имя пользователя либо пароль"); return(View(user)); } token = await _tokenservice.GetAPIToken(user); if (!token.Success) { ModelState.AddModelError(string.Empty, "Неправильное имя пользователя либо пароль"); return(View(user)); } if (user.ReturnUrl != null) { return(LocalRedirect(user.ReturnUrl)); } else { return(LocalRedirect("/MyTask/Index")); } } return(View(user)); }
public APIToken CreateAPIToken(APIToken APIToken) { if (string.IsNullOrEmpty(APIToken.Token)) { APIToken.CreateToken(_tokenSize); } using var connection = GetNpgsqlConnection(); connection.Open(); using NpgsqlTransaction transaction = connection.BeginTransaction(); string insertOrUpdate = "INSERT INTO APIToken (account, channel, token, description, canread, canwrite, validfrom) " + "VALUES(@account, @channel, @token, @description, @canread, @canwrite, @validfrom) " + "RETURNING *;"; var createdAPIToken = connection.Query <APIToken>(insertOrUpdate, new { account = APIToken.Account, channel = APIToken.Channel, token = APIToken.Token, description = APIToken.Description, canread = APIToken.CanRead, canwrite = APIToken.CanWrite, validfrom = DateTime.UtcNow } ).Single(); transaction.Commit(); return(createdAPIToken); }
public object GetFooterData(string secureToken, string userName) { Dictionary <string, object> param = new Dictionary <string, object>(); APIToken token = new APIToken(_memoryCache); return(token.WebClientInvokerPOST("CbuilderApis/GetFooterData", param, secureToken, userName)); }
public ActionResult Index(String apikey, string wt = "") { Guid apikeyGuid; try { apikeyGuid = new Guid(apikey); } catch (ArgumentNullException) { return(InvalidApikeyArg(apikey)); } catch (FormatException) { return(InvalidApikeyArg(apikey)); } catch (OverflowException) { return(InvalidApikeyArg(apikey)); } APIToken token = null; APIToken widgetToken = null; Core.DataLayer.Models.Customer customer = null; if (!string.IsNullOrWhiteSpace(wt)) { widgetToken = APIToken.ParseToken(wt); } using (var context = ContextFactory.APIContext) { var k = context.APIKeys.Where(i => i.KeyValue == apikeyGuid && i.IsActive).FirstOrDefault(); if (k == null) { Response.StatusCode = 401; return(Content("The product key (\"apikey\") is invalid. Please see https://www.sizeup.com/developers/documentation for help.", "text/plain")); // It would be nice to do this instead, but first we need to plug in a page somewhere to // render the reason. Else you get an opaque HTTP 500 error. // throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized) { // ReasonPhrase = "Product key not recognized." // }); } token = APIToken.Create(k.Id); using (var sizeupContext = ContextFactory.SizeUpContext) { try { customer = SizeUp.Core.DataLayer.Customer.GetCustomerByKey(context, sizeupContext, apikeyGuid); } catch (System.Data.ObjectNotFoundException exc) { // This is actually an error, but the error is a real possibility and I don't // want it to abort the function. An entire API refactor is planned, which will // eventually remove the possibility of failure here. // TODO: if we get a logging framework, log the error. } } } ViewBag.Customer = customer; ViewBag.Token = token.GetToken(); ViewBag.SessionId = APISession.Current.SessionId; ViewBag.InstanceId = RandomString.Get(25); ViewBag.WidgetToken = widgetToken != null?widgetToken.GetToken() : ""; return(View()); }
public APITokenViewModelGet(APIToken APIToken) { Id = APIToken.Id.ToString(); Token = APIToken.Token; Description = APIToken.Description; Can_read = APIToken.CanRead; Can_write = APIToken.CanWrite; }
public object OnlineCompoSearchFilters(string secureToken, string userName) { Dictionary <string, object> dict = new Dictionary <string, object>(); APIToken token = new APIToken(_memoryCache); object objResult = token.WebClientInvokerPOST("CbuilderApis/GetComponentCatAndTypes", dict, secureToken, userName); return(objResult); }
public object ApplyDesign(string dataToSend) { string aiAPI = "http://52.170.3.135:9222/webscrapper"; //string aiAPI = sfConfig.GetSettingValueByIndividualKey(SettingKeys.AIAPI).Result; APIToken objToken = new APIToken(_memoryCache); return(objToken.APICall(aiAPI + "/gettemplate", dataToSend)); }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { if (Request.Headers.ContainsKey("Authorization")) { Request.Headers.TryGetValue("Authorization", out StringValues authorizationData); if (authorizationData.Count == 1 && AuthenticationHeaderValue.TryParse(authorizationData[0], out AuthenticationHeaderValue authHeader)) { if (authHeader.Scheme != AuthenticationSchema) { Logger.LogWarning($"The authorization header provided ({authHeader.Scheme}) is not valid."); return(AuthenticateResult.Fail(SPVChannelsHTTPError.Unauthorized.Description)); } APIToken apiToken = await authRepository.GetAPITokenAsync(authHeader.Parameter); if (apiToken != null) { // Check that token is still valid if (!apiToken.ValidTo.HasValue || apiToken.ValidTo.Value > DateTime.UtcNow) { var routeData = Request.HttpContext.GetRouteData(); routeData.Values.TryGetValue("action", out object action); if ((HttpMethods.IsPost(Request.Method) && (action.ToString() == "MarkMessage" && !apiToken.CanRead || action.ToString() != "MarkMessage" && !apiToken.CanWrite)) || (HttpMethods.IsDelete(Request.Method) && !apiToken.CanWrite) || ((HttpMethods.IsGet(Request.Method) || HttpMethods.IsHead(Request.Method)) && !apiToken.CanRead)) { Logger.LogWarning($"APIToken Id({apiToken.Id}) isn't authorized to access action ({action})."); return(AuthenticateResult.Fail(SPVChannelsHTTPError.Unauthorized.Description)); } else { Logger.LogInformation($"Request was authenticated as API token: {apiToken.Id}."); var claims = new[] { new Claim(ClaimTypes.NameIdentifier, $"{apiToken.Id}"), new Claim(ClaimTypes.Name, $"{apiToken.Token}") }; var identity = new ClaimsIdentity(claims, Scheme.Name); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, Scheme.Name); ticket.Properties.SetParameter <APIToken>("APIToken", apiToken); return(AuthenticateResult.Success(ticket)); } } } } Logger.LogWarning("The authorization header provided was not valid (Invalid Authorization Header)."); } else { Logger.LogWarning("Missing Authorization Header."); } return(AuthenticateResult.Fail(SPVChannelsHTTPError.Unauthorized.Description)); }
public ActionResult Index() { using (var context = ContextFactory.SizeUpContext) { var token = APIToken.Create(APIContext.Current.ApiToken.APIKeyId); var data = token.GetToken(); return(Json(data, JsonRequestBehavior.AllowGet)); } }
public object GetCompTemplateTags(string componentName, string secureToken, string userName) { Dictionary <string, object> param = new Dictionary <string, object> { { "ComponentName", componentName } }; APIToken token = new APIToken(_memoryCache); return(token.WebClientInvokerPOST("CbuilderApis/GetCompTemplateTags", param, secureToken, userName)); }
public object GetOnlineTheme(int themeID, string userName, string secureToken, string version) { Dictionary <string, object> param = new Dictionary <string, object>(); param.Add("themeID", themeID); param.Add("cbuilderVersion", version); param.Add("userName", userName); APIToken token = new APIToken(_memoryCache); return(token.WebClientInvokerPOST("CbuilderApis/InstallThemeFile", param, secureToken, userName)); }
public object GetOnlineHelp(int offset, int limit, string searchText, string secureToken, string userName) { Dictionary <string, object> param = new Dictionary <string, object> { { "Offset", offset }, { "Limit", limit }, { "SearchText", searchText } }; APIToken token = new APIToken(_memoryCache); return(token.WebClientInvokerPOST("CbuilderApis/GetOnlineWebHelp", param, secureToken, userName)); }
public object PaymentSuccessful(string url, string secureToken, string userName, string tranitToken, string version) { Dictionary <string, object> param = new Dictionary <string, object> { { "Url", url }, { "Tranittoken", tranitToken }, { "UserName", userName } }; APIToken token = new APIToken(_memoryCache); return(token.WebClientInvokerPOST("CbuilderApis/PaymentSuccessful", param, secureToken, userName)); }
public async Task <IActionResult> Register(RegisterViewModel user) { if (ModelState.IsValid) { APIToken token = await _tokenservice.GetIdentityToken(new LoginViewModel() { UserName = "******", Password = "******" }); if (!token.Success) { throw new System.Exception(token.Error); } var model = new RegisterUserBL() { UserName = user.UserName, Email = user.Email, Password = user.Password }; APIResult res = await _client.CreateUser <RegisterUserBL>("api/createuser", model, token.token); if (res.Success) { var tokenmodel = new LoginViewModel() { UserName = user.UserName, Password = user.Password }; token = await _tokenservice.GetIdentityToken(tokenmodel); if (!token.Success) { throw new System.Exception(token.Error); } token = await _tokenservice.GetAPIToken(tokenmodel); if (!token.Success) { throw new System.Exception(token.Error); } return(LocalRedirect("/Profile")); } else { ModelState.AddModelError("", res.Error); } } return(View()); }
public object ReviewFromClient(ReviewEntity review, string url, string secureToken, string userName) { Dictionary <string, object> param = new Dictionary <string, object> { { "UserName", review.UserName }, { "Password", review.Password }, { "Review", review.Review }, { "Url", url } }; APIToken token = new APIToken(_memoryCache); return(token.WebClientInvokerPOST("CbuilderApis/ReviewFromClient", param, secureToken, userName)); }
private static async Task <RestRequest> BuildRestRequest(Method method) { if (String.IsNullOrEmpty(currentToken.AccessToken)) { currentToken = await GetToken(); } var request = new RestRequest(method); request.AddHeader("Accept", "application/json"); request.AddHeader("Authorization", String.Format("Bearer {0}", currentToken.AccessToken)); request.AddHeader("x-api-key", apiKey); return(request); }
public object GetComponentTemplate(string componentName, int offset, int limit, string searchText, string tagIDs, string secureToken, string userName) { Dictionary <string, object> param = new Dictionary <string, object> { { "Offset", offset }, { "Limit", limit }, { "ComponentName", componentName }, { "SearchText", searchText }, { "TagIDs", tagIDs } }; APIToken token = new APIToken(_memoryCache); return(token.WebClientInvokerPOST("CbuilderApis/GetComponentTemplate", param, secureToken, userName)); }
public static async Task <APIToken> GetToken() { var client = new RestClient(tokenUrl); var request = new RestRequest(Method.POST); request.AddHeader("cache-control", "no-cache"); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=tenant_client_credentials&scope=client_data client_financial_data&" + credentials, ParameterType.RequestBody); IRestResponse response = await client.ExecuteAsync(request); APIToken token = JsonConvert.DeserializeObject <APIToken>(response.Content); return(token); }
public object InstallComponent(int componentID, string downloadType, decimal version, string userName, string secureToken, string systemversion) { Dictionary <string, object> param = new Dictionary <string, object> { { "ComponentID", componentID }, { "DownloadType", downloadType }, { "Version", version }, { "CbuilderVersion", systemversion }, { "UserName", userName } }; APIToken token = new APIToken(_memoryCache); object result = token.WebClientInvokerPOST("CbuilderApis/InstallComponent", param, secureToken, userName); return(result); }
public object GetInstalledComponents(int offset, int limit, string searchText, string type, string category, string applicationName, string secureToken, string userName, string version) { Dictionary <string, object> param = new Dictionary <string, object> { { "Offset", offset }, { "Limit", limit }, { "SearchText", searchText }, { "Version", version }, { "Type", type }, { "Category", category }, { "ApplicationName", applicationName } }; APIToken token = new APIToken(_memoryCache); return(token.WebClientInvokerPOST("CbuilderApis/GetInstalledComponents", param, secureToken, userName)); }
public async Task <IActionResult> GetTokenInfo() { await RequireSiteAdmin(); if (await GetIdentity() is TokenIdentity) { throw new BaseAPIException("Tokens cannot manage this resource.", APIError.TokenCannotManageThisResource); } APIToken apiToken = await TokenRepository.CreateDefault(_serviceProvider).GetToken(); apiToken.TokenHash = null; apiToken.TokenSalt = null; return(Ok(apiToken)); }
public object GetInstalledSites(int offset, int limit, string themeName, int sectorID, int siteCategoryID, int businessTypeID, string applicationName, string authToken, string userName, string version) { Dictionary <string, object> args = new Dictionary <string, object> { { "Offset", offset }, { "Limit", limit }, { "ThemeName", themeName }, { "SectorID", sectorID }, { "SiteCategoryID", siteCategoryID }, { "BusinessTypeID", businessTypeID }, { "Version", version }, { "ApplicationName", applicationName } }; APIToken token = new APIToken(_memoryCache); return(token.WebClientInvokerPOST("CbuilderApis/GetInstalledSites", args, authToken, userName)); }
public object FeedBackFromClient(FeedbackDetails feedBack, string secureToken, string userName) { Dictionary <string, object> param = new Dictionary <string, object> { { "Category", feedBack.Category }, { "Description", feedBack.Description }, { "Domain", feedBack.Domain }, { "EmailID", feedBack.EmailID }, { "Keyword", feedBack.Keyword }, { "Name", feedBack.Name }, { "Rating", feedBack.Rating }, { "Title", feedBack.Title }, { "UserName", feedBack.Username } }; APIToken token = new APIToken(_memoryCache); return(token.WebClientInvokerPOST("CbuilderApis/FeedBackFromClient", param, secureToken, userName).ToString()); }
public async Task <ActionResult <IEnumerable <MessageViewModelGet> > > GetMessages(string channelid, [FromQuery] bool?unread) { var error = SPVChannelsHTTPError.NotFound; logger.LogInformation($"Get messages for channel(id):{channelid}."); // Retrieve token information from identity APIToken apiToken = await authRepository.GetAPITokenAsync(HttpContext.User.Identity.Name); // Retrieve message list and convert it to view model var messageList = messageRepository.GetMessages(apiToken.Id, unread ?? false, out string maxSequence); logger.LogInformation($"Returning {messageList.Count()} messages for channel: {channelid}."); // Add ETag header Response.Headers.Add("ETag", maxSequence); return(Ok(messageList.Select(x => new MessageViewModelGet(x)))); }
public object GetRowOnlineComponents(int offset, int limit, string searchText, string type, string category, string applicationName, string secureToken, string userName, string version) { SettingHelper sfConfig = new SettingHelper(); string onlineStorePath = sfConfig.GetSettingValueByIndividualKey(SettingKeys.OnlineStore).Result; Dictionary <string, object> objCollection = new Dictionary <string, object> { { "Offset", offset }, { "Limit", limit }, { "SearchText", searchText }, { "Version", version }, { "Type", type }, { "Category", category }, { "ApplicationName", applicationName } }; APIToken objToken = new APIToken(_memoryCache); object objResult = objToken.WebClientInvokerPOST("CbuilderApis/GetRowOnlineComponents", objCollection, secureToken, userName); return(objResult); }